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.

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