You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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