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.

991 lines
40KB

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