You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

858 satır
38KB

  1. <?php
  2. /**
  3. * Copyright Guillaume Bourgeois (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. $producer = $this->getProducerCurrent();
  101. $dateObject = DateTime::createFromFormat('Y-m-d', $date);
  102. $json = ['distribution' => [], 'products' => []];
  103. $json['means_payment'] = MeanPayment::getAll();
  104. $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
  105. $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
  106. $json['leave_period_dates'] = $this->buildAjaxInfosResponseLeavePeriod($producer);
  107. $json['units'] = Product::$unitsArray;
  108. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  109. $distribution = $distributionModule->createDistributionIfNotExist($date);
  110. $ordersArray = $orderModule->findOrdersByDistribution($distribution, false);
  111. $ordersArrayObject = $ordersArray;
  112. $productsArray = $productModule->findProductsByDistribution($distribution, false);
  113. $json['products'] = $this->buildAjaxInfosResponseProducts($distribution, $productsArray, $ordersArray);
  114. $json['distribution'] = $this->buildAjaxInfosResponseDistribution($distribution, $ordersArrayObject, $productsArray);
  115. $json['orders'] = $this->buildAjaxInfosResponseOrders($ordersArray, $productsArray);
  116. $json['points_sale'] = $this->buildAjaxInfosResponsePointsSale($distribution);
  117. $json['delivery_notes'] = $this->buildAjaxInfosResponseDeliveryNotes($date);
  118. $json['order_create'] = $this->buildAjaxInfosResponseOrderCreate($distribution, $productsArray);
  119. $json['users'] = $this->buildAjaxInfosResponseUsers();
  120. $json['one_distribution_week_active'] = $distributionModule->isOneDistributionWeekActive($date);
  121. $json['tiller_is_synchro'] = $this->buildAjaxInfosResponseTiller($producer, $date);
  122. $json['tiller_is_authenticated'] = $this->getOrderModule()->getTillerManager()->isAuthenticated();
  123. $json['tiller_url_authorize_code'] = $this->getOrderModule()->getTillerManager()->getUrlAuthorizeCode();
  124. $json['tiller_total_amount_orders'] = $this->getOrderModule()->getTillerManager()->getTotalAmountOrdersByDate($date, true);
  125. $json['missing_subscriptions'] = $this->buildAjaxInfosResponseMissingSubscriptions($date, $distribution, $ordersArrayObject);
  126. }
  127. return $json;
  128. }
  129. public function buildAjaxInfosResponseUsers()
  130. {
  131. $usersArray = $this->getUserModule()->getRepository()->findUsers();
  132. foreach($usersArray as $key => $user) {
  133. $usersArray[$key]['username'] = $this->getUserModule()->getSolver()->getUsernameFromArray($user, true);
  134. }
  135. return $usersArray;
  136. }
  137. public function buildAjaxInfosResponseLeavePeriod(Producer $producer)
  138. {
  139. $producerModule = $this->getProducerModule();
  140. $leavePeriodDatesArray = [];
  141. if($producerModule->getSolver()->hasLeavePeriodDefined($producer)) {
  142. $leavePeriodStart = $producerModule->getSolver()->getLeavePeriodStartDateTime($producer);
  143. $leavePeriodEnd = $producerModule->getSolver()->getLeavePeriodEndDateTime($producer);
  144. for($date = $leavePeriodStart; $date <= $leavePeriodEnd; $date->modify('+1 day')) {
  145. $leavePeriodDatesArray[] = $date->format('Y-m-d');
  146. }
  147. }
  148. return $leavePeriodDatesArray;
  149. }
  150. public function buildAjaxInfosResponsePointsSale(Distribution $distribution)
  151. {
  152. $producerModule = $this->getProducerModule();
  153. $pointSaleModule = $this->getPointSaleModule();
  154. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  155. $sharedPointSaleModule = $this->getSharedPointSaleModule();
  156. $featureModule = $this->getFeatureModule();
  157. $pointsSaleArray = $pointSaleModule->findPointSalesByDistributionAsArray($distribution);
  158. // @TODO : à gérer autrement
  159. foreach($pointsSaleArray as &$pointSaleArray) {
  160. $idPointSale = $pointSaleArray['id'];
  161. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  162. if(!isset($pointSaleArray['pointSaleDistribution']) || !$pointSaleArray['pointSaleDistribution'] || !count($pointSaleArray['pointSaleDistribution'])) {
  163. $pointSaleDistribution = $pointSaleDistributionModule->createPointSaleDistributionIfNotExist($distribution, $pointSale);
  164. $pointSaleArray['pointSaleDistribution'] = [
  165. [
  166. 'id_distribution' => $pointSaleDistribution->id_distribution,
  167. 'id_point_sale' => $pointSaleDistribution->id_point_sale,
  168. 'delivery' => $pointSaleDistribution->delivery
  169. ]
  170. ];
  171. }
  172. $pointSaleArray['credit_functioning'] = $producerModule->getPointSaleCreditFunctioning($pointSale);
  173. $pointSaleArray['producers_sharing_point_sale_as_string'] = false;
  174. if($featureModule->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  175. $pointSaleArray['producers_sharing_point_sale_as_string'] = $sharedPointSaleModule->getResolver()->getProducersSharingPointSaleAsString($pointSale, $distribution);
  176. }
  177. }
  178. return $pointsSaleArray;
  179. }
  180. public function buildAjaxInfosResponseProducts(Distribution $distribution, array $productsArray, array $ordersArray)
  181. {
  182. $distributionModule = $this-> getDistributionModule();
  183. $orderModule = $this->getOrderModule();
  184. $jsonProductsArray = [];
  185. foreach ($productsArray as $product) {
  186. $jsonProduct = $product->getAttributes();
  187. $quantityOrder = $orderModule->getProductQuantity($product, $ordersArray);
  188. $jsonProduct['quantity_ordered'] = $quantityOrder;
  189. if (!isset($product->productDistribution[0])) {
  190. $productDistributionAdd = $distributionModule->addProduct($distribution, $product);
  191. if($productDistributionAdd) {
  192. $jsonProduct['productDistribution'][0] = $productDistributionAdd->getAttributes();
  193. $product->populateRelation('productDistribution', [$productDistributionAdd]);
  194. }
  195. }
  196. else {
  197. foreach($product->productDistribution as $key => $productDistribution) {
  198. $jsonProduct['productDistribution'][$key] = $productDistribution->getAttributes();
  199. }
  200. }
  201. $jsonProduct['quantity_max'] = $orderModule->getResolver()->getProductQuantityMax($product, $distribution);
  202. $jsonProduct['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($product, $distribution);
  203. $jsonProduct['quantity_form'] = 0;
  204. $jsonProduct['accessories'] = [];
  205. foreach($product->getProductAccessories() as $productAccessory) {
  206. $jsonProduct['accessories'][] = [
  207. 'id_accessory' => $productAccessory->getAccessory()->getId(),
  208. 'quantity' => $productAccessory->getQuantity(),
  209. ];
  210. }
  211. if ($product->taxRate) {
  212. $jsonProduct['taxRate'] = $product->taxRate->getAttributes();
  213. }
  214. else {
  215. $jsonProduct['taxRate'] = $this->getProducerCurrent()->taxRate->getAttributes();
  216. }
  217. $jsonProductsArray[] = $jsonProduct;
  218. }
  219. return $jsonProductsArray;
  220. }
  221. public function buildAjaxInfosResponseProducer($producer)
  222. {
  223. return [
  224. 'credit' => $producer->credit,
  225. 'tiller' => $producer->tiller,
  226. 'option_distribution_export_orders_grid_pdf' => $producer->option_distribution_export_orders_grid_pdf,
  227. 'feature_product_accessory_enabled' => $this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_PRODUCT_ACCESSORY)
  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($order->isOrderStatusValid()) {
  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']) && $productOrderFormArray[$product->id]['quantity']) {
  523. $quantity = $productOrderFormArray[$product->id]['quantity'] / $productModule->getSolver()->getUnitCoefficient($product);
  524. }
  525. $productOrderArray[$product->id] = [
  526. 'quantity' => $quantity,
  527. 'unit' => $product->unit,
  528. 'prices' => $priceArray,
  529. 'active' => $product->productDistribution[0]->active
  530. && (!$pointSale || $productModule->isAvailableOnPointSale($product, $pointSale)),
  531. 'invoice_price' => $invoicePrice,
  532. ];
  533. }
  534. // construction de $orderOverride
  535. $orderOverride = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrderArray, $order);
  536. foreach($productOrderArray as $idProduct => $productOrder) {
  537. $product = $productModule->getRepository()->findOneProductById($idProduct);
  538. if($product) {
  539. $productOrderArray[$idProduct]['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($product, $distribution, $orderOverride);
  540. }
  541. }
  542. return $productOrderArray;
  543. }
  544. public function actionAjaxUpdateInvoicePrices($idOrder)
  545. {
  546. $orderModule = $this->getOrderModule();
  547. $userProducerModule = $this->getUserProducerModule();
  548. $productModule = $this->getProductModule();
  549. $order = $orderModule->findOneOrderById($idOrder);
  550. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  551. $userProducer = null;
  552. if ($order->id_user) {
  553. $userProducer = $userProducerModule->findOneUserProducer($order->user);
  554. }
  555. foreach ($order->productOrder as $productOrder) {
  556. $invoicePrice = $productModule->getPrice($productOrder->product, [
  557. 'user' => $orderModule->getUserForInvoicing($order),
  558. 'point_sale' => $order->pointSale,
  559. 'user_producer' => $userProducer,
  560. 'quantity' => $productOrder->quantity
  561. ]);
  562. if ($invoicePrice != $productOrder->price) {
  563. $productOrder->invoice_price = $invoicePrice;
  564. } else {
  565. $productOrder->invoice_price = null;
  566. }
  567. $productOrder->save();
  568. }
  569. }
  570. }
  571. /**
  572. * Génére un export pour une distribution.
  573. */
  574. public function actionExport(string $name, string $date = '')
  575. {
  576. $distributionModule = $this-> getDistributionModule();
  577. $distribution = $distributionModule->getRepository()->findOneDistribution($date);
  578. if ($distribution) {
  579. try {
  580. return $distributionModule->getExportManager()->getGenerator($name)->generate($distribution);
  581. }
  582. catch(ErrorException $exception) {
  583. //$this->setFlash('error', "Une erreur est survenue lors de la génération de l'export.");
  584. $this->setFlash('error', $exception->getMessage());
  585. return $this->redirectReferer();
  586. }
  587. }
  588. }
  589. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  590. {
  591. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  592. $orderModule = $this->getOrderModule();
  593. $productDistributionModule = $this->getProductDistributionModule();
  594. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  595. $productDistributionModule->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  596. return [
  597. 'quantity_max' => $orderModule->getResolver()
  598. ->getProductQuantityMax(
  599. $productDistribution->product,
  600. $productDistribution->distribution
  601. ),
  602. 'quantity_remaining' => $orderModule->getResolver()
  603. ->getProductQuantityRemaining(
  604. $productDistribution->product,
  605. $productDistribution->distribution
  606. )
  607. ];
  608. }
  609. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  610. {
  611. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  612. $productDistributionModule = $this->getProductDistributionModule();
  613. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  614. $productDistributionModule->updateProductDistributionActive($productDistribution, $active);
  615. return ['success'];
  616. }
  617. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  618. {
  619. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  620. $distributionModule = $this-> getDistributionModule();
  621. $pointSaleModule = $this->getPointSaleModule();
  622. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  623. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution(
  624. $distributionModule->findOneDistributionById($idDistribution),
  625. $pointSaleModule->findOnePointSaleById($idPointSale)
  626. );
  627. $pointSaleDistribution->delivery = $delivery;
  628. $pointSaleDistributionModule->update($pointSaleDistribution);
  629. return ['success'];
  630. }
  631. public function getProductDistribution(int $idProduct, int $idDistribution)
  632. {
  633. $distributionModule = $this-> getDistributionModule();
  634. $productModule = $this->getProductModule();
  635. $productDistributionModule = $this->getProductDistributionModule();
  636. return $productDistributionModule->findOneProductDistribution(
  637. $distributionModule->findOneDistributionById($idDistribution),
  638. $productModule->findOneProductById($idProduct)
  639. );
  640. }
  641. /**
  642. * Active/désactive un jour de distribution.
  643. */
  644. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  645. {
  646. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  647. $distributionModule = $this-> getDistributionModule();
  648. $distribution = null;
  649. if ($idDistribution) {
  650. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  651. }
  652. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  653. $distribution = $distributionModule->getBuilder()->createDistributionIfNotExist($date);
  654. }
  655. if ($distribution) {
  656. $distributionModule->getBuilder()->activeDistribution($distribution, $active);
  657. return ['success'];
  658. }
  659. return ['error'];
  660. }
  661. /**
  662. * Change l'état d'une semaine de distribution (activé, désactivé).
  663. */
  664. public function actionAjaxProcessActiveWeekDistribution(string $date, int $active)
  665. {
  666. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  667. $this->getDistributionModule()->getBuilder()->activeDistributionsOfWeek($date, $active);
  668. return ['success'];
  669. }
  670. /**
  671. * Ajoute les commandes récurrentes pour une date donnée.
  672. */
  673. public function actionAjaxProcessAddSubscriptions(string $date)
  674. {
  675. $ordersArray = $this->getOrderModule()->getManager()
  676. ->createAllOrdersFromSubscriptions($date, $this->getUserCurrent(), true);
  677. if($ordersArray && count($ordersArray)) {
  678. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  679. }
  680. return Ajax::responseError('Aucun abonnement à importer.');
  681. }
  682. /**
  683. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  684. */
  685. public function actionAjaxProcessSynchroTiller(string $date)
  686. {
  687. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  688. return $this->getOrderModule()->getTillerManager()->synchronizeDistribution($date);
  689. }
  690. public function actionAjaxForceSynchronizeOrderTiller(int $idOrder)
  691. {
  692. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  693. $order = $this->getOrderModule()->getRepository()->findOneOrderById($idOrder);
  694. return $this->getOrderModule()->getTillerManager()->synchronizeOrder($order, true);
  695. }
  696. public function actionAjaxGenerateDeliveryNotePointSale(string $idOrders)
  697. {
  698. if (strlen($idOrders)) {
  699. $idOrders = json_decode($idOrders, true);
  700. if(is_array($idOrders)) {
  701. try {
  702. if($this->getOrderModule()->getDocumentManager()->generateDeliveryNoteForPointSale($idOrders)) {
  703. return Ajax::responseSuccess("Bon de livraison généré");
  704. }
  705. }
  706. catch(Exception $exception) {
  707. return Ajax::responseError($exception->getMessage());
  708. }
  709. }
  710. }
  711. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  712. }
  713. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  714. {
  715. $orderModule = $this->getOrderModule();
  716. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  717. $orderModule->getDocumentManager()->generateDeliveryNoteForUser($order);
  718. return Ajax::responseSuccess('Bon de livraison généré');
  719. }
  720. public function actionAjaxSendDeliveryNote(int $idOrder)
  721. {
  722. $orderModule = $this->getOrderModule();
  723. $documentModule = $this->getDocumentModule();
  724. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  725. if($order->deliveryNote) {
  726. $documentModule->getManager()->sendDocument($order->deliveryNote);
  727. return Ajax::responseSuccess('Bon de livraison envoyé');
  728. }
  729. return Ajax::responseSuccess('Une erreur est survenue lors de l\'envoi du bon de livraison.');
  730. }
  731. public function actionAjaxGenerateDeliveryNoteEachUser(string $idOrders)
  732. {
  733. if (strlen($idOrders)) {
  734. $idOrders = json_decode($idOrders, true);
  735. $this->getOrderModule()->getDocumentManager()->generateDeliveryNotesForUser($idOrders);
  736. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  737. }
  738. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  739. }
  740. public function actionAjaxValidateDeliveryNotes(string $idOrders)
  741. {
  742. if (strlen($idOrders)) {
  743. $idOrders = json_decode($idOrders, true);
  744. if($this->getOrderModule()->getDocumentManager()->validateDeliveryNotes($idOrders)) {
  745. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  746. }
  747. }
  748. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  749. }
  750. }