Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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