Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1783 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, 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' => $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, 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. $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. $lines = [];
  1247. foreach ($order->productOrder as $productOrder) {
  1248. $lines[] = [
  1249. 'name' => $productOrder->product->name,
  1250. 'price' => $productOrderManager->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
  1251. 'tax' => $productOrder->taxRate->value * 100,
  1252. 'date' => $strDate,
  1253. 'quantity' => $productOrder->quantity
  1254. ];
  1255. }
  1256. $typePaymentTiller = '';
  1257. if ($order->mean_payment == MeanPayment::MONEY) {
  1258. $typePaymentTiller = 'CASH';
  1259. }
  1260. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  1261. || $order->mean_payment == MeanPayment::CREDIT
  1262. || $order->mean_payment == MeanPayment::TRANSFER
  1263. || $order->mean_payment == MeanPayment::OTHER) {
  1264. $typePaymentTiller = 'CARD';
  1265. }
  1266. if ($order->mean_payment == MeanPayment::CHEQUE) {
  1267. $typePaymentTiller = 'BANK_CHECK';
  1268. }
  1269. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  1270. $typePaymentTiller = 'CASH';
  1271. }
  1272. $returnTiller = $tiller->postOrder([
  1273. 'externalId' => $order->id,
  1274. 'type' => 1,
  1275. 'status' => 'IN_PROGRESS',
  1276. 'openDate' => $strDate,
  1277. 'closeDate' => $strDate,
  1278. 'lines' => $lines,
  1279. 'payments' => [
  1280. [
  1281. 'type' => $typePaymentTiller,
  1282. 'amount' => $orderManager->getOrderAmountWithTax(
  1283. $order,
  1284. Order::AMOUNT_TOTAL
  1285. ) * 100,
  1286. 'status' => 'ACCEPTED',
  1287. 'date' => $strDate
  1288. ]
  1289. ]
  1290. ]);
  1291. $returnTillerObject = json_decode($returnTiller);
  1292. $order->tiller_external_id = '' . $returnTillerObject->id;
  1293. $order->save();
  1294. $return[] = $returnTiller;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. return $return;
  1300. }
  1301. public function actionAjaxValidateDeliveryNotes($idOrders)
  1302. {
  1303. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1304. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1305. if (strlen($idOrders)) {
  1306. $idOrders = json_decode($idOrders, true);
  1307. if (is_array($idOrders) && count($idOrders) > 0) {
  1308. foreach ($idOrders as $idOrder) {
  1309. $order = Order::searchOne([
  1310. 'id' => (int)$idOrder
  1311. ]);
  1312. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1313. $deliveryNote = DeliveryNote::searchOne([
  1314. 'id' => (int)$order->id_delivery_note
  1315. ]);
  1316. if ($deliveryNote && $deliveryNoteManager->isStatusDraft($deliveryNote)) {
  1317. $deliveryNoteManager->changeStatus($deliveryNote, Document::STATUS_VALID);
  1318. $deliveryNoteManager->saveUpdate($deliveryNote);
  1319. }
  1320. }
  1321. }
  1322. return [
  1323. 'return' => 'success',
  1324. 'alert' => [
  1325. 'type' => 'success',
  1326. 'message' => 'Bon(s) de livraison validé(s)'
  1327. ]
  1328. ];
  1329. }
  1330. }
  1331. return [
  1332. 'return' => 'error',
  1333. 'alert' => [
  1334. 'type' => 'danger',
  1335. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  1336. ]
  1337. ];
  1338. }
  1339. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  1340. {
  1341. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1342. $userManager = $this->getUserManager();
  1343. $userProducerManager = $this->getUserProducerManager();
  1344. $orderManager = $this->getOrderManager();
  1345. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1346. $producerCurrent = $this->getProducerCurrent();
  1347. if (strlen($idOrders)) {
  1348. $idOrders = json_decode($idOrders, true);
  1349. if (is_array($idOrders) && count($idOrders) > 0) {
  1350. foreach ($idOrders as $idOrder) {
  1351. $order = Order::searchOne([
  1352. 'id' => (int)$idOrder
  1353. ]);
  1354. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_user) {
  1355. $deliveryNote = null;
  1356. $idDeliveryNote = $order->id_delivery_note;
  1357. if ($idDeliveryNote) {
  1358. $deliveryNote = DeliveryNote::searchOne([
  1359. 'id' => (int)$idDeliveryNote
  1360. ]);
  1361. }
  1362. // on regénére le document si c'est un brouillon
  1363. if ($deliveryNote && $deliveryNoteManager->isStatusDraft($deliveryNote)) {
  1364. $deliveryNote->delete();
  1365. $deliveryNote = null;
  1366. }
  1367. if (!$deliveryNote) {
  1368. $deliveryNote = new DeliveryNote();
  1369. $deliveryNoteManager->initTaxCalculationMethod($deliveryNote);
  1370. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1371. $deliveryNote->id_user = $order->id_user;
  1372. $deliveryNote->name = 'Bon de livraison ' . $orderManager->getOrderUsername($order) . ' (' . date(
  1373. 'd/m/Y',
  1374. strtotime(
  1375. $order->distribution->date
  1376. )
  1377. ) . ')';
  1378. $deliveryNote->address = $userManager->getFullAddress($order->user);
  1379. $deliveryNote->save();
  1380. }
  1381. if ($deliveryNote) {
  1382. $order->id_delivery_note = $deliveryNote->id;
  1383. $order->save();
  1384. // init invoice prices
  1385. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1386. $userProducer = $userProducerManager->findOneUserProducer($user, $producerCurrent);
  1387. $orderManager->updateOrderInvoicePrices($order, [
  1388. 'user' => $user,
  1389. 'user_producer' => $userProducer,
  1390. 'point_sale' => $order->pointSale
  1391. ]);
  1392. }
  1393. }
  1394. }
  1395. }
  1396. return [
  1397. 'return' => 'success',
  1398. 'alert' => [
  1399. 'type' => 'success',
  1400. 'message' => 'Bon(s) de livraison généré(s)'
  1401. ]
  1402. ];
  1403. }
  1404. return [
  1405. 'return' => 'error',
  1406. 'alert' => [
  1407. 'type' => 'danger',
  1408. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1409. ]
  1410. ];
  1411. }
  1412. public function actionAjaxGenerateDeliveryNote($idOrders)
  1413. {
  1414. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1415. $userManager = $this->getUserManager();
  1416. $userProducerManager = $this->getUserProducerManager();
  1417. $orderManager = $this->getOrderManager();
  1418. $deliveryNoteManager = $this->getDeliveryNoteManager();
  1419. $producerCurrent = $this->getProducerCurrent();
  1420. if (strlen($idOrders)) {
  1421. $idOrders = json_decode($idOrders, true);
  1422. if (is_array($idOrders) && count($idOrders) > 0) {
  1423. // récupération première commande pour obtenir des infos
  1424. reset($idOrders);
  1425. $firstOrder = Order::searchOne([
  1426. 'id' => (int)$idOrders[key($idOrders)]
  1427. ]);
  1428. // deliveryNote existant
  1429. $deliveryNote = null;
  1430. $isUpdate = false;
  1431. $i = 0;
  1432. $ordersArray = Order::searchAll([
  1433. 'id' => $idOrders,
  1434. ]);
  1435. do {
  1436. $order = $ordersArray[$i];
  1437. if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  1438. $deliveryNote = DeliveryNote::searchOne([
  1439. 'id' => $order->id_delivery_note
  1440. ]);
  1441. $isUpdate = true;
  1442. }
  1443. $i++;
  1444. } while ($deliveryNote == null && isset($ordersArray[$i]));
  1445. if ($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1446. return [
  1447. 'return' => 'error',
  1448. 'alert' => [
  1449. 'type' => 'danger',
  1450. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1451. ]
  1452. ];
  1453. }
  1454. if ($firstOrder) {
  1455. // génération du BL
  1456. if (!$deliveryNote) {
  1457. $deliveryNote = new DeliveryNote;
  1458. $deliveryNoteManager->initTaxCalculationMethod($deliveryNote);
  1459. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date(
  1460. 'd/m/Y',
  1461. strtotime(
  1462. $firstOrder->distribution->date
  1463. )
  1464. ) . ')';
  1465. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1466. if ($firstOrder->pointSale->id_user) {
  1467. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1468. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1469. $userProducer = $userProducerManager->findOneUserProducer($user, $producerCurrent);
  1470. } else {
  1471. $user = new User();
  1472. $user->type = User::TYPE_LEGAL_PERSON;
  1473. $user->name_legal_person = $firstOrder->pointSale->name;
  1474. $user->address = $firstOrder->pointSale->address;
  1475. $user->id_producer = 0;
  1476. $userManager->setPassword($user, Password::generate());
  1477. $userManager->generateAuthKey($user);
  1478. $user->email = '';
  1479. if (!strlen($user->email)) {
  1480. $user->username = 'inconnu@opendistrib.net';
  1481. }
  1482. $user->save();
  1483. $userProducer = new UserProducer();
  1484. $userProducer->id_user = $user->id;
  1485. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1486. $userProducer->credit = 0;
  1487. $userProducer->active = 1;
  1488. $userProducer->save();
  1489. $firstOrder->pointSale->id_user = $user->id;
  1490. $firstOrder->pointSale->save();
  1491. $deliveryNote->id_user = $user->id;
  1492. }
  1493. $deliveryNote->address = $userManager->getFullAddress($user);
  1494. $deliveryNote->save();
  1495. } else {
  1496. // réinitialisation des order.id_delivery_note
  1497. Order::updateAll([
  1498. 'id_delivery_note' => null
  1499. ], [
  1500. 'id_delivery_note' => $deliveryNote->id
  1501. ]);
  1502. }
  1503. if (!isset($user) || !$user) {
  1504. $user = $userManager->findOneUserById($deliveryNote->id_user);
  1505. $userProducer = $userProducerManager->findOneUserProducer($user, $producerCurrent);
  1506. }
  1507. // affectation du BL aux commandes
  1508. foreach ($idOrders as $idOrder) {
  1509. $order = $orderManager->findOneOrderById((int)$idOrder);
  1510. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1511. $order->id_delivery_note = $deliveryNote->id;
  1512. $order->save();
  1513. }
  1514. // init invoice price
  1515. $order = $orderManager->findOneOrderById((int)$idOrder);
  1516. if ($order) {
  1517. $orderManager->updateOrderInvoicePrices($order,
  1518. [
  1519. 'user' => $user,
  1520. 'user_producer' => $userProducer,
  1521. 'point_sale' => $firstOrder->pointSale
  1522. ]);
  1523. }
  1524. }
  1525. return [
  1526. 'return' => 'success',
  1527. 'alert' => [
  1528. 'type' => 'success',
  1529. 'message' => 'Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré')
  1530. ]
  1531. ];
  1532. }
  1533. }
  1534. }
  1535. return [
  1536. 'return' => 'error',
  1537. 'alert' => [
  1538. 'type' => 'danger',
  1539. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1540. ]
  1541. ];
  1542. }
  1543. }