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.

882 line
39KB

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