Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

DistributionController.php 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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\Order\Order\Order;
  45. use domain\Producer\Producer\Producer;
  46. use DateTime;
  47. use domain\Product\Product\Product;
  48. use yii\base\ErrorException;
  49. use yii\base\Exception;
  50. use yii\filters\AccessControl;
  51. class DistributionController extends BackendController
  52. {
  53. public function behaviors()
  54. {
  55. return [
  56. 'access' => [
  57. 'class' => AccessControl::class,
  58. 'rules' => [
  59. [
  60. 'actions' => ['report-cron', 'report-terredepains'],
  61. 'allow' => true,
  62. 'roles' => ['?']
  63. ],
  64. [
  65. 'allow' => true,
  66. 'roles' => ['@'],
  67. 'matchCallback' => function ($rule, $action) {
  68. return $this->getUserModule()
  69. ->getAuthorizationChecker()
  70. ->isGrantedAsProducer($this->getUserCurrent());
  71. }
  72. ]
  73. ],
  74. ],
  75. ];
  76. }
  77. public function actionIndex(string $date = '', int $idOrderUpdate = 0)
  78. {
  79. $this->checkProductsPointsSale();
  80. if(!$this->getDistributionModule()->getSolver()->validateDistributionDate($date)) {
  81. $date = '';
  82. }
  83. $orderUpdate = null;
  84. if($idOrderUpdate) {
  85. $orderUpdate = $this->getOrderModule()->getRepository()
  86. ->findOneOrderById($idOrderUpdate);
  87. }
  88. return $this->render('index', [
  89. 'date' => $date,
  90. 'orderUpdate' => $orderUpdate
  91. ]);
  92. }
  93. public function actionAjaxInfos($date = '')
  94. {
  95. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  96. $distributionModule = $this-> getDistributionModule();
  97. $orderModule = $this->getOrderModule();
  98. $productModule = $this->getProductModule();
  99. $userModule = $this->getUserModule();
  100. $producerModule = $this->getProducerModule();
  101. $producer = $this->getProducerCurrent();
  102. $dateObject = DateTime::createFromFormat('Y-m-d', $date);
  103. $json = ['distribution' => [], 'products' => []];
  104. $json['means_payment'] = MeanPayment::getAll();
  105. $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
  106. $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
  107. $json['leave_period_dates'] = $this->buildAjaxInfosResponseLeavePeriod($producer);
  108. $json['units'] = Product::$unitsArray;
  109. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  110. $distribution = $distributionModule->createDistributionIfNotExist($date);
  111. $ordersArray = $orderModule->findOrdersByDistribution($distribution, false);
  112. $ordersArrayObject = $ordersArray;
  113. $productsArray = $productModule->findProductsByDistribution($distribution, false);
  114. $json['products'] = $this->buildAjaxInfosResponseProducts($distribution, $productsArray, $ordersArray);
  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'] = $userModule->findUsers();
  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 buildAjaxInfosResponseLeavePeriod(Producer $producer)
  130. {
  131. $producerModule = $this->getProducerModule();
  132. $leavePeriodDatesArray = [];
  133. if($producerModule->getSolver()->hasLeavePeriodDefined($producer)) {
  134. $leavePeriodStart = $producerModule->getSolver()->getLeavePeriodStartDateTime($producer);
  135. $leavePeriodEnd = $producerModule->getSolver()->getLeavePeriodEndDateTime($producer);
  136. for($date = $leavePeriodStart; $date <= $leavePeriodEnd; $date->modify('+1 day')) {
  137. $leavePeriodDatesArray[] = $date->format('Y-m-d');
  138. }
  139. }
  140. return $leavePeriodDatesArray;
  141. }
  142. public function buildAjaxInfosResponsePointsSale(Distribution $distribution)
  143. {
  144. $producerModule = $this->getProducerModule();
  145. $pointSaleModule = $this->getPointSaleModule();
  146. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  147. $pointsSaleArray = $pointSaleModule->findPointSalesByDistributionAsArray($distribution);
  148. // @TODO : à gérer autrement
  149. foreach($pointsSaleArray as &$pointSaleArray) {
  150. $idPointSale = $pointSaleArray['id'];
  151. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  152. if(!isset($pointSaleArray['pointSaleDistribution']) || !$pointSaleArray['pointSaleDistribution'] || !count($pointSaleArray['pointSaleDistribution'])) {
  153. $pointSaleDistribution = $pointSaleDistributionModule->createPointSaleDistributionIfNotExist($distribution, $pointSale);
  154. $pointSaleArray['pointSaleDistribution'] = [
  155. [
  156. 'id_distribution' => $pointSaleDistribution->id_distribution,
  157. 'id_point_sale' => $pointSaleDistribution->id_point_sale,
  158. 'delivery' => $pointSaleDistribution->delivery
  159. ]
  160. ];
  161. }
  162. $pointSaleArray['credit_functioning'] = $producerModule->getPointSaleCreditFunctioning($pointSale);
  163. }
  164. return $pointsSaleArray;
  165. }
  166. public function buildAjaxInfosResponseProducts(Distribution $distribution, array $productsArray, array $ordersArray)
  167. {
  168. $distributionModule = $this-> getDistributionModule();
  169. $orderModule = $this->getOrderModule();
  170. $jsonProductsArray = [];
  171. foreach ($productsArray as $product) {
  172. $jsonProduct = $product->getAttributes();
  173. $quantityOrder = $orderModule->getProductQuantity($product, $ordersArray);
  174. $jsonProduct['quantity_ordered'] = $quantityOrder;
  175. if (!isset($product->productDistribution[0])) {
  176. $productDistributionAdd = $distributionModule->addProduct($distribution, $product);
  177. if($productDistributionAdd) {
  178. $jsonProduct['productDistribution'][0] = $productDistributionAdd->getAttributes();
  179. $product->populateRelation('productDistribution', [$productDistributionAdd]);
  180. }
  181. }
  182. else {
  183. foreach($product->productDistribution as $key => $productDistribution) {
  184. $jsonProduct['productDistribution'][$key] = $productDistribution->getAttributes();
  185. }
  186. }
  187. if (!isset($product->productDistribution[0]) || !is_numeric($product->productDistribution[0]->quantity_max)) {
  188. $jsonProduct['quantity_remaining'] = null;
  189. } else {
  190. $jsonProduct['quantity_remaining'] = $product->productDistribution[0]->quantity_max - $quantityOrder;
  191. }
  192. $jsonProduct['quantity_form'] = 0;
  193. if ($product->taxRate) {
  194. $jsonProduct['taxRate'] = $product->taxRate->getAttributes();
  195. }
  196. else {
  197. $jsonProduct['taxRate'] = $this->getProducerCurrent()->taxRate->getAttributes();
  198. }
  199. $jsonProductsArray[] = $jsonProduct;
  200. }
  201. return $jsonProductsArray;
  202. }
  203. public function buildAjaxInfosResponseProducer($producer)
  204. {
  205. return [
  206. 'credit' => $producer->credit,
  207. 'tiller' => $producer->tiller,
  208. 'option_distribution_export_orders_grid_pdf' => $producer->option_distribution_export_orders_grid_pdf
  209. ];
  210. }
  211. public function buildAjaxInfosResponseDistributions($dateObject)
  212. {
  213. $numberOfLoadedMonthes = '3 month';
  214. if (is_object($dateObject)) {
  215. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  216. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  217. } else {
  218. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  219. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  220. }
  221. return Distribution::searchAll([
  222. 'active' => 1
  223. ], [
  224. 'conditions' => [
  225. 'date > :date_begin',
  226. 'date < :date_end'
  227. ],
  228. 'params' => [
  229. ':date_begin' => date(
  230. 'Y-m-d',
  231. $dateBegin
  232. ),
  233. ':date_end' => date(
  234. 'Y-m-d',
  235. $dateEnd
  236. ),
  237. ],
  238. 'as_array' => true
  239. ]);
  240. }
  241. public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray, array $productsArray)
  242. {
  243. $producerModule = $this->getProducerModule();
  244. $productModule = $this->getProductModule();
  245. $orderModule = $this->getOrderModule();
  246. $distributionModule = $this-> getDistributionModule();
  247. $distributionJsonData = [
  248. 'id' => $distribution->id,
  249. 'active' => $distribution->active,
  250. 'exports' => $distributionModule->getExportManager()->getAjaxArray($distribution),
  251. 'url_order' => $distributionModule->getLinkOrder($distribution),
  252. 'is_leave_period' => $producerModule->getSolver()->isOnLeavePeriod($distribution->producer, DateTime::createFromFormat('Y-m-d', $distribution->date))
  253. ];
  254. // montant et poids des commandes
  255. $revenues = 0;
  256. $revenuesWithTax = 0;
  257. $weight = 0;
  258. if ($ordersArray) {
  259. foreach ($ordersArray as $order) {
  260. $orderModule->initOrder($order);
  261. if($orderModule->getSolver()->isOrderStatusValid($order)) {
  262. $revenues += $orderModule->getOrderAmount($order);
  263. $revenuesWithTax += $orderModule->getOrderAmountWithTax($order);
  264. $weight += $order->weight;
  265. }
  266. }
  267. }
  268. $distributionJsonData['revenues'] = Price::format($revenues);
  269. $distributionJsonData['revenues_with_tax'] = Price::format($revenuesWithTax);
  270. $distributionJsonData['weight'] = number_format($weight, 2);
  271. $distributionJsonData['potential_revenues'] = Price::format($productModule->getProductDistributionPotentialRevenues($productsArray));
  272. $distributionJsonData['potential_revenues_with_tax'] = Price::format($productModule->getProductDistributionPotentialRevenues($productsArray, true));
  273. $distributionJsonData['potential_weight'] = number_format($productModule->getProductDistributionPotentialWeight($productsArray), 2);
  274. return $distributionJsonData;
  275. }
  276. public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
  277. {
  278. $userModule = $this->getUserModule();
  279. $orderModule = $this->getOrderModule();
  280. $paymentManager = $this->getPaymentModule();
  281. $productOrderModule = $this->getProductOrderModule();
  282. $userProducerModule = $this->getUserProducerModule();
  283. if ($ordersArray) {
  284. foreach ($ordersArray as &$order) {
  285. $orderModule->initOrder($order);
  286. $productOrderArray = [];
  287. foreach ($order->productOrder as $productOrder) {
  288. $productOrderArray[$productOrder->id_product] = [
  289. 'quantity' => $productOrderModule->getSolver()->getQuantityToCoefficientOfUnit($productOrder),
  290. 'unit' => $productOrder->unit,
  291. 'price' => number_format($productOrder->price, 5),
  292. 'invoice_price' => number_format($productOrder->invoice_price, 5),
  293. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  294. ];
  295. }
  296. foreach ($productsArray as $product) {
  297. if (!isset($productOrderArray[$product['id']])) {
  298. $productOrderArray[$product['id']] = [
  299. 'quantity' => 0,
  300. 'unit' => $product['unit'],
  301. 'price' => number_format($product['price'], 5),
  302. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  303. ];
  304. }
  305. }
  306. $paymentArray = [];
  307. foreach ($order->payment as $payment) {
  308. $paymentArray[] = [
  309. 'type' => $payment->type,
  310. 'wording_type' => $paymentManager->getStrType($payment),
  311. 'mean_payment' => $payment->mean_payment,
  312. 'wording_mean_payment' => $paymentManager->getStrMeanPayment($payment),
  313. 'date' => date('d/m/Y H:i:s', strtotime($payment->date)),
  314. 'user' => $payment->getUserObject() ? $userModule->getUsername($payment->getUserObject()) : '',
  315. 'user_action' => $paymentManager->getStrUserAction($payment),
  316. 'wording' => $paymentManager->getStrWording($payment, $order),
  317. 'amount' => $paymentManager->getAmount($payment, Order::AMOUNT_TOTAL, true),
  318. ];
  319. }
  320. $arrayDatasUser = [];
  321. if(isset($order->user) && $order->user) {
  322. $arrayDatasUser['credit'] = $userModule->getCredit($order->user);
  323. $arrayDatasUser['credit_active'] = $userModule->getCreditActive($order->user);
  324. $userProducer = $userProducerModule->getRepository()->findOneUserProducer($order->user);
  325. $arrayDatasUser['trust_alert'] = $userProducer->trust_alert;
  326. $arrayDatasUser['trust_alert_comment'] = $userProducer->trust_alert_comment;
  327. }
  328. $oneProductUnactivated = false;
  329. foreach ($order->productOrder as $productOrder) {
  330. foreach ($productsArray as $product) {
  331. if ($productOrder->id_product == $product['id'] && isset($product['productDistribution'][0]) && !$product['productDistribution'][0]['active']) {
  332. $oneProductUnactivated = true;
  333. }
  334. }
  335. }
  336. $order = array_merge($order->getAttributes(), [
  337. 'selected' => false,
  338. 'weight' => $order->weight,
  339. 'amount' => (float) Price::numberTwoDecimals($orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  340. 'amount_paid' => (float) Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_PAID)),
  341. 'amount_remaining' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_REMAINING)),
  342. 'amount_surplus' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
  343. 'user' => (isset($order->user)) ? array_merge(
  344. $order->user->getAttributes(),
  345. $arrayDatasUser
  346. ) : null,
  347. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  348. 'productOrder' => $productOrderArray,
  349. 'paymentsArray' => $paymentArray,
  350. 'oneProductUnactivated' => $oneProductUnactivated,
  351. 'isLinkedToValidDocument' => $orderModule->getSolver()->isLinkedToValidDocument($order),
  352. 'isLinkedToValidInvoice' => $orderModule->getSolver()->isLinkedToValidInvoice($order),
  353. 'isCreditAutoPayment' => $orderModule->getRepository()->isCreditAutoPayment($order),
  354. 'isCreditContext' => $orderModule->getRepository()->isCreditContext($order),
  355. 'isPaid' => $orderModule->getRepository()->isOrderPaid($order),
  356. 'isPaidViaInvoice' => $orderModule->getRepository()->isOrderPaidViaInvoice($order),
  357. 'paymentLabelShort' => $orderModule->getRepository()->getPaymentLabelShort($order),
  358. 'isCreditFunctioningMandatory' => $orderModule->getRepository()->isOrderCreditFunctioningMandatory($order),
  359. 'isCreditFunctioningUser' => $orderModule->getRepository()->isOrderCreditFunctioningUser($order),
  360. 'debitCredit' => false,
  361. 'deliveryNote' => $order->deliveryNote ? $order->deliveryNote->getAttributes() : null,
  362. 'labelDeleteAction' => $orderModule->getSolver()->getLabelDeleteAction($order),
  363. 'labelOrigin' => $orderModule->getSolver()->getLabelOrigin($order, true),
  364. 'orderStatusHistorySummaryTitleTag' => $orderModule->getSolver()->getOrderStatusHistorySummaryTitleTag($order, "\n"),
  365. ]);
  366. }
  367. }
  368. return $ordersArray;
  369. }
  370. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  371. {
  372. $deliveryNotesArray = DeliveryNote::searchAll([
  373. 'distribution.date' => $date,
  374. ], [
  375. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  376. ]);
  377. $deliveryNotesByPointSaleArray = [];
  378. foreach ($deliveryNotesArray as $deliveryNote) {
  379. if (isset($deliveryNote->orders[0])) {
  380. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  381. $deliveryNote->getAttributes();
  382. }
  383. }
  384. return $deliveryNotesByPointSaleArray;
  385. }
  386. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  387. {
  388. $pointSaleModule = $this->getPointSaleModule();
  389. $pointSaleDefault = $pointSaleModule->findOnePointSaleDefaultByDistribution($distribution);
  390. $productOrderArray = [];
  391. foreach ($productsArray as $product) {
  392. $productOrderArray[$product['id']] = [
  393. 'quantity' => 0,
  394. 'unit' => $product['unit'],
  395. 'price' => number_format($product['price'], 5),
  396. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  397. ];
  398. }
  399. return [
  400. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
  401. 'id_user' => 0,
  402. 'username' => '',
  403. 'comment' => '',
  404. 'productOrder' => $productOrderArray
  405. ];
  406. }
  407. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  408. {
  409. return $this->getOrderModule()->getTillerManager()->isSynchronized($date);
  410. }
  411. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  412. {
  413. $subscriptionModule = $this->getSubscriptionModule();
  414. $missingSubscriptionsArray = [];
  415. $arraySubscriptions = $subscriptionModule->findSubscriptionsByDate($date);
  416. if ($distribution->active) {
  417. foreach ($arraySubscriptions as $subscription) {
  418. if (!$subscriptionModule->hasOrderAlreadyExist($subscription, $ordersArray)
  419. && $subscription->productSubscription && count($subscription->productSubscription)
  420. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  421. $missingSubscriptionsArray[] = [
  422. 'username' => $subscriptionModule->getUsername($subscription)
  423. ];
  424. }
  425. }
  426. }
  427. return $missingSubscriptionsArray;
  428. }
  429. public function actionAjaxPointSaleFavorite($idUser, $idDistribution)
  430. {
  431. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  432. $userModule = $this->getUserModule();
  433. $orderModule = $this->getOrderModule();
  434. $distributionModule = $this->getDistributionModule();
  435. $user = $userModule->findOneUserById($idUser);
  436. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  437. $idFavoritePointSale = 0;
  438. if($user) {
  439. $favoritePointSale = $orderModule->getUserFavoritePointSale($user, $distribution);
  440. if ($favoritePointSale) {
  441. $idFavoritePointSale = $favoritePointSale->id;
  442. }
  443. }
  444. return [
  445. 'id_favorite_point_sale' => $idFavoritePointSale
  446. ];
  447. }
  448. public function actionAjaxUpdateProductOrder(
  449. $idDistribution,
  450. $idUser = false,
  451. $idPointSale = false,
  452. $idOrder = false
  453. )
  454. {
  455. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  456. $distributionModule = $this-> getDistributionModule();
  457. $orderModule = $this->getOrderModule();
  458. $userModule = $this->getUserModule();
  459. $pointSaleModule = $this->getPointSaleModule();
  460. $productModule = $this->getProductModule();
  461. $order = $orderModule->findOneOrderById($idOrder);
  462. $distribution = $distributionModule->findOneDistributionById($idDistribution);
  463. $user = $userModule->findOneUserById($idUser);
  464. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  465. $productsArray = Product::find()
  466. ->where([
  467. 'id_producer' => GlobalParam::getCurrentProducerId(),
  468. ])->joinWith([
  469. 'productPrice',
  470. 'productDistribution' => function ($q) use ($distribution) {
  471. $q->where(['id_distribution' => $distribution->id]);
  472. }
  473. ])->all();
  474. $productOrderArray = [];
  475. foreach ($productsArray as $product) {
  476. $priceArray = $productModule->getPriceArray($product, $user, $pointSale);
  477. $quantity = 0;
  478. $invoicePrice = null;
  479. if (isset($order->productOrder)) {
  480. foreach ($order->productOrder as $productOrder) {
  481. if ($productOrder->id_product == $product['id']) {
  482. if ($productOrder->invoice_price) {
  483. $invoicePrice = number_format($productOrder->invoice_price, 5);
  484. } else {
  485. $invoicePrice = number_format($productOrder->price, 5);
  486. }
  487. $quantity = $productOrder->quantity;
  488. }
  489. }
  490. }
  491. $productOrderArray[$product['id']] = [
  492. 'quantity' => $quantity,
  493. 'unit' => $product->unit,
  494. 'prices' => $priceArray,
  495. 'active' => $product->productDistribution[0]->active
  496. && (!$pointSale || $productModule->isAvailableOnPointSale($product, $pointSale)),
  497. 'invoice_price' => $invoicePrice
  498. ];
  499. }
  500. return $productOrderArray;
  501. }
  502. public function actionAjaxUpdateInvoicePrices($idOrder)
  503. {
  504. $orderModule = $this->getOrderModule();
  505. $userProducerModule = $this->getUserProducerModule();
  506. $productModule = $this->getProductModule();
  507. $order = $orderModule->findOneOrderById($idOrder);
  508. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  509. $userProducer = null;
  510. if ($order->id_user) {
  511. $userProducer = $userProducerModule->findOneUserProducer($order->user);
  512. }
  513. foreach ($order->productOrder as $productOrder) {
  514. $invoicePrice = $productModule->getPrice($productOrder->product, [
  515. 'user' => $orderModule->getUserForInvoicing($order),
  516. 'point_sale' => $order->pointSale,
  517. 'user_producer' => $userProducer,
  518. 'quantity' => $productOrder->quantity
  519. ]);
  520. if ($invoicePrice != $productOrder->price) {
  521. $productOrder->invoice_price = $invoicePrice;
  522. } else {
  523. $productOrder->invoice_price = null;
  524. }
  525. $productOrder->save();
  526. }
  527. }
  528. }
  529. /**
  530. * Génére un export pour une distribution.
  531. */
  532. public function actionExport(string $name, string $date = '')
  533. {
  534. $distributionModule = $this-> getDistributionModule();
  535. $distribution = $distributionModule->getRepository()->findOneDistribution($date);
  536. if ($distribution) {
  537. try {
  538. return $distributionModule->getExportManager()->getGenerator($name)->generate($distribution);
  539. }
  540. catch(ErrorException $exception) {
  541. //$this->setFlash('error', "Une erreur est survenue lors de la génération de l'export.");
  542. $this->setFlash('error', $exception->getMessage());
  543. return $this->redirectReferer();
  544. }
  545. }
  546. }
  547. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  548. {
  549. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  550. $productDistributionModule = $this->getProductDistributionModule();
  551. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  552. $productDistributionModule->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  553. return ['success'];
  554. }
  555. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  556. {
  557. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  558. $productDistributionModule = $this->getProductDistributionModule();
  559. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  560. $productDistributionModule->updateProductDistributionActive($productDistribution, $active);
  561. return ['success'];
  562. }
  563. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  564. {
  565. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  566. $distributionModule = $this-> getDistributionModule();
  567. $pointSaleModule = $this->getPointSaleModule();
  568. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  569. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution(
  570. $distributionModule->findOneDistributionById($idDistribution),
  571. $pointSaleModule->findOnePointSaleById($idPointSale)
  572. );
  573. $pointSaleDistribution->delivery = $delivery;
  574. $pointSaleDistributionModule->update($pointSaleDistribution);
  575. return ['success'];
  576. }
  577. public function getProductDistribution(int $idProduct, int $idDistribution)
  578. {
  579. $distributionModule = $this-> getDistributionModule();
  580. $productModule = $this->getProductModule();
  581. $productDistributionModule = $this->getProductDistributionModule();
  582. return $productDistributionModule->findOneProductDistribution(
  583. $distributionModule->findOneDistributionById($idDistribution),
  584. $productModule->findOneProductById($idProduct)
  585. );
  586. }
  587. /**
  588. * Active/désactive un jour de distribution.
  589. */
  590. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  591. {
  592. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  593. $distributionModule = $this-> getDistributionModule();
  594. $distribution = null;
  595. if ($idDistribution) {
  596. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  597. }
  598. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  599. $distribution = $distributionModule->getBuilder()->createDistributionIfNotExist($date);
  600. }
  601. if ($distribution) {
  602. $distributionModule->getBuilder()->activeDistribution($distribution, $active);
  603. return ['success'];
  604. }
  605. return ['error'];
  606. }
  607. /**
  608. * Change l'état d'une semaine de distribution (activé, désactivé).
  609. */
  610. public function actionAjaxProcessActiveWeekDistribution(string $date, int $active)
  611. {
  612. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  613. $this->getDistributionModule()->getBuilder()->activeDistributionsOfWeek($date, $active);
  614. return ['success'];
  615. }
  616. /**
  617. * Ajoute les commandes récurrentes pour une date donnée.
  618. */
  619. public function actionAjaxProcessAddSubscriptions(string $date)
  620. {
  621. $ordersArray = $this->getOrderModule()->getManager()
  622. ->createAllOrdersFromSubscriptions($date, $this->getUserCurrent(), true);
  623. if($ordersArray && count($ordersArray)) {
  624. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  625. }
  626. return Ajax::responseError('Aucun abonnement à importer.');
  627. }
  628. /**
  629. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  630. */
  631. public function actionAjaxProcessSynchroTiller(string $date)
  632. {
  633. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  634. return $this->getOrderModule()->getTillerManager()->synchronizeDistribution($date);
  635. }
  636. public function actionAjaxGenerateDeliveryNotePointSale(string $idOrders)
  637. {
  638. if (strlen($idOrders)) {
  639. $idOrders = json_decode($idOrders, true);
  640. if(is_array($idOrders)) {
  641. try {
  642. if($this->getOrderModule()->getDocumentManager()->generateDeliveryNoteForPointSale($idOrders)) {
  643. return Ajax::responseSuccess("Bon de livraison généré");
  644. }
  645. }
  646. catch(Exception $exception) {
  647. return Ajax::responseError($exception->getMessage());
  648. }
  649. }
  650. }
  651. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  652. }
  653. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  654. {
  655. $orderModule = $this->getOrderModule();
  656. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  657. $orderModule->getDocumentManager()->generateDeliveryNoteForUser($order);
  658. return Ajax::responseSuccess('Bon de livraison généré');
  659. }
  660. public function actionAjaxSendDeliveryNote(int $idOrder)
  661. {
  662. $orderModule = $this->getOrderModule();
  663. $documentModule = $this->getDocumentModule();
  664. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  665. if($order->deliveryNote) {
  666. $documentModule->getManager()->sendDocument($order->deliveryNote);
  667. return Ajax::responseSuccess('Bon de livraison envoyé');
  668. }
  669. return Ajax::responseSuccess('Une erreur est survenue lors de l\'envoi du bon de livraison.');
  670. }
  671. public function actionAjaxGenerateDeliveryNoteEachUser(string $idOrders)
  672. {
  673. if (strlen($idOrders)) {
  674. $idOrders = json_decode($idOrders, true);
  675. $this->getOrderModule()->getDocumentManager()->generateDeliveryNotesForUser($idOrders);
  676. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  677. }
  678. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  679. }
  680. public function actionAjaxValidateDeliveryNotes(string $idOrders)
  681. {
  682. if (strlen($idOrders)) {
  683. $idOrders = json_decode($idOrders, true);
  684. if($this->getOrderModule()->getDocumentManager()->validateDeliveryNotes($idOrders)) {
  685. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  686. }
  687. }
  688. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  689. }
  690. }