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.

806 lines
35KB

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