Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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