您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1077 行
40KB

  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 $id_pv
  706. * @param integer $id_user
  707. * @param string $username
  708. * @param array $produits
  709. * @param string $commentaire
  710. */
  711. public function actionAjaxCreate(
  712. $date, $idPointSale, $idUser, $username, $products, $comment)
  713. {
  714. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  715. $products = json_decode($products);
  716. $pointSale = PointSale::findOne($idPointSale);
  717. $distribution = Distribution::searchOne([
  718. 'date' => $date
  719. ]);
  720. if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date) &&
  721. ($idUser || strlen($username)) &&
  722. $pointSale &&
  723. count($products) &&
  724. $distribution) {
  725. $order = new Order;
  726. $order->date = date('Y-m-d H:i:s', strtotime($date . ' ' . date('H:i:s')));
  727. $order->id_point_sale = $idPointSale;
  728. $order->id_distribution = $distribution->id;
  729. $order->origin = Order::ORIGIN_ADMIN;
  730. $order->comment = $comment;
  731. if ($idUser) {
  732. $order->id_user = $idUser;
  733. // commentaire du point de vente
  734. $userPointSale = UserPointSale::searchOne([
  735. 'id_point_sale' => $idPointSale,
  736. 'id_user' => $idUser
  737. ]) ;
  738. if ($userPointSale && strlen($userPointSale->comment)) {
  739. $order->comment_point_sale = $userPointSale->comment;
  740. }
  741. } else {
  742. $order->username = $username;
  743. $order->id_user = 0;
  744. }
  745. $order->save();
  746. foreach ($products as $key => $quantity) {
  747. $product = Product::findOne($key);
  748. if ($product && $quantity) {
  749. $productOrder = new ProductOrder;
  750. $productOrder->id_order = $order->id;
  751. $productOrder->id_product = $key;
  752. $productOrder->quantity = $quantity;
  753. $productOrder->price = $product->price;
  754. $productOrder->save();
  755. }
  756. }
  757. }
  758. return ['success'] ;
  759. }
  760. /**
  761. * Met à jour une commande via une requête AJAX.
  762. *
  763. * @param integer $idOrder
  764. * @param array $products
  765. * @param string $date
  766. * @param string $comment
  767. */
  768. public function actionAjaxUpdate(
  769. $date, $idOrder, $idPointSale, $idUser, $username, $products, $comment)
  770. {
  771. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  772. $order = Order::searchOne(['id' => $idOrder]) ;
  773. if ($order &&
  774. $order->distribution->id_producer == Producer::getId()) {
  775. $products = json_decode($products);
  776. foreach ($products as $key => $quantity) {
  777. $productOrder = ProductOrder::findOne([
  778. 'id_order' => $idOrder,
  779. 'id_product' => $key
  780. ]);
  781. if ($quantity) {
  782. if ($productOrder) {
  783. $productOrder->quantity = $quantity;
  784. } else {
  785. $product = Product::findOne($key);
  786. if ($product) {
  787. $productOrder = new ProductOrder;
  788. $productOrder->id_order = $idOrder;
  789. $productOrder->id_product = $key;
  790. $productOrder->quantity = $quantity;
  791. $productOrder->price = $product->price;
  792. }
  793. }
  794. $productOrder->save();
  795. } else {
  796. if ($productOrder) {
  797. $productOrder->delete();
  798. }
  799. }
  800. }
  801. $order->id_point_sale = $idPointSale;
  802. $order->date_update = date('Y-m-d H:i:s');
  803. $order->comment = $comment;
  804. if ($idUser) {
  805. $order->id_user = $idUser;
  806. // commentaire du point de vente
  807. $userPointSale = UserPointSale::searchOne([
  808. 'id_point_sale' => $order->id_point_sale,
  809. 'id_user' => $idUser
  810. ]) ;
  811. if ($userPointSale && strlen($userPointSale->comment)) {
  812. $order->comment_point_sale = $userPointSale->comment;
  813. }
  814. } else {
  815. $order->username = $username;
  816. $order->id_user = 0;
  817. }
  818. $order->save();
  819. }
  820. }
  821. /**
  822. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
  823. *
  824. * @param integer $idOrder
  825. */
  826. public function actionPaymentStatus($idOrder)
  827. {
  828. $order = Order::searchOne(['id' => $idOrder]) ;
  829. if ($order) {
  830. $html = '';
  831. if ($order->id_user) {
  832. $userProducer = UserProducer::find()
  833. ->where([
  834. 'id_user' => $order->id_user,
  835. 'id_producer' => $order->distribution->id_producer
  836. ])
  837. ->one();
  838. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  839. if (abs($order->amount - $amountPaid) < 0.0001) {
  840. $html .= '<span class="label label-success">Payé</span>';
  841. $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']);
  842. } elseif ($order->amount > $amountPaid) {
  843. $amountToPay = $order->amount - $amountPaid;
  844. $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
  845. $buttonsCredit = Html::a('Payer ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
  846. } elseif ($order->amount < $amountPaid) {
  847. $amountToRefund = $amountPaid - $order->amount;
  848. $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à rembourser';
  849. $buttonsCredit = Html::a('Rembourser ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
  850. }
  851. $html .= '<span class="buttons-credit">'
  852. . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
  853. . $buttonsCredit
  854. . '</span>';
  855. // historique
  856. $history = CreditHistory::find()
  857. ->with('userAction')
  858. ->where(['id_order' => $idOrder])
  859. ->all();
  860. $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
  861. . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
  862. . '<tbody>';
  863. if ($history && is_array($history) && count($history)) {
  864. foreach ($history as $h) {
  865. $html .= '<tr>'
  866. . '<td>' . date('d/m/Y H:i:s', strtotime($h->date)) . '</td>'
  867. . '<td>' . Html::encode($h->strUserAction()) . '</td>'
  868. . '<td>' . $h->getStrWording() . '</td>'
  869. . '<td>' . ($h->isTypeDebit() ? '- '.$h->getAmount(Order::AMOUNT_TOTAL,true) : '') . '</td>'
  870. . '<td>' . ($h->isTypeCredit() ? '+ '.$h->getAmount(Order::AMOUNT_TOTAL,true) : '') . '</td>'
  871. . '</tr>';
  872. }
  873. } else {
  874. $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
  875. }
  876. $html .= '</tbody></table>';
  877. } else {
  878. $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>';
  879. }
  880. echo json_encode([
  881. 'html_payment_status' => $html,
  882. 'json_order' => $order->getDataJson()
  883. ]);
  884. }
  885. die();
  886. }
  887. /**
  888. * Effectue le paiement/remboursement d'une commande.
  889. *
  890. * @param integer $idOrder
  891. * @param string $type
  892. * @param float $amount
  893. * @return string
  894. */
  895. public function actionAjaxPayment($idOrder, $type, $amount)
  896. {
  897. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  898. $order = Order::searchOne([
  899. 'id' => $idOrder
  900. ]) ;
  901. if ($order) {
  902. $order->saveCreditHistory(
  903. $type,
  904. $amount,
  905. Producer::getId(),
  906. $order->id_user,
  907. User::getCurrentId()
  908. );
  909. }
  910. return ['success'];
  911. }
  912. }