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.

1024 lines
42KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  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\CSV;
  40. use common\helpers\GlobalParam;
  41. use common\helpers\MeanPayment;
  42. use common\helpers\Password;
  43. use common\helpers\Price;
  44. use common\helpers\Tiller;
  45. use common\logic\Distribution\Distribution\Model\Distribution;
  46. use common\logic\Document\DeliveryNote\Model\DeliveryNote;
  47. use common\logic\Document\Document\Model\Document;
  48. use common\logic\Order\Order\Model\Order;
  49. use common\logic\PointSale\PointSale\Model\PointSale;
  50. use common\logic\Producer\Producer\Model\Producer;
  51. use common\logic\Product\Product\Model\Product;
  52. use common\logic\User\User\Model\User;
  53. use common\logic\User\UserProducer\Model\UserProducer;
  54. use DateTime;
  55. use kartik\mpdf\Pdf;
  56. use yii\filters\AccessControl;
  57. class DistributionController extends BackendController
  58. {
  59. public function behaviors()
  60. {
  61. return [
  62. 'access' => [
  63. 'class' => AccessControl::class,
  64. 'rules' => [
  65. [
  66. 'actions' => ['report-cron', 'report-terredepains'],
  67. 'allow' => true,
  68. 'roles' => ['?']
  69. ],
  70. [
  71. 'allow' => true,
  72. 'roles' => ['@'],
  73. 'matchCallback' => function ($rule, $action) {
  74. $userModule = $this->getUserModule();
  75. return $userModule->isCurrentAdmin() || $userModule->isCurrentProducer();
  76. }
  77. ]
  78. ],
  79. ],
  80. ];
  81. }
  82. public function actionIndex($date = '', $idOrderUpdate = 0)
  83. {
  84. $this->checkProductsPointsSale();
  85. $orderManager = $this->getOrderManager();
  86. $format = 'Y-m-d';
  87. $theDate = '';
  88. $dateObject = DateTime::createFromFormat($format, $date);
  89. if ($dateObject && $dateObject->format($format) === $date) {
  90. $theDate = $date;
  91. }
  92. $orderUpdate = null;
  93. if ($idOrderUpdate) {
  94. $orderUpdate = $orderManager->findOneOrderById($idOrderUpdate);
  95. }
  96. return $this->render('index', [
  97. 'date' => $theDate,
  98. 'orderUpdate' => $orderUpdate
  99. ]);
  100. }
  101. public function actionAjaxInfos($date = '')
  102. {
  103. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  104. $distributionManager = $this->getDistributionManager();
  105. $orderManager = $this->getOrderManager();
  106. $productManager = $this->getProductManager();
  107. $userModule = $this->getUserModule();
  108. $producer = $this->getProducerCurrent();
  109. $format = 'Y-m-d';
  110. $dateObject = DateTime::createFromFormat($format, $date);
  111. $json = ['distribution' => [], 'products' => []];
  112. $json['means_payment'] = MeanPayment::getAll();
  113. $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
  114. $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
  115. $json['units'] = Product::$unitsArray;
  116. if ($dateObject && $dateObject->format($format) === $date) {
  117. $distribution = $distributionManager->createDistributionIfNotExist($date);
  118. $ordersArray = $orderManager->findOrdersByDistribution($distribution, false);
  119. $ordersArrayObject = $ordersArray;
  120. $productsArray = $productManager->findProductsByDistribution($distribution, false);
  121. $json['products'] = $this->buildAjaxInfosResponseProducts($distribution, $productsArray, $ordersArray);
  122. $json['distribution'] = $this->buildAjaxInfosResponseDistribution($distribution, $ordersArrayObject, $productsArray);
  123. $json['orders'] = $this->buildAjaxInfosResponseOrders($ordersArray, $productsArray);
  124. $json['points_sale'] = $this->buildAjaxInfosResponsePointsSale($distribution);
  125. $json['delivery_notes'] = $this->buildAjaxInfosResponseDeliveryNotes($date);
  126. $json['order_create'] = $this->buildAjaxInfosResponseOrderCreate($distribution, $productsArray);
  127. $json['users'] = $userModule->findUsers();
  128. $json['one_distribution_week_active'] = $distributionManager->isOneDistributionWeekActive($date);
  129. $json['tiller_is_synchro'] = $this->buildAjaxInfosResponseTiller($producer, $date);
  130. $json['missing_subscriptions'] = $this->buildAjaxInfosResponseMissingSubscriptions($date, $distribution, $ordersArrayObject);
  131. }
  132. return $json;
  133. }
  134. public function buildAjaxInfosResponsePointsSale(Distribution $distribution)
  135. {
  136. $producerManager = $this->getProducerManager();
  137. $pointSaleManager = $this->getPointSaleManager();
  138. $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
  139. $pointsSaleArray = $pointSaleManager->findPointSalesByDistributionAsArray($distribution);
  140. // @TODO : à gérer autrement
  141. foreach($pointsSaleArray as &$pointSaleArray) {
  142. $idPointSale = $pointSaleArray['id'];
  143. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  144. if(!isset($pointSaleArray['pointSaleDistribution']) || !$pointSaleArray['pointSaleDistribution'] || !count($pointSaleArray['pointSaleDistribution'])) {
  145. $pointSaleDistribution = $pointSaleDistributionManager->createPointSaleDistributionIfNotExist($distribution, $pointSale);
  146. $pointSaleArray['pointSaleDistribution'] = [
  147. [
  148. 'id_distribution' => $pointSaleDistribution->id_distribution,
  149. 'id_point_sale' => $pointSaleDistribution->id_point_sale,
  150. 'delivery' => $pointSaleDistribution->delivery
  151. ]
  152. ];
  153. }
  154. $pointSaleArray['credit_functioning'] = $producerManager->getPointSaleCreditFunctioning($pointSale);
  155. }
  156. return $pointsSaleArray;
  157. }
  158. public function buildAjaxInfosResponseProducts(Distribution $distribution, array $productsArray, array $ordersArray)
  159. {
  160. $distributionManager = $this->getDistributionManager();
  161. $orderManager = $this->getOrderManager();
  162. $jsonProductsArray = [];
  163. foreach ($productsArray as $product) {
  164. $jsonProduct = $product->getAttributes();
  165. $quantityOrder = $orderManager->getProductQuantity($product, $ordersArray);
  166. $jsonProduct['quantity_ordered'] = $quantityOrder;
  167. if (!isset($product->productDistribution[0])) {
  168. $productDistributionAdd = $distributionManager->addProduct($distribution, $product);
  169. if($productDistributionAdd) {
  170. $jsonProduct['productDistribution'][0] = $productDistributionAdd->getAttributes();
  171. $product->populateRelation('productDistribution', [$productDistributionAdd]);
  172. }
  173. }
  174. else {
  175. foreach($product->productDistribution as $key => $productDistribution) {
  176. $jsonProduct['productDistribution'][$key] = $productDistribution->getAttributes();
  177. }
  178. }
  179. if (!isset($product->productDistribution[0]) || !is_numeric($product->productDistribution[0]->quantity_max)) {
  180. $jsonProduct['quantity_remaining'] = null;
  181. } else {
  182. $jsonProduct['quantity_remaining'] = $product->productDistribution[0]->quantity_max - $quantityOrder;
  183. }
  184. $jsonProduct['quantity_form'] = 0;
  185. if ($product->taxRate) {
  186. $jsonProduct['taxRate'] = $product->taxRate->getAttributes();
  187. }
  188. else {
  189. $jsonProduct['taxRate'] = $this->getProducerCurrent()->taxRate->getAttributes();
  190. }
  191. $jsonProductsArray[] = $jsonProduct;
  192. }
  193. return $jsonProductsArray;
  194. }
  195. public function buildAjaxInfosResponseProducer($producer)
  196. {
  197. return [
  198. 'credit' => $producer->credit,
  199. 'tiller' => $producer->tiller,
  200. 'option_display_export_grid' => $producer->option_display_export_grid
  201. ];
  202. }
  203. public function buildAjaxInfosResponseDistributions($dateObject)
  204. {
  205. $numberOfLoadedMonthes = '3 month';
  206. if (is_object($dateObject)) {
  207. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  208. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  209. } else {
  210. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  211. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  212. }
  213. return Distribution::searchAll([
  214. 'active' => 1
  215. ], [
  216. 'conditions' => [
  217. 'date > :date_begin',
  218. 'date < :date_end'
  219. ],
  220. 'params' => [
  221. ':date_begin' => date(
  222. 'Y-m-d',
  223. $dateBegin
  224. ),
  225. ':date_end' => date(
  226. 'Y-m-d',
  227. $dateEnd
  228. ),
  229. ],
  230. 'as_array' => true
  231. ]);
  232. }
  233. public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray, array $productsArray)
  234. {
  235. $productManager = $this->getProductManager();
  236. $orderManager = $this->getOrderManager();
  237. $distributionJsonData = [
  238. 'id' => $distribution->id,
  239. 'active' => $distribution->active,
  240. 'url_report' => $this->getUrlManagerBackend()->createUrl(
  241. ['distribution/report', 'date' => $distribution->date]
  242. ),
  243. 'url_report_grid' => $this->getUrlManagerBackend()->createUrl(
  244. ['distribution/report-grid', 'date' => $distribution->date]
  245. ),
  246. 'url_export_shopping_cart_labels' => $this->getUrlManagerBackend()->createUrl(
  247. ['distribution/export-shopping-cart-labels', 'date' => $distribution->date]
  248. ),
  249. ];
  250. // montant et poids des commandes
  251. $revenues = 0;
  252. $weight = 0;
  253. if ($ordersArray) {
  254. foreach ($ordersArray as $order) {
  255. $orderManager->initOrder($order);
  256. if (is_null($order->date_delete)) {
  257. $revenues += $orderManager->getOrderAmountWithTax($order);
  258. $weight += $order->weight;
  259. }
  260. }
  261. }
  262. $distributionJsonData['revenues'] = Price::format($revenues);
  263. $distributionJsonData['weight'] = number_format($weight, 2);
  264. $distributionJsonData['potential_revenues'] = Price::format($productManager->getProductDistributionPotentialRevenues($productsArray));
  265. $distributionJsonData['potential_weight'] = number_format($productManager->getProductDistributionPotentialWeight($productsArray), 2);
  266. return $distributionJsonData;
  267. }
  268. public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
  269. {
  270. $userModule = $this->getUserModule();
  271. $orderManager = $this->getOrderManager();
  272. $paymentManager = $this->getPaymentManager();
  273. if ($ordersArray) {
  274. foreach ($ordersArray as &$order) {
  275. $orderManager->initOrder($order);
  276. $productOrderArray = [];
  277. foreach ($order->productOrder as $productOrder) {
  278. $productOrderArray[$productOrder->id_product] = [
  279. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  280. 'unit' => $productOrder->unit,
  281. 'price' => number_format($productOrder->price, 5),
  282. 'invoice_price' => number_format($productOrder->invoice_price, 5),
  283. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  284. ];
  285. }
  286. foreach ($productsArray as $product) {
  287. if (!isset($productOrderArray[$product['id']])) {
  288. $productOrderArray[$product['id']] = [
  289. 'quantity' => 0,
  290. 'unit' => $product['unit'],
  291. 'price' => number_format($product['price'], 5),
  292. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  293. ];
  294. }
  295. }
  296. $paymentArray = [];
  297. foreach ($order->payment as $payment) {
  298. $paymentArray[] = [
  299. 'type' => $payment->type,
  300. 'wording_type' => $paymentManager->getStrType($payment),
  301. 'mean_payment' => $payment->mean_payment,
  302. 'wording_mean_payment' => $paymentManager->getStrMeanPayment($payment),
  303. 'date' => date('d/m/Y H:i:s', strtotime($payment->date)),
  304. 'user' => $payment->getUserObject() ? $userModule->getUsername($payment->getUserObject()) : '',
  305. 'user_action' => $paymentManager->getStrUserAction($payment),
  306. 'wording' => $paymentManager->getStrWording($payment, $order),
  307. 'amount' => $paymentManager->getAmount($payment, Order::AMOUNT_TOTAL, true),
  308. ];
  309. }
  310. $arrayCreditUser = [];
  311. if(isset($order->user)) {
  312. $arrayCreditUser['credit'] = $userModule->getCredit($order->user);
  313. $arrayCreditUser['credit_active'] = $userModule->getCreditActive($order->user);
  314. }
  315. $oneProductUnactivated = false;
  316. foreach ($order->productOrder as $productOrder) {
  317. foreach ($productsArray as $product) {
  318. if ($productOrder->id_product == $product['id'] && isset($product['productDistribution'][0]) && !$product['productDistribution'][0]['active']) {
  319. $oneProductUnactivated = true;
  320. }
  321. }
  322. }
  323. $order = array_merge($order->getAttributes(), [
  324. 'selected' => false,
  325. 'weight' => $order->weight,
  326. 'amount' => (float) Price::numberTwoDecimals($orderManager->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  327. 'amount_paid' => (float) Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_PAID)),
  328. 'amount_remaining' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING)),
  329. 'amount_surplus' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
  330. 'user' => (isset($order->user)) ? array_merge(
  331. $order->user->getAttributes(),
  332. $arrayCreditUser
  333. ) : null,
  334. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  335. 'productOrder' => $productOrderArray,
  336. 'paymentsArray' => $paymentArray,
  337. 'oneProductUnactivated' => $oneProductUnactivated,
  338. 'isLinkedToValidDocument' => $orderManager->isLinkedToValidDocument($order),
  339. 'isLinkedToValidInvoice' => $orderManager->isLinkedToValidInvoice($order),
  340. 'isCreditAutoPayment' => $orderManager->isCreditAutoPayment($order),
  341. 'isCreditContext' => $orderManager->isCreditContext($order),
  342. 'isPaid' => $orderManager->isOrderPaid($order),
  343. 'isPaidViaInvoice' => $orderManager->isOrderPaidViaInvoice($order),
  344. 'paymentLabelShort' => $orderManager->getPaymentLabelShort($order),
  345. 'isCreditFunctioningMandatory' => $orderManager->isOrderCreditFunctioningMandatory($order),
  346. 'isCreditFunctioningUser' => $orderManager->isOrderCreditFunctioningUser($order),
  347. 'debitCredit' => false,
  348. ]);
  349. }
  350. }
  351. return $ordersArray;
  352. }
  353. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  354. {
  355. $deliveryNotesArray = DeliveryNote::searchAll([
  356. 'distribution.date' => $date,
  357. ], [
  358. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  359. ]);
  360. $deliveryNotesByPointSaleArray = [];
  361. foreach ($deliveryNotesArray as $deliveryNote) {
  362. if (isset($deliveryNote->orders[0])) {
  363. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  364. $deliveryNote->getAttributes();
  365. }
  366. }
  367. return $deliveryNotesByPointSaleArray;
  368. }
  369. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  370. {
  371. $pointSaleManager = $this->getPointSaleManager();
  372. $pointSaleDefault = $pointSaleManager->findOnePointSaleDefaultByDistribution($distribution);
  373. $productOrderArray = [];
  374. foreach ($productsArray as $product) {
  375. $productOrderArray[$product['id']] = [
  376. 'quantity' => 0,
  377. 'unit' => $product['unit'],
  378. 'price' => number_format($product['price'], 5),
  379. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  380. ];
  381. }
  382. return [
  383. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
  384. 'id_user' => 0,
  385. 'username' => '',
  386. 'comment' => '',
  387. 'productOrder' => $productOrderArray
  388. ];
  389. }
  390. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  391. {
  392. if ($producer->tiller) {
  393. $tiller = new Tiller();
  394. return (int) $tiller->isSynchro($date);
  395. }
  396. return false;
  397. }
  398. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  399. {
  400. $subscriptionManager = $this->getSubscriptionManager();
  401. $missingSubscriptionsArray = [];
  402. $arraySubscriptions = $subscriptionManager->findSubscriptionsByDate($date);
  403. if ($distribution->active) {
  404. foreach ($arraySubscriptions as $subscription) {
  405. if (!$subscriptionManager->hasOrderAlreadyExist($subscription, $ordersArray)
  406. && $subscription->productSubscription && count($subscription->productSubscription)
  407. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  408. $missingSubscriptionsArray[] = [
  409. 'username' => $subscriptionManager->getUsername($subscription)
  410. ];
  411. }
  412. }
  413. }
  414. return $missingSubscriptionsArray;
  415. }
  416. public function actionAjaxPointSaleFavorite($idUser)
  417. {
  418. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  419. $userModule = $this->getUserModule();
  420. $orderManager = $this->getOrderManager();
  421. $user = $userModule->findOneUserById($idUser);
  422. $idFavoritePointSale = 0;
  423. if($user) {
  424. $favoritePointSale = $orderManager->getUserFavoritePointSale($user);
  425. if ($favoritePointSale) {
  426. $idFavoritePointSale = $favoritePointSale->id;
  427. }
  428. }
  429. return [
  430. 'id_favorite_point_sale' => $idFavoritePointSale
  431. ];
  432. }
  433. public function actionAjaxUpdateProductOrder(
  434. $idDistribution,
  435. $idUser = false,
  436. $idPointSale = false,
  437. $idOrder = false
  438. )
  439. {
  440. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  441. $distributionManager = $this->getDistributionManager();
  442. $orderManager = $this->getOrderManager();
  443. $userModule = $this->getUserModule();
  444. $pointSaleManager = $this->getPointSaleManager();
  445. $productManager = $this->getProductManager();
  446. $order = $orderManager->findOneOrderById($idOrder);
  447. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  448. $user = $userModule->findOneUserById($idUser);
  449. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  450. $productsArray = Product::find()
  451. ->where([
  452. 'id_producer' => GlobalParam::getCurrentProducerId(),
  453. ])->joinWith([
  454. 'productPrice',
  455. 'productDistribution' => function ($q) use ($distribution) {
  456. $q->where(['id_distribution' => $distribution->id]);
  457. }
  458. ])->all();
  459. $productOrderArray = [];
  460. foreach ($productsArray as $product) {
  461. $priceArray = $productManager->getPriceArray($product, $user, $pointSale);
  462. $quantity = 0;
  463. $invoicePrice = null;
  464. if (isset($order->productOrder)) {
  465. foreach ($order->productOrder as $productOrder) {
  466. if ($productOrder->id_product == $product['id']) {
  467. if ($productOrder->invoice_price) {
  468. $invoicePrice = number_format($productOrder->invoice_price, 5);
  469. } else {
  470. $invoicePrice = number_format($productOrder->price, 5);
  471. }
  472. $quantity = $productOrder->quantity;
  473. }
  474. }
  475. }
  476. $productOrderArray[$product['id']] = [
  477. 'quantity' => $quantity,
  478. 'unit' => $product->unit,
  479. 'prices' => $priceArray,
  480. 'active' => $product->productDistribution[0]->active
  481. && (!$pointSale || $productManager->isAvailableOnPointSale($product, $pointSale)),
  482. 'invoice_price' => $invoicePrice
  483. ];
  484. }
  485. return $productOrderArray;
  486. }
  487. public function actionAjaxUpdateInvoicePrices($idOrder)
  488. {
  489. $orderManager = $this->getOrderManager();
  490. $userProducerManager = $this->getUserProducerManager();
  491. $productManager = $this->getProductManager();
  492. $order = $orderManager->findOneOrderById($idOrder);
  493. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  494. $userProducer = null;
  495. if ($order->id_user) {
  496. $userProducer = $userProducerManager->findOneUserProducer($order->user);
  497. }
  498. foreach ($order->productOrder as $productOrder) {
  499. $invoicePrice = $productManager->getPrice($productOrder->product, [
  500. 'user' => $order->user ?: null,
  501. 'point_sale' => $order->pointSale,
  502. 'user_producer' => $userProducer,
  503. 'quantity' => $productOrder->quantity
  504. ]);
  505. if ($invoicePrice != $productOrder->price) {
  506. $productOrder->invoice_price = $invoicePrice;
  507. } else {
  508. $productOrder->invoice_price = null;
  509. }
  510. $productOrder->save();
  511. }
  512. }
  513. }
  514. /**
  515. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  516. * date donnée (Méthode appelable via CRON)
  517. *
  518. * @param string $date
  519. * @param boolean $save
  520. * @param integer $idProducer
  521. * @param string $key
  522. * @return Pdf|null
  523. */
  524. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  525. {
  526. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  527. $this->actionReport($date, $save, $idProducer);
  528. }
  529. }
  530. /**
  531. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  532. * date donnée.
  533. */
  534. public function actionReport(string $date = '', bool $save = false, int $idProducer = 0, string $type = "pdf")
  535. {
  536. if (!$idProducer) {
  537. $idProducer = $this->getProducerCurrent()->id;
  538. }
  539. $distributionManager = $this->getDistributionManager();
  540. $producerManager = $this->getProducerManager();
  541. $producerCurrent = $producerManager->findOneProducerById($idProducer);
  542. $this->getLogic()->setProducerContext($producerCurrent);
  543. $distribution = $distributionManager->findOneDistribution($date);
  544. if ($distribution) {
  545. if ($type == 'pdf') {
  546. return $distributionManager->generateDistributionReportPdf($distribution, $save);
  547. }
  548. elseif ($type == 'csv') {
  549. $distributionManager->generateDistributionReportCsv($distribution);
  550. }
  551. }
  552. }
  553. public function actionReportGrid(string $date = '', bool $save = false, int $idProducer = 0)
  554. {
  555. if (!$idProducer) {
  556. $idProducer = $this->getProducerCurrent()->id;
  557. }
  558. $distributionManager = $this->getDistributionManager();
  559. $producerManager = $this->getProducerManager();
  560. $producerCurrent = $producerManager->findOneProducerById($idProducer);
  561. $this->getLogic()->setProducerContext($producerCurrent);
  562. $distribution = $distributionManager->findOneDistribution($date);
  563. if ($distribution) {
  564. return $distributionManager->generateDistributionReportGridPdf($distribution, $save);
  565. }
  566. }
  567. public function actionExportShoppingCartLabels(string $date)
  568. {
  569. $distributionManager = $this->getDistributionManager();
  570. $distribution = $distributionManager->findOneDistribution($date);
  571. if($distribution) {
  572. return $distributionManager->generateDistributionShoppingCartLabelsPdf($distribution);
  573. }
  574. }
  575. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  576. {
  577. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  578. $productDistributionManager = $this->getProductDistributionManager();
  579. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  580. $productDistributionManager->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  581. return ['success'];
  582. }
  583. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  584. {
  585. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  586. $productDistributionManager = $this->getProductDistributionManager();
  587. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  588. $productDistributionManager->updateProductDistributionActive($productDistribution, $active);
  589. return ['success'];
  590. }
  591. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  592. {
  593. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  594. $distributionManager = $this->getDistributionManager();
  595. $pointSaleManager = $this->getPointSaleManager();
  596. $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
  597. $pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution(
  598. $distributionManager->findOneDistributionById($idDistribution),
  599. $pointSaleManager->findOnePointSaleById($idPointSale)
  600. );
  601. $pointSaleDistribution->delivery = $delivery;
  602. $pointSaleDistributionManager->update($pointSaleDistribution);
  603. return ['success'];
  604. }
  605. public function getProductDistribution(int $idProduct, int $idDistribution)
  606. {
  607. $distributionManager = $this->getDistributionManager();
  608. $productManager = $this->getProductManager();
  609. $productDistributionManager = $this->getProductDistributionManager();
  610. return $productDistributionManager->findOneProductDistribution(
  611. $distributionManager->findOneDistributionById($idDistribution),
  612. $productManager->findOneProductById($idProduct)
  613. );
  614. }
  615. /**
  616. * Active/désactive un jour de distribution.
  617. *
  618. * @param integer $idDistribution
  619. * @param string $date
  620. * @param boolean $active
  621. * @return array
  622. */
  623. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  624. {
  625. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  626. $distributionManager = $this->getDistributionManager();
  627. if ($idDistribution) {
  628. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  629. }
  630. $format = 'Y-m-d';
  631. $dateObject = DateTime::createFromFormat($format, $date);
  632. if ($dateObject && $dateObject->format($format) === $date) {
  633. $distribution = $distributionManager->createDistributionIfNotExist($date);
  634. }
  635. if (isset($distribution) && $distribution) {
  636. $distributionManager->activeDistribution($distribution, $active);
  637. return ['success'];
  638. }
  639. return ['error'];
  640. }
  641. /**
  642. * Change l'état d'une semaine de production (activé, désactivé).
  643. *
  644. * @param string $date
  645. * @param integer $active
  646. */
  647. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  648. {
  649. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  650. $week = sprintf('%02d', date('W', strtotime($date)));
  651. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  652. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  653. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  654. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  655. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  656. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  657. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  658. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  659. $pointsSaleArray = PointSale::searchAll(['status' => 1]);
  660. $activeMonday = false;
  661. $activeTuesday = false;
  662. $activeWednesday = false;
  663. $activeThursday = false;
  664. $activeFriday = false;
  665. $activeSaturday = false;
  666. $activeSunday = false;
  667. foreach ($pointsSaleArray as $pointSale) {
  668. if ($pointSale->delivery_monday) {
  669. $activeMonday = true;
  670. }
  671. if ($pointSale->delivery_tuesday) {
  672. $activeTuesday = true;
  673. }
  674. if ($pointSale->delivery_wednesday) {
  675. $activeWednesday = true;
  676. }
  677. if ($pointSale->delivery_thursday) {
  678. $activeThursday = true;
  679. }
  680. if ($pointSale->delivery_friday) {
  681. $activeFriday = true;
  682. }
  683. if ($pointSale->delivery_saturday) {
  684. $activeSaturday = true;
  685. }
  686. if ($pointSale->delivery_sunday) {
  687. $activeSunday = true;
  688. }
  689. }
  690. if ($activeMonday || !$active) {
  691. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  692. }
  693. if ($activeTuesday || !$active) {
  694. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  695. }
  696. if ($activeWednesday || !$active) {
  697. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  698. }
  699. if ($activeThursday || !$active) {
  700. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  701. }
  702. if ($activeFriday || !$active) {
  703. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  704. }
  705. if ($activeSaturday || !$active) {
  706. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  707. }
  708. if ($activeSunday || !$active) {
  709. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  710. }
  711. return ['success'];
  712. }
  713. /**
  714. * Ajoute les commandes récurrentes pour une date donnée.
  715. *
  716. * @param string $date
  717. */
  718. public function actionAjaxProcessAddSubscriptions($date)
  719. {
  720. $ordersArray = $this->getOrderManager()->createAllOrdersFromSubscriptions($date, true);
  721. if($ordersArray && count($ordersArray)) {
  722. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  723. }
  724. return Ajax::responseError('Aucun abonnement à importer.');
  725. }
  726. /**
  727. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  728. *
  729. * @param string $date
  730. */
  731. public function actionAjaxProcessSynchroTiller($date)
  732. {
  733. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  734. $producerManager = $this->getProducerManager();
  735. $productOrderManager = $this->getProductOrderManager();
  736. $orderManager = $this->getOrderManager();
  737. $return = [];
  738. $producerTiller = $producerManager->getConfig('tiller');
  739. if ($producerTiller) {
  740. $tiller = new Tiller();
  741. $isSynchro = $tiller->isSynchro($date);
  742. if (!$isSynchro) {
  743. $orders = Order::searchAll([
  744. 'distribution.date' => $date,
  745. 'order.tiller_synchronization' => 1
  746. ], [
  747. 'conditions' => 'date_delete IS NULL'
  748. ]);
  749. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  750. if ($orders && count($orders)) {
  751. foreach ($orders as $order) {
  752. $orderManager->initOrder($order);
  753. $lines = [];
  754. foreach ($order->productOrder as $productOrder) {
  755. $lines[] = [
  756. 'name' => $productOrder->product->name,
  757. 'price' => $productOrderManager->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
  758. 'tax' => $productOrder->taxRate->value * 100,
  759. 'date' => $strDate,
  760. 'quantity' => $productOrder->quantity
  761. ];
  762. }
  763. $typePaymentTiller = '';
  764. if ($order->mean_payment == MeanPayment::MONEY) {
  765. $typePaymentTiller = 'CASH';
  766. }
  767. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  768. || $order->mean_payment == MeanPayment::CREDIT
  769. || $order->mean_payment == MeanPayment::TRANSFER
  770. || $order->mean_payment == MeanPayment::OTHER) {
  771. $typePaymentTiller = 'CARD';
  772. }
  773. if ($order->mean_payment == MeanPayment::CHEQUE) {
  774. $typePaymentTiller = 'BANK_CHECK';
  775. }
  776. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  777. $typePaymentTiller = 'CASH';
  778. }
  779. if(!$tiller->isSynchro($date, $order->id)) {
  780. $returnTiller = $tiller->postOrder([
  781. 'externalId' => $order->id,
  782. 'type' => 1,
  783. 'status' => 'IN_PROGRESS',
  784. 'openDate' => $strDate,
  785. 'closeDate' => $strDate,
  786. 'lines' => $lines,
  787. 'payments' => [
  788. [
  789. 'type' => $typePaymentTiller,
  790. 'amount' => $orderManager->getOrderAmountWithTax(
  791. $order,
  792. Order::AMOUNT_PAID
  793. ) * 100,
  794. 'status' => 'ACCEPTED',
  795. 'date' => $strDate
  796. ]
  797. ]
  798. ]);
  799. $returnTillerObject = json_decode($returnTiller);
  800. $order->tiller_external_id = '' . $returnTillerObject->id;
  801. $order->save();
  802. $return[] = $returnTiller;
  803. }
  804. }
  805. }
  806. }
  807. }
  808. return $return;
  809. }
  810. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  811. {
  812. $this->generateDeliveryNote($idOrder);
  813. return Ajax::responseSuccess('Bon de livraison généré');
  814. }
  815. public function actionAjaxGenerateDeliveryNotePointSale($idOrders)
  816. {
  817. $orderManager = $this->getOrderManager();
  818. $deliveryNoteManager = $this->getDeliveryNoteManager();
  819. if (strlen($idOrders)) {
  820. $idOrders = json_decode($idOrders, true);
  821. if (is_array($idOrders) && count($idOrders) > 0) {
  822. reset($idOrders);
  823. $firstOrder = $orderManager->findOneOrderById((int)$idOrders[key($idOrders)]);
  824. $ordersArray = Order::searchAll(['id' => $idOrders,]);
  825. $deliveryNote = $deliveryNoteManager->getOneDeliveryNoteExistingFromOrders($ordersArray);
  826. $isUpdate = (bool) $deliveryNote;
  827. if ($deliveryNote && $deliveryNoteManager->isStatusValid($deliveryNote)) {
  828. return Ajax::responseError('Vous ne pouvez pas modifier un bon de livraison déjà validé.');
  829. }
  830. if(!$deliveryNote && $firstOrder && !$firstOrder->pointSale->id_user) {
  831. return Ajax::responseError("Vous devez définir un contact de facturation pour ce point de vente.");
  832. }
  833. if ($firstOrder) {
  834. if (!$deliveryNote) {
  835. $deliveryNoteManager->createDeliveryNoteForPointSale(
  836. $firstOrder->pointSale,
  837. $firstOrder->distribution,
  838. $idOrders
  839. );
  840. }
  841. return Ajax::responseSuccess('Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré'));
  842. }
  843. }
  844. }
  845. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  846. }
  847. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  848. {
  849. if (strlen($idOrders)) {
  850. $idOrders = json_decode($idOrders, true);
  851. if (is_array($idOrders) && count($idOrders) > 0) {
  852. foreach ($idOrders as $idOrder) {
  853. $this->generateDeliveryNote($idOrder);
  854. }
  855. }
  856. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  857. }
  858. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  859. }
  860. public function generateDeliveryNote(int $idOrder)
  861. {
  862. $orderManager = $this->getOrderManager();
  863. $deliveryNoteManager = $this->getDeliveryNoteManager();
  864. $order = $orderManager->findOneOrderById($idOrder);
  865. if ($orderManager->isOrderFromProducer($order) && $order->id_user) {
  866. $deliveryNoteManager->createDeliveryNoteForOrder($order);
  867. }
  868. }
  869. public function actionAjaxValidateDeliveryNotes($idOrders)
  870. {
  871. $orderManager = $this->getOrderManager();
  872. $deliveryNoteManager = $this->getDeliveryNoteManager();
  873. if (strlen($idOrders)) {
  874. $idOrders = json_decode($idOrders, true);
  875. if (is_array($idOrders) && count($idOrders) > 0) {
  876. foreach ($idOrders as $idOrder) {
  877. $order = $orderManager->findOneOrderById($idOrder);
  878. if ($orderManager->isOrderFromProducer($order)) {
  879. $deliveryNote = $deliveryNoteManager->findOneDeliveryNoteById((int) $order->id_delivery_note);
  880. if($deliveryNote) {
  881. $deliveryNoteManager->validateDocument($deliveryNote);
  882. }
  883. }
  884. }
  885. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  886. }
  887. }
  888. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  889. }
  890. }