You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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