You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

768 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. $revenuesWithTax = 0;
  257. $weight = 0;
  258. if ($ordersArray) {
  259. foreach ($ordersArray as $order) {
  260. $orderModule->initOrder($order);
  261. if (is_null($order->date_delete)) {
  262. $revenues += $orderModule->getOrderAmount($order);
  263. $revenuesWithTax += $orderModule->getOrderAmountWithTax($order);
  264. $weight += $order->weight;
  265. }
  266. }
  267. }
  268. $distributionJsonData['revenues'] = Price::format($revenues);
  269. $distributionJsonData['revenues_with_tax'] = Price::format($revenuesWithTax);
  270. $distributionJsonData['weight'] = number_format($weight, 2);
  271. $distributionJsonData['potential_revenues'] = Price::format($productModule->getProductDistributionPotentialRevenues($productsArray));
  272. $distributionJsonData['potential_revenues_with_tax'] = Price::format($productModule->getProductDistributionPotentialRevenues($productsArray, true));
  273. $distributionJsonData['potential_weight'] = number_format($productModule->getProductDistributionPotentialWeight($productsArray), 2);
  274. return $distributionJsonData;
  275. }
  276. public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
  277. {
  278. $userModule = $this->getUserModule();
  279. $orderModule = $this->getOrderModule();
  280. $paymentManager = $this->getPaymentModule();
  281. $productOrderModule = $this->getProductOrderModule();
  282. if ($ordersArray) {
  283. foreach ($ordersArray as &$order) {
  284. $orderModule->initOrder($order);
  285. $productOrderArray = [];
  286. foreach ($order->productOrder as $productOrder) {
  287. $productOrderArray[$productOrder->id_product] = [
  288. 'quantity' => $productOrderModule->getSolver()->getQuantityToCoefficientOfUnit($productOrder),
  289. 'unit' => $productOrder->unit,
  290. 'price' => number_format($productOrder->price, 5),
  291. 'invoice_price' => number_format($productOrder->invoice_price, 5),
  292. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  293. ];
  294. }
  295. foreach ($productsArray as $product) {
  296. if (!isset($productOrderArray[$product['id']])) {
  297. $productOrderArray[$product['id']] = [
  298. 'quantity' => 0,
  299. 'unit' => $product['unit'],
  300. 'price' => number_format($product['price'], 5),
  301. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  302. ];
  303. }
  304. }
  305. $paymentArray = [];
  306. foreach ($order->payment as $payment) {
  307. $paymentArray[] = [
  308. 'type' => $payment->type,
  309. 'wording_type' => $paymentManager->getStrType($payment),
  310. 'mean_payment' => $payment->mean_payment,
  311. 'wording_mean_payment' => $paymentManager->getStrMeanPayment($payment),
  312. 'date' => date('d/m/Y H:i:s', strtotime($payment->date)),
  313. 'user' => $payment->getUserObject() ? $userModule->getUsername($payment->getUserObject()) : '',
  314. 'user_action' => $paymentManager->getStrUserAction($payment),
  315. 'wording' => $paymentManager->getStrWording($payment, $order),
  316. 'amount' => $paymentManager->getAmount($payment, Order::AMOUNT_TOTAL, true),
  317. ];
  318. }
  319. $arrayCreditUser = [];
  320. if(isset($order->user)) {
  321. $arrayCreditUser['credit'] = $userModule->getCredit($order->user);
  322. $arrayCreditUser['credit_active'] = $userModule->getCreditActive($order->user);
  323. }
  324. $oneProductUnactivated = false;
  325. foreach ($order->productOrder as $productOrder) {
  326. foreach ($productsArray as $product) {
  327. if ($productOrder->id_product == $product['id'] && isset($product['productDistribution'][0]) && !$product['productDistribution'][0]['active']) {
  328. $oneProductUnactivated = true;
  329. }
  330. }
  331. }
  332. $order = array_merge($order->getAttributes(), [
  333. 'selected' => false,
  334. 'weight' => $order->weight,
  335. 'amount' => (float) Price::numberTwoDecimals($orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  336. 'amount_paid' => (float) Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_PAID)),
  337. 'amount_remaining' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_REMAINING)),
  338. 'amount_surplus' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
  339. 'user' => (isset($order->user)) ? array_merge(
  340. $order->user->getAttributes(),
  341. $arrayCreditUser
  342. ) : null,
  343. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  344. 'productOrder' => $productOrderArray,
  345. 'paymentsArray' => $paymentArray,
  346. 'oneProductUnactivated' => $oneProductUnactivated,
  347. 'isLinkedToValidDocument' => $orderModule->isLinkedToValidDocument($order),
  348. 'isLinkedToValidInvoice' => $orderModule->isLinkedToValidInvoice($order),
  349. 'isCreditAutoPayment' => $orderModule->isCreditAutoPayment($order),
  350. 'isCreditContext' => $orderModule->isCreditContext($order),
  351. 'isPaid' => $orderModule->isOrderPaid($order),
  352. 'isPaidViaInvoice' => $orderModule->isOrderPaidViaInvoice($order),
  353. 'paymentLabelShort' => $orderModule->getPaymentLabelShort($order),
  354. 'isCreditFunctioningMandatory' => $orderModule->isOrderCreditFunctioningMandatory($order),
  355. 'isCreditFunctioningUser' => $orderModule->isOrderCreditFunctioningUser($order),
  356. 'debitCredit' => false,
  357. ]);
  358. }
  359. }
  360. return $ordersArray;
  361. }
  362. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  363. {
  364. $deliveryNotesArray = DeliveryNote::searchAll([
  365. 'distribution.date' => $date,
  366. ], [
  367. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  368. ]);
  369. $deliveryNotesByPointSaleArray = [];
  370. foreach ($deliveryNotesArray as $deliveryNote) {
  371. if (isset($deliveryNote->orders[0])) {
  372. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  373. $deliveryNote->getAttributes();
  374. }
  375. }
  376. return $deliveryNotesByPointSaleArray;
  377. }
  378. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  379. {
  380. $pointSaleModule = $this->getPointSaleModule();
  381. $pointSaleDefault = $pointSaleModule->findOnePointSaleDefaultByDistribution($distribution);
  382. $productOrderArray = [];
  383. foreach ($productsArray as $product) {
  384. $productOrderArray[$product['id']] = [
  385. 'quantity' => 0,
  386. 'unit' => $product['unit'],
  387. 'price' => number_format($product['price'], 5),
  388. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  389. ];
  390. }
  391. return [
  392. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
  393. 'id_user' => 0,
  394. 'username' => '',
  395. 'comment' => '',
  396. 'productOrder' => $productOrderArray
  397. ];
  398. }
  399. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  400. {
  401. return $this->getOrderModule()->getTillerManager()->isSynchronized($date);
  402. }
  403. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  404. {
  405. $subscriptionModule = $this->getSubscriptionModule();
  406. $missingSubscriptionsArray = [];
  407. $arraySubscriptions = $subscriptionModule->findSubscriptionsByDate($date);
  408. if ($distribution->active) {
  409. foreach ($arraySubscriptions as $subscription) {
  410. if (!$subscriptionModule->hasOrderAlreadyExist($subscription, $ordersArray)
  411. && $subscription->productSubscription && count($subscription->productSubscription)
  412. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  413. $missingSubscriptionsArray[] = [
  414. 'username' => $subscriptionModule->getUsername($subscription)
  415. ];
  416. }
  417. }
  418. }
  419. return $missingSubscriptionsArray;
  420. }
  421. public function actionAjaxPointSaleFavorite($idUser, $idDistribution)
  422. {
  423. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  424. $userModule = $this->getUserModule();
  425. $orderModule = $this->getOrderModule();
  426. $distributionModule = $this->getDistributionModule();
  427. $user = $userModule->findOneUserById($idUser);
  428. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  429. $idFavoritePointSale = 0;
  430. if($user) {
  431. $favoritePointSale = $orderModule->getUserFavoritePointSale($user, $distribution);
  432. if ($favoritePointSale) {
  433. $idFavoritePointSale = $favoritePointSale->id;
  434. }
  435. }
  436. return [
  437. 'id_favorite_point_sale' => $idFavoritePointSale
  438. ];
  439. }
  440. public function actionAjaxUpdateProductOrder(
  441. $idDistribution,
  442. $idUser = false,
  443. $idPointSale = false,
  444. $idOrder = false
  445. )
  446. {
  447. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  448. $distributionModule = $this-> getDistributionModule();
  449. $orderModule = $this->getOrderModule();
  450. $userModule = $this->getUserModule();
  451. $pointSaleModule = $this->getPointSaleModule();
  452. $productModule = $this->getProductModule();
  453. $order = $orderModule->findOneOrderById($idOrder);
  454. $distribution = $distributionModule->findOneDistributionById($idDistribution);
  455. $user = $userModule->findOneUserById($idUser);
  456. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  457. $productsArray = Product::find()
  458. ->where([
  459. 'id_producer' => GlobalParam::getCurrentProducerId(),
  460. ])->joinWith([
  461. 'productPrice',
  462. 'productDistribution' => function ($q) use ($distribution) {
  463. $q->where(['id_distribution' => $distribution->id]);
  464. }
  465. ])->all();
  466. $productOrderArray = [];
  467. foreach ($productsArray as $product) {
  468. $priceArray = $productModule->getPriceArray($product, $user, $pointSale);
  469. $quantity = 0;
  470. $invoicePrice = null;
  471. if (isset($order->productOrder)) {
  472. foreach ($order->productOrder as $productOrder) {
  473. if ($productOrder->id_product == $product['id']) {
  474. if ($productOrder->invoice_price) {
  475. $invoicePrice = number_format($productOrder->invoice_price, 5);
  476. } else {
  477. $invoicePrice = number_format($productOrder->price, 5);
  478. }
  479. $quantity = $productOrder->quantity;
  480. }
  481. }
  482. }
  483. $productOrderArray[$product['id']] = [
  484. 'quantity' => $quantity,
  485. 'unit' => $product->unit,
  486. 'prices' => $priceArray,
  487. 'active' => $product->productDistribution[0]->active
  488. && (!$pointSale || $productModule->isAvailableOnPointSale($product, $pointSale)),
  489. 'invoice_price' => $invoicePrice
  490. ];
  491. }
  492. return $productOrderArray;
  493. }
  494. public function actionAjaxUpdateInvoicePrices($idOrder)
  495. {
  496. $orderModule = $this->getOrderModule();
  497. $userProducerModule = $this->getUserProducerModule();
  498. $productModule = $this->getProductModule();
  499. $order = $orderModule->findOneOrderById($idOrder);
  500. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  501. $userProducer = null;
  502. if ($order->id_user) {
  503. $userProducer = $userProducerModule->findOneUserProducer($order->user);
  504. }
  505. foreach ($order->productOrder as $productOrder) {
  506. $invoicePrice = $productModule->getPrice($productOrder->product, [
  507. 'user' => $orderModule->getUserForInvoicing($order),
  508. 'point_sale' => $order->pointSale,
  509. 'user_producer' => $userProducer,
  510. 'quantity' => $productOrder->quantity
  511. ]);
  512. if ($invoicePrice != $productOrder->price) {
  513. $productOrder->invoice_price = $invoicePrice;
  514. } else {
  515. $productOrder->invoice_price = null;
  516. }
  517. $productOrder->save();
  518. }
  519. }
  520. }
  521. /**
  522. * Génére un export pour une distribution.
  523. */
  524. public function actionExport(string $name, string $date = '')
  525. {
  526. $distributionModule = $this-> getDistributionModule();
  527. $distribution = $distributionModule->getRepository()->findOneDistribution($date);
  528. if ($distribution) {
  529. try {
  530. return $distributionModule->getExportManager()->getGenerator($name)->generate($distribution);
  531. }
  532. catch(ErrorException $exception) {
  533. //$this->setFlash('error', "Une erreur est survenue lors de la génération de l'export.");
  534. $this->setFlash('error', $exception->getMessage());
  535. return $this->redirectReferer();
  536. }
  537. }
  538. }
  539. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  540. {
  541. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  542. $productDistributionModule = $this->getProductDistributionModule();
  543. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  544. $productDistributionModule->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  545. return ['success'];
  546. }
  547. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  548. {
  549. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  550. $productDistributionModule = $this->getProductDistributionModule();
  551. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  552. $productDistributionModule->updateProductDistributionActive($productDistribution, $active);
  553. return ['success'];
  554. }
  555. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  556. {
  557. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  558. $distributionModule = $this-> getDistributionModule();
  559. $pointSaleModule = $this->getPointSaleModule();
  560. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  561. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution(
  562. $distributionModule->findOneDistributionById($idDistribution),
  563. $pointSaleModule->findOnePointSaleById($idPointSale)
  564. );
  565. $pointSaleDistribution->delivery = $delivery;
  566. $pointSaleDistributionModule->update($pointSaleDistribution);
  567. return ['success'];
  568. }
  569. public function getProductDistribution(int $idProduct, int $idDistribution)
  570. {
  571. $distributionModule = $this-> getDistributionModule();
  572. $productModule = $this->getProductModule();
  573. $productDistributionModule = $this->getProductDistributionModule();
  574. return $productDistributionModule->findOneProductDistribution(
  575. $distributionModule->findOneDistributionById($idDistribution),
  576. $productModule->findOneProductById($idProduct)
  577. );
  578. }
  579. /**
  580. * Active/désactive un jour de distribution.
  581. */
  582. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  583. {
  584. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  585. $distributionModule = $this-> getDistributionModule();
  586. $distribution = null;
  587. if ($idDistribution) {
  588. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  589. }
  590. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  591. $distribution = $distributionModule->getBuilder()->createDistributionIfNotExist($date);
  592. }
  593. if ($distribution) {
  594. $distributionModule->getBuilder()->activeDistribution($distribution, $active);
  595. return ['success'];
  596. }
  597. return ['error'];
  598. }
  599. /**
  600. * Change l'état d'une semaine de distribution (activé, désactivé).
  601. */
  602. public function actionAjaxProcessActiveWeekDistribution(string $date, int $active)
  603. {
  604. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  605. $this->getDistributionModule()->getBuilder()->activeDistributionsOfWeek($date, $active);
  606. return ['success'];
  607. }
  608. /**
  609. * Ajoute les commandes récurrentes pour une date donnée.
  610. */
  611. public function actionAjaxProcessAddSubscriptions(string $date)
  612. {
  613. $ordersArray = $this->getSubscriptionModule()->getOrderManager()
  614. ->createAllOrdersFromSubscriptions($date, true);
  615. if($ordersArray && count($ordersArray)) {
  616. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  617. }
  618. return Ajax::responseError('Aucun abonnement à importer.');
  619. }
  620. /**
  621. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  622. */
  623. public function actionAjaxProcessSynchroTiller(string $date)
  624. {
  625. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  626. return $this->getOrderModule()->getTillerManager()->synchronizeDistribution($date);
  627. }
  628. public function actionAjaxGenerateDeliveryNotePointSale(string $idOrders)
  629. {
  630. if (strlen($idOrders)) {
  631. $idOrders = json_decode($idOrders, true);
  632. if(is_array($idOrders)) {
  633. try {
  634. if($this->getOrderModule()->getDocumentManager()->generateDeliveryNoteForPointSale($idOrders)) {
  635. return Ajax::responseSuccess("Bon de livraison généré");
  636. }
  637. }
  638. catch(Exception $exception) {
  639. return Ajax::responseError($exception->getMessage());
  640. }
  641. }
  642. }
  643. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  644. }
  645. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  646. {
  647. $orderModule = $this->getOrderModule();
  648. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  649. $orderModule->getDocumentManager()->generateDeliveryNoteForUser($order);
  650. return Ajax::responseSuccess('Bon de livraison généré');
  651. }
  652. public function actionAjaxGenerateDeliveryNoteEachUser(string $idOrders)
  653. {
  654. if (strlen($idOrders)) {
  655. $idOrders = json_decode($idOrders, true);
  656. $this->getOrderModule()->getDocumentManager()->generateDeliveryNotesForUser($idOrders);
  657. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  658. }
  659. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  660. }
  661. public function actionAjaxValidateDeliveryNotes(string $idOrders)
  662. {
  663. if (strlen($idOrders)) {
  664. $idOrders = json_decode($idOrders, true);
  665. if($this->getOrderModule()->getDocumentManager()->validateDeliveryNotes($idOrders)) {
  666. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  667. }
  668. }
  669. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  670. }
  671. }