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.

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