Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1695 lines
74KB

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