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.

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