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

1398 Zeilen
73KB

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