No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1028 líneas
42KB

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