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.

816 lines
36KB

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