You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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