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.

1773 lines
71KB

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