Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1020 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. $userManager = $this->getUserManager();
  75. return $userManager->isCurrentAdmin() || $userManager->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. $userManager = $this->getUserManager();
  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);
  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'] = $userManager->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. $userManager = $this->getUserManager();
  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() ? $userManager->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'] = $userManager->getCredit($order->user);
  313. $arrayCreditUser['credit_active'] = $userManager->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' => Price::numberTwoDecimals($orderManager->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  327. 'amount_paid' => 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. 'isCreditAutoPayment' => $orderManager->isCreditAutoPayment($order),
  340. 'isCreditContext' => $orderManager->isCreditContext($order),
  341. 'isPaid' => $orderManager->isOrderPaid($order),
  342. 'isPaidViaInvoice' => $orderManager->isOrderPaidViaInvoice($order),
  343. 'paymentLabelShort' => $orderManager->getPaymentLabelShort($order),
  344. 'isCreditFunctioningMandatory' => $orderManager->isOrderCreditFunctioningMandatory($order),
  345. 'isCreditFunctioningUser' => $orderManager->isOrderCreditFunctioningUser($order),
  346. ]);
  347. }
  348. }
  349. return $ordersArray;
  350. }
  351. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  352. {
  353. $deliveryNotesArray = DeliveryNote::searchAll([
  354. 'distribution.date' => $date,
  355. ], [
  356. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  357. ]);
  358. $deliveryNotesByPointSaleArray = [];
  359. foreach ($deliveryNotesArray as $deliveryNote) {
  360. if (isset($deliveryNote->orders[0])) {
  361. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  362. $deliveryNote->getAttributes();
  363. }
  364. }
  365. return $deliveryNotesByPointSaleArray;
  366. }
  367. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  368. {
  369. $pointSaleManager = $this->getPointSaleManager();
  370. $pointSaleDefault = $pointSaleManager->findOnePointSaleDefaultByDistribution($distribution);
  371. $productOrderArray = [];
  372. foreach ($productsArray as $product) {
  373. $productOrderArray[$product['id']] = [
  374. 'quantity' => 0,
  375. 'unit' => $product['unit'],
  376. 'price' => number_format($product['price'], 5),
  377. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  378. ];
  379. }
  380. return [
  381. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
  382. 'id_user' => 0,
  383. 'username' => '',
  384. 'comment' => '',
  385. 'productOrder' => $productOrderArray
  386. ];
  387. }
  388. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  389. {
  390. if ($producer->tiller) {
  391. $tiller = new Tiller();
  392. return (int) $tiller->isSynchro($date);
  393. }
  394. return false;
  395. }
  396. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  397. {
  398. $subscriptionManager = $this->getSubscriptionManager();
  399. $missingSubscriptionsArray = [];
  400. $arraySubscriptions = $subscriptionManager->findSubscriptionsByDate($date);
  401. if ($distribution->active) {
  402. foreach ($arraySubscriptions as $subscription) {
  403. if (!$subscriptionManager->hasOrderAlreadyExist($subscription, $ordersArray)
  404. && $subscription->productSubscription && count($subscription->productSubscription)
  405. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  406. $missingSubscriptionsArray[] = [
  407. 'username' => $subscriptionManager->getUsername($subscription)
  408. ];
  409. }
  410. }
  411. }
  412. return $missingSubscriptionsArray;
  413. }
  414. public function actionAjaxPointSaleFavorite($idUser)
  415. {
  416. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  417. $userManager = $this->getUserManager();
  418. $orderManager = $this->getOrderManager();
  419. $user = $userManager->findOneUserById($idUser);
  420. $idFavoritePointSale = 0;
  421. if($user) {
  422. $favoritePointSale = $orderManager->getUserFavoritePointSale($user);
  423. if ($favoritePointSale) {
  424. $idFavoritePointSale = $favoritePointSale->id;
  425. }
  426. }
  427. return [
  428. 'id_favorite_point_sale' => $idFavoritePointSale
  429. ];
  430. }
  431. public function actionAjaxUpdateProductOrder(
  432. $idDistribution,
  433. $idUser = false,
  434. $idPointSale = false,
  435. $idOrder = false
  436. )
  437. {
  438. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  439. $distributionManager = $this->getDistributionManager();
  440. $orderManager = $this->getOrderManager();
  441. $userManager = $this->getUserManager();
  442. $pointSaleManager = $this->getPointSaleManager();
  443. $productManager = $this->getProductManager();
  444. $order = $orderManager->findOneOrderById($idOrder);
  445. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  446. $user = $userManager->findOneUserById($idUser);
  447. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  448. $productsArray = Product::find()
  449. ->where([
  450. 'id_producer' => GlobalParam::getCurrentProducerId(),
  451. ])->joinWith([
  452. 'productPrice',
  453. 'productDistribution' => function ($q) use ($distribution) {
  454. $q->where(['id_distribution' => $distribution->id]);
  455. }
  456. ])->all();
  457. $productOrderArray = [];
  458. foreach ($productsArray as $product) {
  459. $priceArray = $productManager->getPriceArray($product, $user, $pointSale);
  460. $quantity = 0;
  461. $invoicePrice = null;
  462. if (isset($order->productOrder)) {
  463. foreach ($order->productOrder as $productOrder) {
  464. if ($productOrder->id_product == $product['id']) {
  465. if ($productOrder->invoice_price) {
  466. $invoicePrice = number_format($productOrder->invoice_price, 5);
  467. } else {
  468. $invoicePrice = number_format($productOrder->price, 5);
  469. }
  470. $quantity = $productOrder->quantity;
  471. }
  472. }
  473. }
  474. $productOrderArray[$product['id']] = [
  475. 'quantity' => $quantity,
  476. 'unit' => $product->unit,
  477. 'prices' => $priceArray,
  478. 'active' => $product->productDistribution[0]->active
  479. && (!$pointSale || $productManager->isAvailableOnPointSale($product, $pointSale)),
  480. 'invoice_price' => $invoicePrice
  481. ];
  482. }
  483. return $productOrderArray;
  484. }
  485. public function actionAjaxUpdateInvoicePrices($idOrder)
  486. {
  487. $orderManager = $this->getOrderManager();
  488. $userProducerManager = $this->getUserProducerManager();
  489. $productManager = $this->getProductManager();
  490. $order = $orderManager->findOneOrderById($idOrder);
  491. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  492. $userProducer = null;
  493. if ($order->id_user) {
  494. $userProducer = $userProducerManager->findOneUserProducer($order->user);
  495. }
  496. foreach ($order->productOrder as $productOrder) {
  497. $invoicePrice = $productManager->getPrice($productOrder->product, [
  498. 'user' => $order->user ?: null,
  499. 'point_sale' => $order->pointSale,
  500. 'user_producer' => $userProducer,
  501. 'quantity' => $productOrder->quantity
  502. ]);
  503. if ($invoicePrice != $productOrder->price) {
  504. $productOrder->invoice_price = $invoicePrice;
  505. } else {
  506. $productOrder->invoice_price = null;
  507. }
  508. $productOrder->save();
  509. }
  510. }
  511. }
  512. /**
  513. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  514. * date donnée (Méthode appelable via CRON)
  515. *
  516. * @param string $date
  517. * @param boolean $save
  518. * @param integer $idProducer
  519. * @param string $key
  520. * @return Pdf|null
  521. */
  522. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  523. {
  524. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  525. $this->actionReport($date, $save, $idProducer);
  526. }
  527. }
  528. /**
  529. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  530. * date donnée.
  531. */
  532. public function actionReport(string $date = '', bool $save = false, int $idProducer = 0, string $type = "pdf")
  533. {
  534. if (!$idProducer) {
  535. $idProducer = $this->getProducerCurrent()->id;
  536. }
  537. $distributionManager = $this->getDistributionManager();
  538. $producerManager = $this->getProducerManager();
  539. $producerCurrent = $producerManager->findOneProducerById($idProducer);
  540. $this->getLogic()->setProducerContext($producerCurrent);
  541. $distribution = $distributionManager->findOneDistribution($date);
  542. if ($distribution) {
  543. if ($type == 'pdf') {
  544. return $distributionManager->generateDistributionReportPdf($distribution, $save);
  545. }
  546. elseif ($type == 'csv') {
  547. $distributionManager->generateDistributionReportCsv($distribution);
  548. }
  549. }
  550. }
  551. public function actionReportGrid(string $date = '', bool $save = false, int $idProducer = 0)
  552. {
  553. if (!$idProducer) {
  554. $idProducer = $this->getProducerCurrent()->id;
  555. }
  556. $distributionManager = $this->getDistributionManager();
  557. $producerManager = $this->getProducerManager();
  558. $producerCurrent = $producerManager->findOneProducerById($idProducer);
  559. $this->getLogic()->setProducerContext($producerCurrent);
  560. $distribution = $distributionManager->findOneDistribution($date);
  561. if ($distribution) {
  562. return $distributionManager->generateDistributionReportGridPdf($distribution, $save);
  563. }
  564. }
  565. public function actionExportShoppingCartLabels(string $date)
  566. {
  567. $distributionManager = $this->getDistributionManager();
  568. $distribution = $distributionManager->findOneDistribution($date);
  569. if($distribution) {
  570. return $distributionManager->generateDistributionShoppingCartLabelsPdf($distribution);
  571. }
  572. }
  573. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  574. {
  575. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  576. $productDistributionManager = $this->getProductDistributionManager();
  577. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  578. $productDistributionManager->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  579. return ['success'];
  580. }
  581. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  582. {
  583. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  584. $productDistributionManager = $this->getProductDistributionManager();
  585. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  586. $productDistributionManager->updateProductDistributionActive($productDistribution, $active);
  587. return ['success'];
  588. }
  589. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  590. {
  591. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  592. $distributionManager = $this->getDistributionManager();
  593. $pointSaleManager = $this->getPointSaleManager();
  594. $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
  595. $pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution(
  596. $distributionManager->findOneDistributionById($idDistribution),
  597. $pointSaleManager->findOnePointSaleById($idPointSale)
  598. );
  599. $pointSaleDistribution->delivery = $delivery;
  600. $pointSaleDistributionManager->update($pointSaleDistribution);
  601. return ['success'];
  602. }
  603. public function getProductDistribution(int $idProduct, int $idDistribution)
  604. {
  605. $distributionManager = $this->getDistributionManager();
  606. $productManager = $this->getProductManager();
  607. $productDistributionManager = $this->getProductDistributionManager();
  608. return $productDistributionManager->findOneProductDistribution(
  609. $distributionManager->findOneDistributionById($idDistribution),
  610. $productManager->findOneProductById($idProduct)
  611. );
  612. }
  613. /**
  614. * Active/désactive un jour de distribution.
  615. *
  616. * @param integer $idDistribution
  617. * @param string $date
  618. * @param boolean $active
  619. * @return array
  620. */
  621. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  622. {
  623. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  624. $distributionManager = $this->getDistributionManager();
  625. if ($idDistribution) {
  626. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  627. }
  628. $format = 'Y-m-d';
  629. $dateObject = DateTime::createFromFormat($format, $date);
  630. if ($dateObject && $dateObject->format($format) === $date) {
  631. $distribution = $distributionManager->createDistributionIfNotExist($date);
  632. }
  633. if (isset($distribution) && $distribution) {
  634. $distributionManager->activeDistribution($distribution, $active);
  635. return ['success'];
  636. }
  637. return ['error'];
  638. }
  639. /**
  640. * Change l'état d'une semaine de production (activé, désactivé).
  641. *
  642. * @param string $date
  643. * @param integer $active
  644. */
  645. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  646. {
  647. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  648. $week = sprintf('%02d', date('W', strtotime($date)));
  649. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  650. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  651. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  652. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  653. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  654. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  655. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  656. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  657. $pointsSaleArray = PointSale::searchAll(['status' => 1]);
  658. $activeMonday = false;
  659. $activeTuesday = false;
  660. $activeWednesday = false;
  661. $activeThursday = false;
  662. $activeFriday = false;
  663. $activeSaturday = false;
  664. $activeSunday = false;
  665. foreach ($pointsSaleArray as $pointSale) {
  666. if ($pointSale->delivery_monday) {
  667. $activeMonday = true;
  668. }
  669. if ($pointSale->delivery_tuesday) {
  670. $activeTuesday = true;
  671. }
  672. if ($pointSale->delivery_wednesday) {
  673. $activeWednesday = true;
  674. }
  675. if ($pointSale->delivery_thursday) {
  676. $activeThursday = true;
  677. }
  678. if ($pointSale->delivery_friday) {
  679. $activeFriday = true;
  680. }
  681. if ($pointSale->delivery_saturday) {
  682. $activeSaturday = true;
  683. }
  684. if ($pointSale->delivery_sunday) {
  685. $activeSunday = true;
  686. }
  687. }
  688. if ($activeMonday || !$active) {
  689. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  690. }
  691. if ($activeTuesday || !$active) {
  692. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  693. }
  694. if ($activeWednesday || !$active) {
  695. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  696. }
  697. if ($activeThursday || !$active) {
  698. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  699. }
  700. if ($activeFriday || !$active) {
  701. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  702. }
  703. if ($activeSaturday || !$active) {
  704. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  705. }
  706. if ($activeSunday || !$active) {
  707. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  708. }
  709. return ['success'];
  710. }
  711. /**
  712. * Ajoute les commandes récurrentes pour une date donnée.
  713. *
  714. * @param string $date
  715. */
  716. public function actionAjaxProcessAddSubscriptions($date)
  717. {
  718. $ordersArray = $this->getOrderManager()->createAllOrdersFromSubscriptions($date, true);
  719. if($ordersArray && count($ordersArray)) {
  720. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  721. }
  722. return Ajax::responseError('Aucun abonnement à importer.');
  723. }
  724. /**
  725. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  726. *
  727. * @param string $date
  728. */
  729. public function actionAjaxProcessSynchroTiller($date)
  730. {
  731. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  732. $producerManager = $this->getProducerManager();
  733. $productOrderManager = $this->getProductOrderManager();
  734. $orderManager = $this->getOrderManager();
  735. $return = [];
  736. $producerTiller = $producerManager->getConfig('tiller');
  737. if ($producerTiller) {
  738. $tiller = new Tiller();
  739. $isSynchro = $tiller->isSynchro($date);
  740. if (!$isSynchro) {
  741. $orders = Order::searchAll([
  742. 'distribution.date' => $date,
  743. 'order.tiller_synchronization' => 1
  744. ], [
  745. 'conditions' => 'date_delete IS NULL'
  746. ]);
  747. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  748. if ($orders && count($orders)) {
  749. foreach ($orders as $order) {
  750. $orderManager->initOrder($order);
  751. $lines = [];
  752. foreach ($order->productOrder as $productOrder) {
  753. $lines[] = [
  754. 'name' => $productOrder->product->name,
  755. 'price' => $productOrderManager->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
  756. 'tax' => $productOrder->taxRate->value * 100,
  757. 'date' => $strDate,
  758. 'quantity' => $productOrder->quantity
  759. ];
  760. }
  761. $typePaymentTiller = '';
  762. if ($order->mean_payment == MeanPayment::MONEY) {
  763. $typePaymentTiller = 'CASH';
  764. }
  765. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  766. || $order->mean_payment == MeanPayment::CREDIT
  767. || $order->mean_payment == MeanPayment::TRANSFER
  768. || $order->mean_payment == MeanPayment::OTHER) {
  769. $typePaymentTiller = 'CARD';
  770. }
  771. if ($order->mean_payment == MeanPayment::CHEQUE) {
  772. $typePaymentTiller = 'BANK_CHECK';
  773. }
  774. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  775. $typePaymentTiller = 'CASH';
  776. }
  777. $returnTiller = $tiller->postOrder([
  778. 'externalId' => $order->id,
  779. 'type' => 1,
  780. 'status' => 'IN_PROGRESS',
  781. 'openDate' => $strDate,
  782. 'closeDate' => $strDate,
  783. 'lines' => $lines,
  784. 'payments' => [
  785. [
  786. 'type' => $typePaymentTiller,
  787. 'amount' => $orderManager->getOrderAmountWithTax(
  788. $order,
  789. Order::AMOUNT_PAID
  790. ) * 100,
  791. 'status' => 'ACCEPTED',
  792. 'date' => $strDate
  793. ]
  794. ]
  795. ]);
  796. $returnTillerObject = json_decode($returnTiller);
  797. $order->tiller_external_id = '' . $returnTillerObject->id;
  798. $order->save();
  799. $return[] = $returnTiller;
  800. }
  801. }
  802. }
  803. }
  804. return $return;
  805. }
  806. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  807. {
  808. $this->generateDeliveryNote($idOrder);
  809. return Ajax::responseSuccess('Bon de livraison généré');
  810. }
  811. public function actionAjaxGenerateDeliveryNotePointSale($idOrders)
  812. {
  813. $orderManager = $this->getOrderManager();
  814. $deliveryNoteManager = $this->getDeliveryNoteManager();
  815. if (strlen($idOrders)) {
  816. $idOrders = json_decode($idOrders, true);
  817. if (is_array($idOrders) && count($idOrders) > 0) {
  818. reset($idOrders);
  819. $firstOrder = $orderManager->findOneOrderById((int)$idOrders[key($idOrders)]);
  820. $ordersArray = Order::searchAll(['id' => $idOrders,]);
  821. $deliveryNote = $deliveryNoteManager->getOneDeliveryNoteExistingFromOrders($ordersArray);
  822. $isUpdate = (bool) $deliveryNote;
  823. if ($deliveryNote && $deliveryNoteManager->isStatusValid($deliveryNote)) {
  824. return Ajax::responseError('Vous ne pouvez pas modifier un bon de livraison déjà validé.');
  825. }
  826. if(!$deliveryNote && $firstOrder && !$firstOrder->pointSale->id_user) {
  827. return Ajax::responseError("Vous devez définir un contact de facturation pour ce point de vente.");
  828. }
  829. if ($firstOrder) {
  830. if (!$deliveryNote) {
  831. $deliveryNoteManager->createDeliveryNoteForPointSale(
  832. $firstOrder->pointSale,
  833. $firstOrder->distribution,
  834. $idOrders
  835. );
  836. }
  837. return Ajax::responseSuccess('Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré'));
  838. }
  839. }
  840. }
  841. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  842. }
  843. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  844. {
  845. if (strlen($idOrders)) {
  846. $idOrders = json_decode($idOrders, true);
  847. if (is_array($idOrders) && count($idOrders) > 0) {
  848. foreach ($idOrders as $idOrder) {
  849. $this->generateDeliveryNote($idOrder);
  850. }
  851. }
  852. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  853. }
  854. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  855. }
  856. public function generateDeliveryNote(int $idOrder)
  857. {
  858. $orderManager = $this->getOrderManager();
  859. $deliveryNoteManager = $this->getDeliveryNoteManager();
  860. $order = $orderManager->findOneOrderById($idOrder);
  861. if ($orderManager->isOrderFromProducer($order) && $order->id_user) {
  862. $deliveryNoteManager->createDeliveryNoteForOrder($order);
  863. }
  864. }
  865. public function actionAjaxValidateDeliveryNotes($idOrders)
  866. {
  867. $orderManager = $this->getOrderManager();
  868. $deliveryNoteManager = $this->getDeliveryNoteManager();
  869. if (strlen($idOrders)) {
  870. $idOrders = json_decode($idOrders, true);
  871. if (is_array($idOrders) && count($idOrders) > 0) {
  872. foreach ($idOrders as $idOrder) {
  873. $order = $orderManager->findOneOrderById($idOrder);
  874. if ($orderManager->isOrderFromProducer($order)) {
  875. $deliveryNote = $deliveryNoteManager->findOneDeliveryNoteById((int) $order->id_delivery_note);
  876. if($deliveryNote) {
  877. $deliveryNoteManager->validateDocument($deliveryNote);
  878. }
  879. }
  880. }
  881. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  882. }
  883. }
  884. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  885. }
  886. }