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

864 lines
38KB

  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. //'quantity_remaining' => $orderModule->getResolver()->getProductQuantityRemaining($product, $distribution, $order, $quantityForm),
  533. ];
  534. }
  535. // construction de $orderOverride
  536. $orderOverride = $order;
  537. if(!$orderOverride) {
  538. $orderOverride = new Order();
  539. }
  540. $productOrderModule = $this->getProductOrderModule();
  541. $productOrderObjectArray = [];
  542. foreach($productOrderArray as $idProduct => $productOrder) {
  543. if($productOrder['quantity']) {
  544. $product = $productModule->getRepository()->findOneProductById($idProduct);
  545. $productOrderObject = $productOrderModule->getBuilder()->instanciateProductOrder(
  546. $orderOverride,
  547. $product,
  548. $productOrder['quantity'],
  549. 0
  550. );
  551. $productOrderObjectArray[] = $productOrderObject;
  552. }
  553. }
  554. $orderOverride->populateRelation('productOrder', $productOrderObjectArray);
  555. foreach($productOrderArray as $idProduct => $productOrder) {
  556. $product = $productModule->getRepository()->findOneProductById($idProduct);
  557. $productOrderArray[$idProduct]['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($product, $distribution, $orderOverride);
  558. }
  559. return $productOrderArray;
  560. }
  561. public function actionAjaxUpdateInvoicePrices($idOrder)
  562. {
  563. $orderModule = $this->getOrderModule();
  564. $userProducerModule = $this->getUserProducerModule();
  565. $productModule = $this->getProductModule();
  566. $order = $orderModule->findOneOrderById($idOrder);
  567. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  568. $userProducer = null;
  569. if ($order->id_user) {
  570. $userProducer = $userProducerModule->findOneUserProducer($order->user);
  571. }
  572. foreach ($order->productOrder as $productOrder) {
  573. $invoicePrice = $productModule->getPrice($productOrder->product, [
  574. 'user' => $orderModule->getUserForInvoicing($order),
  575. 'point_sale' => $order->pointSale,
  576. 'user_producer' => $userProducer,
  577. 'quantity' => $productOrder->quantity
  578. ]);
  579. if ($invoicePrice != $productOrder->price) {
  580. $productOrder->invoice_price = $invoicePrice;
  581. } else {
  582. $productOrder->invoice_price = null;
  583. }
  584. $productOrder->save();
  585. }
  586. }
  587. }
  588. /**
  589. * Génére un export pour une distribution.
  590. */
  591. public function actionExport(string $name, string $date = '')
  592. {
  593. $distributionModule = $this-> getDistributionModule();
  594. $distribution = $distributionModule->getRepository()->findOneDistribution($date);
  595. if ($distribution) {
  596. try {
  597. return $distributionModule->getExportManager()->getGenerator($name)->generate($distribution);
  598. }
  599. catch(ErrorException $exception) {
  600. //$this->setFlash('error', "Une erreur est survenue lors de la génération de l'export.");
  601. $this->setFlash('error', $exception->getMessage());
  602. return $this->redirectReferer();
  603. }
  604. }
  605. }
  606. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  607. {
  608. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  609. $productDistributionModule = $this->getProductDistributionModule();
  610. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  611. $productDistributionModule->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  612. return ['success'];
  613. }
  614. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  615. {
  616. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  617. $productDistributionModule = $this->getProductDistributionModule();
  618. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  619. $productDistributionModule->updateProductDistributionActive($productDistribution, $active);
  620. return ['success'];
  621. }
  622. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  623. {
  624. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  625. $distributionModule = $this-> getDistributionModule();
  626. $pointSaleModule = $this->getPointSaleModule();
  627. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  628. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution(
  629. $distributionModule->findOneDistributionById($idDistribution),
  630. $pointSaleModule->findOnePointSaleById($idPointSale)
  631. );
  632. $pointSaleDistribution->delivery = $delivery;
  633. $pointSaleDistributionModule->update($pointSaleDistribution);
  634. return ['success'];
  635. }
  636. public function getProductDistribution(int $idProduct, int $idDistribution)
  637. {
  638. $distributionModule = $this-> getDistributionModule();
  639. $productModule = $this->getProductModule();
  640. $productDistributionModule = $this->getProductDistributionModule();
  641. return $productDistributionModule->findOneProductDistribution(
  642. $distributionModule->findOneDistributionById($idDistribution),
  643. $productModule->findOneProductById($idProduct)
  644. );
  645. }
  646. /**
  647. * Active/désactive un jour de distribution.
  648. */
  649. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  650. {
  651. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  652. $distributionModule = $this-> getDistributionModule();
  653. $distribution = null;
  654. if ($idDistribution) {
  655. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  656. }
  657. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  658. $distribution = $distributionModule->getBuilder()->createDistributionIfNotExist($date);
  659. }
  660. if ($distribution) {
  661. $distributionModule->getBuilder()->activeDistribution($distribution, $active);
  662. return ['success'];
  663. }
  664. return ['error'];
  665. }
  666. /**
  667. * Change l'état d'une semaine de distribution (activé, désactivé).
  668. */
  669. public function actionAjaxProcessActiveWeekDistribution(string $date, int $active)
  670. {
  671. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  672. $this->getDistributionModule()->getBuilder()->activeDistributionsOfWeek($date, $active);
  673. return ['success'];
  674. }
  675. /**
  676. * Ajoute les commandes récurrentes pour une date donnée.
  677. */
  678. public function actionAjaxProcessAddSubscriptions(string $date)
  679. {
  680. $ordersArray = $this->getOrderModule()->getManager()
  681. ->createAllOrdersFromSubscriptions($date, $this->getUserCurrent(), true);
  682. if($ordersArray && count($ordersArray)) {
  683. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  684. }
  685. return Ajax::responseError('Aucun abonnement à importer.');
  686. }
  687. /**
  688. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  689. */
  690. public function actionAjaxProcessSynchroTiller(string $date)
  691. {
  692. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  693. return $this->getOrderModule()->getTillerManager()->synchronizeDistribution($date);
  694. }
  695. public function actionAjaxForceSynchronizeOrderTiller(int $idOrder)
  696. {
  697. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  698. $order = $this->getOrderModule()->getRepository()->findOneOrderById($idOrder);
  699. return $this->getOrderModule()->getTillerManager()->synchronizeOrder($order, true);
  700. }
  701. public function actionAjaxGenerateDeliveryNotePointSale(string $idOrders)
  702. {
  703. if (strlen($idOrders)) {
  704. $idOrders = json_decode($idOrders, true);
  705. if(is_array($idOrders)) {
  706. try {
  707. if($this->getOrderModule()->getDocumentManager()->generateDeliveryNoteForPointSale($idOrders)) {
  708. return Ajax::responseSuccess("Bon de livraison généré");
  709. }
  710. }
  711. catch(Exception $exception) {
  712. return Ajax::responseError($exception->getMessage());
  713. }
  714. }
  715. }
  716. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  717. }
  718. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  719. {
  720. $orderModule = $this->getOrderModule();
  721. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  722. $orderModule->getDocumentManager()->generateDeliveryNoteForUser($order);
  723. return Ajax::responseSuccess('Bon de livraison généré');
  724. }
  725. public function actionAjaxSendDeliveryNote(int $idOrder)
  726. {
  727. $orderModule = $this->getOrderModule();
  728. $documentModule = $this->getDocumentModule();
  729. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  730. if($order->deliveryNote) {
  731. $documentModule->getManager()->sendDocument($order->deliveryNote);
  732. return Ajax::responseSuccess('Bon de livraison envoyé');
  733. }
  734. return Ajax::responseSuccess('Une erreur est survenue lors de l\'envoi du bon de livraison.');
  735. }
  736. public function actionAjaxGenerateDeliveryNoteEachUser(string $idOrders)
  737. {
  738. if (strlen($idOrders)) {
  739. $idOrders = json_decode($idOrders, true);
  740. $this->getOrderModule()->getDocumentManager()->generateDeliveryNotesForUser($idOrders);
  741. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  742. }
  743. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  744. }
  745. public function actionAjaxValidateDeliveryNotes(string $idOrders)
  746. {
  747. if (strlen($idOrders)) {
  748. $idOrders = json_decode($idOrders, true);
  749. if($this->getOrderModule()->getDocumentManager()->validateDeliveryNotes($idOrders)) {
  750. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  751. }
  752. }
  753. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  754. }
  755. }