Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1666 Zeilen
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($idDistribution, $idUser = false, $idPointSale = false)
  383. {
  384. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  385. $distribution = Distribution::findOne($idDistribution);
  386. $user = User::findOne($idUser);
  387. $userProducer = UserProducer::searchOne([
  388. 'id_user' => $idUser,
  389. ]);
  390. $pointSale = PointSale::findOne($idPointSale);
  391. $productsArray = Product::find()
  392. ->where([
  393. 'id_producer' => GlobalParam::getCurrentProducerId(),
  394. 'product.active' => 1,
  395. ])->joinWith([
  396. 'productPrice',
  397. 'productDistribution' => function ($q) use ($distribution) {
  398. $q->where(['id_distribution' => $distribution->id]);
  399. }
  400. ])->all();
  401. $productOrderArray = [];
  402. foreach ($productsArray as $product) {
  403. $productOrderArray[$product['id']] = [
  404. 'quantity' => 0,
  405. 'unit' => $product->unit,
  406. 'price' => $product->getPriceWithTax([
  407. 'user' => $user,
  408. 'user_producer' => $userProducer,
  409. 'point_sale' => $pointSale
  410. ]),
  411. 'active' => $product->productDistribution[0]->active
  412. && (!$pointSale || $product->isAvailableOnPointSale($pointSale))
  413. ];
  414. }
  415. return $productOrderArray;
  416. }
  417. /**
  418. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  419. * date donnée (Méthode appelable via CRON)
  420. *
  421. * @param string $date
  422. * @param boolean $save
  423. * @param integer $idProducer
  424. * @param string $key
  425. * @return PDF|null
  426. */
  427. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  428. {
  429. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  430. $this->actionReport($date, $save, $idProducer);
  431. }
  432. }
  433. /**
  434. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  435. * date donnée.
  436. *
  437. * @param string $date
  438. * @param boolean $save
  439. * @param integer $idProducer
  440. * @return PDF|null
  441. */
  442. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  443. {
  444. if (!Yii::$app->user->isGuest) {
  445. $idProducer = GlobalParam::getCurrentProducerId();
  446. }
  447. $ordersArray = Order::searchAll(
  448. [
  449. 'distribution.date' => $date,
  450. 'distribution.id_producer' => $idProducer
  451. ],
  452. [
  453. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  454. 'conditions' => 'date_delete IS NULL'
  455. ]
  456. );
  457. $distribution = Distribution::searchOne([
  458. 'id_producer' => $idProducer
  459. ], [
  460. 'conditions' => 'date LIKE :date',
  461. 'params' => [':date' => $date]
  462. ]);
  463. if ($distribution) {
  464. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  465. $pointsSaleArray = PointSale::searchAll([
  466. 'point_sale.id_producer' => $idProducer
  467. ]);
  468. foreach ($pointsSaleArray as $pointSale) {
  469. $pointSale->initOrders($ordersArray);
  470. }
  471. // produits
  472. $productsArray = Product::find()
  473. ->joinWith([
  474. 'productDistribution' => function ($q) use ($distribution) {
  475. $q->where(['id_distribution' => $distribution->id]);
  476. }
  477. ])
  478. ->where([
  479. 'id_producer' => $idProducer,
  480. ])
  481. ->orderBy('order ASC')
  482. ->all();
  483. if ($type == 'pdf') {
  484. $viewPdf = 'report';
  485. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  486. $producer = GlobalParam::getCurrentProducer();
  487. if ($producer->slug == 'bourlinguepacotille') {
  488. $viewPdf = 'report-bourlingue';
  489. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  490. }
  491. // get your HTML raw content without any layouts or scripts
  492. $content = $this->renderPartial($viewPdf, [
  493. 'date' => $date,
  494. 'distribution' => $distribution,
  495. 'selectedProductsArray' => $selectedProductsArray,
  496. 'pointsSaleArray' => $pointsSaleArray,
  497. 'productsArray' => $productsArray,
  498. 'ordersArray' => $ordersArray,
  499. 'producer' => Producer::searchOne(['id' => $idProducer])
  500. ]);
  501. $dateStr = date('d/m/Y', strtotime($date));
  502. if ($save) {
  503. $destination = Pdf::DEST_FILE;
  504. } else {
  505. $destination = Pdf::DEST_BROWSER;
  506. }
  507. $pdf = new Pdf([
  508. // set to use core fonts only
  509. 'mode' => Pdf::MODE_UTF8,
  510. // A4 paper format
  511. 'format' => Pdf::FORMAT_A4,
  512. // portrait orientation
  513. 'orientation' => $orientationPdf,
  514. // stream to browser inline
  515. 'destination' => $destination,
  516. 'filename' => Yii::getAlias(
  517. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  518. ),
  519. // your html content input
  520. 'content' => $content,
  521. // format content from your own css file if needed or use the
  522. // enhanced bootstrap css built by Krajee for mPDF formatting
  523. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  524. // any css to be embedded if required
  525. 'cssInline' => '
  526. table {
  527. border-spacing : 0px ;
  528. border-collapse : collapse ;
  529. width: 100% ;
  530. }
  531. table tr th,
  532. table tr td {
  533. padding: 0px ;
  534. margin: 0px ;
  535. border: solid 1px #e0e0e0 ;
  536. padding: 3px 8px ;
  537. vertical-align : top;
  538. page-break-inside: avoid !important;
  539. color: black;
  540. }
  541. table tr th {
  542. font-size: 13px ;
  543. }
  544. table tr td {
  545. font-size: 13px ;
  546. }
  547. ',
  548. // set mPDF properties on the fly
  549. //'options' => ['title' => 'Krajee Report Title'],
  550. // call mPDF methods on the fly
  551. 'methods' => [
  552. 'SetHeader' => ['Commandes du ' . $dateStr],
  553. 'SetFooter' => ['{PAGENO}'],
  554. ]
  555. ]);
  556. // return the pdf output as per the destination setting
  557. return $pdf->render();
  558. } elseif ($type == 'csv') {
  559. $datas = [];
  560. $optionCsvExportAllProducts = Producer::getConfig('option_csv_export_all_products');
  561. $optionCsvExportByPiece = Producer::getConfig('option_csv_export_by_piece');
  562. // produits en colonne
  563. $productsNameArray = ['', 'Commentaire'];
  564. $productsIndexArray = [];
  565. $productsHasQuantity = [];
  566. $cpt = 2;
  567. foreach ($productsArray as $product) {
  568. $productsHasQuantity[$product->id] = 0;
  569. foreach (Product::$unitsArray as $unit => $dataUnit) {
  570. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  571. if ($quantity) {
  572. $productsHasQuantity[$product->id] += $quantity;
  573. }
  574. }
  575. if ($productsHasQuantity[$product->id] > 0 || $optionCsvExportAllProducts) {
  576. $productName = $product->getNameExport();
  577. if ($optionCsvExportByPiece) {
  578. $productUnit = 'piece';
  579. } else {
  580. $productUnit = $product->unit;
  581. }
  582. $productName .= ' (' . Product::strUnit($productUnit, 'wording_short', true) . ')';
  583. $productsNameArray[] = $productName;
  584. $productsIndexArray[$product->id] = $cpt++;
  585. }
  586. }
  587. $datas[] = $productsNameArray;
  588. // points de vente
  589. foreach ($pointsSaleArray as $pointSale) {
  590. if (count($pointSale->orders)) {
  591. // listing commandes
  592. $datas[] = ['> ' . $pointSale->name];
  593. foreach ($pointSale->orders as $order) {
  594. $orderLine = [$order->getStrUser(), $order->getCommentReport()];
  595. if ($optionCsvExportByPiece) {
  596. foreach ($order->productOrder as $productOrder) {
  597. $orderLine[$productsIndexArray[$productOrder->id_product]] = Order::getProductQuantityPieces(
  598. $productOrder->id_product,
  599. [$order]
  600. );
  601. }
  602. } else {
  603. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  604. $orderLine[$indexProduct] = '';
  605. }
  606. foreach ($order->productOrder as $productOrder) {
  607. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  608. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  609. }
  610. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  611. if ($productOrder->product->unit != $productOrder->unit) {
  612. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit(
  613. $productOrder->unit,
  614. 'wording_short',
  615. true
  616. );
  617. }
  618. }
  619. }
  620. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  621. }
  622. // total point de vente
  623. if ($optionCsvExportByPiece) {
  624. $totalsPointSaleArray = $this->_totalReportPiecesCSV(
  625. 'Total',
  626. $pointSale->orders,
  627. $productsArray,
  628. $productsIndexArray
  629. );
  630. } else {
  631. $totalsPointSaleArray = $this->_totalReportCSV(
  632. 'Total',
  633. $pointSale->orders,
  634. $productsArray,
  635. $productsIndexArray
  636. );
  637. }
  638. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  639. $datas[] = [];
  640. }
  641. }
  642. // global
  643. if ($optionCsvExportByPiece) {
  644. $totalsGlobalArray = $this->_totalReportPiecesCSV(
  645. '> Totaux',
  646. $ordersArray,
  647. $productsArray,
  648. $productsIndexArray
  649. );
  650. } else {
  651. $totalsGlobalArray = $this->_totalReportCSV(
  652. '> Totaux',
  653. $ordersArray,
  654. $productsArray,
  655. $productsIndexArray
  656. );
  657. }
  658. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  659. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  660. echo CSV::array2csv($datas);
  661. die();
  662. }
  663. }
  664. return null;
  665. }
  666. public function actionReportGrid($date = '', $save = false, $idProducer = 0, $type = "pdf")
  667. {
  668. if (!Yii::$app->user->isGuest) {
  669. $idProducer = GlobalParam::getCurrentProducerId();
  670. }
  671. $distribution = Distribution::searchOne([
  672. 'id_producer' => $idProducer
  673. ], [
  674. 'conditions' => 'date LIKE :date',
  675. 'params' => [':date' => $date]
  676. ]);
  677. if ($distribution) {
  678. $ordersArray = Order::searchAll(
  679. [
  680. 'distribution.date' => $date,
  681. 'distribution.id_producer' => $idProducer
  682. ],
  683. [
  684. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  685. 'conditions' => 'date_delete IS NULL'
  686. ]
  687. );
  688. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  689. $pointsSaleArray = PointSale::searchAll([
  690. 'point_sale.id_producer' => $idProducer
  691. ]);
  692. foreach ($pointsSaleArray as $pointSale) {
  693. $pointSale->initOrders($ordersArray);
  694. }
  695. $ordersByPage = 22;
  696. $nbPages = ceil(count($ordersArray) / $ordersByPage);
  697. $ordersArrayPaged = [];
  698. foreach ($pointsSaleArray as $pointSale) {
  699. $index = 0;
  700. $indexPage = 0;
  701. foreach ($pointSale->orders as $order) {
  702. if (!isset($ordersArrayPaged[$pointSale->id])) {
  703. $ordersArrayPaged[$pointSale->id] = [];
  704. }
  705. if (!isset($ordersArrayPaged[$pointSale->id][$indexPage])) {
  706. $ordersArrayPaged[$pointSale->id][$indexPage] = [];
  707. }
  708. $ordersArrayPaged[$pointSale->id][$indexPage][] = $order;
  709. $index++;
  710. if ($index == $ordersByPage) {
  711. $index = 0;
  712. $indexPage++;
  713. }
  714. }
  715. }
  716. // catégories
  717. $categoriesArray = ProductCategory::searchAll(
  718. ['id_producer' => $idProducer],
  719. ['orderby' => 'product_category.position ASC']
  720. );
  721. array_unshift($categoriesArray, null);
  722. // produits
  723. $productsArray = Product::find()
  724. ->joinWith([
  725. 'productDistribution' => function ($q) use ($distribution) {
  726. $q->where(['id_distribution' => $distribution->id]);
  727. }
  728. ])
  729. ->where([
  730. 'id_producer' => $idProducer,
  731. ])
  732. ->orderBy('order ASC')
  733. ->all();
  734. $viewPdf = 'report-grid';
  735. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  736. $producer = GlobalParam::getCurrentProducer();
  737. if ($producer->slug == 'bourlinguepacotille') {
  738. $viewPdf = 'report-bourlingue';
  739. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  740. }
  741. // get your HTML raw content without any layouts or scripts
  742. $content = $this->renderPartial($viewPdf, [
  743. 'date' => $date,
  744. 'distribution' => $distribution,
  745. 'selectedProductsArray' => $selectedProductsArray,
  746. 'pointsSaleArray' => $pointsSaleArray,
  747. 'categoriesArray' => $categoriesArray,
  748. 'productsArray' => $productsArray,
  749. 'ordersArray' => $ordersArrayPaged,
  750. 'producer' => Producer::searchOne(['id' => $idProducer])
  751. ]);
  752. $dateStr = date('d/m/Y', strtotime($date));
  753. if ($save) {
  754. $destination = Pdf::DEST_FILE;
  755. } else {
  756. $destination = Pdf::DEST_BROWSER;
  757. }
  758. $pdf = new Pdf([
  759. // set to use core fonts only
  760. 'mode' => Pdf::MODE_UTF8,
  761. // A4 paper format
  762. 'format' => Pdf::FORMAT_A4,
  763. // portrait orientation
  764. 'orientation' => $orientationPdf,
  765. // stream to browser inline
  766. 'destination' => $destination,
  767. 'filename' => Yii::getAlias(
  768. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  769. ),
  770. // your html content input
  771. 'content' => $content,
  772. // format content from your own css file if needed or use the
  773. // enhanced bootstrap css built by Krajee for mPDF formatting
  774. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  775. // any css to be embedded if required
  776. 'cssInline' => '
  777. table {
  778. border-spacing : 0px ;
  779. border-collapse : collapse ;
  780. width: 100% ;
  781. }
  782. table tr th,
  783. table tr td {
  784. padding: 0px ;
  785. margin: 0px ;
  786. border: solid 1px #e0e0e0 ;
  787. padding: 3px ;
  788. vertical-align : top;
  789. page-break-inside: avoid !important;
  790. }
  791. table tr th {
  792. font-size: 10px ;
  793. }
  794. table tr td {
  795. font-size: 10px ;
  796. }
  797. table thead tr {
  798. line-height: 220px;
  799. text-align:left;
  800. }
  801. .th-user,
  802. .td-nb-products {
  803. /* width: 35px ; */
  804. text-align: center ;
  805. }
  806. .th-user {
  807. padding: 10px ;
  808. }
  809. .category-name {
  810. font-weight: bold ;
  811. }
  812. ',
  813. // set mPDF properties on the fly
  814. //'options' => ['title' => 'Krajee Report Title'],
  815. // call mPDF methods on the fly
  816. 'methods' => [
  817. 'SetHeader' => ['Commandes du ' . $dateStr],
  818. 'SetFooter' => ['{PAGENO}'],
  819. ]
  820. ]);
  821. // return the pdf output as per the destination setting
  822. return $pdf->render();
  823. }
  824. }
  825. /**
  826. * Génère un export des commandes au format CSV à destination du Google Drive
  827. * de Terre de pains.
  828. *
  829. * @param type $date
  830. * @return CSV
  831. */
  832. public function actionReportTerredepains($date, $key)
  833. {
  834. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  835. $producer = Producer::searchOne([
  836. 'producer.slug' => 'terredepains'
  837. ]);
  838. $idProducer = $producer->id;
  839. $ordersArray = Order::searchAll(
  840. [
  841. 'distribution.date' => $date,
  842. 'distribution.id_producer' => $idProducer
  843. ],
  844. [
  845. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  846. 'conditions' => 'date_delete IS NULL'
  847. ]
  848. );
  849. $distribution = Distribution::searchOne([
  850. 'distribution.id_producer' => $idProducer
  851. ], [
  852. 'conditions' => 'date LIKE :date',
  853. 'params' => [
  854. ':date' => $date,
  855. ]
  856. ]);
  857. if ($distribution) {
  858. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  859. $pointsSaleArray = PointSale::searchAll([
  860. 'point_sale.id_producer' => $idProducer
  861. ]);
  862. foreach ($pointsSaleArray as $pointSale) {
  863. $pointSale->initOrders($ordersArray);
  864. }
  865. // produits
  866. $productsArray = Product::find()
  867. ->joinWith([
  868. 'productDistribution' => function ($q) use ($distribution) {
  869. $q->where(['id_distribution' => $distribution->id]);
  870. }
  871. ])
  872. ->where([
  873. 'id_producer' => $idProducer,
  874. ])
  875. ->orderBy('order ASC')
  876. ->all();
  877. $datas = [];
  878. // produits en colonne
  879. $productsNameArray = [''];
  880. $productsIndexArray = [];
  881. $productsHasQuantity = [];
  882. $cpt = 1;
  883. foreach ($productsArray as $product) {
  884. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  885. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  886. $productsNameArray[] = $product->name . $theUnit;
  887. $productsIndexArray[$product->id] = $cpt++;
  888. }
  889. $productsNameArray[] = 'Total';
  890. $datas[] = $productsNameArray;
  891. // global
  892. $totalsGlobalArray = $this->_totalReportCSV(
  893. '> Totaux',
  894. $ordersArray,
  895. $productsArray,
  896. $productsIndexArray
  897. );
  898. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  899. $datas[] = [];
  900. // points de vente
  901. foreach ($pointsSaleArray as $pointSale) {
  902. if (count($pointSale->orders)) {
  903. // listing commandes
  904. /*foreach ($pointSale->orders as $order) {
  905. $orderLine = [$order->getStrUser()];
  906. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  907. $orderLine[$indexProduct] = '';
  908. }
  909. foreach ($order->productOrder as $productOrder) {
  910. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  911. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  912. }
  913. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  914. if ($productOrder->product->unit != $productOrder->unit) {
  915. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  916. }
  917. }
  918. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  919. }*/
  920. // total point de vente
  921. $totalsPointSaleArray = $this->_totalReportCSV(
  922. '> ' . $pointSale->name,
  923. $pointSale->orders,
  924. $productsArray,
  925. $productsIndexArray
  926. );
  927. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  928. }
  929. }
  930. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  931. echo CSV::array2csv($datas);
  932. die();
  933. }
  934. return null;
  935. }
  936. }
  937. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  938. {
  939. $totalsPointSaleArray = [$label];
  940. foreach ($productsArray as $product) {
  941. foreach (Product::$unitsArray as $unit => $dataUnit) {
  942. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  943. if ($quantity) {
  944. $index = $productsIndexArray[$product->id];
  945. if (!isset($totalsPointSaleArray[$index])) {
  946. $totalsPointSaleArray[$index] = '';
  947. }
  948. if (strlen($totalsPointSaleArray[$index])) {
  949. $totalsPointSaleArray[$index] .= ' + ';
  950. }
  951. $totalsPointSaleArray[$index] .= $quantity;
  952. if ($product->unit != $unit) {
  953. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  954. }
  955. }
  956. }
  957. }
  958. return $totalsPointSaleArray;
  959. }
  960. public function _totalReportPiecesCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  961. {
  962. $totalsPointSaleArray = [$label];
  963. foreach ($productsArray as $product) {
  964. $quantity = 0;
  965. foreach (Product::$unitsArray as $unit => $dataUnit) {
  966. $quantityProduct = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  967. if ($unit == 'piece') {
  968. $quantity += $quantityProduct;
  969. } else {
  970. if ($product->weight > 0) {
  971. $quantity += ($quantityProduct * $dataUnit['coefficient']) / $product->weight;
  972. }
  973. }
  974. }
  975. if ($quantity) {
  976. $index = $productsIndexArray[$product->id];
  977. $totalsPointSaleArray[$index] = $quantity;
  978. }
  979. }
  980. return $totalsPointSaleArray;
  981. }
  982. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  983. {
  984. $line = [];
  985. $cptTotal = 0;
  986. for ($i = 0; $i <= $cptMax; $i++) {
  987. if (isset($orderLine[$i]) && $orderLine[$i]) {
  988. $line[] = $orderLine[$i];
  989. if (is_numeric($orderLine[$i])) {
  990. $cptTotal += $orderLine[$i];
  991. }
  992. } else {
  993. $line[] = '';
  994. }
  995. }
  996. if ($cptTotal > 0 && $showTotal) {
  997. $line[] = $cptTotal;
  998. }
  999. return $line;
  1000. }
  1001. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  1002. {
  1003. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1004. $productDistribution = ProductDistribution::searchOne([
  1005. 'id_distribution' => $idDistribution,
  1006. 'id_product' => $idProduct,
  1007. ]);
  1008. $productDistribution->quantity_max = (!$quantityMax) ? null : (float)$quantityMax;
  1009. $productDistribution->save();
  1010. return ['success'];
  1011. }
  1012. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  1013. {
  1014. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1015. $productDistribution = ProductDistribution::searchOne([
  1016. 'id_distribution' => $idDistribution,
  1017. 'id_product' => $idProduct,
  1018. ]);
  1019. $productDistribution->active = $active;
  1020. $productDistribution->save();
  1021. return ['success'];
  1022. }
  1023. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  1024. {
  1025. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1026. $pointSaleDistribution = PointSaleDistribution::searchOne([
  1027. 'id_distribution' => $idDistribution,
  1028. 'id_point_sale' => $idPointSale,
  1029. ]);
  1030. $pointSaleDistribution->delivery = $delivery;
  1031. $pointSaleDistribution->save();
  1032. return ['success'];
  1033. }
  1034. /**
  1035. * Active/désactive un jour de distribution.
  1036. *
  1037. * @param integer $idDistribution
  1038. * @param string $date
  1039. * @param boolean $active
  1040. * @return array
  1041. */
  1042. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  1043. {
  1044. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1045. if ($idDistribution) {
  1046. $distribution = Distribution::searchOne([
  1047. 'id' => $idDistribution
  1048. ]);
  1049. }
  1050. $format = 'Y-m-d';
  1051. $dateObject = DateTime::createFromFormat($format, $date);
  1052. if ($dateObject && $dateObject->format($format) === $date) {
  1053. $distribution = Distribution::initDistribution($date);
  1054. }
  1055. if ($distribution) {
  1056. $distribution->active($active);
  1057. return ['success'];
  1058. }
  1059. return ['error'];
  1060. }
  1061. /**
  1062. * Change l'état d'une semaine de production (activé, désactivé).
  1063. *
  1064. * @param string $date
  1065. * @param integer $active
  1066. */
  1067. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  1068. {
  1069. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1070. $week = sprintf('%02d', date('W', strtotime($date)));
  1071. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  1072. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  1073. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  1074. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  1075. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  1076. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  1077. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  1078. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  1079. $pointsSaleArray = PointSale::searchAll();
  1080. $activeMonday = false;
  1081. $activeTuesday = false;
  1082. $activeWednesday = false;
  1083. $activeThursday = false;
  1084. $activeFriday = false;
  1085. $activeSaturday = false;
  1086. $activeSunday = false;
  1087. foreach ($pointsSaleArray as $pointSale) {
  1088. if ($pointSale->delivery_monday) {
  1089. $activeMonday = true;
  1090. }
  1091. if ($pointSale->delivery_tuesday) {
  1092. $activeTuesday = true;
  1093. }
  1094. if ($pointSale->delivery_wednesday) {
  1095. $activeWednesday = true;
  1096. }
  1097. if ($pointSale->delivery_thursday) {
  1098. $activeThursday = true;
  1099. }
  1100. if ($pointSale->delivery_friday) {
  1101. $activeFriday = true;
  1102. }
  1103. if ($pointSale->delivery_saturday) {
  1104. $activeSaturday = true;
  1105. }
  1106. if ($pointSale->delivery_sunday) {
  1107. $activeSunday = true;
  1108. }
  1109. }
  1110. if ($activeMonday || !$active) {
  1111. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  1112. }
  1113. if ($activeTuesday || !$active) {
  1114. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  1115. }
  1116. if ($activeWednesday || !$active) {
  1117. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  1118. }
  1119. if ($activeThursday || !$active) {
  1120. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  1121. }
  1122. if ($activeFriday || !$active) {
  1123. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  1124. }
  1125. if ($activeSaturday || !$active) {
  1126. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  1127. }
  1128. if ($activeSunday || !$active) {
  1129. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  1130. }
  1131. return ['success'];
  1132. }
  1133. /**
  1134. * Ajoute les commandes récurrentes pour une date donnée.
  1135. *
  1136. * @param string $date
  1137. */
  1138. public function actionAjaxProcessAddSubscriptions($date)
  1139. {
  1140. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1141. Subscription::addAll($date, true);
  1142. return ['success'];
  1143. }
  1144. /**
  1145. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  1146. *
  1147. * @param string $date
  1148. */
  1149. public function actionAjaxProcessSynchroTiller($date)
  1150. {
  1151. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1152. $return = [];
  1153. $producerTiller = Producer::getConfig('tiller');
  1154. if ($producerTiller) {
  1155. $tiller = new Tiller();
  1156. $isSynchro = $tiller->isSynchro($date);
  1157. if (!$isSynchro) {
  1158. $orders = Order::searchAll([
  1159. 'distribution.date' => $date,
  1160. 'order.tiller_synchronization' => 1
  1161. ], [
  1162. 'conditions' => 'date_delete IS NULL'
  1163. ]);
  1164. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  1165. if ($orders && count($orders)) {
  1166. foreach ($orders as $order) {
  1167. $lines = [];
  1168. foreach ($order->productOrder as $productOrder) {
  1169. $lines[] = [
  1170. 'name' => $productOrder->product->name,
  1171. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  1172. 'tax' => $productOrder->taxRate->value * 100,
  1173. 'date' => $strDate,
  1174. 'quantity' => $productOrder->quantity
  1175. ];
  1176. }
  1177. $typePaymentTiller = '';
  1178. if ($order->mean_payment == MeanPayment::MONEY) {
  1179. $typePaymentTiller = 'CASH';
  1180. }
  1181. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  1182. || $order->mean_payment == MeanPayment::CREDIT
  1183. || $order->mean_payment == MeanPayment::TRANSFER
  1184. || $order->mean_payment == MeanPayment::OTHER) {
  1185. $typePaymentTiller = 'CARD';
  1186. }
  1187. if ($order->mean_payment == MeanPayment::CHEQUE) {
  1188. $typePaymentTiller = 'BANK_CHECK';
  1189. }
  1190. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  1191. $typePaymentTiller = 'CASH';
  1192. }
  1193. $returnTiller = $tiller->postOrder([
  1194. 'externalId' => $order->id,
  1195. 'type' => 1,
  1196. 'status' => 'IN_PROGRESS',
  1197. 'openDate' => $strDate,
  1198. 'closeDate' => $strDate,
  1199. 'lines' => $lines,
  1200. 'payments' => [
  1201. [
  1202. 'type' => $typePaymentTiller,
  1203. 'amount' => $order->getAmountWithTax(
  1204. Order::AMOUNT_TOTAL
  1205. ) * 100,
  1206. 'status' => 'ACCEPTED',
  1207. 'date' => $strDate
  1208. ]
  1209. ]
  1210. ]);
  1211. $returnTillerObject = json_decode($returnTiller);
  1212. $order->tiller_external_id = ''.$returnTillerObject->id;
  1213. $order->save();
  1214. $return[] = $returnTiller;
  1215. }
  1216. }
  1217. }
  1218. }
  1219. return $return;
  1220. }
  1221. public function actionAjaxValidateDeliveryNotes($idOrders)
  1222. {
  1223. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1224. if (strlen($idOrders)) {
  1225. $idOrders = json_decode($idOrders, true);
  1226. if (is_array($idOrders) && count($idOrders) > 0) {
  1227. foreach ($idOrders as $idOrder) {
  1228. $order = Order::searchOne([
  1229. 'id' => (int)$idOrder
  1230. ]);
  1231. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1232. $deliveryNote = DeliveryNote::searchOne([
  1233. 'id' => (int)$order->id_delivery_note
  1234. ]);
  1235. if ($deliveryNote && $deliveryNote->isStatusDraft()) {
  1236. $deliveryNote->changeStatus(Document::STATUS_VALID);
  1237. $deliveryNote->save();
  1238. }
  1239. }
  1240. }
  1241. return [
  1242. 'return' => 'success',
  1243. 'alert' => [
  1244. 'type' => 'success',
  1245. 'message' => 'Bon(s) de livraison validé(s)'
  1246. ]
  1247. ];
  1248. }
  1249. }
  1250. return [
  1251. 'return' => 'error',
  1252. 'alert' => [
  1253. 'type' => 'danger',
  1254. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  1255. ]
  1256. ];
  1257. }
  1258. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  1259. {
  1260. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1261. if (strlen($idOrders)) {
  1262. $idOrders = json_decode($idOrders, true);
  1263. if (is_array($idOrders) && count($idOrders) > 0) {
  1264. foreach ($idOrders as $idOrder) {
  1265. $order = Order::searchOne([
  1266. 'id' => (int)$idOrder
  1267. ]);
  1268. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId(
  1269. ) && $order->id_user) {
  1270. $deliveryNote = null;
  1271. $idDeliveryNote = $order->id_delivery_note;
  1272. if ($idDeliveryNote) {
  1273. $deliveryNote = DeliveryNote::searchOne([
  1274. 'id' => (int)$idDeliveryNote
  1275. ]);
  1276. }
  1277. // on regénére le document si c'est un brouillon
  1278. if ($deliveryNote && $deliveryNote->isStatusDraft()) {
  1279. $deliveryNote->delete();
  1280. $deliveryNote = null;
  1281. }
  1282. if (!$deliveryNote) {
  1283. $deliveryNote = new DeliveryNote();
  1284. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1285. $deliveryNote->id_user = $order->id_user;
  1286. $deliveryNote->name = 'Bon de livraison ' . $order->getUsername() . ' (' . date(
  1287. 'd/m/Y',
  1288. strtotime(
  1289. $order->distribution->date
  1290. )
  1291. ) . ')';
  1292. $deliveryNote->address = $order->user->getFullAddress();
  1293. $deliveryNote->save();
  1294. }
  1295. if ($deliveryNote) {
  1296. $order->id_delivery_note = $deliveryNote->id;
  1297. $order->save();
  1298. }
  1299. }
  1300. }
  1301. }
  1302. return [
  1303. 'return' => 'success',
  1304. 'alert' => [
  1305. 'type' => 'success',
  1306. 'message' => 'Bon(s) de livraison généré(s)'
  1307. ]
  1308. ];
  1309. }
  1310. return [
  1311. 'return' => 'error',
  1312. 'alert' => [
  1313. 'type' => 'danger',
  1314. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1315. ]
  1316. ];
  1317. }
  1318. public function actionAjaxGenerateDeliveryNote($idOrders)
  1319. {
  1320. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1321. if (strlen($idOrders)) {
  1322. $idOrders = json_decode($idOrders, true);
  1323. if (is_array($idOrders) && count($idOrders) > 0) {
  1324. // récupération première commande pour obtenir des infos
  1325. reset($idOrders);
  1326. $firstOrder = Order::searchOne([
  1327. 'id' => (int)$idOrders[key($idOrders)]
  1328. ]);
  1329. // deliveryNote existant
  1330. $deliveryNote = null;
  1331. $isUpdate = false;
  1332. $i = 0;
  1333. $ordersArray = Order::searchAll([
  1334. 'id' => $idOrders,
  1335. ]);
  1336. do {
  1337. $order = $ordersArray[$i];
  1338. if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId(
  1339. ) && $order->id_delivery_note > 0) {
  1340. $deliveryNote = DeliveryNote::searchOne([
  1341. 'id' => $order->id_delivery_note
  1342. ]);
  1343. $isUpdate = true;
  1344. }
  1345. $i++;
  1346. } while ($deliveryNote == null && isset($ordersArray[$i]));
  1347. if ($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1348. return [
  1349. 'return' => 'error',
  1350. 'alert' => [
  1351. 'type' => 'danger',
  1352. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1353. ]
  1354. ];
  1355. }
  1356. if ($firstOrder) {
  1357. // génération du BL
  1358. if (!$deliveryNote) {
  1359. $deliveryNote = new DeliveryNote;
  1360. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date(
  1361. 'd/m/Y',
  1362. strtotime(
  1363. $firstOrder->distribution->date
  1364. )
  1365. ) . ')';
  1366. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1367. if ($firstOrder->pointSale->id_user) {
  1368. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1369. $user = User::searchOne([
  1370. 'id' => $deliveryNote->id_user
  1371. ]);
  1372. } else {
  1373. $user = new User;
  1374. $user->type = User::TYPE_LEGAL_PERSON;
  1375. $user->name_legal_person = $firstOrder->pointSale->name;
  1376. $user->address = $firstOrder->pointSale->address;
  1377. $user->id_producer = 0;
  1378. $user->setPassword(Password::generate());
  1379. $user->generateAuthKey();
  1380. $user->email = '';
  1381. if (!strlen($user->email)) {
  1382. $user->username = 'inconnu@opendistrib.net';
  1383. }
  1384. $user->save();
  1385. $userProducer = new UserProducer;
  1386. $userProducer->id_user = $user->id;
  1387. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1388. $userProducer->credit = 0;
  1389. $userProducer->active = 1;
  1390. $userProducer->save();
  1391. $firstOrder->pointSale->id_user = $user->id;
  1392. $firstOrder->pointSale->save();
  1393. $deliveryNote->id_user = $user->id;
  1394. }
  1395. $deliveryNote->address = $user->getFullAddress();
  1396. $deliveryNote->save();
  1397. } else {
  1398. // réinitialisation des order.id_delivery_order
  1399. Order::updateAll([
  1400. 'id_delivery_note' => null
  1401. ], [
  1402. 'id_delivery_note' => $deliveryNote->id
  1403. ]);
  1404. }
  1405. if (!isset($user) || !$user) {
  1406. $user = User::searchOne([
  1407. 'id' => $deliveryNote->id_user
  1408. ]);
  1409. $userProducer = UserProducer::searchOne([
  1410. 'id_user' => $deliveryNote->id_user,
  1411. 'id_producer' => GlobalParam::getCurrentProducerId(
  1412. )
  1413. ]);
  1414. }
  1415. // affectation du BL aux commandes
  1416. foreach ($idOrders as $idOrder) {
  1417. $order = Order::searchOne([
  1418. 'id' => (int)$idOrder
  1419. ]);
  1420. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1421. $order->id_delivery_note = $deliveryNote->id;
  1422. $order->save();
  1423. }
  1424. // init invoice price
  1425. $order = Order::searchOne(['id' => $idOrder]);
  1426. if ($order) {
  1427. $order->initInvoicePrices([
  1428. 'user' => $user,
  1429. 'user_producer' => $userProducer,
  1430. 'point_sale' => $firstOrder->pointSale
  1431. ]);
  1432. }
  1433. }
  1434. return [
  1435. 'return' => 'success',
  1436. 'alert' => [
  1437. 'type' => 'success',
  1438. 'message' => 'Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré')
  1439. ]
  1440. ];
  1441. }
  1442. }
  1443. }
  1444. return [
  1445. 'return' => 'error',
  1446. 'alert' => [
  1447. 'type' => 'danger',
  1448. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1449. ]
  1450. ];
  1451. }
  1452. }