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

1124 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(['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. ],
  362. [
  363. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  364. 'conditions' => 'date_delete IS NULL'
  365. ]);
  366. $distribution = Distribution::searchOne([], [
  367. 'conditions' => 'date LIKE :date',
  368. 'params' => [':date' => $date]
  369. ]);
  370. if ($distribution) {
  371. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  372. $pointsSaleArray = PointSale::searchAll();
  373. foreach ($pointsSaleArray as $pointSale) {
  374. $pointSale->initOrders($ordersArray);
  375. }
  376. // produits
  377. $productsArray = Product::find()
  378. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  379. $q->where(['id_distribution' => $distribution->id]);
  380. }])
  381. ->where([
  382. 'id_producer' => GlobalParam::getCurrentProducerId(),
  383. ])
  384. ->orderBy('order ASC')
  385. ->all();
  386. if ($type == 'pdf') {
  387. // get your HTML raw content without any layouts or scripts
  388. $content = $this->renderPartial('report', [
  389. 'date' => $date,
  390. 'distribution' => $distribution,
  391. 'selectedProductsArray' => $selectedProductsArray,
  392. 'pointsSaleArray' => $pointsSaleArray,
  393. 'productsArray' => $productsArray,
  394. 'ordersArray' => $ordersArray
  395. ]);
  396. $dateStr = date('d/m/Y', strtotime($date));
  397. if ($save) {
  398. $destination = Pdf::DEST_FILE;
  399. } else {
  400. $destination = Pdf::DEST_BROWSER;
  401. }
  402. $pdf = new Pdf([
  403. // set to use core fonts only
  404. 'mode' => Pdf::MODE_UTF8,
  405. // A4 paper format
  406. 'format' => Pdf::FORMAT_A4,
  407. // portrait orientation
  408. 'orientation' => Pdf::ORIENT_PORTRAIT,
  409. // stream to browser inline
  410. 'destination' => $destination,
  411. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  412. // your html content input
  413. 'content' => $content,
  414. // format content from your own css file if needed or use the
  415. // enhanced bootstrap css built by Krajee for mPDF formatting
  416. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  417. // any css to be embedded if required
  418. 'cssInline' => '
  419. table {
  420. border-spacing : 0px ;
  421. border-collapse : collapse ;
  422. width: 100% ;
  423. }
  424. table tr th,
  425. table tr td {
  426. padding: 0px ;
  427. margin: 0px ;
  428. border: solid 1px #e0e0e0 ;
  429. padding: 3px 8px ;
  430. vertical-align : top;
  431. }
  432. table tr th {
  433. font-size: 13px ;
  434. }
  435. table tr td {
  436. font-size: 13px ;
  437. }
  438. ',
  439. // set mPDF properties on the fly
  440. //'options' => ['title' => 'Krajee Report Title'],
  441. // call mPDF methods on the fly
  442. 'methods' => [
  443. 'SetHeader' => ['Commandes du ' . $dateStr],
  444. 'SetFooter' => ['{PAGENO}'],
  445. ]
  446. ]);
  447. // return the pdf output as per the destination setting
  448. return $pdf->render();
  449. } elseif ($type == 'csv') {
  450. $datas = [];
  451. // produits en colonne
  452. $productsNameArray = [''];
  453. $productsIndexArray = [];
  454. $productsHasQuantity = [];
  455. $cpt = 1;
  456. foreach ($productsArray as $product) {
  457. $productsHasQuantity[$product->id] = 0;
  458. foreach (Product::$unitsArray as $unit => $dataUnit) {
  459. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  460. if ($quantity) {
  461. $productsHasQuantity[$product->id] += $quantity;
  462. }
  463. }
  464. if ($productsHasQuantity[$product->id] > 0) {
  465. $productsNameArray[] = $product->name . ' (' . Product::strUnit($product->unit, 'wording_short', true) . ')';
  466. $productsIndexArray[$product->id] = $cpt++;
  467. }
  468. }
  469. $datas[] = $productsNameArray;
  470. // points de vente
  471. foreach ($pointsSaleArray as $pointSale) {
  472. if (count($pointSale->orders)) {
  473. // listing commandes
  474. $datas[] = ['> ' . $pointSale->name];
  475. foreach ($pointSale->orders as $order) {
  476. $orderLine = [$order->getStrUser()];
  477. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  478. $orderLine[$indexProduct] = '';
  479. }
  480. foreach ($order->productOrder as $productOrder) {
  481. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  482. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  483. }
  484. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  485. if ($productOrder->product->unit != $productOrder->unit) {
  486. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  487. }
  488. }
  489. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  490. }
  491. // total point de vente
  492. $totalsPointSaleArray = $this->_totalReportCSV(
  493. 'Total',
  494. $pointSale->orders,
  495. $productsArray,
  496. $productsIndexArray
  497. );
  498. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  499. $datas[] = [];
  500. }
  501. }
  502. // global
  503. $totalsGlobalArray = $this->_totalReportCSV(
  504. '> Totaux',
  505. $ordersArray,
  506. $productsArray,
  507. $productsIndexArray
  508. );
  509. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  510. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  511. echo CSV::array2csv($datas);
  512. die();
  513. }
  514. }
  515. return null;
  516. }
  517. /**
  518. * Génère un export des commandes au format CSV à destination du Google Drive
  519. * de Terre de pains.
  520. *
  521. * @param type $date
  522. * @return CSV
  523. */
  524. public function actionReportTerredepains($date, $key)
  525. {
  526. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  527. $producer = Producer::searchOne([
  528. 'producer.slug' => 'terredepains'
  529. ]);
  530. $idProducer = $producer->id;
  531. $ordersArray = Order::searchAll([
  532. 'distribution.date' => $date,
  533. 'distribution.id_producer' => $idProducer
  534. ],
  535. [
  536. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  537. 'conditions' => 'date_delete IS NULL'
  538. ]);
  539. $distribution = Distribution::searchOne([
  540. 'distribution.id_producer' => $idProducer
  541. ], [
  542. 'conditions' => 'date LIKE :date',
  543. 'params' => [
  544. ':date' => $date,
  545. ]
  546. ]);
  547. if ($distribution) {
  548. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  549. $pointsSaleArray = PointSale::searchAll([
  550. 'point_sale.id_producer' => $idProducer
  551. ]);
  552. foreach ($pointsSaleArray as $pointSale) {
  553. $pointSale->initOrders($ordersArray);
  554. }
  555. // produits
  556. $productsArray = Product::find()
  557. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  558. $q->where(['id_distribution' => $distribution->id]);
  559. }])
  560. ->where([
  561. 'id_producer' => $idProducer,
  562. ])
  563. ->orderBy('order ASC')
  564. ->all();
  565. $datas = [];
  566. // produits en colonne
  567. $productsNameArray = [''];
  568. $productsIndexArray = [];
  569. $productsHasQuantity = [];
  570. $cpt = 1;
  571. foreach ($productsArray as $product) {
  572. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  573. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  574. $productsNameArray[] = $product->name . $theUnit;
  575. $productsIndexArray[$product->id] = $cpt++;
  576. }
  577. $productsNameArray[] = 'Total';
  578. $datas[] = $productsNameArray;
  579. // global
  580. $totalsGlobalArray = $this->_totalReportCSV(
  581. '> Totaux',
  582. $ordersArray,
  583. $productsArray,
  584. $productsIndexArray
  585. );
  586. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  587. $datas[] = [];
  588. // points de vente
  589. foreach ($pointsSaleArray as $pointSale) {
  590. if (count($pointSale->orders)) {
  591. // listing commandes
  592. $datas[] = ['> ' . $pointSale->name];
  593. foreach ($pointSale->orders as $order) {
  594. $orderLine = [$order->getStrUser()];
  595. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  596. $orderLine[$indexProduct] = '';
  597. }
  598. foreach ($order->productOrder as $productOrder) {
  599. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  600. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  601. }
  602. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  603. if ($productOrder->product->unit != $productOrder->unit) {
  604. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  605. }
  606. }
  607. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  608. }
  609. // total point de vente
  610. $totalsPointSaleArray = $this->_totalReportCSV(
  611. 'Total point de vente',
  612. $pointSale->orders,
  613. $productsArray,
  614. $productsIndexArray
  615. );
  616. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  617. $datas[] = [];
  618. }
  619. }
  620. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  621. echo CSV::array2csv($datas);
  622. die();
  623. }
  624. return null;
  625. }
  626. }
  627. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  628. {
  629. $totalsPointSaleArray = [$label];
  630. foreach ($productsArray as $product) {
  631. foreach (Product::$unitsArray as $unit => $dataUnit) {
  632. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  633. if ($quantity) {
  634. $index = $productsIndexArray[$product->id];
  635. if (!isset($totalsPointSaleArray[$index])) {
  636. $totalsPointSaleArray[$index] = '';
  637. }
  638. if (strlen($totalsPointSaleArray[$index])) {
  639. $totalsPointSaleArray[$index] .= ' + ';
  640. }
  641. $totalsPointSaleArray[$index] .= $quantity;
  642. if ($product->unit != $unit) {
  643. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  644. }
  645. }
  646. }
  647. }
  648. return $totalsPointSaleArray;
  649. }
  650. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  651. {
  652. $line = [];
  653. $cptTotal = 0;
  654. for ($i = 0; $i <= $cptMax; $i++) {
  655. if (isset($orderLine[$i]) && $orderLine[$i]) {
  656. $line[] = $orderLine[$i];
  657. $cptTotal += $orderLine[$i];
  658. } else {
  659. $line[] = '';
  660. }
  661. }
  662. if ($cptTotal > 0 && $showTotal) {
  663. $line[] = $cptTotal;
  664. }
  665. return $line;
  666. }
  667. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  668. {
  669. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  670. $productDistribution = ProductDistribution::searchOne([
  671. 'id_distribution' => $idDistribution,
  672. 'id_product' => $idProduct,
  673. ]);
  674. $productDistribution->quantity_max = (!$quantityMax) ? null : (int)$quantityMax;
  675. $productDistribution->save();
  676. return ['success'];
  677. }
  678. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  679. {
  680. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  681. $productDistribution = ProductDistribution::searchOne([
  682. 'id_distribution' => $idDistribution,
  683. 'id_product' => $idProduct,
  684. ]);
  685. $productDistribution->active = $active;
  686. $productDistribution->save();
  687. return ['success'];
  688. }
  689. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  690. {
  691. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  692. $pointSaleDistribution = PointSaleDistribution::searchOne([
  693. 'id_distribution' => $idDistribution,
  694. 'id_point_sale' => $idPointSale,
  695. ]);
  696. $pointSaleDistribution->delivery = $delivery;
  697. $pointSaleDistribution->save();
  698. return ['success'];
  699. }
  700. /**
  701. * Active/désactive un jour de distribution.
  702. *
  703. * @param integer $idDistribution
  704. * @param string $date
  705. * @param boolean $active
  706. * @return array
  707. */
  708. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  709. {
  710. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  711. if ($idDistribution) {
  712. $distribution = Distribution::searchOne([
  713. 'id' => $idDistribution
  714. ]);
  715. }
  716. $format = 'Y-m-d';
  717. $dateObject = DateTime::createFromFormat($format, $date);
  718. if ($dateObject && $dateObject->format($format) === $date) {
  719. $distribution = Distribution::initDistribution($date);
  720. }
  721. if ($distribution) {
  722. $distribution->active($active);
  723. return ['success'];
  724. }
  725. return ['error'];
  726. }
  727. /**
  728. * Change l'état d'une semaine de production (activé, désactivé).
  729. *
  730. * @param string $date
  731. * @param integer $active
  732. */
  733. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  734. {
  735. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  736. $week = sprintf('%02d', date('W', strtotime($date)));
  737. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  738. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  739. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  740. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  741. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  742. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  743. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  744. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  745. $pointsSaleArray = PointSale::searchAll();
  746. $activeMonday = false;
  747. $activeTuesday = false;
  748. $activeWednesday = false;
  749. $activeThursday = false;
  750. $activeFriday = false;
  751. $activeSaturday = false;
  752. $activeSunday = false;
  753. foreach ($pointsSaleArray as $pointSale) {
  754. if ($pointSale->delivery_monday) $activeMonday = true;
  755. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  756. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  757. if ($pointSale->delivery_thursday) $activeThursday = true;
  758. if ($pointSale->delivery_friday) $activeFriday = true;
  759. if ($pointSale->delivery_saturday) $activeSaturday = true;
  760. if ($pointSale->delivery_sunday) $activeSunday = true;
  761. }
  762. if ($activeMonday || !$active) {
  763. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  764. }
  765. if ($activeTuesday || !$active) {
  766. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  767. }
  768. if ($activeWednesday || !$active) {
  769. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  770. }
  771. if ($activeThursday || !$active) {
  772. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  773. }
  774. if ($activeFriday || !$active) {
  775. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  776. }
  777. if ($activeSaturday || !$active) {
  778. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  779. }
  780. if ($activeSunday || !$active) {
  781. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  782. }
  783. return ['success'];
  784. }
  785. /**
  786. * Ajoute les commandes récurrentes pour une date donnée.
  787. *
  788. * @param string $date
  789. */
  790. public function actionAjaxProcessAddSubscriptions($date)
  791. {
  792. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  793. Subscription::addAll($date, true);
  794. return ['success'];
  795. }
  796. /**
  797. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  798. *
  799. * @param string $date
  800. */
  801. public function actionAjaxProcessSynchroTiller($date)
  802. {
  803. $producerTiller = Producer::getConfig('tiller');
  804. if ($producerTiller) {
  805. $tiller = new Tiller();
  806. $isSynchro = $tiller->isSynchro($date);
  807. if (!$isSynchro) {
  808. $orders = Order::searchAll([
  809. 'distribution.date' => $date,
  810. 'order.tiller_synchronization' => 1
  811. ]);
  812. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  813. if ($orders && count($orders)) {
  814. foreach ($orders as $order) {
  815. $lines = [];
  816. foreach ($order->productOrder as $productOrder) {
  817. $lines[] = [
  818. 'name' => $productOrder->product->name,
  819. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  820. 'tax' => $productOrder->taxRate->value * 100,
  821. 'date' => $strDate,
  822. 'quantity' => $productOrder->quantity
  823. ];
  824. }
  825. $typePaymentTiller = '';
  826. if ($order->mean_payment == MeanPayment::MONEY
  827. || $order->mean_payment == MeanPayment::CREDIT
  828. || $order->mean_payment == MeanPayment::TRANSFER
  829. || $order->mean_payment == MeanPayment::OTHER) {
  830. $typePaymentTiller = 'CASH';
  831. }
  832. if ($order->mean_payment == MeanPayment::CREDIT_CARD) {
  833. $typePaymentTiller = 'CARD';
  834. }
  835. if ($order->mean_payment == MeanPayment::CHEQUE) {
  836. $typePaymentTiller = 'BANK_CHECK';
  837. }
  838. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  839. $typePaymentTiller = 'CASH';
  840. }
  841. $tiller->postOrder([
  842. 'externalId' => $order->id,
  843. 'type' => 1,
  844. 'status' => "CLOSED",
  845. 'openDate' => $strDate,
  846. 'closeDate' => $strDate,
  847. 'lines' => $lines,
  848. 'payments' => [[
  849. 'type' => $typePaymentTiller,
  850. 'amount' => $order->getAmountWithTax(Order::AMOUNT_TOTAL) * 100,
  851. 'status' => 'ACCEPTED',
  852. 'date' => $strDate
  853. ]]
  854. ]);
  855. }
  856. }
  857. }
  858. }
  859. }
  860. public function actionAjaxGenerateDeliveryNote($idOrders)
  861. {
  862. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  863. if (strlen($idOrders)) {
  864. $idOrders = json_decode($idOrders, true);
  865. if (is_array($idOrders) && count($idOrders) > 0) {
  866. // récupération première commande pour obtenir des infos
  867. reset($idOrders) ;
  868. $firstOrder = Order::searchOne([
  869. 'id' => (int)$idOrders[key($idOrders)]
  870. ]);
  871. // deliveryNote existant
  872. $deliveryNote = null ;
  873. $isUpdate = false ;
  874. $i = 0 ;
  875. $ordersArray = Order::searchAll([
  876. 'id' => $idOrders,
  877. ]) ;
  878. do {
  879. $order = $ordersArray[$i] ;
  880. if($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  881. $deliveryNote = DeliveryNote::searchOne([
  882. 'id' => $order->id_delivery_note
  883. ]) ;
  884. $isUpdate = true ;
  885. }
  886. $i ++ ;
  887. } while($deliveryNote == null && isset($ordersArray[$i])) ;
  888. if($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  889. return [
  890. 'return' => 'error',
  891. 'alert' => [
  892. 'type' => 'danger',
  893. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  894. ]
  895. ] ;
  896. }
  897. if ($firstOrder) {
  898. // génération du BL
  899. if(!$deliveryNote) {
  900. $deliveryNote = new DeliveryNote;
  901. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date('d/m/Y', strtotime($firstOrder->distribution->date)) . ')';
  902. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  903. if($firstOrder->pointSale->id_user) {
  904. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  905. }
  906. else {
  907. $user = new User ;
  908. $user->type = User::TYPE_LEGAL_PERSON ;
  909. $user->name_legal_person = $firstOrder->pointSale->name ;
  910. $user->address = $firstOrder->pointSale->address ;
  911. $user->id_producer = 0 ;
  912. $user->setPassword(Password::generate());
  913. $user->generateAuthKey();
  914. $user->email = '' ;
  915. if (!strlen($user->email)) {
  916. $user->username = 'inconnu@opendistrib.net';
  917. }
  918. $user->save() ;
  919. $userProducer = new UserProducer;
  920. $userProducer->id_user = $user->id;
  921. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  922. $userProducer->credit = 0;
  923. $userProducer->active = 1;
  924. $userProducer->save();
  925. $firstOrder->pointSale->id_user = $user->id ;
  926. $firstOrder->pointSale->save() ;
  927. $deliveryNote->id_user = $user->id;
  928. }
  929. if(!isset($user)) {
  930. $user = User::searchOne([
  931. 'id' => $deliveryNote->id_user
  932. ]) ;
  933. }
  934. $deliveryNote->address = $user->getFullAddress() ;
  935. $deliveryNote->save();
  936. }
  937. else {
  938. // réinitialisation des order.id_delivery_order
  939. Order::updateAll([
  940. 'id_delivery_note' => null
  941. ], [
  942. 'id_delivery_note' => $deliveryNote->id
  943. ]) ;
  944. }
  945. // affectation du BL aux commandes
  946. foreach ($idOrders as $idOrder) {
  947. $order = Order::searchOne([
  948. 'id' => (int)$idOrder
  949. ]);
  950. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  951. $order->id_delivery_note = $deliveryNote->id;
  952. $order->save();
  953. }
  954. }
  955. return [
  956. 'return' => 'success',
  957. 'alert' => [
  958. 'type' => 'success',
  959. 'message' => 'Bon de livraison '.($isUpdate ? 'modifié' : 'généré')
  960. ]
  961. ] ;
  962. }
  963. }
  964. }
  965. return [
  966. 'return' => 'error',
  967. 'alert' => [
  968. 'type' => 'danger',
  969. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  970. ]
  971. ];
  972. }
  973. }