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.

844 satır
37KB

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