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.

1008 lines
41KB

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