Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

744 Zeilen
32KB

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