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

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