Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

797 lines
33KB

  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 common\helpers\Ajax;
  39. use common\helpers\GlobalParam;
  40. use common\helpers\MeanPayment;
  41. use common\helpers\Price;
  42. use common\logic\Distribution\Distribution\Model\Distribution;
  43. use common\logic\Document\DeliveryNote\Model\DeliveryNote;
  44. use common\logic\Order\Order\Model\Order;
  45. use common\logic\Producer\Producer\Model\Producer;
  46. use common\logic\Product\Product\Model\Product;
  47. use DateTime;
  48. use kartik\mpdf\Pdf;
  49. use yii\base\Exception;
  50. use yii\filters\AccessControl;
  51. class DistributionController extends BackendController
  52. {
  53. public function behaviors()
  54. {
  55. return [
  56. 'access' => [
  57. 'class' => AccessControl::class,
  58. 'rules' => [
  59. [
  60. 'actions' => ['report-cron', 'report-terredepains'],
  61. 'allow' => true,
  62. 'roles' => ['?']
  63. ],
  64. [
  65. 'allow' => true,
  66. 'roles' => ['@'],
  67. 'matchCallback' => function ($rule, $action) {
  68. return $this->getUserModule()
  69. ->getAuthorizationChecker()
  70. ->isGrantedAsProducer($this->getUserCurrent());
  71. }
  72. ]
  73. ],
  74. ],
  75. ];
  76. }
  77. public function actionIndex(string $date = '', int $idOrderUpdate = 0)
  78. {
  79. $this->checkProductsPointsSale();
  80. if(!$this->getDistributionModule()->getSolver()->validateDistributionDate($date)) {
  81. $date = '';
  82. }
  83. $orderUpdate = null;
  84. if($idOrderUpdate) {
  85. $orderUpdate = $this->getOrderModule()->getRepository()
  86. ->findOneOrderById($idOrderUpdate);
  87. }
  88. return $this->render('index', [
  89. 'date' => $date,
  90. 'orderUpdate' => $orderUpdate
  91. ]);
  92. }
  93. public function actionAjaxInfos($date = '')
  94. {
  95. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  96. $distributionModule = $this-> getDistributionModule();
  97. $orderModule = $this->getOrderModule();
  98. $productModule = $this->getProductModule();
  99. $userModule = $this->getUserModule();
  100. $producer = $this->getProducerCurrent();
  101. $dateObject = DateTime::createFromFormat('Y-m-d', $date);
  102. $json = ['distribution' => [], 'products' => []];
  103. $json['means_payment'] = MeanPayment::getAll();
  104. $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
  105. $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
  106. $json['units'] = Product::$unitsArray;
  107. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  108. $distribution = $distributionModule->createDistributionIfNotExist($date);
  109. $ordersArray = $orderModule->findOrdersByDistribution($distribution, false);
  110. $ordersArrayObject = $ordersArray;
  111. $productsArray = $productModule->findProductsByDistribution($distribution, false);
  112. $json['products'] = $this->buildAjaxInfosResponseProducts($distribution, $productsArray, $ordersArray);
  113. $json['distribution'] = $this->buildAjaxInfosResponseDistribution($distribution, $ordersArrayObject, $productsArray);
  114. $json['orders'] = $this->buildAjaxInfosResponseOrders($ordersArray, $productsArray);
  115. $json['points_sale'] = $this->buildAjaxInfosResponsePointsSale($distribution);
  116. $json['delivery_notes'] = $this->buildAjaxInfosResponseDeliveryNotes($date);
  117. $json['order_create'] = $this->buildAjaxInfosResponseOrderCreate($distribution, $productsArray);
  118. $json['users'] = $userModule->findUsers();
  119. $json['one_distribution_week_active'] = $distributionModule->isOneDistributionWeekActive($date);
  120. $json['tiller_is_synchro'] = $this->buildAjaxInfosResponseTiller($producer, $date);
  121. $json['missing_subscriptions'] = $this->buildAjaxInfosResponseMissingSubscriptions($date, $distribution, $ordersArrayObject);
  122. }
  123. return $json;
  124. }
  125. public function buildAjaxInfosResponsePointsSale(Distribution $distribution)
  126. {
  127. $producerModule = $this->getProducerModule();
  128. $pointSaleModule = $this->getPointSaleModule();
  129. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  130. $pointsSaleArray = $pointSaleModule->findPointSalesByDistributionAsArray($distribution);
  131. // @TODO : à gérer autrement
  132. foreach($pointsSaleArray as &$pointSaleArray) {
  133. $idPointSale = $pointSaleArray['id'];
  134. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  135. if(!isset($pointSaleArray['pointSaleDistribution']) || !$pointSaleArray['pointSaleDistribution'] || !count($pointSaleArray['pointSaleDistribution'])) {
  136. $pointSaleDistribution = $pointSaleDistributionModule->createPointSaleDistributionIfNotExist($distribution, $pointSale);
  137. $pointSaleArray['pointSaleDistribution'] = [
  138. [
  139. 'id_distribution' => $pointSaleDistribution->id_distribution,
  140. 'id_point_sale' => $pointSaleDistribution->id_point_sale,
  141. 'delivery' => $pointSaleDistribution->delivery
  142. ]
  143. ];
  144. }
  145. $pointSaleArray['credit_functioning'] = $producerModule->getPointSaleCreditFunctioning($pointSale);
  146. }
  147. return $pointsSaleArray;
  148. }
  149. public function buildAjaxInfosResponseProducts(Distribution $distribution, array $productsArray, array $ordersArray)
  150. {
  151. $distributionModule = $this-> getDistributionModule();
  152. $orderModule = $this->getOrderModule();
  153. $jsonProductsArray = [];
  154. foreach ($productsArray as $product) {
  155. $jsonProduct = $product->getAttributes();
  156. $quantityOrder = $orderModule->getProductQuantity($product, $ordersArray);
  157. $jsonProduct['quantity_ordered'] = $quantityOrder;
  158. if (!isset($product->productDistribution[0])) {
  159. $productDistributionAdd = $distributionModule->addProduct($distribution, $product);
  160. if($productDistributionAdd) {
  161. $jsonProduct['productDistribution'][0] = $productDistributionAdd->getAttributes();
  162. $product->populateRelation('productDistribution', [$productDistributionAdd]);
  163. }
  164. }
  165. else {
  166. foreach($product->productDistribution as $key => $productDistribution) {
  167. $jsonProduct['productDistribution'][$key] = $productDistribution->getAttributes();
  168. }
  169. }
  170. if (!isset($product->productDistribution[0]) || !is_numeric($product->productDistribution[0]->quantity_max)) {
  171. $jsonProduct['quantity_remaining'] = null;
  172. } else {
  173. $jsonProduct['quantity_remaining'] = $product->productDistribution[0]->quantity_max - $quantityOrder;
  174. }
  175. $jsonProduct['quantity_form'] = 0;
  176. if ($product->taxRate) {
  177. $jsonProduct['taxRate'] = $product->taxRate->getAttributes();
  178. }
  179. else {
  180. $jsonProduct['taxRate'] = $this->getProducerCurrent()->taxRate->getAttributes();
  181. }
  182. $jsonProductsArray[] = $jsonProduct;
  183. }
  184. return $jsonProductsArray;
  185. }
  186. public function buildAjaxInfosResponseProducer($producer)
  187. {
  188. return [
  189. 'credit' => $producer->credit,
  190. 'tiller' => $producer->tiller,
  191. 'option_display_export_grid' => $producer->option_display_export_grid
  192. ];
  193. }
  194. public function buildAjaxInfosResponseDistributions($dateObject)
  195. {
  196. $numberOfLoadedMonthes = '3 month';
  197. if (is_object($dateObject)) {
  198. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  199. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  200. } else {
  201. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  202. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  203. }
  204. return Distribution::searchAll([
  205. 'active' => 1
  206. ], [
  207. 'conditions' => [
  208. 'date > :date_begin',
  209. 'date < :date_end'
  210. ],
  211. 'params' => [
  212. ':date_begin' => date(
  213. 'Y-m-d',
  214. $dateBegin
  215. ),
  216. ':date_end' => date(
  217. 'Y-m-d',
  218. $dateEnd
  219. ),
  220. ],
  221. 'as_array' => true
  222. ]);
  223. }
  224. public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray, array $productsArray)
  225. {
  226. $productModule = $this->getProductModule();
  227. $orderModule = $this->getOrderModule();
  228. $distributionModule = $this-> getDistributionModule();
  229. $distributionJsonData = [
  230. 'id' => $distribution->id,
  231. 'active' => $distribution->active,
  232. 'url_report' => $this->getUrlManagerBackend()->createUrl(
  233. ['distribution/report', 'date' => $distribution->date]
  234. ),
  235. 'url_report_grid' => $this->getUrlManagerBackend()->createUrl(
  236. ['distribution/report-grid', 'date' => $distribution->date]
  237. ),
  238. 'url_export_shopping_cart_labels' => $this->getUrlManagerBackend()->createUrl(
  239. ['distribution/export-shopping-cart-labels', 'date' => $distribution->date]
  240. ),
  241. 'url_order' => $distributionModule->getLinkOrder($distribution),
  242. ];
  243. // montant et poids des commandes
  244. $revenues = 0;
  245. $weight = 0;
  246. if ($ordersArray) {
  247. foreach ($ordersArray as $order) {
  248. $orderModule->initOrder($order);
  249. if (is_null($order->date_delete)) {
  250. $revenues += $orderModule->getOrderAmountWithTax($order);
  251. $weight += $order->weight;
  252. }
  253. }
  254. }
  255. $distributionJsonData['revenues'] = Price::format($revenues);
  256. $distributionJsonData['weight'] = number_format($weight, 2);
  257. $distributionJsonData['potential_revenues'] = Price::format($productModule->getProductDistributionPotentialRevenues($productsArray));
  258. $distributionJsonData['potential_weight'] = number_format($productModule->getProductDistributionPotentialWeight($productsArray), 2);
  259. return $distributionJsonData;
  260. }
  261. public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
  262. {
  263. $userModule = $this->getUserModule();
  264. $orderModule = $this->getOrderModule();
  265. $paymentManager = $this->getPaymentModule();
  266. if ($ordersArray) {
  267. foreach ($ordersArray as &$order) {
  268. $orderModule->initOrder($order);
  269. $productOrderArray = [];
  270. foreach ($order->productOrder as $productOrder) {
  271. $productOrderArray[$productOrder->id_product] = [
  272. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  273. 'unit' => $productOrder->unit,
  274. 'price' => number_format($productOrder->price, 5),
  275. 'invoice_price' => number_format($productOrder->invoice_price, 5),
  276. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  277. ];
  278. }
  279. foreach ($productsArray as $product) {
  280. if (!isset($productOrderArray[$product['id']])) {
  281. $productOrderArray[$product['id']] = [
  282. 'quantity' => 0,
  283. 'unit' => $product['unit'],
  284. 'price' => number_format($product['price'], 5),
  285. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  286. ];
  287. }
  288. }
  289. $paymentArray = [];
  290. foreach ($order->payment as $payment) {
  291. $paymentArray[] = [
  292. 'type' => $payment->type,
  293. 'wording_type' => $paymentManager->getStrType($payment),
  294. 'mean_payment' => $payment->mean_payment,
  295. 'wording_mean_payment' => $paymentManager->getStrMeanPayment($payment),
  296. 'date' => date('d/m/Y H:i:s', strtotime($payment->date)),
  297. 'user' => $payment->getUserObject() ? $userModule->getUsername($payment->getUserObject()) : '',
  298. 'user_action' => $paymentManager->getStrUserAction($payment),
  299. 'wording' => $paymentManager->getStrWording($payment, $order),
  300. 'amount' => $paymentManager->getAmount($payment, Order::AMOUNT_TOTAL, true),
  301. ];
  302. }
  303. $arrayCreditUser = [];
  304. if(isset($order->user)) {
  305. $arrayCreditUser['credit'] = $userModule->getCredit($order->user);
  306. $arrayCreditUser['credit_active'] = $userModule->getCreditActive($order->user);
  307. }
  308. $oneProductUnactivated = false;
  309. foreach ($order->productOrder as $productOrder) {
  310. foreach ($productsArray as $product) {
  311. if ($productOrder->id_product == $product['id'] && isset($product['productDistribution'][0]) && !$product['productDistribution'][0]['active']) {
  312. $oneProductUnactivated = true;
  313. }
  314. }
  315. }
  316. $order = array_merge($order->getAttributes(), [
  317. 'selected' => false,
  318. 'weight' => $order->weight,
  319. 'amount' => (float) Price::numberTwoDecimals($orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  320. 'amount_paid' => (float) Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_PAID)),
  321. 'amount_remaining' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_REMAINING)),
  322. 'amount_surplus' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
  323. 'user' => (isset($order->user)) ? array_merge(
  324. $order->user->getAttributes(),
  325. $arrayCreditUser
  326. ) : null,
  327. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  328. 'productOrder' => $productOrderArray,
  329. 'paymentsArray' => $paymentArray,
  330. 'oneProductUnactivated' => $oneProductUnactivated,
  331. 'isLinkedToValidDocument' => $orderModule->isLinkedToValidDocument($order),
  332. 'isLinkedToValidInvoice' => $orderModule->isLinkedToValidInvoice($order),
  333. 'isCreditAutoPayment' => $orderModule->isCreditAutoPayment($order),
  334. 'isCreditContext' => $orderModule->isCreditContext($order),
  335. 'isPaid' => $orderModule->isOrderPaid($order),
  336. 'isPaidViaInvoice' => $orderModule->isOrderPaidViaInvoice($order),
  337. 'paymentLabelShort' => $orderModule->getPaymentLabelShort($order),
  338. 'isCreditFunctioningMandatory' => $orderModule->isOrderCreditFunctioningMandatory($order),
  339. 'isCreditFunctioningUser' => $orderModule->isOrderCreditFunctioningUser($order),
  340. 'debitCredit' => false,
  341. ]);
  342. }
  343. }
  344. return $ordersArray;
  345. }
  346. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  347. {
  348. $deliveryNotesArray = DeliveryNote::searchAll([
  349. 'distribution.date' => $date,
  350. ], [
  351. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  352. ]);
  353. $deliveryNotesByPointSaleArray = [];
  354. foreach ($deliveryNotesArray as $deliveryNote) {
  355. if (isset($deliveryNote->orders[0])) {
  356. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  357. $deliveryNote->getAttributes();
  358. }
  359. }
  360. return $deliveryNotesByPointSaleArray;
  361. }
  362. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  363. {
  364. $pointSaleModule = $this->getPointSaleModule();
  365. $pointSaleDefault = $pointSaleModule->findOnePointSaleDefaultByDistribution($distribution);
  366. $productOrderArray = [];
  367. foreach ($productsArray as $product) {
  368. $productOrderArray[$product['id']] = [
  369. 'quantity' => 0,
  370. 'unit' => $product['unit'],
  371. 'price' => number_format($product['price'], 5),
  372. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  373. ];
  374. }
  375. return [
  376. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
  377. 'id_user' => 0,
  378. 'username' => '',
  379. 'comment' => '',
  380. 'productOrder' => $productOrderArray
  381. ];
  382. }
  383. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  384. {
  385. return $this->getOrderModule()->getTillerManager()->isSynchronized($date);
  386. }
  387. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  388. {
  389. $subscriptionModule = $this->getSubscriptionModule();
  390. $missingSubscriptionsArray = [];
  391. $arraySubscriptions = $subscriptionModule->findSubscriptionsByDate($date);
  392. if ($distribution->active) {
  393. foreach ($arraySubscriptions as $subscription) {
  394. if (!$subscriptionModule->hasOrderAlreadyExist($subscription, $ordersArray)
  395. && $subscription->productSubscription && count($subscription->productSubscription)
  396. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  397. $missingSubscriptionsArray[] = [
  398. 'username' => $subscriptionModule->getUsername($subscription)
  399. ];
  400. }
  401. }
  402. }
  403. return $missingSubscriptionsArray;
  404. }
  405. public function actionAjaxPointSaleFavorite($idUser)
  406. {
  407. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  408. $userModule = $this->getUserModule();
  409. $orderModule = $this->getOrderModule();
  410. $user = $userModule->findOneUserById($idUser);
  411. $idFavoritePointSale = 0;
  412. if($user) {
  413. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  414. if ($favoritePointSale) {
  415. $idFavoritePointSale = $favoritePointSale->id;
  416. }
  417. }
  418. return [
  419. 'id_favorite_point_sale' => $idFavoritePointSale
  420. ];
  421. }
  422. public function actionAjaxUpdateProductOrder(
  423. $idDistribution,
  424. $idUser = false,
  425. $idPointSale = false,
  426. $idOrder = false
  427. )
  428. {
  429. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  430. $distributionModule = $this-> getDistributionModule();
  431. $orderModule = $this->getOrderModule();
  432. $userModule = $this->getUserModule();
  433. $pointSaleModule = $this->getPointSaleModule();
  434. $productModule = $this->getProductModule();
  435. $order = $orderModule->findOneOrderById($idOrder);
  436. $distribution = $distributionModule->findOneDistributionById($idDistribution);
  437. $user = $userModule->findOneUserById($idUser);
  438. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  439. $productsArray = Product::find()
  440. ->where([
  441. 'id_producer' => GlobalParam::getCurrentProducerId(),
  442. ])->joinWith([
  443. 'productPrice',
  444. 'productDistribution' => function ($q) use ($distribution) {
  445. $q->where(['id_distribution' => $distribution->id]);
  446. }
  447. ])->all();
  448. $productOrderArray = [];
  449. foreach ($productsArray as $product) {
  450. $priceArray = $productModule->getPriceArray($product, $user, $pointSale);
  451. $quantity = 0;
  452. $invoicePrice = null;
  453. if (isset($order->productOrder)) {
  454. foreach ($order->productOrder as $productOrder) {
  455. if ($productOrder->id_product == $product['id']) {
  456. if ($productOrder->invoice_price) {
  457. $invoicePrice = number_format($productOrder->invoice_price, 5);
  458. } else {
  459. $invoicePrice = number_format($productOrder->price, 5);
  460. }
  461. $quantity = $productOrder->quantity;
  462. }
  463. }
  464. }
  465. $productOrderArray[$product['id']] = [
  466. 'quantity' => $quantity,
  467. 'unit' => $product->unit,
  468. 'prices' => $priceArray,
  469. 'active' => $product->productDistribution[0]->active
  470. && (!$pointSale || $productModule->isAvailableOnPointSale($product, $pointSale)),
  471. 'invoice_price' => $invoicePrice
  472. ];
  473. }
  474. return $productOrderArray;
  475. }
  476. public function actionAjaxUpdateInvoicePrices($idOrder)
  477. {
  478. $orderModule = $this->getOrderModule();
  479. $userProducerModule = $this->getUserProducerModule();
  480. $productModule = $this->getProductModule();
  481. $order = $orderModule->findOneOrderById($idOrder);
  482. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  483. $userProducer = null;
  484. if ($order->id_user) {
  485. $userProducer = $userProducerModule->findOneUserProducer($order->user);
  486. }
  487. foreach ($order->productOrder as $productOrder) {
  488. $invoicePrice = $productModule->getPrice($productOrder->product, [
  489. 'user' => $orderModule->getUserForInvoicing($order),
  490. 'point_sale' => $order->pointSale,
  491. 'user_producer' => $userProducer,
  492. 'quantity' => $productOrder->quantity
  493. ]);
  494. if ($invoicePrice != $productOrder->price) {
  495. $productOrder->invoice_price = $invoicePrice;
  496. } else {
  497. $productOrder->invoice_price = null;
  498. }
  499. $productOrder->save();
  500. }
  501. }
  502. }
  503. /**
  504. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  505. * date donnée (Méthode appelable via CRON)
  506. *
  507. * @param string $date
  508. * @param boolean $save
  509. * @param integer $idProducer
  510. * @param string $key
  511. * @return Pdf|null
  512. */
  513. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  514. {
  515. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  516. $this->actionReport($date, $save, $idProducer);
  517. }
  518. }
  519. /**
  520. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  521. * date donnée.
  522. */
  523. public function actionReport(string $date = '', bool $save = false, int $idProducer = 0, string $type = "pdf")
  524. {
  525. if (!$idProducer) {
  526. $idProducer = $this->getProducerCurrent()->id;
  527. }
  528. $distributionModule = $this-> getDistributionModule();
  529. $producerModule = $this->getProducerModule();
  530. $producerCurrent = $producerModule->findOneProducerById($idProducer);
  531. $this->getLogic()->setProducerContext($producerCurrent);
  532. $distribution = $distributionModule->findOneDistribution($date);
  533. if ($distribution) {
  534. if ($type == 'pdf') {
  535. return $distributionModule->generateDistributionReportPdf($distribution, $save);
  536. }
  537. elseif ($type == 'csv') {
  538. $distributionModule->generateDistributionReportCsv($distribution);
  539. }
  540. }
  541. }
  542. public function actionReportGrid(string $date = '', bool $save = false, int $idProducer = 0)
  543. {
  544. if (!$idProducer) {
  545. $idProducer = $this->getProducerCurrent()->id;
  546. }
  547. $distributionModule = $this-> getDistributionModule();
  548. $producerModule = $this->getProducerModule();
  549. $producerCurrent = $producerModule->findOneProducerById($idProducer);
  550. $this->getLogic()->setProducerContext($producerCurrent);
  551. $distribution = $distributionModule->findOneDistribution($date);
  552. if ($distribution) {
  553. return $distributionModule->generateDistributionReportGridPdf($distribution, $save);
  554. }
  555. }
  556. public function actionExportShoppingCartLabels(string $date)
  557. {
  558. $distributionModule = $this-> getDistributionModule();
  559. $distribution = $distributionModule->findOneDistribution($date);
  560. if($distribution) {
  561. return $distributionModule->generateDistributionShoppingCartLabelsPdf($distribution);
  562. }
  563. }
  564. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  565. {
  566. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  567. $productDistributionModule = $this->getProductDistributionManager();
  568. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  569. $productDistributionModule->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  570. return ['success'];
  571. }
  572. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  573. {
  574. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  575. $productDistributionModule = $this->getProductDistributionManager();
  576. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  577. $productDistributionModule->updateProductDistributionActive($productDistribution, $active);
  578. return ['success'];
  579. }
  580. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  581. {
  582. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  583. $distributionModule = $this-> getDistributionModule();
  584. $pointSaleModule = $this->getPointSaleModule();
  585. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  586. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution(
  587. $distributionModule->findOneDistributionById($idDistribution),
  588. $pointSaleModule->findOnePointSaleById($idPointSale)
  589. );
  590. $pointSaleDistribution->delivery = $delivery;
  591. $pointSaleDistributionModule->update($pointSaleDistribution);
  592. return ['success'];
  593. }
  594. public function getProductDistribution(int $idProduct, int $idDistribution)
  595. {
  596. $distributionModule = $this-> getDistributionModule();
  597. $productModule = $this->getProductModule();
  598. $productDistributionModule = $this->getProductDistributionManager();
  599. return $productDistributionModule->findOneProductDistribution(
  600. $distributionModule->findOneDistributionById($idDistribution),
  601. $productModule->findOneProductById($idProduct)
  602. );
  603. }
  604. /**
  605. * Active/désactive un jour de distribution.
  606. */
  607. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  608. {
  609. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  610. $distributionModule = $this-> getDistributionModule();
  611. $distribution = null;
  612. if ($idDistribution) {
  613. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  614. }
  615. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  616. $distribution = $distributionModule->getBuilder()->createDistributionIfNotExist($date);
  617. }
  618. if ($distribution) {
  619. $distributionModule->getBuilder()->activeDistribution($distribution, $active);
  620. return ['success'];
  621. }
  622. return ['error'];
  623. }
  624. /**
  625. * Change l'état d'une semaine de distribution (activé, désactivé).
  626. */
  627. public function actionAjaxProcessActiveWeekDistribution(string $date, int $active)
  628. {
  629. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  630. $this->getDistributionModule()->getBuilder()->activeDistributionsOfWeek($date, $active);
  631. return ['success'];
  632. }
  633. /**
  634. * Ajoute les commandes récurrentes pour une date donnée.
  635. */
  636. public function actionAjaxProcessAddSubscriptions(string $date)
  637. {
  638. $ordersArray = $this->getSubscriptionModule()->getOrderManager()
  639. ->createAllOrdersFromSubscriptions($date, true);
  640. if($ordersArray && count($ordersArray)) {
  641. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  642. }
  643. return Ajax::responseError('Aucun abonnement à importer.');
  644. }
  645. /**
  646. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  647. */
  648. public function actionAjaxProcessSynchroTiller(string $date)
  649. {
  650. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  651. return $this->getOrderModule()->getTillerManager()->synchronizeDistribution($date);
  652. }
  653. public function actionAjaxGenerateDeliveryNotePointSale(string $idOrders)
  654. {
  655. if (strlen($idOrders)) {
  656. $idOrders = json_decode($idOrders, true);
  657. if(is_array($idOrders)) {
  658. try {
  659. if($this->getOrderModule()->getDocumentManager()->generateDeliveryNoteForPointSale($idOrders)) {
  660. return Ajax::responseSuccess("Bon de livraison généré");
  661. }
  662. }
  663. catch(Exception $exception) {
  664. return Ajax::responseError($exception->getMessage());
  665. }
  666. }
  667. }
  668. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  669. }
  670. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  671. {
  672. $orderModule = $this->getOrderModule();
  673. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  674. $orderModule->getDocumentManager()->generateDeliveryNoteForUser($order);
  675. return Ajax::responseSuccess('Bon de livraison généré');
  676. }
  677. public function actionAjaxGenerateDeliveryNoteEachUser(string $idOrders)
  678. {
  679. if (strlen($idOrders)) {
  680. $idOrders = json_decode($idOrders, true);
  681. $this->getOrderModule()->getDocumentManager()->generateDeliveryNotesForUser($idOrders);
  682. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  683. }
  684. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  685. }
  686. public function actionAjaxValidateDeliveryNotes(string $idOrders)
  687. {
  688. if (strlen($idOrders)) {
  689. $idOrders = json_decode($idOrders, true);
  690. if($this->getOrderModule()->getDocumentManager()->validateDeliveryNotes($idOrders)) {
  691. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  692. }
  693. }
  694. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  695. }
  696. }