Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1803 lines
73KB

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