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

1083 Zeilen
41KB

  1. <?php
  2. /**
  3. Copyright distrib (2018)
  4. contact@opendistrib.net
  5. Ce logiciel est un programme informatique servant à aider les producteurs
  6. à distribuer leur production en circuits courts.
  7. Ce logiciel est régi par la licence CeCILL soumise au droit français et
  8. respectant les principes de diffusion des logiciels libres. Vous pouvez
  9. utiliser, modifier et/ou redistribuer ce programme sous les conditions
  10. de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  11. sur le site "http://www.cecill.info".
  12. En contrepartie de l'accessibilité au code source et des droits de copie,
  13. de modification et de redistribution accordés par cette licence, il n'est
  14. offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  15. seule une responsabilité restreinte pèse sur l'auteur du programme, le
  16. titulaire des droits patrimoniaux et les concédants successifs.
  17. A cet égard l'attention de l'utilisateur est attirée sur les risques
  18. associés au chargement, à l'utilisation, à la modification et/ou au
  19. développement et à la reproduction du logiciel par l'utilisateur étant
  20. donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  21. manipuler et qui le réserve donc à des développeurs et des professionnels
  22. avertis possédant des connaissances informatiques approfondies. Les
  23. utilisateurs sont donc invités à charger et tester l'adéquation du
  24. logiciel à leurs besoins dans des conditions permettant d'assurer la
  25. sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  26. à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  27. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  28. pris connaissance de la licence CeCILL, et que vous en avez accepté les
  29. termes.
  30. */
  31. namespace backend\controllers;
  32. use common\models\Order ;
  33. use common\models\ProductOrder ;
  34. use common\models\Product ;
  35. use common\models\User ;
  36. use common\models\ProductDistribution ;
  37. use common\models\Distribution ;
  38. class OrderController extends BackendController
  39. {
  40. var $enableCsrfValidation = false;
  41. public function behaviors()
  42. {
  43. return [
  44. 'access' => [
  45. 'class' => AccessControl::className(),
  46. 'rules' => [
  47. [
  48. 'allow' => true,
  49. 'roles' => ['@'],
  50. 'matchCallback' => function ($rule, $action) {
  51. return User::getCurrentStatus() == USER::STATUS_ADMIN
  52. || User::getCurrentStatus() == USER::STATUS_PRODUCER;
  53. }
  54. ]
  55. ],
  56. ],
  57. ];
  58. }
  59. /**
  60. * Traite le formulaire d'ajout/modification de commande.
  61. *
  62. * @param Distribution $distribution
  63. * @param string $date
  64. * @param array $points_vente
  65. * @param array $produits
  66. * @param array $users
  67. */
  68. public function processOrderForm(
  69. $distribution, $date, $pointsSale, $products, $users)
  70. {
  71. if ($date != '') {
  72. // commandes
  73. $orders = Order::searchAll([
  74. 'distribution.date' => $date
  75. ]) ;
  76. foreach ($pointsSale as $point) {
  77. $point->initOrders($orders);
  78. if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {
  79. // modifs
  80. foreach ($point->orders as $order) {
  81. // suppression des product_order
  82. ProductOrder::deleteAll(['id_order' => $order->id]) ;
  83. // création des commande_produit modifiés
  84. foreach ($products as $product) {
  85. $quantity = Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
  86. if ($quantity) {
  87. $productOrder = new ProductOrder;
  88. $productOrder->id_order = $order->id;
  89. $productOrder->id_product = $product->id;
  90. $productOrder->quantity = $quantity;
  91. $productOrder->price = $p->price;
  92. $productOrder->save();
  93. }
  94. }
  95. }
  96. $username = Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
  97. $date = Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
  98. $oneProduct = false;
  99. foreach ($products as $product) {
  100. $quantity = Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  101. if ($quantity) {
  102. $oneProduct = true;
  103. }
  104. }
  105. if (strlen($username) && $date && $oneProduct) {
  106. $order = new Order;
  107. $order->id_point_sale = $point->id;
  108. $order->id_production = $distribution->id;
  109. $order->id_user = 0;
  110. $order->username = $username;
  111. $arrayDate = explode('/', $date);
  112. $order->date = $arrayDate[2] . '-' . $arrayDate[1] . '-' . $arrayDate[0] . ' 00:00:00';
  113. $order->save();
  114. foreach ($products as $product) {
  115. $quantity = Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  116. if ($quantity) {
  117. $productOrder = new ProductOrder;
  118. $productOrder->id_order = $order->id;
  119. $productOrder->id_product = $product->id;
  120. $productOrder->quantity = $quantity;
  121. $productOrder->price = $p->price;
  122. $productOrder->save();
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. }
  130. /**
  131. * Page principale de la gestion des commandes.
  132. *
  133. * @param string $date
  134. * @param boolean $returnData
  135. * @return string
  136. */
  137. public function actionIndex($date = '', $returnData = false)
  138. {
  139. if (!Product::searchCount() || !PointSale::searchCount()) {
  140. $this->redirect(['site/index', 'error_products_points_sale' => 1]);
  141. }
  142. $orders = [];
  143. // users
  144. $arrayUsers = [0 => '--'];
  145. $users = User::searchAll([],['orderby' => 'lastname, name ASC']) ;
  146. foreach ($users as $user) {
  147. $arrayUsers[$user->id] = $user->name . ' ' . $user->lastname;
  148. }
  149. // création du jour de distribution
  150. $distribution = Distribution::initDistribution($date) ;
  151. // points de vente
  152. if ($distribution) {
  153. $arrayPointsSale = PointSale::find()
  154. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  155. $q->where(['id_distribution' => $distribution->id]);
  156. }])
  157. ->where([
  158. 'id_producer' => Producer::getId(),
  159. ])
  160. ->all();
  161. } else {
  162. $arrayPointsSale = PointSale::searchAll() ;
  163. }
  164. // produits
  165. $arrayProducts = Product::searchAll();
  166. // gestion des commandes
  167. $this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users);
  168. // commandes
  169. $arrayOrders = Order::searchAll([
  170. 'distribution.date' => $date,
  171. ]);
  172. $revenues = 0;
  173. $weight = 0 ;
  174. $revenuesDelivered = 0;
  175. if($arrayOrders) {
  176. foreach ($arrayOrders as $order) {
  177. if(is_null($order->date_delete)) {
  178. $revenues += $order->amount;
  179. if ($order->id_point_sale != 1) {
  180. $revenuesDelivered += $order->amount;
  181. }
  182. $weight += $order->weight;
  183. }
  184. }
  185. }
  186. $revenues = number_format($revenues, 2);
  187. // init commandes point de vente
  188. foreach ($arrayPointsSale as $pointSale) {
  189. $pointSale->initOrders($arrayOrders);
  190. $dataSelectOrders = [];
  191. $dataOptionsOrders = [];
  192. foreach ($pointSale->orders as $order) {
  193. if ($order->user) {
  194. $dataSelectOrders[$order->id] = $order->user->name . ' ' . $order->user->lastname;
  195. } else {
  196. $dataSelectOrders[$order->id] = $order->username;
  197. }
  198. $dataOptionsOrders[$order->id] = [];
  199. $arrayOptions = [];
  200. $arrayOptions[$order->id]['amount'] = $order->amount;
  201. $arrayOptions[$order->id]['str_amount'] = number_format($order->amount, 2, ',', '') . ' €';
  202. $arrayOptions[$order->id]['paid_amount'] = $order->paid_amount;
  203. $arrayOptions[$order->id]['products'] = [];
  204. $arrayOptions[$order->id]['comment'] = Html::encode($order->comment);
  205. foreach ($order->productOrder as $productOrder) {
  206. $arrayOptions[$order->id]['products'][$productOrder->id_product] = $productOrder->quantity;
  207. }
  208. $dataOptionsOrders[$order->id]['data-order'] = json_encode($arrayOptions[$order->id]);
  209. $dataOptionsOrders[$order->id]['value'] = $order->id;
  210. }
  211. $pointSale->data_select_orders = $dataSelectOrders ;
  212. $pointSale->data_options_orders = $dataOptionsOrders ;
  213. }
  214. // gestion produits selec
  215. if (isset($_POST['valider_produit_selec'])) {
  216. if (isset($_POST['Product'])) {
  217. foreach ($arrayProducts as $product) {
  218. $productDistribution = ProductDistribution::searchOne([
  219. 'id_distribution' => $distribution->id,
  220. 'id_product' => $product->id
  221. ]) ;
  222. if (!$productDistribution) {
  223. $productDistribution = new ProductDistribution();
  224. $productDistribution->id_distribution = $distribution->id;
  225. $productDistribution->id_product = $product->id;
  226. $productDistribution->active = 0;
  227. if (isset($product->quantity_max)) {
  228. $productDistribution->quantity_max = $product->quantity_max;
  229. }
  230. else {
  231. $productDistribution->quantity_max = null;
  232. }
  233. $productDistribution->save();
  234. }
  235. if (isset($_POST['Product'][$product->id]['active'])) {
  236. $productDistribution->active = 1;
  237. } else {
  238. $productDistribution->active = 0;
  239. }
  240. if ((isset($_POST['Product'][$product->id]['quantity_max']) && $_POST['Product'][$product->id]['quantity_max'] != '')) {
  241. $productDistribution->quantity_max = (int) $_POST['Product'][$product->id]['quantity_max'];
  242. } else {
  243. $productDistribution->quantity_max = null;
  244. }
  245. $productDistribution->save();
  246. }
  247. }
  248. }
  249. $arrayProductsSelected = [] ;
  250. if($distribution) {
  251. // produits selec pour production
  252. $arrayProductsSelected = ProductDistribution::searchByDistribution($distribution->id) ;
  253. }
  254. // produits
  255. if ($distribution) {
  256. $arrayProducts = Product::searchByDistribution($distribution->id) ;
  257. }
  258. // poids total de la production et CA potentiel
  259. $potentialTurnover = 0;
  260. $totalWeight = 0;
  261. foreach ($arrayProductsSelected as $idSelectedProduct => $selectedProduct) {
  262. if ($selectedProduct['active']) {
  263. foreach ($arrayProducts as $product) {
  264. if ($product->id == $idSelectedProduct) {
  265. $potentialTurnover += $selectedProduct['quantity_max'] * $product->price;
  266. $totalWeight += $selectedProduct['quantity_max'] * $product->weight / 1000;
  267. }
  268. }
  269. }
  270. }
  271. // jours de distribution
  272. $arrayDistributionDays = Distribution::searchAll([
  273. 'active' => 1
  274. ]) ;
  275. // commandes auto
  276. $subscriptionForm = new SubscriptionForm;
  277. // productions point vente
  278. $pointSaleDistribution = new PointSaleDistribution;
  279. $oointsSaleDistribution = [];
  280. if ($distribution) {
  281. $pointsSaleDistribution = PointSaleDistribution::searchAll([
  282. 'id_distribution' => $distribution->id
  283. ]) ;
  284. }
  285. $arrayPointsSaleDistribution = [];
  286. if(isset($pointsSaleDistribution)) {
  287. foreach ($pointsSaleDistribution as $pointSaleDistrib) {
  288. $key = $pointSaleDistrib->id_distribution . '-' . $pointSaleDistrib->id_point_sale;
  289. if ($pointSaleDistrib->delivery == 1) {
  290. $pointSaleDistribution->points_sale_distribution[] = $key;
  291. }
  292. if(isset($pointSaleDistrib->pointSale) && strlen($pointSaleDistrib->pointSale->name)) {
  293. $arrayPointsSaleDistribution[$key] = Html::encode($pointSaleDistrib->pointSale->name);
  294. }
  295. }
  296. }
  297. // une production de la semaine activée ou non
  298. $oneDistributionWeekActive = false ;
  299. $week = sprintf('%02d',date('W',strtotime($date)));
  300. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  301. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  302. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  303. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  304. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  305. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  306. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  307. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  308. $weekDistribution = Distribution::find()
  309. ->andWhere([
  310. 'id_producer' => Producer::getId(),
  311. 'active' => 1,
  312. ])
  313. ->andWhere(['or',
  314. ['date' => $dateMonday],
  315. ['date' => $dateTuesday],
  316. ['date' => $dateWednesday],
  317. ['date' => $dateThursday],
  318. ['date' => $dateFriday],
  319. ['date' => $dateSaturday],
  320. ['date' => $dateSunday],
  321. ])
  322. ->one();
  323. if($weekDistribution) {
  324. $oneDistributionWeekActive = true ;
  325. }
  326. $datas = [
  327. 'arrayProducts' => $arrayProducts,
  328. 'arrayPointsSale' => $arrayPointsSale,
  329. 'arrayOrders' => $arrayOrders,
  330. 'date' => $date,
  331. 'distribution' => $distribution,
  332. 'arrayDistributionDays' => $arrayDistributionDays,
  333. 'selectedProducts' => $arrayProductsSelected,
  334. 'users' => $arrayUsers,
  335. 'revenues' => $revenues,
  336. 'revenuesDelivered' => $revenuesDelivered,
  337. 'weight' => $weight,
  338. 'potentialTurnover' => $potentialTurnover,
  339. 'totalWeight' => $totalWeight,
  340. 'subscriptionForm' => $subscriptionForm,
  341. 'pointSaleDistribution' => $pointSaleDistribution,
  342. 'arrayPointsSaleDistribution' => $arrayPointsSaleDistribution,
  343. 'oneDistributionWeekActive' => $oneDistributionWeekActive
  344. ];
  345. if ($returnData) {
  346. return $datas;
  347. } else {
  348. return $this->render('index', $datas);
  349. }
  350. }
  351. /**
  352. * Génère un fichier d'export des commandes au format CSV.
  353. *
  354. * @param string $date
  355. * @param integer $id_point_vente
  356. * @param boolean $global
  357. */
  358. public function actionDownload($date = '', $idPointSale = 0, $global = 0)
  359. {
  360. // commandes
  361. $ordersArray = Order::searchAll([
  362. 'distribution.date' => $date
  363. ]) ;
  364. // points de vente
  365. $pointsSaleArray = PointSale::searchAll() ;
  366. foreach ($pointsSaleArray as $pointSale) {
  367. $pv->initOrders($ordersArray);
  368. }
  369. // produits
  370. $productsArray = Product::find()->orderBy('order ASC')->all();
  371. $distribution = Distribution::find()
  372. ->where('date LIKE \':date\'')
  373. ->params([':date' => $date])
  374. ->one();
  375. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  376. /*
  377. * export global
  378. */
  379. if ($global) {
  380. $data = [];
  381. $filename = 'export_' . $date . '_global';
  382. $dayWeek = date('w', strtotime($date));
  383. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  384. $fieldsHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  385. // par point de vente
  386. foreach ($pointsSaleArray as $pointSale) {
  387. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  388. $line = [$pointSale->name, 'Produits', 'Montant', 'Commentaire'];
  389. $data[] = $line;
  390. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $pointSale->id);
  391. foreach ($res['data'] as $line) {
  392. $data[] = $line;
  393. }
  394. }
  395. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  396. $line = ['Total'];
  397. $strProducts = '';
  398. foreach ($productsArray as $product) {
  399. if ( isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  400. $quantity = Order::getProductQuantity($product->id, $pointSale->orders);
  401. $strQuantity = '';
  402. if ($quantity) {
  403. $strQuantity = $quantity;
  404. $strProducts .= $strQuantity . ', ';
  405. }
  406. }
  407. }
  408. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  409. $line[] = number_format($pointSale->revenues, 2) . ' €';
  410. $data[] = $line;
  411. $data[] = [];
  412. }
  413. }
  414. $line = ['Total'];
  415. $strProducts = '';
  416. foreach ($productsArray as $product) {
  417. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  418. $quantity = Order::getProductQuantity($product->id, $ordersArray);
  419. $strQuantity = '';
  420. if ($quantity) {
  421. $strQuantity = $quantity;
  422. $strQuantity .= $strQuantity . ', ';
  423. }
  424. }
  425. }
  426. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  427. $data[] = $line;
  428. $infos = $this->actionIndex($date, true);
  429. CSV::downloadSendHeaders($filename . '.csv');
  430. echo CSV::array2csv($data);
  431. die();
  432. }
  433. /*
  434. * export individuel
  435. */
  436. else {
  437. if ($ordersArray && count($ordersArray)) {
  438. $data = [];
  439. // par point de vente
  440. if ($idPointSale) {
  441. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $idPointSale);
  442. $data = $res['data'];
  443. $filename = $res['filename'];
  444. }
  445. // récapitulatif
  446. else {
  447. $res = $this->contentRecapCSV($date, $productsArray, $pointsSaleArray, $ordersArray);
  448. $filename = 'summary_' . $date;
  449. $data = $res['data'];
  450. }
  451. CSV::downloadSendHeaders($filename . '.csv');
  452. echo CSV::array2csv($data);
  453. die();
  454. }
  455. }
  456. }
  457. /**
  458. * Génère le contenu nécessaire aux exports au format CSV.
  459. *
  460. * @see OrderController::actionDownload()
  461. * @param string $date
  462. * @param array $products
  463. * @param array $pointsSale
  464. * @param array $orders
  465. * @return array
  466. */
  467. public function contentRecapCSV($date, $products, $pointsSale, $orders)
  468. {
  469. $data = [];
  470. $filename = 'summary_' . $date;
  471. $distribution = Distribution::find()
  472. ->where('date LIKE \':date\'')
  473. ->params([':date' => $date])
  474. ->one();
  475. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  476. // head
  477. $data[0] = ['Lieu'];
  478. foreach ($products as $product) {
  479. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  480. $data[0][] = $product->description;
  481. }
  482. }
  483. $dayWeek = date('w', strtotime($date));
  484. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  485. $fieldHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  486. // datas
  487. foreach ($pointsSale as $pointSale) {
  488. if (count($pointSale->orders) && strlen($pointSale->$fieldHoursPointSale)) {
  489. $dataAdd = [$pointSale->name];
  490. foreach ($products as $product) {
  491. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  492. $dataAdd[] = Order::getProductQuantity($product->id, $pointSale->orders);
  493. }
  494. }
  495. $data[] = $dataAdd;
  496. }
  497. }
  498. $dataAdd = ['Total'];
  499. foreach ($products as $product) {
  500. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  501. $dataAdd[] = Order::getProductQuantity($product->id, $orders);
  502. }
  503. }
  504. $data[] = $dataAdd;
  505. return [
  506. 'data' => $data,
  507. 'filename' => $filename
  508. ];
  509. }
  510. /**
  511. * Génère le contenu relatif aux points de vente nécessaires aux exports au
  512. * format CSV.
  513. *
  514. * @param string $date
  515. * @param array $produits
  516. * @param array $points_vente
  517. * @param integer $id_point_vente
  518. * @return array
  519. */
  520. public function contentPointSaleCSV($date, $products, $pointsSale, $idPointSale)
  521. {
  522. $data = [];
  523. $distribution = Distribution::find()->where('date LIKE \':date\'')->params([':date' => $date])->one();
  524. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  525. // datas
  526. foreach ($pointsSale as $pointSale) {
  527. if ($pointSale->id == $idPointSale) {
  528. $filename = 'export_' . $date . '_' . strtolower(str_replace(' ', '-', $pointSale->name));
  529. foreach ($pointSale->orders as $order) {
  530. $strUser = '';
  531. // username
  532. if ($order->user) {
  533. $strUser = $order->user->name . " " . $order->user->lastname;
  534. } else {
  535. $strUser = $order->username;
  536. }
  537. // téléphone
  538. if (isset($order->user) && strlen($order->user->phone)) {
  539. $strUser .= ' (' . $order->user->phone . ')';
  540. }
  541. $dataAdd = [$strUser];
  542. // produits
  543. $strProducts = '';
  544. foreach ($products as $product) {
  545. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  546. $add = false;
  547. foreach ($product->productOrder as $productOrder) {
  548. if ($product->id == $productOrder->id_product) {
  549. $strProducts .= $productOrder->quantity ;
  550. $add = true;
  551. }
  552. }
  553. }
  554. }
  555. $dataAdd[] = substr($strProducts, 0, strlen($strProducts) - 2);
  556. $dataAdd[] = number_format($order->amount, 2) . ' €';
  557. $dataAdd[] = $order->comment;
  558. $data[] = $dataAdd;
  559. }
  560. }
  561. }
  562. return [
  563. 'data' => $data,
  564. 'filename' => $filename
  565. ];
  566. }
  567. /**
  568. * Change l'état d'un jour de production (activé, désactivé).
  569. *
  570. * @param string $date
  571. * @param integer $actif
  572. * @param boolean $redirect
  573. */
  574. public function actionChangeState($date, $active, $redirect = true)
  575. {
  576. // changement état
  577. $distribution = Distribution::initDistribution($date) ;
  578. $distribution->active = $active;
  579. $distribution->save();
  580. if ($active) {
  581. // add commandes automatiques
  582. Subscription::addAll($date);
  583. }
  584. if($redirect) {
  585. $this->redirect(['index', 'date' => $date]);
  586. }
  587. }
  588. /**
  589. * Change l'état d'une semaine de production (activé, désactivé).
  590. *
  591. * @param string $date
  592. * @param integer $actif
  593. */
  594. public function actionChangeStateWeek($date, $active)
  595. {
  596. $week = sprintf('%02d',date('W',strtotime($date)));
  597. $start = strtotime(date('Y',strtotime($date)).'W'.$week);
  598. $dateMonday = date('Y-m-d',strtotime('Monday',$start)) ;
  599. $dateTuesday = date('Y-m-d',strtotime('Tuesday',$start)) ;
  600. $dateWednesday = date('Y-m-d',strtotime('Wednesday',$start)) ;
  601. $dateThursday = date('Y-m-d',strtotime('Thursday',$start)) ;
  602. $dateFriday = date('Y-m-d',strtotime('Friday',$start)) ;
  603. $dateSaturday = date('Y-m-d',strtotime('Saturday',$start)) ;
  604. $dateSunday = date('Y-m-d',strtotime('Sunday',$start)) ;
  605. $pointsSaleArray = PointSale::searchAll() ;
  606. $activeMonday = false ;
  607. $activeTuesday = false ;
  608. $activeWednesday = false ;
  609. $activeThursday = false ;
  610. $activeFriday = false ;
  611. $activeSaturday = false ;
  612. $activeSunday = false ;
  613. foreach($pointsSaleArray as $pointSale) {
  614. if($pointSale->delivery_monday) $activeMonday = true ;
  615. if($pointSale->delivery_tuesday) $activeTuesday = true ;
  616. if($pointSale->delivery_wednesday) $activeWednesday = true ;
  617. if($pointSale->delivery_thursday) $activeThursday = true ;
  618. if($pointSale->delivery_friday) $activeFriday = true ;
  619. if($pointSale->delivery_saturday) $activeSaturday = true ;
  620. if($pointSale->delivery_sunday) $activeSunday = true ;
  621. }
  622. if($activeMonday || !$active) $this->actionChangeState($dateMonday, $active, false) ;
  623. if($activeTuesday || !$active) $this->actionChangeState($activeTuesday, $active, false) ;
  624. if($activeWednesday || !$active) $this->actionChangeState($activeWednesday, $active, false) ;
  625. if($activeThursday || !$active) $this->actionChangeState($activeThursday, $active, false) ;
  626. if($activeFriday || !$active) $this->actionChangeState($activeFriday, $active, false) ;
  627. if($activeSaturday || !$active) $this->actionChangeState($activeSaturday, $active, false) ;
  628. if($activeSunday || !$active) $this->actionChangeState($activeSunday, $active, false) ;
  629. $this->redirect(['index', 'date' => $date]);
  630. }
  631. /**
  632. * Supprime une commande via une requête AJAX.
  633. *
  634. * @param string $date
  635. * @param integer $idOrder
  636. */
  637. public function actionAjaxDelete($idOrder)
  638. {
  639. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  640. $order = Order::searchOne([
  641. 'id' => $idOrder
  642. ]) ;
  643. // delete
  644. if ($order) {
  645. // remboursement si l'utilisateur a payé pour cette commande
  646. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  647. if ($amountPaid > 0.01) {
  648. $order->saveCreditHistory(
  649. CreditHistory::TYPE_REFUND,
  650. $amountPaid,
  651. Producer::getId(),
  652. $order->id_user,
  653. User::getCurrentId()
  654. );
  655. }
  656. $order->delete();
  657. ProductOrder::deleteAll(['id_order' => $idOrder]);
  658. }
  659. return ['success'] ;
  660. }
  661. /**
  662. * Supprime une commande.
  663. *
  664. * @param string $date
  665. * @param integer $idOrder
  666. */
  667. public function actionDelete($date, $idOrder)
  668. {
  669. $order = Order::searchOne(['id' =>$idOrder]) ;
  670. if ($order) {
  671. // remboursement de la commande
  672. if ($order->id_user && $order->getAmount(Order::AMOUNT_PAID) && Producer::getConfig('credit')) {
  673. $order->saveCreditHistory(
  674. CreditHistory::TYPE_REFUND,
  675. $order->getAmount(Order::AMOUNT_PAID),
  676. $order->distribution->id_producer,
  677. $order->id_user,
  678. User::getCurrentId()
  679. );
  680. }
  681. $order->delete();
  682. ProductOrder::deleteAll(['id_order' => $idOrder]);
  683. }
  684. $this->redirect(['index', 'date' => $date]);
  685. }
  686. /**
  687. * Crée une commande via une requête AJAX.
  688. *
  689. * @param string $date
  690. * @param integer $idPointSale
  691. * @param integer $idUser
  692. * @param string $username
  693. * @param array $produits
  694. * @param string $commentaire
  695. * @param string $processCredit
  696. */
  697. public function actionAjaxCreate(
  698. $date, $idPointSale, $idUser, $username, $products, $comment, $processCredit = 0)
  699. {
  700. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  701. $products = json_decode($products);
  702. $pointSale = PointSale::findOne($idPointSale);
  703. $distribution = Distribution::searchOne([
  704. 'date' => $date
  705. ]);
  706. if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date) &&
  707. ($idUser || strlen($username)) &&
  708. $pointSale &&
  709. count($products) &&
  710. $distribution) {
  711. $order = new Order;
  712. $order->date = date('Y-m-d H:i:s', strtotime($date . ' ' . date('H:i:s')));
  713. $order->id_point_sale = $idPointSale;
  714. $order->id_distribution = $distribution->id;
  715. $order->origin = Order::ORIGIN_ADMIN;
  716. $order->comment = $comment;
  717. if ($idUser) {
  718. $order->id_user = $idUser;
  719. // commentaire du point de vente
  720. $userPointSale = UserPointSale::searchOne([
  721. 'id_point_sale' => $idPointSale,
  722. 'id_user' => $idUser
  723. ]) ;
  724. if ($userPointSale && strlen($userPointSale->comment)) {
  725. $order->comment_point_sale = $userPointSale->comment;
  726. }
  727. } else {
  728. $order->username = $username;
  729. $order->id_user = 0;
  730. }
  731. $order->save();
  732. foreach ($products as $key => $dataProductOrder) {
  733. $product = Product::findOne($key);
  734. $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'] ;
  735. if ($product && $quantity) {
  736. $productOrder = new ProductOrder;
  737. $productOrder->id_order = $order->id;
  738. $productOrder->id_product = $key;
  739. $productOrder->quantity = $quantity;
  740. $productOrder->unit = $product->unit;
  741. $productOrder->price = $product->price;
  742. $productOrder->save();
  743. }
  744. }
  745. $order = Order::searchOne(['id' => $order->id]) ;
  746. if($order && $processCredit) {
  747. $order->processCredit() ;
  748. }
  749. // lien utilisateur / point de vente
  750. if($idUser && $pointSale) {
  751. $pointSale->linkUser($idUser) ;
  752. }
  753. }
  754. return ['success'] ;
  755. }
  756. /**
  757. * Met à jour une commande via une requête AJAX.
  758. *
  759. * @param integer $idOrder
  760. * @param array $products
  761. * @param string $date
  762. * @param string $comment
  763. */
  764. public function actionAjaxUpdate(
  765. $date, $idOrder, $idPointSale, $idUser, $username, $products, $comment = '', $processCredit = 0)
  766. {
  767. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  768. $order = Order::searchOne(['id' => $idOrder]) ;
  769. if ($order &&
  770. $order->distribution->id_producer == Producer::getId()) {
  771. $products = json_decode($products);
  772. foreach ($products as $key => $dataProductOrder) {
  773. $productOrder = ProductOrder::findOne([
  774. 'id_order' => $idOrder,
  775. 'id_product' => $key
  776. ]);
  777. $quantity = $dataProductOrder->quantity
  778. / Product::$unitsArray[$dataProductOrder->unit]['coefficient'] ;
  779. if ($quantity) {
  780. if ($productOrder) {
  781. $productOrder->quantity = $quantity;
  782. } else {
  783. $product = Product::findOne($key);
  784. if ($product) {
  785. $productOrder = new ProductOrder;
  786. $productOrder->id_order = $idOrder;
  787. $productOrder->id_product = $key;
  788. $productOrder->quantity = $quantity;
  789. $productOrder->unit = $product->unit;
  790. $productOrder->price = $product->price;
  791. }
  792. }
  793. $productOrder->save();
  794. } else {
  795. if ($productOrder) {
  796. $productOrder->delete();
  797. }
  798. }
  799. }
  800. $order->id_point_sale = $idPointSale;
  801. $order->date_update = date('Y-m-d H:i:s');
  802. $order->comment = $comment;
  803. if ($idUser) {
  804. $order->id_user = $idUser;
  805. // commentaire du point de vente
  806. $userPointSale = UserPointSale::searchOne([
  807. 'id_point_sale' => $order->id_point_sale,
  808. 'id_user' => $idUser
  809. ]) ;
  810. if ($userPointSale && strlen($userPointSale->comment)) {
  811. $order->comment_point_sale = $userPointSale->comment;
  812. }
  813. } else {
  814. $order->username = $username;
  815. $order->id_user = 0;
  816. }
  817. $order->save();
  818. $order = Order::searchOne(['id' => $order->id]) ;
  819. if($order && $processCredit) {
  820. $order->processCredit() ;
  821. }
  822. }
  823. }
  824. /**
  825. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
  826. *
  827. * @param integer $idOrder
  828. */
  829. public function actionPaymentStatus($idOrder)
  830. {
  831. $order = Order::searchOne(['id' => $idOrder]) ;
  832. if ($order) {
  833. $html = '';
  834. if ($order->id_user) {
  835. $userProducer = UserProducer::find()
  836. ->where([
  837. 'id_user' => $order->id_user,
  838. 'id_producer' => $order->distribution->id_producer
  839. ])
  840. ->one();
  841. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  842. if (abs($order->amount - $amountPaid) < 0.0001) {
  843. $html .= '<span class="label label-success">Payé</span>';
  844. $buttonsCredit = Html::a('Rembourser ' . $order->getAmount(Order::AMOUNT_TOTAL, true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $order->amount, 'data-type' => 'refund']);
  845. } elseif ($order->amount > $amountPaid) {
  846. $amountToPay = $order->amount - $amountPaid;
  847. $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
  848. $buttonsCredit = Html::a('Payer ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
  849. } elseif ($order->amount < $amountPaid) {
  850. $amountToRefund = $amountPaid - $order->amount;
  851. $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à rembourser';
  852. $buttonsCredit = Html::a('Rembourser ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
  853. }
  854. $html .= '<span class="buttons-credit">'
  855. . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
  856. . $buttonsCredit
  857. . '</span>';
  858. // historique
  859. $history = CreditHistory::find()
  860. ->with('userAction')
  861. ->where(['id_order' => $idOrder])
  862. ->all();
  863. $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
  864. . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
  865. . '<tbody>';
  866. if ($history && is_array($history) && count($history)) {
  867. foreach ($history as $h) {
  868. $html .= '<tr>'
  869. . '<td>' . date('d/m/Y H:i:s', strtotime($h->date)) . '</td>'
  870. . '<td>' . Html::encode($h->strUserAction()) . '</td>'
  871. . '<td>' . $h->getStrWording() . '</td>'
  872. . '<td>' . ($h->isTypeDebit() ? '- '.$h->getAmount(Order::AMOUNT_TOTAL,true) : '') . '</td>'
  873. . '<td>' . ($h->isTypeCredit() ? '+ '.$h->getAmount(Order::AMOUNT_TOTAL,true) : '') . '</td>'
  874. . '</tr>';
  875. }
  876. } else {
  877. $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
  878. }
  879. $html .= '</tbody></table>';
  880. } else {
  881. $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>';
  882. }
  883. echo json_encode([
  884. 'html_payment_status' => $html,
  885. 'json_order' => $order->getDataJson()
  886. ]);
  887. }
  888. die();
  889. }
  890. /**
  891. * Effectue le paiement/remboursement d'une commande.
  892. *
  893. * @param integer $idOrder
  894. * @param string $type
  895. * @param float $amount
  896. * @return string
  897. */
  898. public function actionAjaxPayment($idOrder, $type, $amount)
  899. {
  900. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  901. $order = Order::searchOne([
  902. 'id' => $idOrder
  903. ]) ;
  904. if ($order) {
  905. $order->saveCreditHistory(
  906. $type,
  907. $amount,
  908. Producer::getId(),
  909. $order->id_user,
  910. User::getCurrentId()
  911. );
  912. }
  913. return ['success'];
  914. }
  915. }