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

1754 lines
70KB

  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\CSV;
  39. use common\helpers\GlobalParam;
  40. use common\helpers\MeanPayment;
  41. use common\helpers\Password;
  42. use common\helpers\Price;
  43. use common\helpers\Tiller;
  44. use common\logic\Distribution\Distribution\Model\Distribution;
  45. use common\logic\Document\DeliveryNote\Model\DeliveryNote;
  46. use common\logic\Document\Document\Model\Document;
  47. use common\logic\Order\Order\Model\Order;
  48. use common\logic\PointSale\PointSale\Model\PointSale;
  49. use common\logic\Producer\Producer\Model\Producer;
  50. use common\logic\Product\Product\Model\Product;
  51. use common\logic\User\User\Model\User;
  52. use common\logic\User\UserProducer\Model\UserProducer;
  53. use DateTime;
  54. use kartik\mpdf\Pdf;
  55. use yii\filters\AccessControl;
  56. class DistributionController extends BackendController
  57. {
  58. public function behaviors()
  59. {
  60. return [
  61. 'access' => [
  62. 'class' => AccessControl::class,
  63. 'rules' => [
  64. [
  65. 'actions' => ['report-cron', 'report-terredepains'],
  66. 'allow' => true,
  67. 'roles' => ['?']
  68. ],
  69. [
  70. 'allow' => true,
  71. 'roles' => ['@'],
  72. 'matchCallback' => function ($rule, $action) {
  73. $userManager = $this->getUserManager();
  74. return $userManager->isCurrentAdmin() || $userManager->isCurrentProducer();
  75. }
  76. ]
  77. ],
  78. ],
  79. ];
  80. }
  81. public function actionIndex($date = '', $idOrderUpdate = 0)
  82. {
  83. $this->checkProductsPointsSale();
  84. $orderManager = $this->getOrderManager();
  85. $format = 'Y-m-d';
  86. $theDate = '';
  87. $dateObject = DateTime::createFromFormat($format, $date);
  88. if ($dateObject && $dateObject->format($format) === $date) {
  89. $theDate = $date;
  90. }
  91. $orderUpdate = null;
  92. if ($idOrderUpdate) {
  93. $orderUpdate = $orderManager->findOneOrderById($idOrderUpdate);
  94. }
  95. return $this->render('index', [
  96. 'date' => $theDate,
  97. 'orderUpdate' => $orderUpdate
  98. ]);
  99. }
  100. public function actionAjaxInfos($date = '')
  101. {
  102. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  103. $distributionManager = $this->getDistributionManager();
  104. $orderManager = $this->getOrderManager();
  105. $productManager = $this->getProductManager();
  106. $userManager = $this->getUserManager();
  107. $pointSaleManager = $this->getPointSaleManager();
  108. $producer = $this->getProducerCurrent();
  109. $format = 'Y-m-d';
  110. $dateObject = DateTime::createFromFormat($format, $date);
  111. $json = ['distribution' => [], 'products' => []];
  112. $json['means_payment'] = MeanPayment::getAll();
  113. $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
  114. $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
  115. if ($dateObject && $dateObject->format($format) === $date) {
  116. $distribution = $distributionManager->createDistributionIfNotExist($date);
  117. $ordersArray = $orderManager->findOrdersByDistribution($distribution);
  118. $ordersArrayObject = $ordersArray;
  119. $productsArray = $productManager->findProductsByDistributionAsArray($distribution);
  120. $json['products'] = $this->buildAjaxInfosResponseProducts($producer, $distribution, $productsArray, $ordersArray);
  121. $json['distribution'] = $this->buildAjaxInfosResponseDistribution($distribution, $ordersArrayObject, $productsArray);
  122. $json['orders'] = $this->buildAjaxInfosResponseOrders($ordersArray, $productsArray);
  123. $json['points_sale'] = $pointSaleManager->findPointSalesByDistributionAsArray($distribution);
  124. $json['delivery_notes'] = $this->buildAjaxInfosResponseDeliveryNotes($date);
  125. $json['order_create'] = $this->buildAjaxInfosResponseOrderCreate($distribution, $productsArray);
  126. $json['users'] = $userManager->findUsers();
  127. $json['one_distribution_week_active'] = $distributionManager->isOneDistributionWeekActive($date);
  128. $json['tiller_is_synchro'] = $this->buildAjaxInfosResponseTiller($producer, $date);
  129. $json['missing_subscriptions'] = $this->buildAjaxInfosResponseMissingSubscriptions($date, $distribution, $ordersArrayObject);
  130. }
  131. return $json;
  132. }
  133. public function buildAjaxInfosResponseProducts(Producer $producer, Distribution $distribution, array &$productsArray, array $ordersArray)
  134. {
  135. $distributionManager = $this->getDistributionManager();
  136. $orderManager = $this->getOrderManager();
  137. $productManager = $this->getProductManager();
  138. foreach ($productsArray as &$theProduct) {
  139. $productObject = $productManager->findOneProductById($theProduct['id']);
  140. $quantityOrder = $orderManager->getProductQuantity($productObject, $ordersArray);
  141. $theProduct['quantity_ordered'] = $quantityOrder;
  142. if (!isset($theProduct['productDistribution'][0])) {
  143. $theProduct['productDistribution'][0] = $distributionManager->addProduct($distribution, $productObject);
  144. }
  145. if (!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  146. $theProduct['quantity_remaining'] = null;
  147. } else {
  148. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder;
  149. }
  150. $theProduct['quantity_form'] = 0;
  151. if (!isset($theProduct['taxRate'])) {
  152. $theProduct['taxRate'] = $producer->taxRate;
  153. }
  154. }
  155. return $productsArray;
  156. }
  157. public function buildAjaxInfosResponseProducer($producer)
  158. {
  159. return [
  160. 'credit' => $producer->credit,
  161. 'tiller' => $producer->tiller,
  162. 'option_display_export_grid' => $producer->option_display_export_grid
  163. ];
  164. }
  165. public function buildAjaxInfosResponseDistributions($dateObject)
  166. {
  167. $numberOfLoadedMonthes = '3 month';
  168. if (is_object($dateObject)) {
  169. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  170. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  171. } else {
  172. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  173. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  174. }
  175. return Distribution::searchAll([
  176. 'active' => 1
  177. ], [
  178. 'conditions' => [
  179. 'date > :date_begin',
  180. 'date < :date_end'
  181. ],
  182. 'params' => [
  183. ':date_begin' => date(
  184. 'Y-m-d',
  185. $dateBegin
  186. ),
  187. ':date_end' => date(
  188. 'Y-m-d',
  189. $dateEnd
  190. ),
  191. ],
  192. 'as_array' => true
  193. ]);
  194. }
  195. public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray, array $productsArray)
  196. {
  197. $productManager = $this->getProductManager();
  198. $orderManager = $this->getOrderManager();
  199. $distributionJsonData = [
  200. 'id' => $distribution->id,
  201. 'active' => $distribution->active,
  202. 'url_report' => $this->getUrlManagerBackend()->createUrl(
  203. ['distribution/report', 'date' => $distribution->date]
  204. ),
  205. 'url_report_grid' => $this->getUrlManagerBackend()->createUrl(
  206. ['distribution/report-grid', 'date' => $distribution->date]
  207. ),
  208. ];
  209. // montant et poids des commandes
  210. $revenues = 0;
  211. $weight = 0;
  212. if ($ordersArray) {
  213. foreach ($ordersArray as $order) {
  214. $orderManager->initOrder($order);
  215. if (is_null($order->date_delete)) {
  216. $revenues += $orderManager->getOrderAmountWithTax($order);
  217. $weight += $order->weight;
  218. }
  219. }
  220. }
  221. $distributionJsonData['revenues'] = Price::format($revenues);
  222. $distributionJsonData['weight'] = number_format($weight, 2);
  223. $distributionJsonData['potential_revenues'] = Price::format($productManager->getProductDistributionPotentialRevenues($productsArray));
  224. $distributionJsonData['potential_weight'] = number_format($productManager->getProductDistributionPotentialWeight($productsArray), 2);
  225. return $distributionJsonData;
  226. }
  227. public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
  228. {
  229. $userManager = $this->getUserManager();
  230. $orderManager = $this->getOrderManager();
  231. $creditHistoryManager = $this->getCreditHistoryManager();
  232. if ($ordersArray) {
  233. foreach ($ordersArray as &$order) {
  234. $orderManager->initOrder($order);
  235. $productOrderArray = [];
  236. foreach ($order->productOrder as $productOrder) {
  237. $productOrderArray[$productOrder->id_product] = [
  238. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  239. 'unit' => $productOrder->unit,
  240. 'price' => number_format($productOrder->price, 5),
  241. 'invoice_price' => number_format($productOrder->invoice_price, 5),
  242. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  243. ];
  244. }
  245. foreach ($productsArray as $product) {
  246. if (!isset($productOrderArray[$product['id']])) {
  247. $productOrderArray[$product['id']] = [
  248. 'quantity' => 0,
  249. 'unit' => $product['unit'],
  250. 'price' => number_format($product['price'], 3),
  251. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  252. ];
  253. }
  254. }
  255. $creditHistoryArray = [];
  256. foreach ($order->creditHistory as $creditHistory) {
  257. $creditHistoryArray[] = [
  258. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  259. 'user' => $userManager->getUsername($creditHistory->getUserObject()),
  260. 'user_action' => $creditHistoryManager->getStrUserAction($creditHistory),
  261. 'wording' => $creditHistoryManager->getStrWording($creditHistory),
  262. 'debit' => ($creditHistoryManager->isTypeDebit($creditHistory) ? '-&nbsp;' . $creditHistoryManager->getAmount(
  263. $creditHistory,
  264. Order::AMOUNT_TOTAL,
  265. true
  266. ) : ''),
  267. 'credit' => ($creditHistoryManager->isTypeCredit($creditHistory) ? '+&nbsp;' . $creditHistoryManager->getAmount(
  268. $creditHistory,
  269. Order::AMOUNT_TOTAL,
  270. true
  271. ) : '')
  272. ];
  273. }
  274. $arrayCreditUser = [];
  275. if (isset($order->user) && isset($order->user->userProducer) && isset($order->user->userProducer[0])) {
  276. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
  277. }
  278. $oneProductUnactivated = false;
  279. foreach ($order->productOrder as $productOrder) {
  280. foreach ($productsArray as $product) {
  281. if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  282. $oneProductUnactivated = true;
  283. }
  284. }
  285. }
  286. $order = array_merge($order->getAttributes(), [
  287. 'selected' => false,
  288. 'weight' => $order->weight,
  289. 'amount' => Price::numberTwoDecimals($orderManager->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  290. 'amount_paid' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_PAID)),
  291. 'amount_remaining' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING)),
  292. 'amount_surplus' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
  293. 'user' => (isset($order->user)) ? array_merge(
  294. $order->user->getAttributes(),
  295. $arrayCreditUser
  296. ) : null,
  297. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  298. 'productOrder' => $productOrderArray,
  299. 'creditHistory' => $creditHistoryArray,
  300. 'oneProductUnactivated' => $oneProductUnactivated,
  301. 'isLinkedToValidDocument' => $orderManager->isLinkedToValidDocument($order),
  302. ]);
  303. }
  304. }
  305. return $ordersArray;
  306. }
  307. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  308. {
  309. $deliveryNotesArray = DeliveryNote::searchAll([
  310. 'distribution.date' => $date,
  311. ], [
  312. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  313. ]);
  314. $deliveryNotesByPointSaleArray = [];
  315. foreach ($deliveryNotesArray as $deliveryNote) {
  316. if (isset($deliveryNote->orders[0])) {
  317. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  318. $deliveryNote->getAttributes();
  319. }
  320. }
  321. return $deliveryNotesByPointSaleArray;
  322. }
  323. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  324. {
  325. $pointSaleManager = $this->getPointSaleManager();
  326. $pointSaleDefault = $pointSaleManager->findOnePointSaleDefaultByDistribution($distribution);
  327. $productOrderArray = [];
  328. foreach ($productsArray as $product) {
  329. $productOrderArray[$product['id']] = [
  330. 'quantity' => 0,
  331. 'unit' => $product['unit'],
  332. //'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  333. ];
  334. }
  335. return [
  336. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : false,
  337. 'id_user' => 0,
  338. 'username' => '',
  339. 'comment' => '',
  340. 'productOrder' => $productOrderArray
  341. ];
  342. }
  343. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  344. {
  345. if ($producer->tiller) {
  346. $tiller = new Tiller();
  347. return (int) $tiller->isSynchro($date);
  348. }
  349. return false;
  350. }
  351. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  352. {
  353. $subscriptionManager = $this->getSubscriptionManager();
  354. $missingSubscriptionsArray = [];
  355. $arraySubscriptions = $subscriptionManager->findSubscriptionsByDate($date);
  356. if ($distribution->active) {
  357. foreach ($arraySubscriptions as $subscription) {
  358. if (!$subscriptionManager->hasOrderAlreadyExist($subscription, $ordersArray)
  359. && $subscription->productSubscription && count($subscription->productSubscription)
  360. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  361. $missingSubscriptionsArray[] = [
  362. 'username' => $subscriptionManager->getUsername($subscription)
  363. ];
  364. }
  365. }
  366. }
  367. return $missingSubscriptionsArray;
  368. }
  369. public function actionAjaxPointSaleFavorite($idUser)
  370. {
  371. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  372. $userManager = $this->getUserManager();
  373. $orderManager = $this->getOrderManager();
  374. $user = $userManager->findOneUserById($idUser);
  375. $idFavoritePointSale = 0;
  376. if($user) {
  377. $favoritePointSale = $orderManager->getUserFavoritePointSale($user);
  378. if ($favoritePointSale) {
  379. $idFavoritePointSale = $favoritePointSale->id;
  380. }
  381. }
  382. return [
  383. 'id_favorite_point_sale' => $idFavoritePointSale
  384. ];
  385. }
  386. public function actionAjaxUpdateProductOrder(
  387. $idDistribution,
  388. $idUser = false,
  389. $idPointSale = false,
  390. $idOrder = false
  391. )
  392. {
  393. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  394. $distributionManager = $this->getDistributionManager();
  395. $orderManager = $this->getOrderManager();
  396. $userManager = $this->getUserManager();
  397. $pointSaleManager = $this->getPointSaleManager();
  398. $productManager = $this->getProductManager();
  399. $order = $orderManager->findOneOrderById($idOrder);
  400. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  401. $user = $userManager->findOneUserById($idUser);
  402. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  403. $productsArray = Product::find()
  404. ->where([
  405. 'id_producer' => GlobalParam::getCurrentProducerId(),
  406. ])->joinWith([
  407. 'productPrice',
  408. 'productDistribution' => function ($q) use ($distribution) {
  409. $q->where(['id_distribution' => $distribution->id]);
  410. }
  411. ])->all();
  412. $productOrderArray = [];
  413. foreach ($productsArray as $product) {
  414. $priceArray = $productManager->getPriceArray($product, $user, $pointSale);
  415. $quantity = 0;
  416. $invoicePrice = null;
  417. if (isset($order->productOrder)) {
  418. foreach ($order->productOrder as $productOrder) {
  419. if ($productOrder->id_product == $product['id']) {
  420. if ($productOrder->invoice_price) {
  421. $invoicePrice = number_format($productOrder->invoice_price, 3);
  422. } else {
  423. $invoicePrice = number_format($productOrder->price, 3);
  424. }
  425. $quantity = $productOrder->quantity;
  426. }
  427. }
  428. }
  429. $productOrderArray[$product['id']] = [
  430. 'quantity' => $quantity,
  431. 'unit' => $product->unit,
  432. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  433. 'prices' => $priceArray,
  434. 'active' => $product->productDistribution[0]->active
  435. && (!$pointSale || $productManager->isAvailableOnPointSale($product, $pointSale)),
  436. 'invoice_price' => $invoicePrice
  437. ];
  438. }
  439. return $productOrderArray;
  440. }
  441. public function actionAjaxUpdateInvoicePrices($idOrder)
  442. {
  443. $orderManager = $this->getOrderManager();
  444. $userProducerManager = $this->getUserProducerManager();
  445. $productManager = $this->getProductManager();
  446. $order = $orderManager->findOneOrderById($idOrder);
  447. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  448. $userProducer = null;
  449. if ($order->id_user) {
  450. $userProducer = $userProducerManager->findOneUserProducer($order->user);
  451. }
  452. foreach ($order->productOrder as $productOrder) {
  453. $invoicePrice = $productManager->getPrice($productOrder->product, [
  454. 'user' => $order->user ?: null,
  455. 'point_sale' => $order->pointSale,
  456. 'user_producer' => $userProducer,
  457. 'quantity' => $productOrder->quantity
  458. ]);
  459. if ($invoicePrice != $productOrder->price) {
  460. $productOrder->invoice_price = $invoicePrice;
  461. } else {
  462. $productOrder->invoice_price = null;
  463. }
  464. $productOrder->save();
  465. }
  466. }
  467. }
  468. /**
  469. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  470. * date donnée (Méthode appelable via CRON)
  471. *
  472. * @param string $date
  473. * @param boolean $save
  474. * @param integer $idProducer
  475. * @param string $key
  476. * @return Pdf|null
  477. */
  478. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  479. {
  480. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  481. $this->actionReport($date, $save, $idProducer);
  482. }
  483. }
  484. /**
  485. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  486. * date donnée.
  487. *
  488. * @param string $date
  489. * @param boolean $save
  490. * @param integer $idProducer
  491. * @return Pdf|null|string
  492. */
  493. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  494. {
  495. $productDistributionManager = $this->getProductDistributionManager();
  496. $producerManager = $this->getProducerManager();
  497. $orderManager = $this->getOrderManager();
  498. $productManager = $this->getProductManager();
  499. $pointSaleManager = $this->getPointSaleManager();
  500. if (!\Yii::$app->user->isGuest) {
  501. $idProducer = GlobalParam::getCurrentProducerId();
  502. }
  503. $ordersArray = Order::searchAll(
  504. [
  505. 'distribution.date' => $date,
  506. 'distribution.id_producer' => $idProducer
  507. ],
  508. [
  509. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  510. 'conditions' => 'date_delete IS NULL'
  511. ]
  512. );
  513. $distribution = Distribution::searchOne([
  514. 'id_producer' => $idProducer
  515. ], [
  516. 'conditions' => 'date LIKE :date',
  517. 'params' => [':date' => $date]
  518. ]);
  519. if ($distribution) {
  520. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  521. $pointsSaleArray = PointSale::searchAll([
  522. 'point_sale.id_producer' => $idProducer
  523. ]);
  524. foreach ($pointsSaleArray as $pointSale) {
  525. $orderManager->initPointSaleOrders($pointSale, $ordersArray);
  526. }
  527. // produits
  528. $productsArray = Product::find()
  529. ->joinWith([
  530. 'productDistribution' => function ($q) use ($distribution) {
  531. $q->where(['id_distribution' => $distribution->id]);
  532. }
  533. ])
  534. ->where([
  535. 'id_producer' => $idProducer,
  536. ])
  537. ->orderBy('order ASC')
  538. ->all();
  539. if ($type == 'pdf') {
  540. $viewPdf = 'report';
  541. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  542. $producer = GlobalParam::getCurrentProducer();
  543. if ($producer->slug == 'bourlinguepacotille') {
  544. $viewPdf = 'report-bourlingue';
  545. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  546. }
  547. // get your HTML raw content without any layouts or scripts
  548. $content = $this->renderPartial($viewPdf, [
  549. 'date' => $date,
  550. 'distribution' => $distribution,
  551. 'selectedProductsArray' => $selectedProductsArray,
  552. 'pointsSaleArray' => $pointsSaleArray,
  553. 'productsArray' => $productsArray,
  554. 'ordersArray' => $ordersArray,
  555. 'producer' => $producerManager->findOneProducerById($idProducer)
  556. ]);
  557. $dateStr = date('d/m/Y', strtotime($date));
  558. if ($save) {
  559. $destination = Pdf::DEST_FILE;
  560. } else {
  561. $destination = Pdf::DEST_BROWSER;
  562. }
  563. $pdf = new Pdf([
  564. // set to use core fonts only
  565. 'mode' => Pdf::MODE_UTF8,
  566. // A4 paper format
  567. 'format' => Pdf::FORMAT_A4,
  568. // portrait orientation
  569. 'orientation' => $orientationPdf,
  570. // stream to browser inline
  571. 'destination' => $destination,
  572. 'filename' => \Yii::getAlias(
  573. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  574. ),
  575. // your html content input
  576. 'content' => $content,
  577. // format content from your own css file if needed or use the
  578. // enhanced bootstrap css built by Krajee for mPDF formatting
  579. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  580. // any css to be embedded if required
  581. 'cssInline' => '
  582. table {
  583. border-spacing : 0px ;
  584. border-collapse : collapse ;
  585. width: 100% ;
  586. }
  587. table tr th,
  588. table tr td {
  589. padding: 0px ;
  590. margin: 0px ;
  591. border: solid 1px #e0e0e0 ;
  592. padding: 3px 8px ;
  593. vertical-align : top;
  594. page-break-inside: avoid !important;
  595. color: black;
  596. }
  597. table tr th {
  598. font-size: 13px ;
  599. }
  600. table tr td {
  601. font-size: 13px ;
  602. }
  603. ',
  604. // set mPDF properties on the fly
  605. //'options' => ['title' => 'Krajee Report Title'],
  606. // call mPDF methods on the fly
  607. 'methods' => [
  608. 'SetHeader' => ['Commandes du ' . $dateStr],
  609. 'SetFooter' => ['{PAGENO}'],
  610. ]
  611. ]);
  612. // return the pdf output as per the destination setting
  613. return $pdf->render();
  614. } elseif ($type == 'csv') {
  615. $datas = [];
  616. $optionCsvExportAllProducts = $producerManager->getConfig('option_csv_export_all_products');
  617. $optionCsvExportByPiece = $producerManager->getConfig('option_csv_export_by_piece');
  618. // produits en colonne
  619. $productsNameArray = ['', 'Commentaire'];
  620. $productsIndexArray = [];
  621. $productsHasQuantity = [];
  622. $cpt = 2;
  623. foreach ($productsArray as $product) {
  624. $productsHasQuantity[$product->id] = 0;
  625. foreach (Product::$unitsArray as $unit => $dataUnit) {
  626. $quantity = $orderManager->getProductQuantity($product, $ordersArray, true, $unit);
  627. if ($quantity) {
  628. $productsHasQuantity[$product->id] += $quantity;
  629. }
  630. }
  631. if ($productsHasQuantity[$product->id] > 0 || $optionCsvExportAllProducts) {
  632. $productName = $productManager->getNameExport($product);
  633. if ($optionCsvExportByPiece) {
  634. $productUnit = 'piece';
  635. } else {
  636. $productUnit = $product->unit;
  637. }
  638. $productName .= ' (' . $productManager->strUnit($productUnit, 'wording_short', true) . ')';
  639. $productsNameArray[] = $productName;
  640. $productsIndexArray[$product->id] = $cpt++;
  641. }
  642. }
  643. $datas[] = $productsNameArray;
  644. // points de vente
  645. foreach ($pointsSaleArray as $pointSale) {
  646. if (count($pointSale->orders)) {
  647. // listing commandes
  648. $datas[] = ['> ' . $pointSale->name];
  649. foreach ($pointSale->orders as $order) {
  650. $orderLine = [$orderManager->getOrderUsername($order), $orderManager->getCommentReport($order)];
  651. if ($optionCsvExportByPiece) {
  652. foreach ($order->productOrder as $productOrder) {
  653. $orderLine[$productsIndexArray[$productOrder->id_product]] = $orderManager->getProductQuantityPieces(
  654. $productOrder->product,
  655. [$order]
  656. );
  657. }
  658. } else {
  659. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  660. $orderLine[$indexProduct] = '';
  661. }
  662. foreach ($order->productOrder as $productOrder) {
  663. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  664. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  665. }
  666. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  667. if ($productOrder->product->unit != $productOrder->unit) {
  668. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productManager->strUnit(
  669. $productOrder->unit,
  670. 'wording_short',
  671. true
  672. );
  673. }
  674. }
  675. }
  676. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  677. }
  678. // total point de vente
  679. if ($optionCsvExportByPiece) {
  680. $totalsPointSaleArray = $this->_totalReportPiecesCSV(
  681. 'Total',
  682. $pointSale->orders,
  683. $productsArray,
  684. $productsIndexArray
  685. );
  686. } else {
  687. $totalsPointSaleArray = $this->_totalReportCSV(
  688. 'Total',
  689. $pointSale->orders,
  690. $productsArray,
  691. $productsIndexArray
  692. );
  693. }
  694. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  695. $datas[] = [];
  696. }
  697. }
  698. // global
  699. if ($optionCsvExportByPiece) {
  700. $totalsGlobalArray = $this->_totalReportPiecesCSV(
  701. '> Totaux',
  702. $ordersArray,
  703. $productsArray,
  704. $productsIndexArray
  705. );
  706. } else {
  707. $totalsGlobalArray = $this->_totalReportCSV(
  708. '> Totaux',
  709. $ordersArray,
  710. $productsArray,
  711. $productsIndexArray
  712. );
  713. }
  714. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  715. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  716. echo CSV::array2csv($datas);
  717. die();
  718. }
  719. }
  720. return null;
  721. }
  722. public function actionReportGrid($date = '', $save = false, $idProducer = 0, $type = "pdf")
  723. {
  724. $producerManager = $this->getProducerManager();
  725. $productDistribution = $this->getProductDistributionManager();
  726. $orderManager = $this->getOrderManager();
  727. $productCategoryManager = $this->getProductCategoryManager();
  728. if (!\Yii::$app->user->isGuest) {
  729. $idProducer = GlobalParam::getCurrentProducerId();
  730. }
  731. $distribution = Distribution::searchOne([
  732. 'id_producer' => $idProducer
  733. ], [
  734. 'conditions' => 'date LIKE :date',
  735. 'params' => [':date' => $date]
  736. ]);
  737. if ($distribution) {
  738. $ordersArray = Order::searchAll(
  739. [
  740. 'distribution.date' => $date,
  741. 'distribution.id_producer' => $idProducer
  742. ],
  743. [
  744. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  745. 'conditions' => 'date_delete IS NULL'
  746. ]
  747. );
  748. $selectedProductsArray = $productDistribution->findProductDistributionsByDistribution($distribution);
  749. $pointsSaleArray = PointSale::searchAll([
  750. 'point_sale.id_producer' => $idProducer
  751. ]);
  752. foreach ($pointsSaleArray as $pointSale) {
  753. $orderManager->initPointSaleOrders($pointSale, $ordersArray);
  754. }
  755. $ordersByPage = 22;
  756. $nbPages = ceil(count($ordersArray) / $ordersByPage);
  757. $ordersArrayPaged = [];
  758. foreach ($pointsSaleArray as $pointSale) {
  759. $index = 0;
  760. $indexPage = 0;
  761. foreach ($pointSale->orders as $order) {
  762. if (!isset($ordersArrayPaged[$pointSale->id])) {
  763. $ordersArrayPaged[$pointSale->id] = [];
  764. }
  765. if (!isset($ordersArrayPaged[$pointSale->id][$indexPage])) {
  766. $ordersArrayPaged[$pointSale->id][$indexPage] = [];
  767. }
  768. $ordersArrayPaged[$pointSale->id][$indexPage][] = $order;
  769. $index++;
  770. if ($index == $ordersByPage) {
  771. $index = 0;
  772. $indexPage++;
  773. }
  774. }
  775. }
  776. // catégories
  777. $categoriesArray = $productCategoryManager->findProductCategories();
  778. array_unshift($categoriesArray, null);
  779. // produits
  780. $productsArray = Product::find()
  781. ->joinWith([
  782. 'productDistribution' => function ($q) use ($distribution) {
  783. $q->where(['id_distribution' => $distribution->id]);
  784. }
  785. ])
  786. ->where([
  787. 'id_producer' => $idProducer,
  788. ])
  789. ->orderBy('order ASC')
  790. ->all();
  791. $viewPdf = 'report-grid';
  792. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  793. $producer = GlobalParam::getCurrentProducer();
  794. if ($producer->slug == 'bourlinguepacotille') {
  795. $viewPdf = 'report-bourlingue';
  796. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  797. }
  798. // get your HTML raw content without any layouts or scripts
  799. $content = $this->renderPartial($viewPdf, [
  800. 'date' => $date,
  801. 'distribution' => $distribution,
  802. 'selectedProductsArray' => $selectedProductsArray,
  803. 'pointsSaleArray' => $pointsSaleArray,
  804. 'categoriesArray' => $categoriesArray,
  805. 'productsArray' => $productsArray,
  806. 'ordersArray' => $ordersArrayPaged,
  807. 'producer' => $producerManager->findOneProducerById($idProducer)
  808. ]);
  809. $dateStr = date('d/m/Y', strtotime($date));
  810. if ($save) {
  811. $destination = Pdf::DEST_FILE;
  812. } else {
  813. $destination = Pdf::DEST_BROWSER;
  814. }
  815. $pdf = new Pdf([
  816. // set to use core fonts only
  817. 'mode' => Pdf::MODE_UTF8,
  818. // A4 paper format
  819. 'format' => Pdf::FORMAT_A4,
  820. // portrait orientation
  821. 'orientation' => $orientationPdf,
  822. // stream to browser inline
  823. 'destination' => $destination,
  824. 'filename' => \Yii::getAlias(
  825. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  826. ),
  827. // your html content input
  828. 'content' => $content,
  829. // format content from your own css file if needed or use the
  830. // enhanced bootstrap css built by Krajee for mPDF formatting
  831. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  832. // any css to be embedded if required
  833. 'cssInline' => '
  834. table {
  835. border-spacing : 0px ;
  836. border-collapse : collapse ;
  837. width: 100% ;
  838. }
  839. table tr th,
  840. table tr td {
  841. padding: 0px ;
  842. margin: 0px ;
  843. border: solid 1px #e0e0e0 ;
  844. padding: 3px ;
  845. vertical-align : top;
  846. page-break-inside: avoid !important;
  847. }
  848. table tr th {
  849. font-size: 10px ;
  850. }
  851. table tr td {
  852. font-size: 10px ;
  853. }
  854. table thead tr {
  855. line-height: 220px;
  856. text-align:left;
  857. }
  858. .th-user,
  859. .td-nb-products {
  860. /* width: 35px ; */
  861. text-align: center ;
  862. }
  863. .th-user {
  864. padding: 10px ;
  865. }
  866. .category-name {
  867. font-weight: bold ;
  868. }
  869. ',
  870. // set mPDF properties on the fly
  871. //'options' => ['title' => 'Krajee Report Title'],
  872. // call mPDF methods on the fly
  873. 'methods' => [
  874. 'SetHeader' => ['Commandes du ' . $dateStr],
  875. 'SetFooter' => ['{PAGENO}'],
  876. ]
  877. ]);
  878. // return the pdf output as per the destination setting
  879. return $pdf->render();
  880. }
  881. }
  882. /**
  883. * Génère un export des commandes au format CSV à destination du Google Drive
  884. * de Terre de pains.
  885. */
  886. public function actionReportTerredepains($date, $key)
  887. {
  888. $producerManager = $this->getProducerManager();
  889. $orderManager = $this->getOrderManager();
  890. $productManager = $this->getProductManager();
  891. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  892. $producer = $producerManager->findOneProducerBySlug('terredepains');
  893. $idProducer = $producer->id;
  894. $ordersArray = Order::searchAll(
  895. [
  896. 'distribution.date' => $date,
  897. 'distribution.id_producer' => $idProducer
  898. ],
  899. [
  900. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  901. 'conditions' => 'date_delete IS NULL'
  902. ]
  903. );
  904. $distribution = Distribution::searchOne([
  905. 'distribution.id_producer' => $idProducer
  906. ], [
  907. 'conditions' => 'date LIKE :date',
  908. 'params' => [
  909. ':date' => $date,
  910. ]
  911. ]);
  912. if ($distribution) {
  913. $pointsSaleArray = PointSale::searchAll([
  914. 'point_sale.id_producer' => $idProducer
  915. ]);
  916. foreach ($pointsSaleArray as $pointSale) {
  917. $orderManager->initPointSaleOrders($pointSale, $ordersArray);
  918. }
  919. // produits
  920. $productsArray = Product::find()
  921. ->joinWith([
  922. 'productDistribution' => function ($q) use ($distribution) {
  923. $q->where(['id_distribution' => $distribution->id]);
  924. }
  925. ])
  926. ->where([
  927. 'id_producer' => $idProducer,
  928. ])
  929. ->orderBy('order ASC')
  930. ->all();
  931. $datas = [];
  932. // produits en colonne
  933. $productsNameArray = [''];
  934. $productsIndexArray = [];
  935. $productsHasQuantity = [];
  936. $cpt = 1;
  937. foreach ($productsArray as $product) {
  938. $theUnit = $productManager->strUnit($product->unit, 'wording_short', true);
  939. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  940. $productsNameArray[] = $product->name . $theUnit;
  941. $productsIndexArray[$product->id] = $cpt++;
  942. }
  943. $productsNameArray[] = 'Total';
  944. $datas[] = $productsNameArray;
  945. // global
  946. $totalsGlobalArray = $this->_totalReportCSV(
  947. '> Totaux',
  948. $ordersArray,
  949. $productsArray,
  950. $productsIndexArray
  951. );
  952. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  953. $datas[] = [];
  954. // points de vente
  955. foreach ($pointsSaleArray as $pointSale) {
  956. if (count($pointSale->orders)) {
  957. // total point de vente
  958. $totalsPointSaleArray = $this->_totalReportCSV(
  959. '> ' . $pointSale->name,
  960. $pointSale->orders,
  961. $productsArray,
  962. $productsIndexArray
  963. );
  964. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  965. }
  966. }
  967. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  968. echo CSV::array2csv($datas);
  969. die();
  970. }
  971. return null;
  972. }
  973. }
  974. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  975. {
  976. $orderManager = $this->getOrderManager();
  977. $productManager = $this->getProductManager();
  978. $totalsPointSaleArray = [$label];
  979. foreach ($productsArray as $product) {
  980. foreach (Product::$unitsArray as $unit => $dataUnit) {
  981. $quantity = $orderManager->getProductQuantity($product, $ordersArray, false, $unit);
  982. if ($quantity) {
  983. $index = $productsIndexArray[$product->id];
  984. if (!isset($totalsPointSaleArray[$index])) {
  985. $totalsPointSaleArray[$index] = '';
  986. }
  987. if (strlen($totalsPointSaleArray[$index])) {
  988. $totalsPointSaleArray[$index] .= ' + ';
  989. }
  990. $totalsPointSaleArray[$index] .= $quantity;
  991. if ($product->unit != $unit) {
  992. $totalsPointSaleArray[$index] .= '' . $productManager->strUnit($unit, 'wording_short', true);
  993. }
  994. }
  995. }
  996. }
  997. return $totalsPointSaleArray;
  998. }
  999. public function _totalReportPiecesCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  1000. {
  1001. $orderManager = $this->getOrderManager();
  1002. $totalsPointSaleArray = [$label];
  1003. foreach ($productsArray as $product) {
  1004. $quantity = 0;
  1005. foreach (Product::$unitsArray as $unit => $dataUnit) {
  1006. $quantityProduct = $orderManager->getProductQuantity($product, $ordersArray, false, $unit);
  1007. if ($unit == 'piece') {
  1008. $quantity += $quantityProduct;
  1009. } else {
  1010. if ($product->weight > 0) {
  1011. $quantity += ($quantityProduct * $dataUnit['coefficient']) / $product->weight;
  1012. }
  1013. }
  1014. }
  1015. if ($quantity) {
  1016. $index = $productsIndexArray[$product->id];
  1017. $totalsPointSaleArray[$index] = $quantity;
  1018. }
  1019. }
  1020. return $totalsPointSaleArray;
  1021. }
  1022. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  1023. {
  1024. $line = [];
  1025. $cptTotal = 0;
  1026. for ($i = 0; $i <= $cptMax; $i++) {
  1027. if (isset($orderLine[$i]) && $orderLine[$i]) {
  1028. $line[] = $orderLine[$i];
  1029. if (is_numeric($orderLine[$i])) {
  1030. $cptTotal += $orderLine[$i];
  1031. }
  1032. } else {
  1033. $line[] = '';
  1034. }
  1035. }
  1036. if ($cptTotal > 0 && $showTotal) {
  1037. $line[] = $cptTotal;
  1038. }
  1039. return $line;
  1040. }
  1041. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  1042. {
  1043. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1044. $productDistributionManager = $this->getProductDistributionManager();
  1045. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  1046. $productDistribution->quantity_max = ($quantityMax == -1) ? null : (float) abs($quantityMax);
  1047. $productDistributionManager->saveUpdate($productDistribution);
  1048. return ['success'];
  1049. }
  1050. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  1051. {
  1052. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1053. $productDistributionManager = $this->getProductDistributionManager();
  1054. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  1055. $productDistribution->active = $active;
  1056. $productDistributionManager->saveUpdate($productDistribution);
  1057. return ['success'];
  1058. }
  1059. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  1060. {
  1061. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1062. $distributionManager = $this->getDistributionManager();
  1063. $pointSaleManager = $this->getPointSaleManager();
  1064. $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
  1065. $pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution(
  1066. $distributionManager->findOneDistributionById($idDistribution),
  1067. $pointSaleManager->findOnePointSaleById($idPointSale)
  1068. );
  1069. $pointSaleDistribution->delivery = $delivery;
  1070. $pointSaleDistributionManager->saveUpdate($pointSaleDistribution);
  1071. return ['success'];
  1072. }
  1073. public function getProductDistribution(int $idProduct, int $idDistribution)
  1074. {
  1075. $distributionManager = $this->getDistributionManager();
  1076. $productManager = $this->getProductManager();
  1077. $productDistributionManager = $this->getProductDistributionManager();
  1078. return $productDistributionManager->findOneProductDistribution(
  1079. $distributionManager->findOneDistributionById($idDistribution),
  1080. $productManager->findOneProductById($idProduct)
  1081. );
  1082. }
  1083. /**
  1084. * Active/désactive un jour de distribution.
  1085. *
  1086. * @param integer $idDistribution
  1087. * @param string $date
  1088. * @param boolean $active
  1089. * @return array
  1090. */
  1091. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  1092. {
  1093. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1094. $distributionManager = $this->getDistributionManager();
  1095. $producerCurrent = $this->getProducerCurrent();
  1096. if ($idDistribution) {
  1097. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  1098. }
  1099. $format = 'Y-m-d';
  1100. $dateObject = DateTime::createFromFormat($format, $date);
  1101. if ($dateObject && $dateObject->format($format) === $date) {
  1102. $distribution = $distributionManager->createDistributionIfNotExist($date);
  1103. }
  1104. if ($distribution) {
  1105. $distributionManager->activeDistribution($distribution, $active);
  1106. return ['success'];
  1107. }
  1108. return ['error'];
  1109. }
  1110. /**
  1111. * Change l'état d'une semaine de production (activé, désactivé).
  1112. *
  1113. * @param string $date
  1114. * @param integer $active
  1115. */
  1116. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  1117. {
  1118. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1119. $week = sprintf('%02d', date('W', strtotime($date)));
  1120. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  1121. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  1122. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  1123. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  1124. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  1125. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  1126. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  1127. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  1128. $pointsSaleArray = PointSale::searchAll(['status' => 1]);
  1129. $activeMonday = false;
  1130. $activeTuesday = false;
  1131. $activeWednesday = false;
  1132. $activeThursday = false;
  1133. $activeFriday = false;
  1134. $activeSaturday = false;
  1135. $activeSunday = false;
  1136. foreach ($pointsSaleArray as $pointSale) {
  1137. if ($pointSale->delivery_monday) {
  1138. $activeMonday = true;
  1139. }
  1140. if ($pointSale->delivery_tuesday) {
  1141. $activeTuesday = true;
  1142. }
  1143. if ($pointSale->delivery_wednesday) {
  1144. $activeWednesday = true;
  1145. }
  1146. if ($pointSale->delivery_thursday) {
  1147. $activeThursday = true;
  1148. }
  1149. if ($pointSale->delivery_friday) {
  1150. $activeFriday = true;
  1151. }
  1152. if ($pointSale->delivery_saturday) {
  1153. $activeSaturday = true;
  1154. }
  1155. if ($pointSale->delivery_sunday) {
  1156. $activeSunday = true;
  1157. }
  1158. }
  1159. if ($activeMonday || !$active) {
  1160. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  1161. }
  1162. if ($activeTuesday || !$active) {
  1163. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  1164. }
  1165. if ($activeWednesday || !$active) {
  1166. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  1167. }
  1168. if ($activeThursday || !$active) {
  1169. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  1170. }
  1171. if ($activeFriday || !$active) {
  1172. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  1173. }
  1174. if ($activeSaturday || !$active) {
  1175. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  1176. }
  1177. if ($activeSunday || !$active) {
  1178. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  1179. }
  1180. return ['success'];
  1181. }
  1182. /**
  1183. * Ajoute les commandes récurrentes pour une date donnée.
  1184. *
  1185. * @param string $date
  1186. */
  1187. public function actionAjaxProcessAddSubscriptions($date)
  1188. {
  1189. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1190. $this->getOrderManager()->createAllOrdersFromSubscriptions($date, true);
  1191. return ['success'];
  1192. }
  1193. /**
  1194. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  1195. *
  1196. * @param string $date
  1197. */
  1198. public function actionAjaxProcessSynchroTiller($date)
  1199. {
  1200. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1201. $producerManager = $this->getProducerManager();
  1202. $productOrderManager = $this->getProductOrderManager();
  1203. $orderManager = $this->getOrderManager();
  1204. $return = [];
  1205. $producerTiller = $producerManager->getConfig('tiller');
  1206. if ($producerTiller) {
  1207. $tiller = new Tiller();
  1208. $isSynchro = $tiller->isSynchro($date);
  1209. if (!$isSynchro) {
  1210. $orders = Order::searchAll([
  1211. 'distribution.date' => $date,
  1212. 'order.tiller_synchronization' => 1
  1213. ], [
  1214. 'conditions' => 'date_delete IS NULL'
  1215. ]);
  1216. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  1217. if ($orders && count($orders)) {
  1218. foreach ($orders as $order) {
  1219. $orderManager->initOrder($order);
  1220. $lines = [];
  1221. foreach ($order->productOrder as $productOrder) {
  1222. $lines[] = [
  1223. 'name' => $productOrder->product->name,
  1224. 'price' => $productOrderManager->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
  1225. 'tax' => $productOrder->taxRate->value * 100,
  1226. 'date' => $strDate,
  1227. 'quantity' => $productOrder->quantity
  1228. ];
  1229. }
  1230. $typePaymentTiller = '';
  1231. if ($order->mean_payment == MeanPayment::MONEY) {
  1232. $typePaymentTiller = 'CASH';
  1233. }
  1234. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  1235. || $order->mean_payment == MeanPayment::CREDIT
  1236. || $order->mean_payment == MeanPayment::TRANSFER
  1237. || $order->mean_payment == MeanPayment::OTHER) {
  1238. $typePaymentTiller = 'CARD';
  1239. }
  1240. if ($order->mean_payment == MeanPayment::CHEQUE) {
  1241. $typePaymentTiller = 'BANK_CHECK';
  1242. }
  1243. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  1244. $typePaymentTiller = 'CASH';
  1245. }
  1246. $returnTiller = $tiller->postOrder([
  1247. 'externalId' => $order->id,
  1248. 'type' => 1,
  1249. 'status' => 'IN_PROGRESS',
  1250. 'openDate' => $strDate,
  1251. 'closeDate' => $strDate,
  1252. 'lines' => $lines,
  1253. 'payments' => [
  1254. [
  1255. 'type' => $typePaymentTiller,
  1256. 'amount' => $orderManager->getOrderAmountWithTax(
  1257. $order,
  1258. Order::AMOUNT_PAID
  1259. ) * 100,
  1260. 'status' => 'ACCEPTED',
  1261. 'date' => $strDate
  1262. ]
  1263. ]
  1264. ]);
  1265. $returnTillerObject = json_decode($returnTiller);
  1266. $order->tiller_external_id = '' . $returnTillerObject->id;
  1267. $order->save();
  1268. $return[] = $returnTiller;
  1269. }
  1270. }
  1271. }
  1272. }
  1273. return $return;
  1274. }
  1275. public function actionAjaxValidateDeliveryNotes($idOrders)
  1276. {
  1277. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1278. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1279. if (strlen($idOrders)) {
  1280. $idOrders = json_decode($idOrders, true);
  1281. if (is_array($idOrders) && count($idOrders) > 0) {
  1282. foreach ($idOrders as $idOrder) {
  1283. $order = Order::searchOne([
  1284. 'id' => (int)$idOrder
  1285. ]);
  1286. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1287. $deliveryNote = DeliveryNote::searchOne([
  1288. 'id' => (int)$order->id_delivery_note
  1289. ]);
  1290. if ($deliveryNote && $deliveryNoteManager->isStatusDraft($deliveryNote)) {
  1291. $deliveryNoteManager->changeStatus($deliveryNote, Document::STATUS_VALID);
  1292. $deliveryNoteManager->saveUpdate($deliveryNote);
  1293. }
  1294. }
  1295. }
  1296. return [
  1297. 'return' => 'success',
  1298. 'alert' => [
  1299. 'type' => 'success',
  1300. 'message' => 'Bon(s) de livraison validé(s)'
  1301. ]
  1302. ];
  1303. }
  1304. }
  1305. return [
  1306. 'return' => 'error',
  1307. 'alert' => [
  1308. 'type' => 'danger',
  1309. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  1310. ]
  1311. ];
  1312. }
  1313. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  1314. {
  1315. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1316. $userManager = $this->getUserManager();
  1317. $userProducerManager = $this->getUserProducerManager();
  1318. $orderManager = $this->getOrderManager();
  1319. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1320. $producerCurrent = $this->getProducerCurrent();
  1321. if (strlen($idOrders)) {
  1322. $idOrders = json_decode($idOrders, true);
  1323. if (is_array($idOrders) && count($idOrders) > 0) {
  1324. foreach ($idOrders as $idOrder) {
  1325. $order = Order::searchOne([
  1326. 'id' => (int)$idOrder
  1327. ]);
  1328. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_user) {
  1329. $deliveryNote = null;
  1330. $idDeliveryNote = $order->id_delivery_note;
  1331. if ($idDeliveryNote) {
  1332. $deliveryNote = DeliveryNote::searchOne([
  1333. 'id' => (int)$idDeliveryNote
  1334. ]);
  1335. }
  1336. // on regénére le document si c'est un brouillon
  1337. if ($deliveryNote && $deliveryNoteManager->isStatusDraft($deliveryNote)) {
  1338. $deliveryNote->delete();
  1339. $deliveryNote = null;
  1340. }
  1341. if (!$deliveryNote) {
  1342. $deliveryNote = new DeliveryNote();
  1343. $deliveryNoteManager->initTaxCalculationMethod($deliveryNote);
  1344. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1345. $deliveryNote->id_user = $order->id_user;
  1346. $deliveryNote->name = 'Bon de livraison ' . $orderManager->getOrderUsername($order) . ' (' . date(
  1347. 'd/m/Y',
  1348. strtotime(
  1349. $order->distribution->date
  1350. )
  1351. ) . ')';
  1352. $deliveryNote->address = $userManager->getFullAddress($order->user);
  1353. $deliveryNote->save();
  1354. }
  1355. if ($deliveryNote) {
  1356. $order->id_delivery_note = $deliveryNote->id;
  1357. $order->save();
  1358. // init invoice prices
  1359. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1360. $userProducer = $userProducerManager->findOneUserProducer($user);
  1361. $orderManager->updateOrderInvoicePrices($order, [
  1362. 'user' => $user,
  1363. 'user_producer' => $userProducer,
  1364. 'point_sale' => $order->pointSale
  1365. ]);
  1366. }
  1367. }
  1368. }
  1369. }
  1370. return [
  1371. 'return' => 'success',
  1372. 'alert' => [
  1373. 'type' => 'success',
  1374. 'message' => 'Bon(s) de livraison généré(s)'
  1375. ]
  1376. ];
  1377. }
  1378. return [
  1379. 'return' => 'error',
  1380. 'alert' => [
  1381. 'type' => 'danger',
  1382. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1383. ]
  1384. ];
  1385. }
  1386. public function actionAjaxGenerateDeliveryNote($idOrders)
  1387. {
  1388. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1389. $userManager = $this->getUserManager();
  1390. $userProducerManager = $this->getUserProducerManager();
  1391. $orderManager = $this->getOrderManager();
  1392. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1393. $producerCurrent = $this->getProducerCurrent();
  1394. if (strlen($idOrders)) {
  1395. $idOrders = json_decode($idOrders, true);
  1396. if (is_array($idOrders) && count($idOrders) > 0) {
  1397. // récupération première commande pour obtenir des infos
  1398. reset($idOrders);
  1399. $firstOrder = Order::searchOne([
  1400. 'id' => (int)$idOrders[key($idOrders)]
  1401. ]);
  1402. // deliveryNote existant
  1403. $deliveryNote = null;
  1404. $isUpdate = false;
  1405. $i = 0;
  1406. $ordersArray = Order::searchAll([
  1407. 'id' => $idOrders,
  1408. ]);
  1409. do {
  1410. $order = $ordersArray[$i];
  1411. if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  1412. $deliveryNote = DeliveryNote::searchOne([
  1413. 'id' => $order->id_delivery_note
  1414. ]);
  1415. $isUpdate = true;
  1416. }
  1417. $i++;
  1418. } while ($deliveryNote == null && isset($ordersArray[$i]));
  1419. if ($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1420. return [
  1421. 'return' => 'error',
  1422. 'alert' => [
  1423. 'type' => 'danger',
  1424. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1425. ]
  1426. ];
  1427. }
  1428. if ($firstOrder) {
  1429. // génération du BL
  1430. if (!$deliveryNote) {
  1431. $deliveryNote = new DeliveryNote;
  1432. $deliveryNoteManager->initTaxCalculationMethod($deliveryNote);
  1433. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date(
  1434. 'd/m/Y',
  1435. strtotime(
  1436. $firstOrder->distribution->date
  1437. )
  1438. ) . ')';
  1439. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1440. if ($firstOrder->pointSale->id_user) {
  1441. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1442. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1443. $userProducer = $userProducerManager->findOneUserProducer($user);
  1444. } else {
  1445. $user = new User();
  1446. $user->type = User::TYPE_LEGAL_PERSON;
  1447. $user->name_legal_person = $firstOrder->pointSale->name;
  1448. $user->address = $firstOrder->pointSale->address;
  1449. $user->id_producer = 0;
  1450. $userManager->setPassword($user, Password::generate());
  1451. $userManager->generateAuthKey($user);
  1452. $user->email = '';
  1453. if (!strlen($user->email)) {
  1454. $user->username = 'inconnu@opendistrib.net';
  1455. }
  1456. $user->save();
  1457. $userProducer = new UserProducer();
  1458. $userProducer->id_user = $user->id;
  1459. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1460. $userProducer->credit = 0;
  1461. $userProducer->active = 1;
  1462. $userProducer->save();
  1463. $firstOrder->pointSale->id_user = $user->id;
  1464. $firstOrder->pointSale->save();
  1465. $deliveryNote->id_user = $user->id;
  1466. }
  1467. $deliveryNote->address = $userManager->getFullAddress($user);
  1468. $deliveryNote->save();
  1469. } else {
  1470. // réinitialisation des order.id_delivery_note
  1471. Order::updateAll([
  1472. 'id_delivery_note' => null
  1473. ], [
  1474. 'id_delivery_note' => $deliveryNote->id
  1475. ]);
  1476. }
  1477. if (!isset($user) || !$user) {
  1478. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1479. $userProducer = $userProducerManager->findOneUserProducer($user);
  1480. }
  1481. // affectation du BL aux commandes
  1482. foreach ($idOrders as $idOrder) {
  1483. $order = $orderManager->findOneOrderById((int)$idOrder);
  1484. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1485. $order->id_delivery_note = $deliveryNote->id;
  1486. $order->save();
  1487. }
  1488. // init invoice price
  1489. $order = $orderManager->findOneOrderById((int)$idOrder);
  1490. if ($order) {
  1491. $orderManager->updateOrderInvoicePrices($order,
  1492. [
  1493. 'user' => $user,
  1494. 'user_producer' => $userProducer,
  1495. 'point_sale' => $firstOrder->pointSale
  1496. ]);
  1497. }
  1498. }
  1499. return [
  1500. 'return' => 'success',
  1501. 'alert' => [
  1502. 'type' => 'success',
  1503. 'message' => 'Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré')
  1504. ]
  1505. ];
  1506. }
  1507. }
  1508. }
  1509. return [
  1510. 'return' => 'error',
  1511. 'alert' => [
  1512. 'type' => 'danger',
  1513. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1514. ]
  1515. ];
  1516. }
  1517. }