您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

963 行
39KB

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