Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1244 rindas
64KB

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