選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1004 行
41KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace backend\controllers;
  38. use common\helpers\Ajax;
  39. use common\helpers\CSV;
  40. use common\helpers\GlobalParam;
  41. use common\helpers\MeanPayment;
  42. use common\helpers\Password;
  43. use common\helpers\Price;
  44. use common\helpers\Tiller;
  45. use common\logic\Distribution\Distribution\Model\Distribution;
  46. use common\logic\Document\DeliveryNote\Model\DeliveryNote;
  47. use common\logic\Document\Document\Model\Document;
  48. use common\logic\Order\Order\Model\Order;
  49. use common\logic\PointSale\PointSale\Model\PointSale;
  50. use common\logic\Producer\Producer\Model\Producer;
  51. use common\logic\Product\Product\Model\Product;
  52. use common\logic\User\User\Model\User;
  53. use common\logic\User\UserProducer\Model\UserProducer;
  54. use DateTime;
  55. use kartik\mpdf\Pdf;
  56. use yii\filters\AccessControl;
  57. class DistributionController extends BackendController
  58. {
  59. public function behaviors()
  60. {
  61. return [
  62. 'access' => [
  63. 'class' => AccessControl::class,
  64. 'rules' => [
  65. [
  66. 'actions' => ['report-cron', 'report-terredepains'],
  67. 'allow' => true,
  68. 'roles' => ['?']
  69. ],
  70. [
  71. 'allow' => true,
  72. 'roles' => ['@'],
  73. 'matchCallback' => function ($rule, $action) {
  74. $userManager = $this->getUserManager();
  75. return $userManager->isCurrentAdmin() || $userManager->isCurrentProducer();
  76. }
  77. ]
  78. ],
  79. ],
  80. ];
  81. }
  82. public function actionIndex($date = '', $idOrderUpdate = 0)
  83. {
  84. $this->checkProductsPointsSale();
  85. $orderManager = $this->getOrderManager();
  86. $format = 'Y-m-d';
  87. $theDate = '';
  88. $dateObject = DateTime::createFromFormat($format, $date);
  89. if ($dateObject && $dateObject->format($format) === $date) {
  90. $theDate = $date;
  91. }
  92. $orderUpdate = null;
  93. if ($idOrderUpdate) {
  94. $orderUpdate = $orderManager->findOneOrderById($idOrderUpdate);
  95. }
  96. return $this->render('index', [
  97. 'date' => $theDate,
  98. 'orderUpdate' => $orderUpdate
  99. ]);
  100. }
  101. public function actionAjaxInfos($date = '')
  102. {
  103. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  104. $distributionManager = $this->getDistributionManager();
  105. $orderManager = $this->getOrderManager();
  106. $productManager = $this->getProductManager();
  107. $userManager = $this->getUserManager();
  108. $pointSaleManager = $this->getPointSaleManager();
  109. $producer = $this->getProducerCurrent();
  110. $format = 'Y-m-d';
  111. $dateObject = DateTime::createFromFormat($format, $date);
  112. $json = ['distribution' => [], 'products' => []];
  113. $json['means_payment'] = MeanPayment::getAll();
  114. $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
  115. $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
  116. if ($dateObject && $dateObject->format($format) === $date) {
  117. $distribution = $distributionManager->createDistributionIfNotExist($date);
  118. $ordersArray = $orderManager->findOrdersByDistribution($distribution);
  119. $ordersArrayObject = $ordersArray;
  120. $productsArray = $productManager->findProductsByDistribution($distribution);
  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. $jsonProduct['productDistribution'][0] = $productDistributionAdd->getAttributes();
  170. $product->populateRelation('productDistribution', [$productDistributionAdd]);
  171. }
  172. else {
  173. foreach($product->productDistribution as $key => $productDistribution) {
  174. $jsonProduct['productDistribution'][$key] = $productDistribution->getAttributes();
  175. }
  176. }
  177. if (!is_numeric($product->productDistribution[0]->quantity_max)) {
  178. $jsonProduct['quantity_remaining'] = null;
  179. } else {
  180. $jsonProduct['quantity_remaining'] = $product->productDistribution[0]->quantity_max - $quantityOrder;
  181. }
  182. $jsonProduct['quantity_form'] = 0;
  183. if (!$product->taxRate) {
  184. $jsonProduct['taxRate'] = $this->getProducerCurrent()->taxRate;
  185. }
  186. $jsonProductsArray[] = $jsonProduct;
  187. }
  188. return $jsonProductsArray;
  189. }
  190. public function buildAjaxInfosResponseProducer($producer)
  191. {
  192. return [
  193. 'credit' => $producer->credit,
  194. 'tiller' => $producer->tiller,
  195. 'option_display_export_grid' => $producer->option_display_export_grid
  196. ];
  197. }
  198. public function buildAjaxInfosResponseDistributions($dateObject)
  199. {
  200. $numberOfLoadedMonthes = '3 month';
  201. if (is_object($dateObject)) {
  202. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  203. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  204. } else {
  205. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  206. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  207. }
  208. return Distribution::searchAll([
  209. 'active' => 1
  210. ], [
  211. 'conditions' => [
  212. 'date > :date_begin',
  213. 'date < :date_end'
  214. ],
  215. 'params' => [
  216. ':date_begin' => date(
  217. 'Y-m-d',
  218. $dateBegin
  219. ),
  220. ':date_end' => date(
  221. 'Y-m-d',
  222. $dateEnd
  223. ),
  224. ],
  225. 'as_array' => true
  226. ]);
  227. }
  228. public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray, array $productsArray)
  229. {
  230. $productManager = $this->getProductManager();
  231. $orderManager = $this->getOrderManager();
  232. $distributionJsonData = [
  233. 'id' => $distribution->id,
  234. 'active' => $distribution->active,
  235. 'url_report' => $this->getUrlManagerBackend()->createUrl(
  236. ['distribution/report', 'date' => $distribution->date]
  237. ),
  238. 'url_report_grid' => $this->getUrlManagerBackend()->createUrl(
  239. ['distribution/report-grid', 'date' => $distribution->date]
  240. ),
  241. ];
  242. // montant et poids des commandes
  243. $revenues = 0;
  244. $weight = 0;
  245. if ($ordersArray) {
  246. foreach ($ordersArray as $order) {
  247. $orderManager->initOrder($order);
  248. if (is_null($order->date_delete)) {
  249. $revenues += $orderManager->getOrderAmountWithTax($order);
  250. $weight += $order->weight;
  251. }
  252. }
  253. }
  254. $distributionJsonData['revenues'] = Price::format($revenues);
  255. $distributionJsonData['weight'] = number_format($weight, 2);
  256. $distributionJsonData['potential_revenues'] = Price::format($productManager->getProductDistributionPotentialRevenues($productsArray));
  257. $distributionJsonData['potential_weight'] = number_format($productManager->getProductDistributionPotentialWeight($productsArray), 2);
  258. return $distributionJsonData;
  259. }
  260. public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
  261. {
  262. $userManager = $this->getUserManager();
  263. $orderManager = $this->getOrderManager();
  264. $paymentManager = $this->getPaymentManager();
  265. if ($ordersArray) {
  266. foreach ($ordersArray as &$order) {
  267. $orderManager->initOrder($order);
  268. $productOrderArray = [];
  269. foreach ($order->productOrder as $productOrder) {
  270. $productOrderArray[$productOrder->id_product] = [
  271. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  272. 'unit' => $productOrder->unit,
  273. 'price' => number_format($productOrder->price, 5),
  274. 'invoice_price' => number_format($productOrder->invoice_price, 5),
  275. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  276. ];
  277. }
  278. foreach ($productsArray as $product) {
  279. if (!isset($productOrderArray[$product['id']])) {
  280. $productOrderArray[$product['id']] = [
  281. 'quantity' => 0,
  282. 'unit' => $product['unit'],
  283. 'price' => number_format($product['price'], 5),
  284. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  285. ];
  286. }
  287. }
  288. $paymentArray = [];
  289. foreach ($order->payment as $payment) {
  290. $paymentArray[] = [
  291. 'type' => $payment->type,
  292. 'wording_type' => $paymentManager->getStrType($payment),
  293. 'mean_payment' => $payment->mean_payment,
  294. 'wording_mean_payment' => $paymentManager->getStrMeanPayment($payment),
  295. 'date' => date('d/m/Y H:i:s', strtotime($payment->date)),
  296. 'user' => $payment->getUserObject() ? $userManager->getUsername($payment->getUserObject()) : '',
  297. 'user_action' => $paymentManager->getStrUserAction($payment),
  298. 'wording' => $paymentManager->getStrWording($payment, $order),
  299. 'amount' => $paymentManager->getAmount($payment, Order::AMOUNT_TOTAL, true),
  300. ];
  301. }
  302. $arrayCreditUser = [];
  303. if(isset($order->user)) {
  304. $arrayCreditUser['credit'] = $userManager->getCredit($order->user);
  305. $arrayCreditUser['credit_active'] = $userManager->getCreditActive($order->user);
  306. }
  307. $oneProductUnactivated = false;
  308. foreach ($order->productOrder as $productOrder) {
  309. foreach ($productsArray as $product) {
  310. if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  311. $oneProductUnactivated = true;
  312. }
  313. }
  314. }
  315. $order = array_merge($order->getAttributes(), [
  316. 'selected' => false,
  317. 'weight' => $order->weight,
  318. 'amount' => Price::numberTwoDecimals($orderManager->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  319. 'amount_paid' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_PAID)),
  320. 'amount_remaining' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING)),
  321. 'amount_surplus' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
  322. 'user' => (isset($order->user)) ? array_merge(
  323. $order->user->getAttributes(),
  324. $arrayCreditUser
  325. ) : null,
  326. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  327. 'productOrder' => $productOrderArray,
  328. 'paymentsArray' => $paymentArray,
  329. 'oneProductUnactivated' => $oneProductUnactivated,
  330. 'isLinkedToValidDocument' => $orderManager->isLinkedToValidDocument($order),
  331. 'isCreditAutoPayment' => $orderManager->isCreditAutoPayment($order),
  332. 'isCreditContext' => $orderManager->isCreditContext($order),
  333. 'isPaid' => $orderManager->isOrderPaid($order),
  334. 'isPaidViaInvoice' => $orderManager->isOrderPaidViaInvoice($order),
  335. 'paymentLabelShort' => $orderManager->getPaymentLabelShort($order),
  336. 'isCreditFunctioningMandatory' => $orderManager->isOrderCreditFunctioningMandatory($order),
  337. 'isCreditFunctioningUser' => $orderManager->isOrderCreditFunctioningUser($order),
  338. ]);
  339. }
  340. }
  341. return $ordersArray;
  342. }
  343. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  344. {
  345. $deliveryNotesArray = DeliveryNote::searchAll([
  346. 'distribution.date' => $date,
  347. ], [
  348. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  349. ]);
  350. $deliveryNotesByPointSaleArray = [];
  351. foreach ($deliveryNotesArray as $deliveryNote) {
  352. if (isset($deliveryNote->orders[0])) {
  353. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  354. $deliveryNote->getAttributes();
  355. }
  356. }
  357. return $deliveryNotesByPointSaleArray;
  358. }
  359. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  360. {
  361. $pointSaleManager = $this->getPointSaleManager();
  362. $pointSaleDefault = $pointSaleManager->findOnePointSaleDefaultByDistribution($distribution);
  363. $productOrderArray = [];
  364. foreach ($productsArray as $product) {
  365. $productOrderArray[$product['id']] = [
  366. 'quantity' => 0,
  367. 'unit' => $product['unit'],
  368. 'price' => number_format($product['price'], 5),
  369. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  370. ];
  371. }
  372. return [
  373. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
  374. 'id_user' => 0,
  375. 'username' => '',
  376. 'comment' => '',
  377. 'productOrder' => $productOrderArray
  378. ];
  379. }
  380. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  381. {
  382. if ($producer->tiller) {
  383. $tiller = new Tiller();
  384. return (int) $tiller->isSynchro($date);
  385. }
  386. return false;
  387. }
  388. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  389. {
  390. $subscriptionManager = $this->getSubscriptionManager();
  391. $missingSubscriptionsArray = [];
  392. $arraySubscriptions = $subscriptionManager->findSubscriptionsByDate($date);
  393. if ($distribution->active) {
  394. foreach ($arraySubscriptions as $subscription) {
  395. if (!$subscriptionManager->hasOrderAlreadyExist($subscription, $ordersArray)
  396. && $subscription->productSubscription && count($subscription->productSubscription)
  397. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  398. $missingSubscriptionsArray[] = [
  399. 'username' => $subscriptionManager->getUsername($subscription)
  400. ];
  401. }
  402. }
  403. }
  404. return $missingSubscriptionsArray;
  405. }
  406. public function actionAjaxPointSaleFavorite($idUser)
  407. {
  408. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  409. $userManager = $this->getUserManager();
  410. $orderManager = $this->getOrderManager();
  411. $user = $userManager->findOneUserById($idUser);
  412. $idFavoritePointSale = 0;
  413. if($user) {
  414. $favoritePointSale = $orderManager->getUserFavoritePointSale($user);
  415. if ($favoritePointSale) {
  416. $idFavoritePointSale = $favoritePointSale->id;
  417. }
  418. }
  419. return [
  420. 'id_favorite_point_sale' => $idFavoritePointSale
  421. ];
  422. }
  423. public function actionAjaxUpdateProductOrder(
  424. $idDistribution,
  425. $idUser = false,
  426. $idPointSale = false,
  427. $idOrder = false
  428. )
  429. {
  430. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  431. $distributionManager = $this->getDistributionManager();
  432. $orderManager = $this->getOrderManager();
  433. $userManager = $this->getUserManager();
  434. $pointSaleManager = $this->getPointSaleManager();
  435. $productManager = $this->getProductManager();
  436. $order = $orderManager->findOneOrderById($idOrder);
  437. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  438. $user = $userManager->findOneUserById($idUser);
  439. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  440. $productsArray = Product::find()
  441. ->where([
  442. 'id_producer' => GlobalParam::getCurrentProducerId(),
  443. ])->joinWith([
  444. 'productPrice',
  445. 'productDistribution' => function ($q) use ($distribution) {
  446. $q->where(['id_distribution' => $distribution->id]);
  447. }
  448. ])->all();
  449. $productOrderArray = [];
  450. foreach ($productsArray as $product) {
  451. $priceArray = $productManager->getPriceArray($product, $user, $pointSale);
  452. $quantity = 0;
  453. $invoicePrice = null;
  454. if (isset($order->productOrder)) {
  455. foreach ($order->productOrder as $productOrder) {
  456. if ($productOrder->id_product == $product['id']) {
  457. if ($productOrder->invoice_price) {
  458. $invoicePrice = number_format($productOrder->invoice_price, 5);
  459. } else {
  460. $invoicePrice = number_format($productOrder->price, 5);
  461. }
  462. $quantity = $productOrder->quantity;
  463. }
  464. }
  465. }
  466. $productOrderArray[$product['id']] = [
  467. 'quantity' => $quantity,
  468. 'unit' => $product->unit,
  469. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  470. 'prices' => $priceArray,
  471. 'active' => $product->productDistribution[0]->active
  472. && (!$pointSale || $productManager->isAvailableOnPointSale($product, $pointSale)),
  473. 'invoice_price' => $invoicePrice
  474. ];
  475. }
  476. return $productOrderArray;
  477. }
  478. public function actionAjaxUpdateInvoicePrices($idOrder)
  479. {
  480. $orderManager = $this->getOrderManager();
  481. $userProducerManager = $this->getUserProducerManager();
  482. $productManager = $this->getProductManager();
  483. $order = $orderManager->findOneOrderById($idOrder);
  484. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  485. $userProducer = null;
  486. if ($order->id_user) {
  487. $userProducer = $userProducerManager->findOneUserProducer($order->user);
  488. }
  489. foreach ($order->productOrder as $productOrder) {
  490. $invoicePrice = $productManager->getPrice($productOrder->product, [
  491. 'user' => $order->user ?: null,
  492. 'point_sale' => $order->pointSale,
  493. 'user_producer' => $userProducer,
  494. 'quantity' => $productOrder->quantity
  495. ]);
  496. if ($invoicePrice != $productOrder->price) {
  497. $productOrder->invoice_price = $invoicePrice;
  498. } else {
  499. $productOrder->invoice_price = null;
  500. }
  501. $productOrder->save();
  502. }
  503. }
  504. }
  505. /**
  506. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  507. * date donnée (Méthode appelable via CRON)
  508. *
  509. * @param string $date
  510. * @param boolean $save
  511. * @param integer $idProducer
  512. * @param string $key
  513. * @return Pdf|null
  514. */
  515. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  516. {
  517. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  518. $this->actionReport($date, $save, $idProducer);
  519. }
  520. }
  521. /**
  522. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  523. * date donnée.
  524. */
  525. public function actionReport(string $date = '', bool $save = false, int $idProducer = 0, string $type = "pdf")
  526. {
  527. if (!$idProducer) {
  528. $idProducer = $this->getProducerCurrent()->id;
  529. }
  530. $distributionManager = $this->getDistributionManager();
  531. $producerManager = $this->getProducerManager();
  532. $producerCurrent = $producerManager->findOneProducerById($idProducer);
  533. $this->getLogic()->setProducerContext($producerCurrent);
  534. $distribution = $distributionManager->findOneDistribution($date);
  535. if ($distribution) {
  536. if ($type == 'pdf') {
  537. return $distributionManager->generateDistributionReportPdf($distribution, $save);
  538. }
  539. elseif ($type == 'csv') {
  540. $distributionManager->generateDistributionReportCsv($distribution);
  541. }
  542. }
  543. }
  544. public function actionReportGrid(string $date = '', bool $save = false, int $idProducer = 0)
  545. {
  546. if (!$idProducer) {
  547. $idProducer = $this->getProducerCurrent()->id;
  548. }
  549. $distributionManager = $this->getDistributionManager();
  550. $producerManager = $this->getProducerManager();
  551. $producerCurrent = $producerManager->findOneProducerById($idProducer);
  552. $this->getLogic()->setProducerContext($producerCurrent);
  553. $distribution = $distributionManager->findOneDistribution($date);
  554. if ($distribution) {
  555. return $distributionManager->generateDistributionReportGridPdf($distribution, $save);
  556. }
  557. }
  558. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  559. {
  560. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  561. $productDistributionManager = $this->getProductDistributionManager();
  562. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  563. $productDistributionManager->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  564. return ['success'];
  565. }
  566. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  567. {
  568. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  569. $productDistributionManager = $this->getProductDistributionManager();
  570. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  571. $productDistributionManager->updateProductDistributionActive($productDistribution, $active);
  572. return ['success'];
  573. }
  574. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  575. {
  576. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  577. $distributionManager = $this->getDistributionManager();
  578. $pointSaleManager = $this->getPointSaleManager();
  579. $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
  580. $pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution(
  581. $distributionManager->findOneDistributionById($idDistribution),
  582. $pointSaleManager->findOnePointSaleById($idPointSale)
  583. );
  584. $pointSaleDistribution->delivery = $delivery;
  585. $pointSaleDistributionManager->update($pointSaleDistribution);
  586. return ['success'];
  587. }
  588. public function getProductDistribution(int $idProduct, int $idDistribution)
  589. {
  590. $distributionManager = $this->getDistributionManager();
  591. $productManager = $this->getProductManager();
  592. $productDistributionManager = $this->getProductDistributionManager();
  593. return $productDistributionManager->findOneProductDistribution(
  594. $distributionManager->findOneDistributionById($idDistribution),
  595. $productManager->findOneProductById($idProduct)
  596. );
  597. }
  598. /**
  599. * Active/désactive un jour de distribution.
  600. *
  601. * @param integer $idDistribution
  602. * @param string $date
  603. * @param boolean $active
  604. * @return array
  605. */
  606. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  607. {
  608. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  609. $distributionManager = $this->getDistributionManager();
  610. if ($idDistribution) {
  611. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  612. }
  613. $format = 'Y-m-d';
  614. $dateObject = DateTime::createFromFormat($format, $date);
  615. if ($dateObject && $dateObject->format($format) === $date) {
  616. $distribution = $distributionManager->createDistributionIfNotExist($date);
  617. }
  618. if (isset($distribution) && $distribution) {
  619. $distributionManager->activeDistribution($distribution, $active);
  620. return ['success'];
  621. }
  622. return ['error'];
  623. }
  624. /**
  625. * Change l'état d'une semaine de production (activé, désactivé).
  626. *
  627. * @param string $date
  628. * @param integer $active
  629. */
  630. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  631. {
  632. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  633. $week = sprintf('%02d', date('W', strtotime($date)));
  634. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  635. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  636. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  637. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  638. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  639. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  640. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  641. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  642. $pointsSaleArray = PointSale::searchAll(['status' => 1]);
  643. $activeMonday = false;
  644. $activeTuesday = false;
  645. $activeWednesday = false;
  646. $activeThursday = false;
  647. $activeFriday = false;
  648. $activeSaturday = false;
  649. $activeSunday = false;
  650. foreach ($pointsSaleArray as $pointSale) {
  651. if ($pointSale->delivery_monday) {
  652. $activeMonday = true;
  653. }
  654. if ($pointSale->delivery_tuesday) {
  655. $activeTuesday = true;
  656. }
  657. if ($pointSale->delivery_wednesday) {
  658. $activeWednesday = true;
  659. }
  660. if ($pointSale->delivery_thursday) {
  661. $activeThursday = true;
  662. }
  663. if ($pointSale->delivery_friday) {
  664. $activeFriday = true;
  665. }
  666. if ($pointSale->delivery_saturday) {
  667. $activeSaturday = true;
  668. }
  669. if ($pointSale->delivery_sunday) {
  670. $activeSunday = true;
  671. }
  672. }
  673. if ($activeMonday || !$active) {
  674. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  675. }
  676. if ($activeTuesday || !$active) {
  677. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  678. }
  679. if ($activeWednesday || !$active) {
  680. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  681. }
  682. if ($activeThursday || !$active) {
  683. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  684. }
  685. if ($activeFriday || !$active) {
  686. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  687. }
  688. if ($activeSaturday || !$active) {
  689. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  690. }
  691. if ($activeSunday || !$active) {
  692. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  693. }
  694. return ['success'];
  695. }
  696. /**
  697. * Ajoute les commandes récurrentes pour une date donnée.
  698. *
  699. * @param string $date
  700. */
  701. public function actionAjaxProcessAddSubscriptions($date)
  702. {
  703. $ordersArray = $this->getOrderManager()->createAllOrdersFromSubscriptions($date, true);
  704. if($ordersArray && count($ordersArray)) {
  705. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  706. }
  707. return Ajax::responseError('Aucun abonnement à importer.');
  708. }
  709. /**
  710. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  711. *
  712. * @param string $date
  713. */
  714. public function actionAjaxProcessSynchroTiller($date)
  715. {
  716. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  717. $producerManager = $this->getProducerManager();
  718. $productOrderManager = $this->getProductOrderManager();
  719. $orderManager = $this->getOrderManager();
  720. $return = [];
  721. $producerTiller = $producerManager->getConfig('tiller');
  722. if ($producerTiller) {
  723. $tiller = new Tiller();
  724. $isSynchro = $tiller->isSynchro($date);
  725. if (!$isSynchro) {
  726. $orders = Order::searchAll([
  727. 'distribution.date' => $date,
  728. 'order.tiller_synchronization' => 1
  729. ], [
  730. 'conditions' => 'date_delete IS NULL'
  731. ]);
  732. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  733. if ($orders && count($orders)) {
  734. foreach ($orders as $order) {
  735. $orderManager->initOrder($order);
  736. $lines = [];
  737. foreach ($order->productOrder as $productOrder) {
  738. $lines[] = [
  739. 'name' => $productOrder->product->name,
  740. 'price' => $productOrderManager->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
  741. 'tax' => $productOrder->taxRate->value * 100,
  742. 'date' => $strDate,
  743. 'quantity' => $productOrder->quantity
  744. ];
  745. }
  746. $typePaymentTiller = '';
  747. if ($order->mean_payment == MeanPayment::MONEY) {
  748. $typePaymentTiller = 'CASH';
  749. }
  750. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  751. || $order->mean_payment == MeanPayment::CREDIT
  752. || $order->mean_payment == MeanPayment::TRANSFER
  753. || $order->mean_payment == MeanPayment::OTHER) {
  754. $typePaymentTiller = 'CARD';
  755. }
  756. if ($order->mean_payment == MeanPayment::CHEQUE) {
  757. $typePaymentTiller = 'BANK_CHECK';
  758. }
  759. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  760. $typePaymentTiller = 'CASH';
  761. }
  762. $returnTiller = $tiller->postOrder([
  763. 'externalId' => $order->id,
  764. 'type' => 1,
  765. 'status' => 'IN_PROGRESS',
  766. 'openDate' => $strDate,
  767. 'closeDate' => $strDate,
  768. 'lines' => $lines,
  769. 'payments' => [
  770. [
  771. 'type' => $typePaymentTiller,
  772. 'amount' => $orderManager->getOrderAmountWithTax(
  773. $order,
  774. Order::AMOUNT_PAID
  775. ) * 100,
  776. 'status' => 'ACCEPTED',
  777. 'date' => $strDate
  778. ]
  779. ]
  780. ]);
  781. $returnTillerObject = json_decode($returnTiller);
  782. $order->tiller_external_id = '' . $returnTillerObject->id;
  783. $order->save();
  784. $return[] = $returnTiller;
  785. }
  786. }
  787. }
  788. }
  789. return $return;
  790. }
  791. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  792. {
  793. $this->generateDeliveryNote($idOrder);
  794. return Ajax::responseSuccess('Bon de livraison généré');
  795. }
  796. public function actionAjaxGenerateDeliveryNotePointSale($idOrders)
  797. {
  798. $orderManager = $this->getOrderManager();
  799. $deliveryNoteManager = $this->getDeliveryNoteManager();
  800. if (strlen($idOrders)) {
  801. $idOrders = json_decode($idOrders, true);
  802. if (is_array($idOrders) && count($idOrders) > 0) {
  803. reset($idOrders);
  804. $firstOrder = $orderManager->findOneOrderById((int)$idOrders[key($idOrders)]);
  805. $ordersArray = Order::searchAll(['id' => $idOrders,]);
  806. $deliveryNote = $deliveryNoteManager->getOneDeliveryNoteExistingFromOrders($ordersArray);
  807. $isUpdate = (bool) $deliveryNote;
  808. if ($deliveryNote && $deliveryNoteManager->isStatusValid($deliveryNote)) {
  809. return Ajax::responseError('Vous ne pouvez pas modifier un bon de livraison déjà validé.');
  810. }
  811. if(!$deliveryNote && $firstOrder && !$firstOrder->pointSale->id_user) {
  812. return Ajax::responseError("Vous devez définir un contact de facturation pour ce point de vente.");
  813. }
  814. if ($firstOrder) {
  815. if (!$deliveryNote) {
  816. $deliveryNoteManager->createDeliveryNoteForPointSale(
  817. $firstOrder->pointSale,
  818. $firstOrder->distribution,
  819. $idOrders
  820. );
  821. }
  822. return Ajax::responseSuccess('Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré'));
  823. }
  824. }
  825. }
  826. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  827. }
  828. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  829. {
  830. if (strlen($idOrders)) {
  831. $idOrders = json_decode($idOrders, true);
  832. if (is_array($idOrders) && count($idOrders) > 0) {
  833. foreach ($idOrders as $idOrder) {
  834. $this->generateDeliveryNote($idOrder);
  835. }
  836. }
  837. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  838. }
  839. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  840. }
  841. public function generateDeliveryNote(int $idOrder)
  842. {
  843. $orderManager = $this->getOrderManager();
  844. $deliveryNoteManager = $this->getDeliveryNoteManager();
  845. $order = $orderManager->findOneOrderById($idOrder);
  846. if ($orderManager->isOrderFromProducer($order) && $order->id_user) {
  847. $deliveryNoteManager->createDeliveryNoteForOrder($order);
  848. }
  849. }
  850. public function actionAjaxValidateDeliveryNotes($idOrders)
  851. {
  852. $orderManager = $this->getOrderManager();
  853. $deliveryNoteManager = $this->getDeliveryNoteManager();
  854. if (strlen($idOrders)) {
  855. $idOrders = json_decode($idOrders, true);
  856. if (is_array($idOrders) && count($idOrders) > 0) {
  857. foreach ($idOrders as $idOrder) {
  858. $order = $orderManager->findOneOrderById($idOrder);
  859. if ($orderManager->isOrderFromProducer($order)) {
  860. $deliveryNote = $deliveryNoteManager->findOneDeliveryNoteById((int) $order->id_delivery_note);
  861. if($deliveryNote) {
  862. $deliveryNoteManager->validateDocument($deliveryNote);
  863. }
  864. }
  865. }
  866. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  867. }
  868. }
  869. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  870. }
  871. }