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.

1586 lines
82KB

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