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.

1287 lines
66KB

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