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.

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