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.

1573 lines
81KB

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