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.

1130 lines
46KB

  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 common\forms\SubscriptionForm;
  39. use common\helpers\CSV;
  40. use common\helpers\GlobalParam;
  41. use common\helpers\Price;
  42. use common\logic\Distribution\Distribution\Model\Distribution;
  43. use common\logic\Distribution\PointSaleDistribution\Model\PointSaleDistribution;
  44. use common\logic\Distribution\ProductDistribution\Model\ProductDistribution;
  45. use common\logic\Order\Order\Model\Order;
  46. use common\logic\Order\ProductOrder\Model\ProductOrder;
  47. use common\logic\PointSale\PointSale\Model\PointSale;
  48. use common\logic\Product\Product\Model\Product;
  49. use common\logic\Payment\Model\Payment;
  50. use common\logic\User\User\Model\User;
  51. use common\logic\User\UserProducer\Model\UserProducer;
  52. use yii\filters\AccessControl;
  53. use yii\helpers\Html;
  54. class OrderController extends BackendController
  55. {
  56. var $enableCsrfValidation = false;
  57. public function behaviors()
  58. {
  59. return [
  60. 'access' => [
  61. 'class' => AccessControl::class,
  62. 'rules' => [
  63. [
  64. 'allow' => true,
  65. 'roles' => ['@'],
  66. 'matchCallback' => function ($rule, $action) {
  67. return $this->getUserModule()
  68. ->getAuthorizationChecker()
  69. ->isGrantedAsProducer($this->getUserCurrent());
  70. }
  71. ]
  72. ],
  73. ],
  74. ];
  75. }
  76. /**
  77. * Traite le formulaire d'ajout/modification de commande.
  78. */
  79. public function processOrderForm(
  80. Distribution $distribution,
  81. string $date,
  82. array $pointsSale,
  83. array $products,
  84. array $users
  85. )
  86. {
  87. $orderModule = $this->getOrderModule();
  88. $pointSaleModule = $this->getPointSaleModule();
  89. if ($date != '') {
  90. $orders = $orderModule->findOrdersByDistribution($distribution);
  91. foreach ($pointsSale as $point) {
  92. $orderModule->initPointSaleOrders($point, $orders);
  93. if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {
  94. // modifs
  95. foreach ($point->orders as $order) {
  96. // suppression des product_order
  97. ProductOrder::deleteAll(['id_order' => $order->id]);
  98. // création des commande_produit modifiés
  99. foreach ($products as $product) {
  100. $quantity = \Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
  101. if ($quantity) {
  102. $productOrder = new ProductOrder;
  103. $productOrder->id_order = $order->id;
  104. $productOrder->id_product = $product->id;
  105. $productOrder->quantity = $quantity;
  106. $productOrder->price = $p->price;
  107. $productOrder->unit = $p->unit;
  108. $productOrder->step = $p->step;
  109. $productOrder->id_tax_rate = $p->taxRate->id;
  110. $productOrder->save();
  111. }
  112. }
  113. }
  114. $username = \Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
  115. $date = \Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
  116. $oneProduct = false;
  117. foreach ($products as $product) {
  118. $quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  119. if ($quantity) {
  120. $oneProduct = true;
  121. }
  122. }
  123. if (strlen($username) && $date && $oneProduct) {
  124. $order = new Order();
  125. $order->id_point_sale = $point->id;
  126. $order->id_production = $distribution->id;
  127. $order->id_user = 0;
  128. $order->username = $username;
  129. $arrayDate = explode('/', $date);
  130. $order->date = $arrayDate[2] . '-' . $arrayDate[1] . '-' . $arrayDate[0] . ' 00:00:00';
  131. $order->save();
  132. foreach ($products as $product) {
  133. $quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  134. if ($quantity) {
  135. $productOrder = new ProductOrder();
  136. $productOrder->id_order = $order->id;
  137. $productOrder->id_product = $product->id;
  138. $productOrder->quantity = $quantity;
  139. $productOrder->price = $p->price;
  140. $productOrder->unit = $p->unit;
  141. $productOrder->step = $p->step;
  142. $productOrder->id_tax_rate = $p->taxRate->id;
  143. $productOrder->save();
  144. }
  145. }
  146. $orderModule->generateOrderReference($order);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. /**
  153. * Page principale de la gestion des commandes.
  154. */
  155. public function actionIndex($date = '', $returnData = false)
  156. {
  157. $distributionModule = $this-> getDistributionModule();
  158. $productModule = $this->getProductModule();
  159. $pointSaleModule = $this->getPointSaleModule();
  160. $orderModule = $this->getOrderModule();
  161. $productDistributionModule = $this->getProductDistributionManager();
  162. if (!Product::searchCount() || !PointSale::searchCount()) {
  163. $this->redirect(['dashboard/index', 'error_products_points_sale' => 1]);
  164. }
  165. $orders = [];
  166. // users
  167. $arrayUsers = [0 => '--'];
  168. $users = User::searchAll([], ['orderby' => 'lastname, name ASC']);
  169. foreach ($users as $user) {
  170. $arrayUsers[$user->id] = $user->name . ' ' . $user->lastname;
  171. }
  172. $distribution = $distributionModule->createDistributionIfNotExist($date);
  173. if ($distribution) {
  174. $arrayPointsSale = PointSale::find()
  175. ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
  176. $q->where(['id_distribution' => $distribution->id]);
  177. }])
  178. ->where([
  179. 'id_producer' => GlobalParam::getCurrentProducerId(),
  180. ])
  181. ->all();
  182. } else {
  183. $arrayPointsSale = $pointSaleModule->findPointSales();
  184. }
  185. $arrayProducts = $productModule->findProducts();
  186. $this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users);
  187. // commandes
  188. $arrayOrders = $orderModule->findOrdersByDistribution($distribution);
  189. $revenues = 0;
  190. $weight = 0;
  191. $revenuesDelivered = 0;
  192. if ($arrayOrders) {
  193. foreach ($arrayOrders as $order) {
  194. if (is_null($order->date_delete)) {
  195. $revenues += $order->amount;
  196. if ($order->id_point_sale != 1) {
  197. $revenuesDelivered += $order->amount;
  198. }
  199. $weight += $order->weight;
  200. }
  201. }
  202. }
  203. $revenues = number_format($revenues, 2);
  204. // init commandes point de vente
  205. foreach ($arrayPointsSale as $pointSale) {
  206. $orderModule->initPointSaleOrders($pointSale, $arrayOrders);
  207. $dataSelectOrders = [];
  208. $dataOptionsOrders = [];
  209. foreach ($pointSale->orders as $order) {
  210. if ($order->user) {
  211. $dataSelectOrders[$order->id] = $order->user->name . ' ' . $order->user->lastname;
  212. } else {
  213. $dataSelectOrders[$order->id] = $order->username;
  214. }
  215. $dataOptionsOrders[$order->id] = [];
  216. $arrayOptions = [];
  217. $arrayOptions[$order->id]['amount'] = $order->amount;
  218. $arrayOptions[$order->id]['str_amount'] = number_format($order->amount, 2, ',', '') . ' €';
  219. $arrayOptions[$order->id]['paid_amount'] = $order->paid_amount;
  220. $arrayOptions[$order->id]['products'] = [];
  221. $arrayOptions[$order->id]['comment'] = Html::encode($order->comment);
  222. foreach ($order->productOrder as $productOrder) {
  223. $arrayOptions[$order->id]['products'][$productOrder->id_product] = $productOrder->quantity;
  224. }
  225. $dataOptionsOrders[$order->id]['data-order'] = json_encode($arrayOptions[$order->id]);
  226. $dataOptionsOrders[$order->id]['value'] = $order->id;
  227. }
  228. $pointSale->data_select_orders = $dataSelectOrders;
  229. $pointSale->data_options_orders = $dataOptionsOrders;
  230. }
  231. // gestion produits selec
  232. if (isset($_POST['valider_produit_selec'])) {
  233. if (isset($_POST['Product'])) {
  234. foreach ($arrayProducts as $product) {
  235. $productDistribution = $productDistributionModule->findOneProductDistribution($distribution, $product);
  236. if (!$productDistribution) {
  237. $productDistribution = new ProductDistribution();
  238. $productDistribution->id_distribution = $distribution->id;
  239. $productDistribution->id_product = $product->id;
  240. $productDistribution->active = 0;
  241. if (isset($product->quantity_max)) {
  242. $productDistribution->quantity_max = $product->quantity_max;
  243. } else {
  244. $productDistribution->quantity_max = null;
  245. }
  246. $productDistributionModule->saveCreate($productDistribution);
  247. }
  248. if (isset($_POST['Product'][$product->id]['active'])) {
  249. $productDistribution->active = 1;
  250. } else {
  251. $productDistribution->active = 0;
  252. }
  253. if ((isset($_POST['Product'][$product->id]['quantity_max']) && $_POST['Product'][$product->id]['quantity_max'] != '')) {
  254. $productDistribution->quantity_max = (int)$_POST['Product'][$product->id]['quantity_max'];
  255. } else {
  256. $productDistribution->quantity_max = null;
  257. }
  258. $productDistributionModule->saveUpdate($productDistribution);
  259. }
  260. }
  261. }
  262. $arrayProductsSelected = [];
  263. if ($distribution) {
  264. $arrayProductsSelected = $productDistributionModule->findProductDistributionsByDistribution($distribution);
  265. $arrayProducts = $productModule->findProductsByDistribution($distribution);
  266. }
  267. // poids total de la production et CA potentiel
  268. $potentialTurnover = 0;
  269. $totalWeight = 0;
  270. foreach ($arrayProductsSelected as $idSelectedProduct => $selectedProduct) {
  271. if ($selectedProduct['active']) {
  272. foreach ($arrayProducts as $product) {
  273. if ($product->id == $idSelectedProduct) {
  274. $potentialTurnover += $selectedProduct['quantity_max'] * $product->price;
  275. $totalWeight += $selectedProduct['quantity_max'] * $product->weight / 1000;
  276. }
  277. }
  278. }
  279. }
  280. $arrayDistributionDays = $distributionModule->findDistributionsActive();
  281. // commandes auto
  282. $subscriptionForm = new SubscriptionForm();
  283. // productions point vente
  284. $pointSaleDistribution = new PointSaleDistribution();
  285. $oointsSaleDistribution = [];
  286. if ($distribution) {
  287. $pointsSaleDistribution = PointSaleDistribution::searchAll([
  288. 'id_distribution' => $distribution->id
  289. ]);
  290. }
  291. $arrayPointsSaleDistribution = [];
  292. if (isset($pointsSaleDistribution)) {
  293. foreach ($pointsSaleDistribution as $pointSaleDistrib) {
  294. $key = $pointSaleDistrib->id_distribution . '-' . $pointSaleDistrib->id_point_sale;
  295. if ($pointSaleDistrib->delivery == 1) {
  296. $pointSaleDistribution->points_sale_distribution[] = $key;
  297. }
  298. if (isset($pointSaleDistrib->pointSale) && strlen($pointSaleDistrib->pointSale->name)) {
  299. $arrayPointsSaleDistribution[$key] = Html::encode($pointSaleDistrib->pointSale->name);
  300. }
  301. }
  302. }
  303. // une production de la semaine activée ou non
  304. $oneDistributionWeekActive = false;
  305. $week = sprintf('%02d', date('W', strtotime($date)));
  306. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  307. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  308. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  309. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  310. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  311. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  312. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  313. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  314. $weekDistribution = Distribution::find()
  315. ->andWhere([
  316. 'id_producer' => GlobalParam::getCurrentProducerId(),
  317. 'active' => 1,
  318. ])
  319. ->andWhere(['or',
  320. ['date' => $dateMonday],
  321. ['date' => $dateTuesday],
  322. ['date' => $dateWednesday],
  323. ['date' => $dateThursday],
  324. ['date' => $dateFriday],
  325. ['date' => $dateSaturday],
  326. ['date' => $dateSunday],
  327. ])
  328. ->one();
  329. if ($weekDistribution) {
  330. $oneDistributionWeekActive = true;
  331. }
  332. $datas = [
  333. 'arrayProducts' => $arrayProducts,
  334. 'arrayPointsSale' => $arrayPointsSale,
  335. 'arrayOrders' => $arrayOrders,
  336. 'date' => $date,
  337. 'distribution' => $distribution,
  338. 'arrayDistributionDays' => $arrayDistributionDays,
  339. 'selectedProducts' => $arrayProductsSelected,
  340. 'users' => $arrayUsers,
  341. 'revenues' => $revenues,
  342. 'revenuesDelivered' => $revenuesDelivered,
  343. 'weight' => $weight,
  344. 'potentialTurnover' => $potentialTurnover,
  345. 'totalWeight' => $totalWeight,
  346. 'subscriptionForm' => $subscriptionForm,
  347. 'pointSaleDistribution' => $pointSaleDistribution,
  348. 'arrayPointsSaleDistribution' => $arrayPointsSaleDistribution,
  349. 'oneDistributionWeekActive' => $oneDistributionWeekActive
  350. ];
  351. if ($returnData) {
  352. return $datas;
  353. } else {
  354. return $this->render('index', $datas);
  355. }
  356. }
  357. /**
  358. * Génère un fichier d'export des commandes au format CSV.
  359. *
  360. * @param string $date
  361. * @param integer $id_point_vente
  362. * @param boolean $global
  363. */
  364. public function actionDownload($date = '', $idPointSale = 0, $global = 0)
  365. {
  366. $orderModule = $this->getOrderModule();
  367. $distributionModule = $this-> getDistributionModule();
  368. $pointSaleModule = $this->getPointSaleModule();
  369. $productModule = $this->getProductModule();
  370. $productDistributionModule = $this->getProductDistributionManager();
  371. $distribution = $distributionModule->findOneDistribution($date);
  372. $selectedProductsArray = $productDistributionModule->findProductDistributionsByDistribution($distribution);
  373. $productsArray = $productModule->findProducts();
  374. $ordersArray = $orderModule->findOrdersByDistributionDate($date);
  375. $pointsSaleArray = $pointSaleModule->findPointSales();
  376. foreach ($pointsSaleArray as $pointSale) {
  377. $pointSaleModule->initOrders($pointSale, $ordersArray);
  378. }
  379. /*
  380. * export global
  381. */
  382. if ($global) {
  383. $data = [];
  384. $filename = 'export_' . $date . '_global';
  385. $dayWeek = date('w', strtotime($date));
  386. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  387. $fieldsHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  388. // par point de vente
  389. foreach ($pointsSaleArray as $pointSale) {
  390. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  391. $line = [$pointSale->name, 'Produits', 'Montant', 'Commentaire'];
  392. $data[] = $line;
  393. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $pointSale->id);
  394. foreach ($res['data'] as $line) {
  395. $data[] = $line;
  396. }
  397. }
  398. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  399. $line = ['Total'];
  400. $strProducts = '';
  401. foreach ($productsArray as $product) {
  402. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  403. $quantity = $orderModule->getProductQuantity($product, $pointSale->orders);
  404. $strQuantity = '';
  405. if ($quantity) {
  406. $strQuantity = $quantity;
  407. $strProducts .= $strQuantity . ', ';
  408. }
  409. }
  410. }
  411. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  412. $line[] = number_format($pointSale->revenues, 2) . ' €';
  413. $data[] = $line;
  414. $data[] = [];
  415. }
  416. }
  417. $line = ['Total'];
  418. $strProducts = '';
  419. foreach ($productsArray as $product) {
  420. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  421. $quantity = $orderModule->getProductQuantity($product, $ordersArray);
  422. $strQuantity = '';
  423. if ($quantity) {
  424. $strQuantity = $quantity;
  425. $strQuantity .= $strQuantity . ', ';
  426. }
  427. }
  428. }
  429. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  430. $data[] = $line;
  431. $infos = $this->actionIndex($date, true);
  432. CSV::downloadSendHeaders($filename . '.csv');
  433. echo CSV::array2csv($data);
  434. die();
  435. } /*
  436. * export individuel
  437. */
  438. else {
  439. if ($ordersArray && count($ordersArray)) {
  440. $data = [];
  441. // par point de vente
  442. if ($idPointSale) {
  443. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $idPointSale);
  444. $data = $res['data'];
  445. $filename = $res['filename'];
  446. } // récapitulatif
  447. else {
  448. $res = $this->contentRecapCSV($date, $productsArray, $pointsSaleArray, $ordersArray);
  449. $filename = 'summary_' . $date;
  450. $data = $res['data'];
  451. }
  452. CSV::downloadSendHeaders($filename . '.csv');
  453. echo CSV::array2csv($data);
  454. die();
  455. }
  456. }
  457. }
  458. /**
  459. * Génère le contenu nécessaire aux exports au format CSV.
  460. *
  461. * @param string $date
  462. * @param array $products
  463. * @param array $pointsSale
  464. * @param array $orders
  465. * @return array
  466. * @see OrderController::actionDownload()
  467. */
  468. public function contentRecapCSV(string $date, array $products, array $pointsSale, array $orders)
  469. {
  470. $orderModule = $this->getOrderModule();
  471. $distributionModule = $this-> getDistributionModule();
  472. $productDistributionModule = $this->getProductDistributionManager();
  473. $data = [];
  474. $filename = 'summary_' . $date;
  475. $distribution = $distributionModule->findOneDistribution($date);
  476. $selectedProductsArray = $productDistributionModule->findProductDistributionsByDistribution($distribution);
  477. // head
  478. $data[0] = ['Lieu'];
  479. foreach ($products as $product) {
  480. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  481. $data[0][] = $product->description;
  482. }
  483. }
  484. $dayWeek = date('w', strtotime($date));
  485. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  486. $fieldHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  487. // datas
  488. foreach ($pointsSale as $pointSale) {
  489. if (count($pointSale->orders) && strlen($pointSale->$fieldHoursPointSale)) {
  490. $dataAdd = [$pointSale->name];
  491. foreach ($products as $product) {
  492. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  493. $dataAdd[] = $orderModule->getProductQuantity($product, $pointSale->orders);
  494. }
  495. }
  496. $data[] = $dataAdd;
  497. }
  498. }
  499. $dataAdd = ['Total'];
  500. foreach ($products as $product) {
  501. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  502. $dataAdd[] = $orderModule->getProductQuantity($product, $orders);
  503. }
  504. }
  505. $data[] = $dataAdd;
  506. return [
  507. 'data' => $data,
  508. 'filename' => $filename
  509. ];
  510. }
  511. /**
  512. * Génère le contenu relatif aux points de vente nécessaires aux exports au
  513. * format CSV.
  514. *
  515. * @param string $date
  516. * @param array $produits
  517. * @param array $points_vente
  518. * @param integer $id_point_vente
  519. * @return array
  520. */
  521. public function contentPointSaleCSV($date, $products, $pointsSale, $idPointSale)
  522. {
  523. $distributionModule = $this-> getDistributionModule();
  524. $productDistributionModule = $this->getProductDistributionManager();
  525. $data = [];
  526. $distribution = $distributionModule->findOneDistribution($date);
  527. $selectedProductsArray = $productDistributionModule->findProductDistributionsByDistribution($distribution);
  528. // datas
  529. foreach ($pointsSale as $pointSale) {
  530. if ($pointSale->id == $idPointSale) {
  531. $filename = 'export_' . $date . '_' . strtolower(str_replace(' ', '-', $pointSale->name));
  532. foreach ($pointSale->orders as $order) {
  533. $strUser = '';
  534. // username
  535. if ($order->user) {
  536. $strUser = $order->user->name . " " . $order->user->lastname;
  537. } else {
  538. $strUser = $order->username;
  539. }
  540. // téléphone
  541. if (isset($order->user) && strlen($order->user->phone)) {
  542. $strUser .= ' (' . $order->user->phone . ')';
  543. }
  544. $dataAdd = [$strUser];
  545. // produits
  546. $strProducts = '';
  547. foreach ($products as $product) {
  548. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  549. $add = false;
  550. foreach ($product->productOrder as $productOrder) {
  551. if ($product->id == $productOrder->id_product) {
  552. $strProducts .= $productOrder->quantity;
  553. $add = true;
  554. }
  555. }
  556. }
  557. }
  558. $dataAdd[] = substr($strProducts, 0, strlen($strProducts) - 2);
  559. $dataAdd[] = number_format($order->amount, 2) . ' €';
  560. $dataAdd[] = $order->comment;
  561. $data[] = $dataAdd;
  562. }
  563. }
  564. }
  565. return [
  566. 'data' => $data,
  567. 'filename' => $filename
  568. ];
  569. }
  570. /**
  571. * Change l'état d'un jour de distribution (activé, désactivé).
  572. */
  573. public function actionChangeState(string $date, bool $active, bool $redirect = true)
  574. {
  575. $distributionModule = $this-> getDistributionModule();
  576. $distribution = $distributionModule->createDistributionIfNotExist($date);
  577. $distributionModule->activeDistribution($distribution, $active);
  578. if ($redirect) {
  579. $this->redirect(['index', 'date' => $date]);
  580. }
  581. }
  582. /**
  583. * Change l'état d'une semaine de production (activé, désactivé).
  584. */
  585. public function actionChangeStateWeek(string $date, bool $active)
  586. {
  587. $pointSaleModule = $this->getPointSaleModule();
  588. $pointsSaleArray = $pointSaleModule->findPointSales();
  589. $week = sprintf('%02d', date('W', strtotime($date)));
  590. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  591. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  592. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  593. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  594. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  595. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  596. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  597. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  598. $activeMonday = false;
  599. $activeTuesday = false;
  600. $activeWednesday = false;
  601. $activeThursday = false;
  602. $activeFriday = false;
  603. $activeSaturday = false;
  604. $activeSunday = false;
  605. foreach ($pointsSaleArray as $pointSale) {
  606. if ($pointSale->delivery_monday) $activeMonday = true;
  607. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  608. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  609. if ($pointSale->delivery_thursday) $activeThursday = true;
  610. if ($pointSale->delivery_friday) $activeFriday = true;
  611. if ($pointSale->delivery_saturday) $activeSaturday = true;
  612. if ($pointSale->delivery_sunday) $activeSunday = true;
  613. }
  614. if ($activeMonday || !$active) $this->actionChangeState($dateMonday, $active, false);
  615. if ($activeTuesday || !$active) $this->actionChangeState($activeTuesday, $active, false);
  616. if ($activeWednesday || !$active) $this->actionChangeState($activeWednesday, $active, false);
  617. if ($activeThursday || !$active) $this->actionChangeState($activeThursday, $active, false);
  618. if ($activeFriday || !$active) $this->actionChangeState($activeFriday, $active, false);
  619. if ($activeSaturday || !$active) $this->actionChangeState($activeSaturday, $active, false);
  620. if ($activeSunday || !$active) $this->actionChangeState($activeSunday, $active, false);
  621. $this->redirect(['index', 'date' => $date]);
  622. }
  623. /**
  624. * Supprime une commande via une requête AJAX.
  625. */
  626. public function actionAjaxDelete(int $idOrder)
  627. {
  628. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  629. $orderModule = $this->getOrderModule();
  630. $order = $orderModule->findOneOrderById($idOrder);
  631. if ($order) {
  632. $orderModule->deleteOrder($order);
  633. }
  634. return ['success'];
  635. }
  636. /**
  637. * Supprime une commande.
  638. */
  639. public function actionDelete(string $date, int $idOrder)
  640. {
  641. $orderModule = $this->getOrderModule();
  642. $order = $orderModule->findOneOrderById($idOrder);
  643. if ($order) {
  644. $orderModule->deleteOrder($order);
  645. }
  646. $this->redirect(['index', 'date' => $date]);
  647. }
  648. /**
  649. * Crée une commande via une requête AJAX.
  650. *
  651. * @param string $date
  652. * @param integer $idPointSale
  653. * @param integer $idUser
  654. * @param string $username
  655. * @param array $produits
  656. * @param string $commentaire
  657. */
  658. public function actionAjaxCreate(
  659. $date, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment, $debitCredit = false)
  660. {
  661. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  662. $distributionModule = $this-> getDistributionModule();
  663. $pointSaleModule = $this->getPointSaleModule();
  664. $userPointSaleModule = $this->getUserPointSaleModule();
  665. $userModule = $this->getUserModule();
  666. $userProducerModule = $this->getUserProducerModule();
  667. $producerModule = $this->getProducerModule();
  668. $productModule = $this->getProductModule();
  669. $orderModule = $this->getOrderModule();
  670. $products = json_decode($products);
  671. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  672. $distribution = $distributionModule->findOneDistribution($date);
  673. $producerCurrent = $this->getProducerCurrent();
  674. if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)
  675. && ($idUser || strlen($username))
  676. && $pointSale
  677. && count(get_object_vars($products))
  678. && $distribution) {
  679. $order = new Order;
  680. $order->date = date('Y-m-d H:i:s');
  681. $order->id_point_sale = $idPointSale;
  682. $order->mean_payment = $meanPayment;
  683. $order->id_distribution = $distribution->id;
  684. $order->origin = Order::ORIGIN_ADMIN;
  685. $order->comment = $comment;
  686. $order->status = 'tmp-order';
  687. if ($idUser) {
  688. $order->id_user = $idUser;
  689. // commentaire du point de vente
  690. $userPointSale = $userPointSaleModule->findOneUserPointSale($userModule->findOneUserById($idUser), $pointSale);
  691. if ($userPointSale && strlen($userPointSale->comment)) {
  692. $order->comment_point_sale = $userPointSale->comment;
  693. }
  694. } else {
  695. $order->username = $username;
  696. $order->id_user = 0;
  697. }
  698. $order->save();
  699. $user = false;
  700. $userProducer = false;
  701. if (isset($order->user) && $order->user) {
  702. $user = $order->user;
  703. $userProducer = $userProducerModule->findOneUserProducer($user);
  704. }
  705. foreach ($products as $key => $dataProductOrder) {
  706. $product = $productModule->findOneProductById($key);
  707. if(isset(Product::$unitsArray[$dataProductOrder->unit]) && Product::$unitsArray[$dataProductOrder->unit]['coefficient']) {
  708. $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  709. if ($product && $quantity) {
  710. $productOrder = new ProductOrder;
  711. $productOrder->id_order = $order->id;
  712. $productOrder->id_product = $key;
  713. $productOrder->quantity = $quantity;
  714. $productOrder->unit = $product->unit;
  715. $productOrder->step = $product->step;
  716. if ($dataProductOrder->price) {
  717. $productOrder->price = $dataProductOrder->price;
  718. } else {
  719. $productOrder->price = $productModule->getPrice($product, [
  720. 'user' => $user,
  721. 'user_producer' => $userProducer,
  722. 'point_sale' => $order->pointSale,
  723. 'quantity' => $productOrder->quantity
  724. ]);
  725. }
  726. $productOrder->id_tax_rate = $product->taxRate->id;
  727. $productOrder->save();
  728. }
  729. }
  730. }
  731. $order = $orderModule->findOneOrderById($order->id);
  732. $orderModule->initOrder($order);
  733. if ($order && $orderModule->isCreditAutoPayment($order, $debitCredit)) {
  734. $orderModule->processCredit($order);
  735. }
  736. $order = $orderModule->findOneOrderById($order->id);
  737. $orderModule->initOrder($order);
  738. if ($order) {
  739. $orderModule->generateOrderReference($order);
  740. $orderModule->updateOrderTillerSynchronization($order);
  741. }
  742. // lien utilisateur / point de vente
  743. if ($idUser && $pointSale) {
  744. $pointSaleModule->addUser($user, $pointSale);
  745. }
  746. }
  747. return ['success'];
  748. }
  749. /**
  750. * Met à jour une commande via une requête AJAX.
  751. *
  752. * @param integer $idOrder
  753. * @param array $products
  754. * @param string $date
  755. * @param string $comment
  756. */
  757. public function actionAjaxUpdate()
  758. {
  759. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  760. $orderModule = $this->getOrderModule();
  761. $userModule = $this->getUserModule();
  762. $pointSaleModule = $this->getPointSaleModule();
  763. $userPointSaleModule = $this->getUserPointSaleModule();
  764. $paymentManager = $this->getPaymentModule();
  765. $productModule = $this->getProductModule();
  766. $request = \Yii::$app->request;
  767. $date = $request->post('date');
  768. $idOrder = $request->post('idOrder');
  769. $idPointSale = $request->post('idPointSale');
  770. $idUser = $request->post('idUser');
  771. $username = $request->post('username');
  772. $meanPayment = $request->post('meanPayment');
  773. $products = $request->post('products');
  774. $comment = $request->post('comment');
  775. $debitCredit = $request->post('debitCredit');
  776. $order = $orderModule->findOneOrderById($idOrder);
  777. $orderModule->initOrder($order);
  778. $user = $userModule->findOneUserById($idUser);
  779. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  780. if ($order
  781. && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  782. // Si changement d'user : on rembourse l'ancien user
  783. $oldIdUser = $order->id_user;
  784. $amountPaid = $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_PAID);
  785. if ($oldIdUser != $idUser && $amountPaid > 0) {
  786. $paymentManager->refundOrderCredit($order, $this->getUserCurrent());
  787. $order = $orderModule->findOneOrderById($idOrder);
  788. $orderModule->initOrder($order);
  789. }
  790. if ($idUser) {
  791. $order->username = '';
  792. $order->id_user = $idUser;
  793. // commentaire du point de vente
  794. $userPointSale = $userPointSaleModule->findOneUserPointSale($user, $pointSale);
  795. if ($userPointSale && strlen($userPointSale->comment)) {
  796. $order->comment_point_sale = $userPointSale->comment;
  797. }
  798. } else {
  799. $order->username = $username;
  800. $order->id_user = 0;
  801. }
  802. $user = User::searchOne(['id' => $order->id_user]);
  803. $userProducer = false;
  804. if ($user) {
  805. $userProducer = UserProducer::searchOne([
  806. 'id_user' => $user->id,
  807. 'id_producer' => $order->distribution->id_producer
  808. ]);
  809. }
  810. $products = json_decode($products);
  811. foreach ($products as $key => $dataProductOrder) {
  812. $productOrder = ProductOrder::findOne([
  813. 'id_order' => $idOrder,
  814. 'id_product' => $key
  815. ]);
  816. $quantity = $dataProductOrder->quantity
  817. / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  818. if ($quantity) {
  819. if ($productOrder) {
  820. $productOrder->quantity = $quantity;
  821. $productOrder->price = $dataProductOrder->price;
  822. if(isset($dataProductOrder->invoice_price) && $dataProductOrder->invoice_price) {
  823. $productOrder->invoice_price = $dataProductOrder->invoice_price;
  824. }
  825. } else {
  826. $product = Product::findOne($key);
  827. if ($product) {
  828. $productOrder = new ProductOrder;
  829. $productOrder->id_order = $idOrder;
  830. $productOrder->id_product = $key;
  831. $productOrder->quantity = $quantity;
  832. $productOrder->unit = $product->unit;
  833. $productOrder->step = $product->step;
  834. $productOrder->id_tax_rate = $product->taxRate->id;
  835. if ($dataProductOrder->price) {
  836. $productOrder->price = $dataProductOrder->price;
  837. } else {
  838. $productOrder->price = $productModule->getPrice($product, [
  839. 'user' => $user,
  840. 'user_producer' => $userProducer,
  841. 'point_sale' => $order->pointSale,
  842. 'quantity' => $productOrder->quantity
  843. ]);
  844. }
  845. }
  846. }
  847. $productOrder->save();
  848. } else {
  849. if ($productOrder) {
  850. $productOrder->delete();
  851. }
  852. }
  853. }
  854. $order->id_point_sale = $idPointSale;
  855. $order->date_update = date('Y-m-d H:i:s');
  856. $order->mean_payment = $meanPayment;
  857. $order->comment = $comment;
  858. $order->save();
  859. $order = Order::searchOne(['id' => $order->id]);
  860. $orderModule->initOrder($order);
  861. if ($order && $orderModule->isCreditAutoPayment($order, $debitCredit)) {
  862. $orderModule->processCredit($order);
  863. }
  864. }
  865. }
  866. /**
  867. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
  868. */
  869. public function actionPaymentStatus(int $idOrder)
  870. {
  871. $orderModule = $this->getOrderModule();
  872. $paymentManager = $this->getPaymentModule();
  873. $order = $orderModule->findOneOrderById($idOrder);
  874. if ($order) {
  875. $html = '';
  876. if ($order->id_user) {
  877. $userProducer = UserProducer::find()
  878. ->where([
  879. 'id_user' => $order->id_user,
  880. 'id_producer' => $order->distribution->id_producer
  881. ])
  882. ->one();
  883. $amountPaid = $orderModule->getOrderAmount($order, Order::AMOUNT_PAID);
  884. if (abs($order->amount - $amountPaid) < 0.0001) {
  885. $html .= '<span class="label label-success">Payé</span>';
  886. $buttonsCredit = Html::a('Recréditer ' . $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL, true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $order->amount, 'data-type' => 'refund']);
  887. } elseif ($order->amount > $amountPaid) {
  888. $amountToPay = $order->amount - $amountPaid;
  889. $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à débiter';
  890. $buttonsCredit = Html::a('Débiter ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
  891. } elseif ($order->amount < $amountPaid) {
  892. $amountToRefund = $amountPaid - $order->amount;
  893. $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à recréditer';
  894. $buttonsCredit = Html::a('Recréditer ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
  895. }
  896. $html .= '<span class="buttons-credit">'
  897. . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
  898. . $buttonsCredit
  899. . '</span>';
  900. // historique
  901. $history = Payment::find()
  902. ->with('userAction')
  903. ->where(['id_order' => $idOrder])
  904. ->all();
  905. $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
  906. . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
  907. . '<tbody>';
  908. if ($history && is_array($history) && count($history)) {
  909. foreach ($history as $creditHistory) {
  910. $html .= '<tr>'
  911. . '<td>' . date('d/m/Y H:i:s', strtotime($paymentManager->getDate($creditHistory))) . '</td>'
  912. . '<td>' . Html::encode($paymentManager->getStrUserAction($creditHistory)) . '</td>'
  913. . '<td>' . $paymentManager->getStrWording($creditHistory) . '</td>'
  914. . '<td>' . ($paymentManager->isTypeDebit($creditHistory) ? '- ' . Price::getPriceWithTax($creditHistory->amount) : '') . '</td>'
  915. . '<td>' . ($paymentManager->isTypeCredit($creditHistory) ? '+ ' . Price::getPriceWithTax($creditHistory->amount) : '') . '</td>'
  916. . '</tr>';
  917. }
  918. } else {
  919. $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
  920. }
  921. $html .= '</tbody></table>';
  922. } else {
  923. $html .= '<div class="alert alert-warning">Pas de gestion de crédit pain pour cette commande car elle n\'est pas liée à un compte utilisateur.</div>';
  924. }
  925. echo json_encode([
  926. 'html_payment_status' => $html,
  927. 'json_order' => $order->getDataJson()
  928. ]);
  929. }
  930. die();
  931. }
  932. /**
  933. * Effectue le paiement/remboursement d'une commande.
  934. */
  935. public function actionAjaxPayment(int $idOrder, string $type, string $meanPayment): array
  936. {
  937. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  938. $orderModule = $this->getOrderModule();
  939. $paymentManager = $this->getPaymentModule();
  940. $order = $orderModule->findOneOrderById($idOrder);
  941. $orderModule->initOrder($order);
  942. if ($order) {
  943. $paymentManager->payOrRefundOrder($type, $order, $meanPayment, $this->getUserCurrent());
  944. }
  945. return ['success'];
  946. }
  947. /**
  948. * Modifie l'état de la synchronisation Tiller d'une commande.
  949. */
  950. public function actionAjaxChangeSynchroTiller(int $idOrder, bool $boolSynchroTiller): array
  951. {
  952. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  953. $orderModule = $this->getOrderModule();
  954. $order = $orderModule->findOneOrderById($idOrder);
  955. if ($order) {
  956. $orderModule->updateOrderTillerSynchronization($order, (int) $boolSynchroTiller);
  957. return ['success'];
  958. }
  959. return ['error'];
  960. }
  961. }