Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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