Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1802 lines
72KB

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