Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1785 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\Product\Product\Model\Product;
  50. use common\logic\User\User\Model\User;
  51. use common\logic\User\UserProducer\Model\UserProducer;
  52. use DateTime;
  53. use kartik\mpdf\Pdf;
  54. use yii\filters\AccessControl;
  55. class DistributionController extends BackendController
  56. {
  57. public function behaviors()
  58. {
  59. return [
  60. 'access' => [
  61. 'class' => AccessControl::class,
  62. 'rules' => [
  63. [
  64. 'actions' => ['report-cron', 'report-terredepains'],
  65. 'allow' => true,
  66. 'roles' => ['?']
  67. ],
  68. [
  69. 'allow' => true,
  70. 'roles' => ['@'],
  71. 'matchCallback' => function ($rule, $action) {
  72. $userManager = $this->getUserManager();
  73. return $userManager->isCurrentAdmin() || $userManager->isCurrentProducer();
  74. }
  75. ]
  76. ],
  77. ],
  78. ];
  79. }
  80. public function actionIndex($date = '', $idOrderUpdate = 0)
  81. {
  82. $this->checkProductsPointsSale();
  83. $orderManager = $this->getOrderManager();
  84. $format = 'Y-m-d';
  85. $theDate = '';
  86. $dateObject = DateTime::createFromFormat($format, $date);
  87. if ($dateObject && $dateObject->format($format) === $date) {
  88. $theDate = $date;
  89. }
  90. $orderUpdate = null;
  91. if ($idOrderUpdate) {
  92. $orderUpdate = $orderManager->findOneOrderById($idOrderUpdate);
  93. }
  94. return $this->render('index', [
  95. 'date' => $theDate,
  96. 'orderUpdate' => $orderUpdate
  97. ]);
  98. }
  99. public function actionAjaxInfos($date = '')
  100. {
  101. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  102. $distributionManager = $this->getDistributionManager();
  103. $orderManager = $this->getOrderManager();
  104. $productManager = $this->getProductManager();
  105. $creditHistoryManager = $this->getCreditHistoryManager();
  106. $userManager = $this->getUserManager();
  107. $subscriptionManager = $this->getSubscriptionManager();
  108. $producer = $this->getProducerCurrent();
  109. $json = [
  110. 'distribution' => [],
  111. 'products' => []
  112. ];
  113. $format = 'Y-m-d';
  114. $dateObject = DateTime::createFromFormat($format, $date);
  115. $numberOfLoadedMonthes = '3 month';
  116. if (is_object($dateObject)) {
  117. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  118. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  119. } else {
  120. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  121. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  122. }
  123. $json['producer'] = [
  124. 'credit' => $producer->credit,
  125. 'tiller' => $producer->tiller,
  126. 'option_display_export_grid' => $producer->option_display_export_grid
  127. ];
  128. $json['means_payment'] = MeanPayment::getAll();
  129. $distributionsArray = Distribution::searchAll([
  130. 'active' => 1
  131. ], [
  132. 'conditions' => [
  133. 'date > :date_begin',
  134. 'date < :date_end'
  135. ],
  136. 'params' => [
  137. ':date_begin' => date(
  138. 'Y-m-d',
  139. $dateBegin
  140. ),
  141. ':date_end' => date(
  142. 'Y-m-d',
  143. $dateEnd
  144. ),
  145. ],
  146. ]);
  147. $json['distributions'] = $distributionsArray;
  148. if ($dateObject && $dateObject->format($format) === $date) {
  149. $distribution = $distributionManager->createDistributionIfNotExist($date);
  150. $json['distribution'] = [
  151. 'id' => $distribution->id,
  152. 'active' => $distribution->active,
  153. 'url_report' => $this->getUrlManagerBackend()->createUrl(
  154. ['distribution/report', 'date' => $distribution->date]
  155. ),
  156. 'url_report_grid' => $this->getUrlManagerBackend()->createUrl(
  157. ['distribution/report-grid', 'date' => $distribution->date]
  158. ),
  159. ];
  160. $ordersArray = Order::searchAll([
  161. 'distribution.id' => $distribution->id,
  162. ], [
  163. 'orderby' => 'user.lastname ASC, user.name ASC'
  164. ]);
  165. // montant et poids des commandes
  166. $revenues = 0;
  167. $weight = 0;
  168. if ($ordersArray) {
  169. foreach ($ordersArray as $order) {
  170. $orderManager->initOrder($order);
  171. if (is_null($order->date_delete)) {
  172. $revenues += $orderManager->getOrderAmountWithTax($order);
  173. $weight += $order->weight;
  174. }
  175. }
  176. }
  177. $json['distribution']['revenues'] = Price::format($revenues);
  178. $json['distribution']['weight'] = number_format($weight, 2);
  179. // products
  180. $productsQuery = Product::find()
  181. ->orWhere(['id_producer' => GlobalParam::getCurrentProducerId(),])
  182. ->joinWith([
  183. 'taxRate',
  184. 'productDistribution' => function ($query) use ($distribution) {
  185. $query->andOnCondition(
  186. 'product_distribution.id_distribution = ' . $distribution->id
  187. );
  188. }
  189. ])
  190. ->orderBy('product_distribution.active DESC, order ASC');
  191. $productsArray = $productsQuery->asArray()->all();
  192. $potentialRevenues = 0;
  193. $potentialWeight = 0;
  194. foreach ($productsArray as &$theProduct) {
  195. $productObject = $productManager->findOneProductById($theProduct['id']);
  196. $quantityOrder = $orderManager->getProductQuantity($productObject, $ordersArray);
  197. $theProduct['quantity_ordered'] = $quantityOrder;
  198. if (!isset($theProduct['productDistribution'][0])) {
  199. $theProductObject = (object)$theProduct;
  200. $theProduct['productDistribution'][0] = $distributionManager->addProduct($distribution, $productObject);
  201. }
  202. if (!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  203. $theProduct['quantity_remaining'] = null;
  204. } else {
  205. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder;
  206. }
  207. $theProduct['quantity_form'] = 0;
  208. if ($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  209. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  210. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  211. }
  212. if (!isset($theProduct['taxRate'])) {
  213. $theProduct['taxRate'] = $producer->taxRate;
  214. }
  215. }
  216. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues);
  217. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2);
  218. $json['products'] = $productsArray;
  219. // orders as array
  220. $ordersArrayObject = $ordersArray;
  221. if ($ordersArray) {
  222. foreach ($ordersArray as &$order) {
  223. $orderManager->initOrder($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, 3),
  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' => $userManager->getUsername($creditHistory->getUserObject()),
  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' => $producer->id,
  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 (!$subscriptionManager->hasOrderAlreadyExist($subscription, $ordersArrayObject)
  388. && $subscription->productSubscription && count($subscription->productSubscription)
  389. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  390. $json['missing_subscriptions'][] = [
  391. 'username' => $subscriptionManager->getUsername($subscription)
  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, 3);
  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. $pointSaleManager = $this->getPointSaleManager();
  527. if (!\Yii::$app->user->isGuest) {
  528. $idProducer = GlobalParam::getCurrentProducerId();
  529. }
  530. $ordersArray = Order::searchAll(
  531. [
  532. 'distribution.date' => $date,
  533. 'distribution.id_producer' => $idProducer
  534. ],
  535. [
  536. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  537. 'conditions' => 'date_delete IS NULL'
  538. ]
  539. );
  540. $distribution = Distribution::searchOne([
  541. 'id_producer' => $idProducer
  542. ], [
  543. 'conditions' => 'date LIKE :date',
  544. 'params' => [':date' => $date]
  545. ]);
  546. if ($distribution) {
  547. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  548. $pointsSaleArray = PointSale::searchAll([
  549. 'point_sale.id_producer' => $idProducer
  550. ]);
  551. foreach ($pointsSaleArray as $pointSale) {
  552. $orderManager->initPointSaleOrders($pointSale, $ordersArray);
  553. }
  554. // produits
  555. $productsArray = Product::find()
  556. ->joinWith([
  557. 'productDistribution' => function ($q) use ($distribution) {
  558. $q->where(['id_distribution' => $distribution->id]);
  559. }
  560. ])
  561. ->where([
  562. 'id_producer' => $idProducer,
  563. ])
  564. ->orderBy('order ASC')
  565. ->all();
  566. if ($type == 'pdf') {
  567. $viewPdf = 'report';
  568. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  569. $producer = GlobalParam::getCurrentProducer();
  570. if ($producer->slug == 'bourlinguepacotille') {
  571. $viewPdf = 'report-bourlingue';
  572. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  573. }
  574. // get your HTML raw content without any layouts or scripts
  575. $content = $this->renderPartial($viewPdf, [
  576. 'date' => $date,
  577. 'distribution' => $distribution,
  578. 'selectedProductsArray' => $selectedProductsArray,
  579. 'pointsSaleArray' => $pointsSaleArray,
  580. 'productsArray' => $productsArray,
  581. 'ordersArray' => $ordersArray,
  582. 'producer' => $producerManager->findOneProducerById($idProducer)
  583. ]);
  584. $dateStr = date('d/m/Y', strtotime($date));
  585. if ($save) {
  586. $destination = Pdf::DEST_FILE;
  587. } else {
  588. $destination = Pdf::DEST_BROWSER;
  589. }
  590. $pdf = new Pdf([
  591. // set to use core fonts only
  592. 'mode' => Pdf::MODE_UTF8,
  593. // A4 paper format
  594. 'format' => Pdf::FORMAT_A4,
  595. // portrait orientation
  596. 'orientation' => $orientationPdf,
  597. // stream to browser inline
  598. 'destination' => $destination,
  599. 'filename' => \Yii::getAlias(
  600. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  601. ),
  602. // your html content input
  603. 'content' => $content,
  604. // format content from your own css file if needed or use the
  605. // enhanced bootstrap css built by Krajee for mPDF formatting
  606. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  607. // any css to be embedded if required
  608. 'cssInline' => '
  609. table {
  610. border-spacing : 0px ;
  611. border-collapse : collapse ;
  612. width: 100% ;
  613. }
  614. table tr th,
  615. table tr td {
  616. padding: 0px ;
  617. margin: 0px ;
  618. border: solid 1px #e0e0e0 ;
  619. padding: 3px 8px ;
  620. vertical-align : top;
  621. page-break-inside: avoid !important;
  622. color: black;
  623. }
  624. table tr th {
  625. font-size: 13px ;
  626. }
  627. table tr td {
  628. font-size: 13px ;
  629. }
  630. ',
  631. // set mPDF properties on the fly
  632. //'options' => ['title' => 'Krajee Report Title'],
  633. // call mPDF methods on the fly
  634. 'methods' => [
  635. 'SetHeader' => ['Commandes du ' . $dateStr],
  636. 'SetFooter' => ['{PAGENO}'],
  637. ]
  638. ]);
  639. // return the pdf output as per the destination setting
  640. return $pdf->render();
  641. } elseif ($type == 'csv') {
  642. $datas = [];
  643. $optionCsvExportAllProducts = $producerManager->getConfig('option_csv_export_all_products');
  644. $optionCsvExportByPiece = $producerManager->getConfig('option_csv_export_by_piece');
  645. // produits en colonne
  646. $productsNameArray = ['', 'Commentaire'];
  647. $productsIndexArray = [];
  648. $productsHasQuantity = [];
  649. $cpt = 2;
  650. foreach ($productsArray as $product) {
  651. $productsHasQuantity[$product->id] = 0;
  652. foreach (Product::$unitsArray as $unit => $dataUnit) {
  653. $quantity = $orderManager->getProductQuantity($product, $ordersArray, true, $unit);
  654. if ($quantity) {
  655. $productsHasQuantity[$product->id] += $quantity;
  656. }
  657. }
  658. if ($productsHasQuantity[$product->id] > 0 || $optionCsvExportAllProducts) {
  659. $productName = $productManager->getNameExport($product);
  660. if ($optionCsvExportByPiece) {
  661. $productUnit = 'piece';
  662. } else {
  663. $productUnit = $product->unit;
  664. }
  665. $productName .= ' (' . $productManager->strUnit($productUnit, 'wording_short', true) . ')';
  666. $productsNameArray[] = $productName;
  667. $productsIndexArray[$product->id] = $cpt++;
  668. }
  669. }
  670. $datas[] = $productsNameArray;
  671. // points de vente
  672. foreach ($pointsSaleArray as $pointSale) {
  673. if (count($pointSale->orders)) {
  674. // listing commandes
  675. $datas[] = ['> ' . $pointSale->name];
  676. foreach ($pointSale->orders as $order) {
  677. $orderLine = [$orderManager->getOrderUsername($order), $orderManager->getCommentReport($order)];
  678. if ($optionCsvExportByPiece) {
  679. foreach ($order->productOrder as $productOrder) {
  680. $orderLine[$productsIndexArray[$productOrder->id_product]] = $orderManager->getProductQuantityPieces(
  681. $productOrder->product,
  682. [$order]
  683. );
  684. }
  685. } else {
  686. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  687. $orderLine[$indexProduct] = '';
  688. }
  689. foreach ($order->productOrder as $productOrder) {
  690. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  691. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  692. }
  693. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  694. if ($productOrder->product->unit != $productOrder->unit) {
  695. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productManager->strUnit(
  696. $productOrder->unit,
  697. 'wording_short',
  698. true
  699. );
  700. }
  701. }
  702. }
  703. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  704. }
  705. // total point de vente
  706. if ($optionCsvExportByPiece) {
  707. $totalsPointSaleArray = $this->_totalReportPiecesCSV(
  708. 'Total',
  709. $pointSale->orders,
  710. $productsArray,
  711. $productsIndexArray
  712. );
  713. } else {
  714. $totalsPointSaleArray = $this->_totalReportCSV(
  715. 'Total',
  716. $pointSale->orders,
  717. $productsArray,
  718. $productsIndexArray
  719. );
  720. }
  721. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  722. $datas[] = [];
  723. }
  724. }
  725. // global
  726. if ($optionCsvExportByPiece) {
  727. $totalsGlobalArray = $this->_totalReportPiecesCSV(
  728. '> Totaux',
  729. $ordersArray,
  730. $productsArray,
  731. $productsIndexArray
  732. );
  733. } else {
  734. $totalsGlobalArray = $this->_totalReportCSV(
  735. '> Totaux',
  736. $ordersArray,
  737. $productsArray,
  738. $productsIndexArray
  739. );
  740. }
  741. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  742. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  743. echo CSV::array2csv($datas);
  744. die();
  745. }
  746. }
  747. return null;
  748. }
  749. public function actionReportGrid($date = '', $save = false, $idProducer = 0, $type = "pdf")
  750. {
  751. $producerManager = $this->getProducerManager();
  752. $productDistribution = $this->getProductDistributionManager();
  753. $orderManager = $this->getOrderManager();
  754. $productCategoryManager = $this->getProductCategoryManager();
  755. if (!\Yii::$app->user->isGuest) {
  756. $idProducer = GlobalParam::getCurrentProducerId();
  757. }
  758. $distribution = Distribution::searchOne([
  759. 'id_producer' => $idProducer
  760. ], [
  761. 'conditions' => 'date LIKE :date',
  762. 'params' => [':date' => $date]
  763. ]);
  764. if ($distribution) {
  765. $ordersArray = Order::searchAll(
  766. [
  767. 'distribution.date' => $date,
  768. 'distribution.id_producer' => $idProducer
  769. ],
  770. [
  771. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  772. 'conditions' => 'date_delete IS NULL'
  773. ]
  774. );
  775. $selectedProductsArray = $productDistribution->findProductDistributionsByDistribution($distribution);
  776. $pointsSaleArray = PointSale::searchAll([
  777. 'point_sale.id_producer' => $idProducer
  778. ]);
  779. foreach ($pointsSaleArray as $pointSale) {
  780. $orderManager->initPointSaleOrders($pointSale, $ordersArray);
  781. }
  782. $ordersByPage = 22;
  783. $nbPages = ceil(count($ordersArray) / $ordersByPage);
  784. $ordersArrayPaged = [];
  785. foreach ($pointsSaleArray as $pointSale) {
  786. $index = 0;
  787. $indexPage = 0;
  788. foreach ($pointSale->orders as $order) {
  789. if (!isset($ordersArrayPaged[$pointSale->id])) {
  790. $ordersArrayPaged[$pointSale->id] = [];
  791. }
  792. if (!isset($ordersArrayPaged[$pointSale->id][$indexPage])) {
  793. $ordersArrayPaged[$pointSale->id][$indexPage] = [];
  794. }
  795. $ordersArrayPaged[$pointSale->id][$indexPage][] = $order;
  796. $index++;
  797. if ($index == $ordersByPage) {
  798. $index = 0;
  799. $indexPage++;
  800. }
  801. }
  802. }
  803. // catégories
  804. $categoriesArray = $productCategoryManager->findProductCategories();
  805. array_unshift($categoriesArray, null);
  806. // produits
  807. $productsArray = Product::find()
  808. ->joinWith([
  809. 'productDistribution' => function ($q) use ($distribution) {
  810. $q->where(['id_distribution' => $distribution->id]);
  811. }
  812. ])
  813. ->where([
  814. 'id_producer' => $idProducer,
  815. ])
  816. ->orderBy('order ASC')
  817. ->all();
  818. $viewPdf = 'report-grid';
  819. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  820. $producer = GlobalParam::getCurrentProducer();
  821. if ($producer->slug == 'bourlinguepacotille') {
  822. $viewPdf = 'report-bourlingue';
  823. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  824. }
  825. // get your HTML raw content without any layouts or scripts
  826. $content = $this->renderPartial($viewPdf, [
  827. 'date' => $date,
  828. 'distribution' => $distribution,
  829. 'selectedProductsArray' => $selectedProductsArray,
  830. 'pointsSaleArray' => $pointsSaleArray,
  831. 'categoriesArray' => $categoriesArray,
  832. 'productsArray' => $productsArray,
  833. 'ordersArray' => $ordersArrayPaged,
  834. 'producer' => $producerManager->findOneProducerById($idProducer)
  835. ]);
  836. $dateStr = date('d/m/Y', strtotime($date));
  837. if ($save) {
  838. $destination = Pdf::DEST_FILE;
  839. } else {
  840. $destination = Pdf::DEST_BROWSER;
  841. }
  842. $pdf = new Pdf([
  843. // set to use core fonts only
  844. 'mode' => Pdf::MODE_UTF8,
  845. // A4 paper format
  846. 'format' => Pdf::FORMAT_A4,
  847. // portrait orientation
  848. 'orientation' => $orientationPdf,
  849. // stream to browser inline
  850. 'destination' => $destination,
  851. 'filename' => \Yii::getAlias(
  852. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  853. ),
  854. // your html content input
  855. 'content' => $content,
  856. // format content from your own css file if needed or use the
  857. // enhanced bootstrap css built by Krajee for mPDF formatting
  858. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  859. // any css to be embedded if required
  860. 'cssInline' => '
  861. table {
  862. border-spacing : 0px ;
  863. border-collapse : collapse ;
  864. width: 100% ;
  865. }
  866. table tr th,
  867. table tr td {
  868. padding: 0px ;
  869. margin: 0px ;
  870. border: solid 1px #e0e0e0 ;
  871. padding: 3px ;
  872. vertical-align : top;
  873. page-break-inside: avoid !important;
  874. }
  875. table tr th {
  876. font-size: 10px ;
  877. }
  878. table tr td {
  879. font-size: 10px ;
  880. }
  881. table thead tr {
  882. line-height: 220px;
  883. text-align:left;
  884. }
  885. .th-user,
  886. .td-nb-products {
  887. /* width: 35px ; */
  888. text-align: center ;
  889. }
  890. .th-user {
  891. padding: 10px ;
  892. }
  893. .category-name {
  894. font-weight: bold ;
  895. }
  896. ',
  897. // set mPDF properties on the fly
  898. //'options' => ['title' => 'Krajee Report Title'],
  899. // call mPDF methods on the fly
  900. 'methods' => [
  901. 'SetHeader' => ['Commandes du ' . $dateStr],
  902. 'SetFooter' => ['{PAGENO}'],
  903. ]
  904. ]);
  905. // return the pdf output as per the destination setting
  906. return $pdf->render();
  907. }
  908. }
  909. /**
  910. * Génère un export des commandes au format CSV à destination du Google Drive
  911. * de Terre de pains.
  912. */
  913. public function actionReportTerredepains($date, $key)
  914. {
  915. $producerManager = $this->getProducerManager();
  916. $orderManager = $this->getOrderManager();
  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. $orderManager->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. // total point de vente
  985. $totalsPointSaleArray = $this->_totalReportCSV(
  986. '> ' . $pointSale->name,
  987. $pointSale->orders,
  988. $productsArray,
  989. $productsIndexArray
  990. );
  991. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  992. }
  993. }
  994. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  995. echo CSV::array2csv($datas);
  996. die();
  997. }
  998. return null;
  999. }
  1000. }
  1001. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  1002. {
  1003. $orderManager = $this->getOrderManager();
  1004. $productManager = $this->getProductManager();
  1005. $totalsPointSaleArray = [$label];
  1006. foreach ($productsArray as $product) {
  1007. foreach (Product::$unitsArray as $unit => $dataUnit) {
  1008. $quantity = $orderManager->getProductQuantity($product, $ordersArray, false, $unit);
  1009. if ($quantity) {
  1010. $index = $productsIndexArray[$product->id];
  1011. if (!isset($totalsPointSaleArray[$index])) {
  1012. $totalsPointSaleArray[$index] = '';
  1013. }
  1014. if (strlen($totalsPointSaleArray[$index])) {
  1015. $totalsPointSaleArray[$index] .= ' + ';
  1016. }
  1017. $totalsPointSaleArray[$index] .= $quantity;
  1018. if ($product->unit != $unit) {
  1019. $totalsPointSaleArray[$index] .= '' . $productManager->strUnit($unit, 'wording_short', true);
  1020. }
  1021. }
  1022. }
  1023. }
  1024. return $totalsPointSaleArray;
  1025. }
  1026. public function _totalReportPiecesCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  1027. {
  1028. $orderManager = $this->getOrderManager();
  1029. $totalsPointSaleArray = [$label];
  1030. foreach ($productsArray as $product) {
  1031. $quantity = 0;
  1032. foreach (Product::$unitsArray as $unit => $dataUnit) {
  1033. $quantityProduct = $orderManager->getProductQuantity($product, $ordersArray, false, $unit);
  1034. if ($unit == 'piece') {
  1035. $quantity += $quantityProduct;
  1036. } else {
  1037. if ($product->weight > 0) {
  1038. $quantity += ($quantityProduct * $dataUnit['coefficient']) / $product->weight;
  1039. }
  1040. }
  1041. }
  1042. if ($quantity) {
  1043. $index = $productsIndexArray[$product->id];
  1044. $totalsPointSaleArray[$index] = $quantity;
  1045. }
  1046. }
  1047. return $totalsPointSaleArray;
  1048. }
  1049. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  1050. {
  1051. $line = [];
  1052. $cptTotal = 0;
  1053. for ($i = 0; $i <= $cptMax; $i++) {
  1054. if (isset($orderLine[$i]) && $orderLine[$i]) {
  1055. $line[] = $orderLine[$i];
  1056. if (is_numeric($orderLine[$i])) {
  1057. $cptTotal += $orderLine[$i];
  1058. }
  1059. } else {
  1060. $line[] = '';
  1061. }
  1062. }
  1063. if ($cptTotal > 0 && $showTotal) {
  1064. $line[] = $cptTotal;
  1065. }
  1066. return $line;
  1067. }
  1068. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  1069. {
  1070. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1071. $productDistributionManager = $this->getProductDistributionManager();
  1072. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  1073. $productDistribution->quantity_max = (!$quantityMax) ? null : (float)$quantityMax;
  1074. $productDistributionManager->saveUpdate($productDistribution);
  1075. return ['success'];
  1076. }
  1077. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  1078. {
  1079. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1080. $productDistributionManager = $this->getProductDistributionManager();
  1081. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  1082. $productDistribution->active = $active;
  1083. $productDistributionManager->saveUpdate($productDistribution);
  1084. return ['success'];
  1085. }
  1086. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  1087. {
  1088. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1089. $distributionManager = $this->getDistributionManager();
  1090. $pointSaleManager = $this->getPointSaleManager();
  1091. $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
  1092. $pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution(
  1093. $distributionManager->findOneDistributionById($idDistribution),
  1094. $pointSaleManager->findOnePointSaleById($idPointSale)
  1095. );
  1096. $pointSaleDistribution->delivery = $delivery;
  1097. $pointSaleDistributionManager->saveUpdate($pointSaleDistribution);
  1098. return ['success'];
  1099. }
  1100. public function getProductDistribution(int $idProduct, int $idDistribution)
  1101. {
  1102. $distributionManager = $this->getDistributionManager();
  1103. $productManager = $this->getProductManager();
  1104. $productDistributionManager = $this->getProductDistributionManager();
  1105. return $productDistributionManager->findOneProductDistribution(
  1106. $distributionManager->findOneDistributionById($idDistribution),
  1107. $productManager->findOneProductById($idProduct)
  1108. );
  1109. }
  1110. /**
  1111. * Active/désactive un jour de distribution.
  1112. *
  1113. * @param integer $idDistribution
  1114. * @param string $date
  1115. * @param boolean $active
  1116. * @return array
  1117. */
  1118. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  1119. {
  1120. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1121. $distributionManager = $this->getDistributionManager();
  1122. $producerCurrent = $this->getProducerCurrent();
  1123. if ($idDistribution) {
  1124. $distribution = $distributionManager->findOneDistributionById($idDistribution);
  1125. }
  1126. $format = 'Y-m-d';
  1127. $dateObject = DateTime::createFromFormat($format, $date);
  1128. if ($dateObject && $dateObject->format($format) === $date) {
  1129. $distribution = $distributionManager->createDistributionIfNotExist($date);
  1130. }
  1131. if ($distribution) {
  1132. $distributionManager->activeDistribution($distribution, $active);
  1133. return ['success'];
  1134. }
  1135. return ['error'];
  1136. }
  1137. /**
  1138. * Change l'état d'une semaine de production (activé, désactivé).
  1139. *
  1140. * @param string $date
  1141. * @param integer $active
  1142. */
  1143. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  1144. {
  1145. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1146. $week = sprintf('%02d', date('W', strtotime($date)));
  1147. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  1148. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  1149. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  1150. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  1151. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  1152. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  1153. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  1154. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  1155. $pointsSaleArray = PointSale::searchAll();
  1156. $activeMonday = false;
  1157. $activeTuesday = false;
  1158. $activeWednesday = false;
  1159. $activeThursday = false;
  1160. $activeFriday = false;
  1161. $activeSaturday = false;
  1162. $activeSunday = false;
  1163. foreach ($pointsSaleArray as $pointSale) {
  1164. if ($pointSale->delivery_monday) {
  1165. $activeMonday = true;
  1166. }
  1167. if ($pointSale->delivery_tuesday) {
  1168. $activeTuesday = true;
  1169. }
  1170. if ($pointSale->delivery_wednesday) {
  1171. $activeWednesday = true;
  1172. }
  1173. if ($pointSale->delivery_thursday) {
  1174. $activeThursday = true;
  1175. }
  1176. if ($pointSale->delivery_friday) {
  1177. $activeFriday = true;
  1178. }
  1179. if ($pointSale->delivery_saturday) {
  1180. $activeSaturday = true;
  1181. }
  1182. if ($pointSale->delivery_sunday) {
  1183. $activeSunday = true;
  1184. }
  1185. }
  1186. if ($activeMonday || !$active) {
  1187. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  1188. }
  1189. if ($activeTuesday || !$active) {
  1190. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  1191. }
  1192. if ($activeWednesday || !$active) {
  1193. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  1194. }
  1195. if ($activeThursday || !$active) {
  1196. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  1197. }
  1198. if ($activeFriday || !$active) {
  1199. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  1200. }
  1201. if ($activeSaturday || !$active) {
  1202. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  1203. }
  1204. if ($activeSunday || !$active) {
  1205. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  1206. }
  1207. return ['success'];
  1208. }
  1209. /**
  1210. * Ajoute les commandes récurrentes pour une date donnée.
  1211. *
  1212. * @param string $date
  1213. */
  1214. public function actionAjaxProcessAddSubscriptions($date)
  1215. {
  1216. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1217. $this->getOrderManager()->createAllOrdersFromSubscriptions($date, true);
  1218. return ['success'];
  1219. }
  1220. /**
  1221. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  1222. *
  1223. * @param string $date
  1224. */
  1225. public function actionAjaxProcessSynchroTiller($date)
  1226. {
  1227. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1228. $producerManager = $this->getProducerManager();
  1229. $productOrderManager = $this->getProductOrderManager();
  1230. $orderManager = $this->getOrderManager();
  1231. $return = [];
  1232. $producerTiller = $producerManager->getConfig('tiller');
  1233. if ($producerTiller) {
  1234. $tiller = new Tiller();
  1235. $isSynchro = $tiller->isSynchro($date);
  1236. if (!$isSynchro) {
  1237. $orders = Order::searchAll([
  1238. 'distribution.date' => $date,
  1239. 'order.tiller_synchronization' => 1
  1240. ], [
  1241. 'conditions' => 'date_delete IS NULL'
  1242. ]);
  1243. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  1244. if ($orders && count($orders)) {
  1245. foreach ($orders as $order) {
  1246. $orderManager->initOrder($order);
  1247. $lines = [];
  1248. foreach ($order->productOrder as $productOrder) {
  1249. $lines[] = [
  1250. 'name' => $productOrder->product->name,
  1251. 'price' => $productOrderManager->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
  1252. 'tax' => $productOrder->taxRate->value * 100,
  1253. 'date' => $strDate,
  1254. 'quantity' => $productOrder->quantity
  1255. ];
  1256. }
  1257. $typePaymentTiller = '';
  1258. if ($order->mean_payment == MeanPayment::MONEY) {
  1259. $typePaymentTiller = 'CASH';
  1260. }
  1261. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  1262. || $order->mean_payment == MeanPayment::CREDIT
  1263. || $order->mean_payment == MeanPayment::TRANSFER
  1264. || $order->mean_payment == MeanPayment::OTHER) {
  1265. $typePaymentTiller = 'CARD';
  1266. }
  1267. if ($order->mean_payment == MeanPayment::CHEQUE) {
  1268. $typePaymentTiller = 'BANK_CHECK';
  1269. }
  1270. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  1271. $typePaymentTiller = 'CASH';
  1272. }
  1273. $returnTiller = $tiller->postOrder([
  1274. 'externalId' => $order->id,
  1275. 'type' => 1,
  1276. 'status' => 'IN_PROGRESS',
  1277. 'openDate' => $strDate,
  1278. 'closeDate' => $strDate,
  1279. 'lines' => $lines,
  1280. 'payments' => [
  1281. [
  1282. 'type' => $typePaymentTiller,
  1283. 'amount' => $orderManager->getOrderAmountWithTax(
  1284. $order,
  1285. Order::AMOUNT_PAID
  1286. ) * 100,
  1287. 'status' => 'ACCEPTED',
  1288. 'date' => $strDate
  1289. ]
  1290. ]
  1291. ]);
  1292. $returnTillerObject = json_decode($returnTiller);
  1293. $order->tiller_external_id = '' . $returnTillerObject->id;
  1294. $order->save();
  1295. $return[] = $returnTiller;
  1296. }
  1297. }
  1298. }
  1299. }
  1300. return $return;
  1301. }
  1302. public function actionAjaxValidateDeliveryNotes($idOrders)
  1303. {
  1304. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1305. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1306. if (strlen($idOrders)) {
  1307. $idOrders = json_decode($idOrders, true);
  1308. if (is_array($idOrders) && count($idOrders) > 0) {
  1309. foreach ($idOrders as $idOrder) {
  1310. $order = Order::searchOne([
  1311. 'id' => (int)$idOrder
  1312. ]);
  1313. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1314. $deliveryNote = DeliveryNote::searchOne([
  1315. 'id' => (int)$order->id_delivery_note
  1316. ]);
  1317. if ($deliveryNote && $deliveryNoteManager->isStatusDraft($deliveryNote)) {
  1318. $deliveryNoteManager->changeStatus($deliveryNote, Document::STATUS_VALID);
  1319. $deliveryNoteManager->saveUpdate($deliveryNote);
  1320. }
  1321. }
  1322. }
  1323. return [
  1324. 'return' => 'success',
  1325. 'alert' => [
  1326. 'type' => 'success',
  1327. 'message' => 'Bon(s) de livraison validé(s)'
  1328. ]
  1329. ];
  1330. }
  1331. }
  1332. return [
  1333. 'return' => 'error',
  1334. 'alert' => [
  1335. 'type' => 'danger',
  1336. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  1337. ]
  1338. ];
  1339. }
  1340. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  1341. {
  1342. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1343. $userManager = $this->getUserManager();
  1344. $userProducerManager = $this->getUserProducerManager();
  1345. $orderManager = $this->getOrderManager();
  1346. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1347. $producerCurrent = $this->getProducerCurrent();
  1348. if (strlen($idOrders)) {
  1349. $idOrders = json_decode($idOrders, true);
  1350. if (is_array($idOrders) && count($idOrders) > 0) {
  1351. foreach ($idOrders as $idOrder) {
  1352. $order = Order::searchOne([
  1353. 'id' => (int)$idOrder
  1354. ]);
  1355. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_user) {
  1356. $deliveryNote = null;
  1357. $idDeliveryNote = $order->id_delivery_note;
  1358. if ($idDeliveryNote) {
  1359. $deliveryNote = DeliveryNote::searchOne([
  1360. 'id' => (int)$idDeliveryNote
  1361. ]);
  1362. }
  1363. // on regénére le document si c'est un brouillon
  1364. if ($deliveryNote && $deliveryNoteManager->isStatusDraft($deliveryNote)) {
  1365. $deliveryNote->delete();
  1366. $deliveryNote = null;
  1367. }
  1368. if (!$deliveryNote) {
  1369. $deliveryNote = new DeliveryNote();
  1370. $deliveryNoteManager->initTaxCalculationMethod($deliveryNote);
  1371. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1372. $deliveryNote->id_user = $order->id_user;
  1373. $deliveryNote->name = 'Bon de livraison ' . $orderManager->getOrderUsername($order) . ' (' . date(
  1374. 'd/m/Y',
  1375. strtotime(
  1376. $order->distribution->date
  1377. )
  1378. ) . ')';
  1379. $deliveryNote->address = $userManager->getFullAddress($order->user);
  1380. $deliveryNote->save();
  1381. }
  1382. if ($deliveryNote) {
  1383. $order->id_delivery_note = $deliveryNote->id;
  1384. $order->save();
  1385. // init invoice prices
  1386. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1387. $userProducer = $userProducerManager->findOneUserProducer($user, $producerCurrent);
  1388. $orderManager->updateOrderInvoicePrices($order, [
  1389. 'user' => $user,
  1390. 'user_producer' => $userProducer,
  1391. 'point_sale' => $order->pointSale
  1392. ]);
  1393. }
  1394. }
  1395. }
  1396. }
  1397. return [
  1398. 'return' => 'success',
  1399. 'alert' => [
  1400. 'type' => 'success',
  1401. 'message' => 'Bon(s) de livraison généré(s)'
  1402. ]
  1403. ];
  1404. }
  1405. return [
  1406. 'return' => 'error',
  1407. 'alert' => [
  1408. 'type' => 'danger',
  1409. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1410. ]
  1411. ];
  1412. }
  1413. public function actionAjaxGenerateDeliveryNote($idOrders)
  1414. {
  1415. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1416. $userManager = $this->getUserManager();
  1417. $userProducerManager = $this->getUserProducerManager();
  1418. $orderManager = $this->getOrderManager();
  1419. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1420. $producerCurrent = $this->getProducerCurrent();
  1421. if (strlen($idOrders)) {
  1422. $idOrders = json_decode($idOrders, true);
  1423. if (is_array($idOrders) && count($idOrders) > 0) {
  1424. // récupération première commande pour obtenir des infos
  1425. reset($idOrders);
  1426. $firstOrder = Order::searchOne([
  1427. 'id' => (int)$idOrders[key($idOrders)]
  1428. ]);
  1429. // deliveryNote existant
  1430. $deliveryNote = null;
  1431. $isUpdate = false;
  1432. $i = 0;
  1433. $ordersArray = Order::searchAll([
  1434. 'id' => $idOrders,
  1435. ]);
  1436. do {
  1437. $order = $ordersArray[$i];
  1438. if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  1439. $deliveryNote = DeliveryNote::searchOne([
  1440. 'id' => $order->id_delivery_note
  1441. ]);
  1442. $isUpdate = true;
  1443. }
  1444. $i++;
  1445. } while ($deliveryNote == null && isset($ordersArray[$i]));
  1446. if ($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1447. return [
  1448. 'return' => 'error',
  1449. 'alert' => [
  1450. 'type' => 'danger',
  1451. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1452. ]
  1453. ];
  1454. }
  1455. if ($firstOrder) {
  1456. // génération du BL
  1457. if (!$deliveryNote) {
  1458. $deliveryNote = new DeliveryNote;
  1459. $deliveryNoteManager->initTaxCalculationMethod($deliveryNote);
  1460. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date(
  1461. 'd/m/Y',
  1462. strtotime(
  1463. $firstOrder->distribution->date
  1464. )
  1465. ) . ')';
  1466. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1467. if ($firstOrder->pointSale->id_user) {
  1468. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1469. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1470. $userProducer = $userProducerManager->findOneUserProducer($user, $producerCurrent);
  1471. } else {
  1472. $user = new User();
  1473. $user->type = User::TYPE_LEGAL_PERSON;
  1474. $user->name_legal_person = $firstOrder->pointSale->name;
  1475. $user->address = $firstOrder->pointSale->address;
  1476. $user->id_producer = 0;
  1477. $userManager->setPassword($user, Password::generate());
  1478. $userManager->generateAuthKey($user);
  1479. $user->email = '';
  1480. if (!strlen($user->email)) {
  1481. $user->username = 'inconnu@opendistrib.net';
  1482. }
  1483. $user->save();
  1484. $userProducer = new UserProducer();
  1485. $userProducer->id_user = $user->id;
  1486. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1487. $userProducer->credit = 0;
  1488. $userProducer->active = 1;
  1489. $userProducer->save();
  1490. $firstOrder->pointSale->id_user = $user->id;
  1491. $firstOrder->pointSale->save();
  1492. $deliveryNote->id_user = $user->id;
  1493. }
  1494. $deliveryNote->address = $userManager->getFullAddress($user);
  1495. $deliveryNote->save();
  1496. } else {
  1497. // réinitialisation des order.id_delivery_note
  1498. Order::updateAll([
  1499. 'id_delivery_note' => null
  1500. ], [
  1501. 'id_delivery_note' => $deliveryNote->id
  1502. ]);
  1503. }
  1504. if (!isset($user) || !$user) {
  1505. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1506. $userProducer = $userProducerManager->findOneUserProducer($user, $producerCurrent);
  1507. }
  1508. // affectation du BL aux commandes
  1509. foreach ($idOrders as $idOrder) {
  1510. $order = $orderManager->findOneOrderById((int)$idOrder);
  1511. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1512. $order->id_delivery_note = $deliveryNote->id;
  1513. $order->save();
  1514. }
  1515. // init invoice price
  1516. $order = $orderManager->findOneOrderById((int)$idOrder);
  1517. if ($order) {
  1518. $orderManager->updateOrderInvoicePrices($order,
  1519. [
  1520. 'user' => $user,
  1521. 'user_producer' => $userProducer,
  1522. 'point_sale' => $firstOrder->pointSale
  1523. ]);
  1524. }
  1525. }
  1526. return [
  1527. 'return' => 'success',
  1528. 'alert' => [
  1529. 'type' => 'success',
  1530. 'message' => 'Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré')
  1531. ]
  1532. ];
  1533. }
  1534. }
  1535. }
  1536. return [
  1537. 'return' => 'error',
  1538. 'alert' => [
  1539. 'type' => 'danger',
  1540. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1541. ]
  1542. ];
  1543. }
  1544. }