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.

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