Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1001 lines
41KB

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