Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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