Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

741 lines
31KB

  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)
  400. {
  401. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  402. $userModule = $this->getUserModule();
  403. $orderModule = $this->getOrderModule();
  404. $user = $userModule->findOneUserById($idUser);
  405. $idFavoritePointSale = 0;
  406. if($user) {
  407. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  408. if ($favoritePointSale) {
  409. $idFavoritePointSale = $favoritePointSale->id;
  410. }
  411. }
  412. return [
  413. 'id_favorite_point_sale' => $idFavoritePointSale
  414. ];
  415. }
  416. public function actionAjaxUpdateProductOrder(
  417. $idDistribution,
  418. $idUser = false,
  419. $idPointSale = false,
  420. $idOrder = false
  421. )
  422. {
  423. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  424. $distributionModule = $this-> getDistributionModule();
  425. $orderModule = $this->getOrderModule();
  426. $userModule = $this->getUserModule();
  427. $pointSaleModule = $this->getPointSaleModule();
  428. $productModule = $this->getProductModule();
  429. $order = $orderModule->findOneOrderById($idOrder);
  430. $distribution = $distributionModule->findOneDistributionById($idDistribution);
  431. $user = $userModule->findOneUserById($idUser);
  432. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  433. $productsArray = Product::find()
  434. ->where([
  435. 'id_producer' => GlobalParam::getCurrentProducerId(),
  436. ])->joinWith([
  437. 'productPrice',
  438. 'productDistribution' => function ($q) use ($distribution) {
  439. $q->where(['id_distribution' => $distribution->id]);
  440. }
  441. ])->all();
  442. $productOrderArray = [];
  443. foreach ($productsArray as $product) {
  444. $priceArray = $productModule->getPriceArray($product, $user, $pointSale);
  445. $quantity = 0;
  446. $invoicePrice = null;
  447. if (isset($order->productOrder)) {
  448. foreach ($order->productOrder as $productOrder) {
  449. if ($productOrder->id_product == $product['id']) {
  450. if ($productOrder->invoice_price) {
  451. $invoicePrice = number_format($productOrder->invoice_price, 5);
  452. } else {
  453. $invoicePrice = number_format($productOrder->price, 5);
  454. }
  455. $quantity = $productOrder->quantity;
  456. }
  457. }
  458. }
  459. $productOrderArray[$product['id']] = [
  460. 'quantity' => $quantity,
  461. 'unit' => $product->unit,
  462. 'prices' => $priceArray,
  463. 'active' => $product->productDistribution[0]->active
  464. && (!$pointSale || $productModule->isAvailableOnPointSale($product, $pointSale)),
  465. 'invoice_price' => $invoicePrice
  466. ];
  467. }
  468. return $productOrderArray;
  469. }
  470. public function actionAjaxUpdateInvoicePrices($idOrder)
  471. {
  472. $orderModule = $this->getOrderModule();
  473. $userProducerModule = $this->getUserProducerModule();
  474. $productModule = $this->getProductModule();
  475. $order = $orderModule->findOneOrderById($idOrder);
  476. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  477. $userProducer = null;
  478. if ($order->id_user) {
  479. $userProducer = $userProducerModule->findOneUserProducer($order->user);
  480. }
  481. foreach ($order->productOrder as $productOrder) {
  482. $invoicePrice = $productModule->getPrice($productOrder->product, [
  483. 'user' => $orderModule->getUserForInvoicing($order),
  484. 'point_sale' => $order->pointSale,
  485. 'user_producer' => $userProducer,
  486. 'quantity' => $productOrder->quantity
  487. ]);
  488. if ($invoicePrice != $productOrder->price) {
  489. $productOrder->invoice_price = $invoicePrice;
  490. } else {
  491. $productOrder->invoice_price = null;
  492. }
  493. $productOrder->save();
  494. }
  495. }
  496. }
  497. /**
  498. * Génére un export pour une distribution.
  499. */
  500. public function actionExport(string $name, string $date = '')
  501. {
  502. $distributionModule = $this-> getDistributionModule();
  503. $distribution = $distributionModule->getRepository()->findOneDistribution($date);
  504. if ($distribution) {
  505. try {
  506. return $distributionModule->getExportManager()->getGenerator($name)->generate($distribution);
  507. }
  508. catch(ErrorException $exception) {
  509. $this->setFlash('error', "Une erreur est survenue lors de la génération de l'export.");
  510. return $this->redirectReferer();
  511. }
  512. }
  513. }
  514. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  515. {
  516. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  517. $productDistributionModule = $this->getProductDistributionModule();
  518. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  519. $productDistributionModule->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  520. return ['success'];
  521. }
  522. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  523. {
  524. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  525. $productDistributionModule = $this->getProductDistributionModule();
  526. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  527. $productDistributionModule->updateProductDistributionActive($productDistribution, $active);
  528. return ['success'];
  529. }
  530. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  531. {
  532. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  533. $distributionModule = $this-> getDistributionModule();
  534. $pointSaleModule = $this->getPointSaleModule();
  535. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  536. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution(
  537. $distributionModule->findOneDistributionById($idDistribution),
  538. $pointSaleModule->findOnePointSaleById($idPointSale)
  539. );
  540. $pointSaleDistribution->delivery = $delivery;
  541. $pointSaleDistributionModule->update($pointSaleDistribution);
  542. return ['success'];
  543. }
  544. public function getProductDistribution(int $idProduct, int $idDistribution)
  545. {
  546. $distributionModule = $this-> getDistributionModule();
  547. $productModule = $this->getProductModule();
  548. $productDistributionModule = $this->getProductDistributionModule();
  549. return $productDistributionModule->findOneProductDistribution(
  550. $distributionModule->findOneDistributionById($idDistribution),
  551. $productModule->findOneProductById($idProduct)
  552. );
  553. }
  554. /**
  555. * Active/désactive un jour de distribution.
  556. */
  557. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  558. {
  559. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  560. $distributionModule = $this-> getDistributionModule();
  561. $distribution = null;
  562. if ($idDistribution) {
  563. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  564. }
  565. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  566. $distribution = $distributionModule->getBuilder()->createDistributionIfNotExist($date);
  567. }
  568. if ($distribution) {
  569. $distributionModule->getBuilder()->activeDistribution($distribution, $active);
  570. return ['success'];
  571. }
  572. return ['error'];
  573. }
  574. /**
  575. * Change l'état d'une semaine de distribution (activé, désactivé).
  576. */
  577. public function actionAjaxProcessActiveWeekDistribution(string $date, int $active)
  578. {
  579. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  580. $this->getDistributionModule()->getBuilder()->activeDistributionsOfWeek($date, $active);
  581. return ['success'];
  582. }
  583. /**
  584. * Ajoute les commandes récurrentes pour une date donnée.
  585. */
  586. public function actionAjaxProcessAddSubscriptions(string $date)
  587. {
  588. $ordersArray = $this->getSubscriptionModule()->getOrderManager()
  589. ->createAllOrdersFromSubscriptions($date, true);
  590. if($ordersArray && count($ordersArray)) {
  591. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  592. }
  593. return Ajax::responseError('Aucun abonnement à importer.');
  594. }
  595. /**
  596. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  597. */
  598. public function actionAjaxProcessSynchroTiller(string $date)
  599. {
  600. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  601. return $this->getOrderModule()->getTillerManager()->synchronizeDistribution($date);
  602. }
  603. public function actionAjaxGenerateDeliveryNotePointSale(string $idOrders)
  604. {
  605. if (strlen($idOrders)) {
  606. $idOrders = json_decode($idOrders, true);
  607. if(is_array($idOrders)) {
  608. try {
  609. if($this->getOrderModule()->getDocumentManager()->generateDeliveryNoteForPointSale($idOrders)) {
  610. return Ajax::responseSuccess("Bon de livraison généré");
  611. }
  612. }
  613. catch(Exception $exception) {
  614. return Ajax::responseError($exception->getMessage());
  615. }
  616. }
  617. }
  618. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  619. }
  620. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  621. {
  622. $orderModule = $this->getOrderModule();
  623. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  624. $orderModule->getDocumentManager()->generateDeliveryNoteForUser($order);
  625. return Ajax::responseSuccess('Bon de livraison généré');
  626. }
  627. public function actionAjaxGenerateDeliveryNoteEachUser(string $idOrders)
  628. {
  629. if (strlen($idOrders)) {
  630. $idOrders = json_decode($idOrders, true);
  631. $this->getOrderModule()->getDocumentManager()->generateDeliveryNotesForUser($idOrders);
  632. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  633. }
  634. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  635. }
  636. public function actionAjaxValidateDeliveryNotes(string $idOrders)
  637. {
  638. if (strlen($idOrders)) {
  639. $idOrders = json_decode($idOrders, true);
  640. if($this->getOrderModule()->getDocumentManager()->validateDeliveryNotes($idOrders)) {
  641. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  642. }
  643. }
  644. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  645. }
  646. }