张保健 преди 4 години
родител
ревизия
176a57ac34
променени са 80 файла, в които са добавени 9490 реда и са изтрити 0 реда
  1. 225 0
      app/Common/Api.php
  2. 162 0
      app/Common/Curl.php
  3. 23 0
      app/Common/Singleton.php
  4. 86 0
      app/Console/Commands/AghCorpList.php
  5. 104 0
      app/Console/Commands/Prize.php
  6. 100 0
      app/Console/Commands/Vip.php
  7. 42 0
      app/Console/Kernel.php
  8. 53 0
      app/Exceptions/Handler.php
  9. 255 0
      app/Http/Controllers/ActivityController.php
  10. 393 0
      app/Http/Controllers/Api/ActivityController.php
  11. 139 0
      app/Http/Controllers/Api/IndexController.php
  12. 329 0
      app/Http/Controllers/Api/LoginController.php
  13. 93 0
      app/Http/Controllers/Api/PrizeController.php
  14. 254 0
      app/Http/Controllers/Api/QuestionController.php
  15. 201 0
      app/Http/Controllers/Api/UserController.php
  16. 32 0
      app/Http/Controllers/Auth/ForgotPasswordController.php
  17. 39 0
      app/Http/Controllers/Auth/LoginController.php
  18. 72 0
      app/Http/Controllers/Auth/RegisterController.php
  19. 39 0
      app/Http/Controllers/Auth/ResetPasswordController.php
  20. 13 0
      app/Http/Controllers/Controller.php
  21. 169 0
      app/Http/Controllers/DdController.php
  22. 42 0
      app/Http/Controllers/LogApiController.php
  23. 152 0
      app/Http/Controllers/LoginController.php
  24. 279 0
      app/Http/Controllers/PayController.php
  25. 453 0
      app/Http/Controllers/SuperAdmin/BrainstormingController.php
  26. 77 0
      app/Http/Controllers/SuperAdmin/GamesController.php
  27. 208 0
      app/Http/Controllers/SuperAdmin/LogController.php
  28. 183 0
      app/Http/Controllers/SuperAdminController.php
  29. 673 0
      app/Http/Controllers/brainstorming/ActivityController.php
  30. 164 0
      app/Http/Controllers/brainstorming/PrizeController.php
  31. 317 0
      app/Http/Controllers/brainstorming/QuestionController.php
  32. 268 0
      app/Http/Controllers/brainstorming/UserController.php
  33. 72 0
      app/Http/Kernel.php
  34. 34 0
      app/Http/Middleware/CacheClear.php
  35. 37 0
      app/Http/Middleware/CheckLogin.php
  36. 17 0
      app/Http/Middleware/EncryptCookies.php
  37. 42 0
      app/Http/Middleware/Logs.php
  38. 26 0
      app/Http/Middleware/RedirectIfAuthenticated.php
  39. 32 0
      app/Http/Middleware/SuperAuth.php
  40. 18 0
      app/Http/Middleware/TrimStrings.php
  41. 23 0
      app/Http/Middleware/TrustProxies.php
  42. 31 0
      app/Http/Middleware/VerifyCsrfToken.php
  43. 38 0
      app/Models/Activitys.php
  44. 15 0
      app/Models/Admin.php
  45. 16 0
      app/Models/AdminVip.php
  46. 16 0
      app/Models/ApiLogs.php
  47. 15 0
      app/Models/Apps.php
  48. 16 0
      app/Models/BlockadeAnswer.php
  49. 16 0
      app/Models/Blockades.php
  50. 16 0
      app/Models/Categorys.php
  51. 19 0
      app/Models/Configs.php
  52. 16 0
      app/Models/CorpVip.php
  53. 21 0
      app/Models/Corps.php
  54. 16 0
      app/Models/Departments.php
  55. 16 0
      app/Models/KnowledgeRecords.php
  56. 16 0
      app/Models/LotteryBoxs.php
  57. 16 0
      app/Models/Lotterys.php
  58. 16 0
      app/Models/Messages.php
  59. 16 0
      app/Models/Orders.php
  60. 16 0
      app/Models/PkAnswer.php
  61. 16 0
      app/Models/PkRooms.php
  62. 20 0
      app/Models/Prizes.php
  63. 16 0
      app/Models/Questions.php
  64. 16 0
      app/Models/Users.php
  65. 16 0
      app/Models/VipConfig.php
  66. 10 0
      app/Models/Wechats.php
  67. 29 0
      app/Providers/AppServiceProvider.php
  68. 30 0
      app/Providers/AuthServiceProvider.php
  69. 21 0
      app/Providers/BroadcastServiceProvider.php
  70. 32 0
      app/Providers/EventServiceProvider.php
  71. 73 0
      app/Providers/RouteServiceProvider.php
  72. 704 0
      app/Services/ActivityService.php
  73. 162 0
      app/Services/AghApiService.php
  74. 107 0
      app/Services/DdService.php
  75. 148 0
      app/Services/LogService.php
  76. 233 0
      app/Services/PrizeService.php
  77. 587 0
      app/Services/QuestionService.php
  78. 551 0
      app/Services/QuestionService.php.bak
  79. 403 0
      app/Services/UserService.php
  80. 29 0
      app/User.php

+ 225 - 0
app/Common/Api.php Целия файл

@@ -0,0 +1,225 @@
1
+<?php
2
+namespace App\Common;
3
+
4
+use App\Http\Requests;
5
+use Illuminate\Support\Facades\Log;
6
+
7
+class Api{
8
+
9
+    /**
10
+     * 接口返回信息json转化
11
+     * @param null $code
12
+     * @param null $msg
13
+     * @param array $data
14
+     * @return string
15
+     */
16
+    public static function json($code=NULL, $msg=NULL, $data=array()){
17
+        if(isset($code)){
18
+            $res['error'] = $code;
19
+        }
20
+        if($msg){
21
+            $res['message'] = $msg;
22
+        }
23
+
24
+        if(empty($data)){
25
+            $res['data'] = [];
26
+        } else {
27
+            $res['data'] = $data;
28
+        }
29
+
30
+
31
+        return json_encode($res);
32
+    }
33
+
34
+    /**
35
+     * 分页数据格式化
36
+     * @param $info
37
+     * @return array
38
+     */
39
+    public static function page($info){
40
+        $info = collect($info)->toArray();
41
+
42
+        $data = [];
43
+        $data['total']      = $info['total'];
44
+        $data['total_page'] = $info['last_page'];
45
+        $data['page']       = $info['current_page'];
46
+        $data['page_size']  = $info['per_page'];
47
+        $data['data']       = $info['data'];
48
+
49
+        return $data;
50
+    }
51
+
52
+    /**
53
+     * 接口数据数组化
54
+     * @param $code
55
+     * @param $msg
56
+     * @param string $data
57
+     * @return array
58
+     */
59
+    public static function arr($code, $msg, $data=''){
60
+        $res = [];
61
+        if(isset($code)){
62
+            $res['code'] = $code;
63
+        }
64
+        if($msg){
65
+            $res['msg'] = $msg;
66
+        }
67
+        $res['data'] = $data;
68
+        return $res;
69
+    }
70
+
71
+    /**
72
+     * 日期时间数据格式化
73
+     * @param $data
74
+     * @return mixed
75
+     */
76
+    public static function dateFormat($data){
77
+        collect($data)->toArray();
78
+
79
+        if(isset($data['update_time']) && !empty($data['update_time'])){
80
+            $data['update_time'] = date('Y-m-d H:i:s', $data['update_time']);
81
+        }
82
+        if(isset($data['create_time']) && !empty($data['create_time'])){
83
+            $data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);
84
+        }
85
+        if(isset($data['start_time']) && !empty($data['start_time'])){
86
+            $data['start_time'] = date('Y-m-d H:i:s', $data['start_time']);
87
+        }
88
+        if(isset($data['end_time']) && !empty($data['end_time'])){
89
+            $data['end_time'] = date('Y-m-d H:i:s', $data['end_time']);
90
+        }
91
+        return $data;
92
+    }
93
+
94
+    /**
95
+     * 请求外部链接
96
+     * @param $url
97
+     * @param string $post
98
+     */
99
+    public static function curl($url, $post=''){
100
+        $ch = curl_init();
101
+        $timeout = 5;
102
+        curl_setopt($ch, CURLOPT_URL, $url);
103
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
104
+        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
105
+
106
+        if($post){
107
+            curl_setopt($ch, CURLOPT_POST,true);
108
+        }
109
+
110
+        $contents = curl_exec($ch);
111
+        curl_close($ch);
112
+
113
+        return $contents;
114
+    }
115
+
116
+    /**
117
+     * 去除字符串中的空格
118
+     * @param $str
119
+     * @return mixed
120
+     */
121
+    public static function trimAll($str){
122
+        $null_str=array(" "," ","\t","\n","\r");
123
+        $replace_str=array("","","","","");
124
+        return str_replace($null_str,$replace_str,$str);
125
+    }
126
+
127
+    /**
128
+     * 服务器错误处理
129
+     * @param $e
130
+     * @return string
131
+     */
132
+    public static function serviceError($e){
133
+        Log::info($e);
134
+        return self::json(config('code.service_error'), trans('msg.service_error'));
135
+    }
136
+
137
+    /**
138
+     * unicode转码为utf-8
139
+     * 用于去除电话号码中隐藏的unicode编码
140
+     * @param $name
141
+     * @return string
142
+     */
143
+    public static function unicode_decode($ostr)
144
+    {
145
+        $json = '{"str":"'.$ostr.'"}';
146
+        $arr = json_decode($json,true);
147
+        if(empty($arr)) return '';
148
+
149
+        preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $ostr, $matches);
150
+        $str = join('', $matches[0]);
151
+        if($str==''){   //含有特殊字符需要逐個處理
152
+            $returnstr = '';
153
+            $i = 0;
154
+            $str_length = strlen($ostr);
155
+            while ($i<=$str_length){
156
+                $temp_str = substr($ostr, $i, 1);
157
+                $ascnum = Ord($temp_str);
158
+                if ($ascnum>=224){
159
+                    $returnstr = $returnstr.substr($ostr, $i, 3);
160
+                    $i = $i + 3;
161
+                }elseif ($ascnum>=192){
162
+                    $returnstr = $returnstr.substr($ostr, $i, 2);
163
+                    $i = $i + 2;
164
+                }elseif ($ascnum>=65 && $ascnum<=90){
165
+                    $returnstr = $returnstr.substr($ostr, $i, 1);
166
+                    $i = $i + 1;
167
+                }elseif ($ascnum>=128 && $ascnum<=191){ // 特殊字符
168
+                    $i = $i + 1;
169
+                }else{
170
+                    $returnstr = $returnstr.substr($ostr, $i, 1);
171
+                    $i = $i + 1;
172
+                }
173
+            }
174
+            $str = $returnstr;
175
+            preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $str, $matches);
176
+            $str = join('', $matches[0]);
177
+        }
178
+        return $str;
179
+        //return $arr['str'];
180
+    }
181
+
182
+    /**
183
+     * 替换不见unicode字符
184
+     * 用于去除guid和部门导入时的特殊字符
185
+     * 添加保留符号时在中括号中添加
186
+     * @param $str
187
+     * @return mixed
188
+     */
189
+    public static function trimUnicode($str){
190
+        $str = self::setFilter($str);
191
+        $res = preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9\-\_\(\)\[\]\{\}\<\>\*\=\+]#u','',$str);
192
+        return $res;
193
+    }
194
+
195
+    /**
196
+     * 全半角转换
197
+     * @param $html
198
+     * @return string
199
+     */
200
+    public static function setFilter($html){
201
+        $arr = array('0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
202
+            '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
203
+            'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
204
+            'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
205
+            'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
206
+            'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
207
+            'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
208
+            'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
209
+            'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
210
+            'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
211
+            'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
212
+            't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
213
+            'y' => 'y', 'z' => 'z',
214
+            '(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
215
+            '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
216
+            '‘' => '[', '’' => ']', '{' => '{', '}' => '}', '《' => '<',
217
+            '》' => '>',
218
+            '%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',
219
+            ':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',
220
+            ';' => ',', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
221
+            '”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"',
222
+            ' ' => ' ');
223
+        return strtr($html, $arr);
224
+    }
225
+}?>

+ 162 - 0
app/Common/Curl.php Целия файл

@@ -0,0 +1,162 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/5/24
6
+ * Time: 11:30
7
+ */
8
+
9
+namespace App\Common;
10
+
11
+class Curl {
12
+    private $http_code_ = 0;
13
+    private $errno_ = 0;
14
+    private $error_ = '';
15
+    private $response_ = '';
16
+    private $headers_ = array();
17
+    private $options_ = array();
18
+    private $info_ = array();
19
+    private $handle_ = null;
20
+
21
+
22
+    /**
23
+     * CuteCurl constructor.
24
+     * @param $url
25
+     * @param bool|false $require_response_body 非200状态保存返回内容
26
+     */
27
+    function __construct($url, $require_response_body = false) {
28
+        $this->handle_ = curl_init($url);
29
+        $this->option(CURLOPT_FAILONERROR, !$require_response_body);
30
+    }
31
+
32
+    public function setTimeout($t) {
33
+        $this->option('timeout', $t);
34
+    }
35
+
36
+    /**
37
+     * @return int
38
+     */
39
+    public function getErrno() {
40
+        return $this->errno_;
41
+    }
42
+
43
+    /**
44
+     * @return string
45
+     */
46
+    public function getError() {
47
+        return $this->error_;
48
+    }
49
+
50
+    /**
51
+     * @return array
52
+     */
53
+    public function getInfo() {
54
+        return $this->info_;
55
+    }
56
+
57
+    /**
58
+     * @return int
59
+     */
60
+    public function getHttpCode() {
61
+        return $this->http_code_;
62
+    }
63
+
64
+
65
+    public function httpGet() {
66
+        return $this->send();
67
+    }
68
+
69
+    public function httpPost($params = array(), $options = array()) {
70
+        // If its an array (instead of a query string) then format it correctly
71
+        if (is_array($params)) {
72
+            $params = http_build_query($params);
73
+        }
74
+        // Add in the specific options provided
75
+        $this->options($options);
76
+        $this->option(CURLOPT_POST, TRUE);
77
+        $this->option(CURLOPT_POSTFIELDS, $params);
78
+        return $this->send();
79
+    }
80
+
81
+    public function httpHeader($header, $content = NULL) {
82
+        $this->headers_[] = $content ? $header . ': ' . $content : $header;
83
+    }
84
+
85
+    public function sendCookie($cookie,$prefix) {
86
+        if(!empty($cookie)) {
87
+            $str = '';
88
+            foreach ($cookie as $key => $value) {
89
+                if(strpos($key,$prefix) === 0 ) {
90
+                    $str .= $key.'='.$value.';';
91
+                }
92
+            }
93
+            $this->headers_[] = 'Cookie: '.substr($str,0,-1);
94
+        }
95
+    }
96
+
97
+    private function send() {
98
+        // Set two default options_, and merge any extra ones in
99
+        if (!isset($this->options_[CURLOPT_TIMEOUT])) {
100
+            $this->options_[CURLOPT_TIMEOUT] = 30;
101
+        }
102
+        if (!isset($this->options_[CURLOPT_RETURNTRANSFER])) {
103
+            $this->options_[CURLOPT_RETURNTRANSFER] = TRUE;
104
+        }
105
+        if (!isset($this->options_[CURLOPT_FAILONERROR])) {
106
+            $this->options_[CURLOPT_FAILONERROR] = TRUE;
107
+        }
108
+
109
+        if (!empty($this->headers_)) {
110
+            $this->option(CURLOPT_HTTPHEADER, $this->headers_);
111
+        }
112
+
113
+        $this->options();
114
+
115
+        // Execute the request & and hide all output
116
+        $this->response_ = curl_exec($this->handle_);
117
+        $this->info_ = curl_getinfo($this->handle_);
118
+        $this->http_code_ = $this->info_['http_code'];
119
+
120
+        // Request failed
121
+        if ($this->response_ === FALSE) {
122
+            $this->errno_ = curl_errno($this->handle_);
123
+            $this->error_ = curl_error($this->handle_);
124
+            curl_close($this->handle_);
125
+            return FALSE;
126
+        } // Request successful
127
+        else {
128
+            curl_close($this->handle_);
129
+            return $this->response_;
130
+        }
131
+    }
132
+
133
+    public function ssl($verify_peer = TRUE, $verify_host = 2, $path_to_cert = NULL) {
134
+        if ($verify_peer) {
135
+            $this->option(CURLOPT_SSL_VERIFYPEER, TRUE);
136
+            $this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
137
+            $this->option(CURLOPT_CAINFO, $path_to_cert);
138
+        } else {
139
+            $this->option(CURLOPT_SSL_VERIFYPEER, FALSE);
140
+        }
141
+        return $this;
142
+    }
143
+
144
+    public function options($options = array()) {
145
+        // Merge options in with the rest - done as array_merge() does not overwrite numeric keys
146
+        foreach ($options as $option_code => $option_value) {
147
+            $this->option($option_code, $option_value);
148
+        }
149
+        // Set all options provided
150
+        curl_setopt_array($this->handle_, $this->options_);
151
+        return $this;
152
+    }
153
+
154
+    public function option($code, $value) {
155
+        if (is_string($code) && !is_numeric($code)) {
156
+            $code = constant('CURLOPT_' . strtoupper($code));
157
+        }
158
+        $this->options_[$code] = $value;
159
+        return $this;
160
+    }
161
+
162
+}

+ 23 - 0
app/Common/Singleton.php Целия файл

@@ -0,0 +1,23 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/22
7
+ * Time: 19:57
8
+ */
9
+namespace App\Common;
10
+
11
+
12
+trait Singleton
13
+{
14
+    private static $instance;
15
+
16
+    static function getInstance(...$args)
17
+    {
18
+        if(!isset(self::$instance)){
19
+            self::$instance = new static(...$args);
20
+        }
21
+        return self::$instance;
22
+    }
23
+}

+ 86 - 0
app/Console/Commands/AghCorpList.php Целия файл

@@ -0,0 +1,86 @@
1
+<?php
2
+
3
+namespace App\Console\Commands;
4
+
5
+use Illuminate\Console\Command;
6
+use App\Models\Corps;
7
+use App\Services\AghApiService;
8
+
9
+class AghCorpList extends Command
10
+{
11
+    /**
12
+     * The name and signature of the console command.
13
+     *
14
+     * @var string
15
+     */
16
+    protected $signature = 'command:aghcorplist';
17
+
18
+    /**
19
+     * The console command description.
20
+     *
21
+     * @var string
22
+     */
23
+    protected $description = '同步企业信息列表';
24
+
25
+    /**
26
+     * Create a new command instance.
27
+     *
28
+     * @return void
29
+     */
30
+    public function __construct()
31
+    {
32
+        parent::__construct();
33
+    }
34
+
35
+    /**
36
+     * Execute the console command.
37
+     *
38
+     * @return mixed
39
+     */
40
+    public function handle()
41
+    {
42
+        $page = 1;
43
+        $page_size  = 100;
44
+
45
+        $corpList  = AghApiService::getInstance()->getCorpList($page, $page_size);
46
+//        print_r($corpList['body']['list'][0]['createAt']);exit;
47
+//        print_r($corpList);exit;
48
+        $totalPage = $corpList['body']['totalPage'];
49
+
50
+        $update_num = 0;
51
+        $create_num = 0;
52
+        for($page; $page<=$totalPage; $page++) {
53
+            $corpLists = AghApiService::getInstance()->getCorpList($page, $page_size);
54
+
55
+            if (empty($corpLists)) {
56
+                return '数据为空';
57
+            } else {
58
+                foreach ($corpLists['body']['list'] as $k => $v) {
59
+                    $query = [];
60
+                    $query['source_id']         = $v['enterpriseId'];
61
+                    $query['source_type']       = 'agh';
62
+                    $query['corp_name']         = $v['fullName'];
63
+                    $query['corp_short_name']   = $v['abbName'];
64
+                    $query['contact_name']      = $v['contact'];
65
+                    $query['contact_phone']     = $v['cellPhone'];
66
+                    $query['contact_email']     = $v['email'];
67
+                    $query['contact_address']   = $v['address'];
68
+                    $query['status']            = $v['state'] == true ? 1 : 0;
69
+                    $query['register_time']     = round($v['createAt']/1000);
70
+                    $query['update_time']       = time();
71
+
72
+                    $res = Corps::where('source_id', $query['source_id'])->where('source_type', $query['source_type'])->first();
73
+                    if ($res) {
74
+                        Corps::where('source_id', $query['source_id'])->where('source_type', $query['source_type'])->update($query);
75
+                        $update_num += 1;
76
+                    } else {
77
+                        $query['create_time'] = time();
78
+                        Corps::insert($query);
79
+                        $create_num += 1;
80
+                    }
81
+                }
82
+            }
83
+        }
84
+        echo '更新企业信息:' . $update_num . '条;' . PHP_EOL . '插入企业信息:' . $create_num . '条!'.PHP_EOL;
85
+    }
86
+}

+ 104 - 0
app/Console/Commands/Prize.php Целия файл

@@ -0,0 +1,104 @@
1
+<?php
2
+
3
+namespace App\Console\Commands;
4
+
5
+use Illuminate\Console\Command;
6
+use App\Models\Configs;
7
+use App\Models\Activitys;
8
+use App\Models\LotteryBoxs;
9
+
10
+class Prize extends Command
11
+{
12
+    /**
13
+     * The name and signature of the console command.
14
+     *
15
+     * @var string
16
+     */
17
+    protected $signature = 'command:prize';
18
+
19
+    /**
20
+     * The console command description.
21
+     *
22
+     * @var string
23
+     */
24
+    protected $description = '抽奖宝箱信息处理';
25
+
26
+    /**
27
+     * Create a new command instance.
28
+     *
29
+     * @return void
30
+     */
31
+    public function __construct()
32
+    {
33
+        parent::__construct();
34
+    }
35
+
36
+    /**
37
+     * Execute the console command.
38
+     * @return mixed
39
+     */
40
+    public function handle()
41
+    {
42
+        $actIds = Activitys::where('status', 1)->where('is_complete_set', 1)->pluck('activity_id')->toArray();
43
+        $prizeOpenIds = Configs::where('is_open_prize', 1)->whereIn('activity_id', $actIds)->pluck('activity_id');
44
+        $i = 0;
45
+        foreach($prizeOpenIds as  $k=>$v){
46
+            $actConfig = Configs::where('activity_id', $v)->first()->toArray();
47
+            $levels = [1,2,3,4];
48
+            $querys = [];
49
+            foreach($levels as $key=>$val){
50
+                $query['activity_id']   = $actConfig['activity_id'];
51
+                $query['corp_id']       = $actConfig['corp_id'];
52
+                switch($val){
53
+                    case 1:
54
+                        $query['lottery_level'] = 1;
55
+                        $query['lottery_name']  = '铜宝箱';
56
+                        $query['status']        = 1;
57
+                        $query['open_rule']     = $actConfig['copper_box_km'];
58
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_one.png';
59
+                        break;
60
+                    case 2:
61
+                        $query['lottery_level'] = 2;
62
+                        $query['lottery_name'] = '银宝箱';
63
+                        $query['status'] = 1;
64
+                        $query['open_rule'] = $actConfig['silver_box_km'];
65
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_two.png';
66
+                        break;
67
+                    case 3:
68
+                        $query['lottery_level'] = 3;
69
+                        $query['lottery_name'] = '金宝箱';
70
+                        $query['status'] = 1;
71
+                        $query['open_rule'] = $actConfig['gold_box_km'];
72
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_three.png';
73
+                        break;
74
+                    case 4:
75
+                        $query['lottery_level'] = 4;
76
+                        $query['lottery_name'] = '幸运宝箱';
77
+                        $query['status'] = 0;
78
+                        $query['open_rule'] = 0;
79
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_four.png';
80
+                        break;
81
+                }
82
+                $query['open_mode'] = 'km';
83
+                $query['create_time'] = time();
84
+                $query['update_time'] = time();
85
+                $box = LotteryBoxs::where('activity_id', $actConfig['activity_id'])
86
+                                    ->where('corp_id', $actConfig['corp_id'])
87
+                                    ->where('lottery_level', $query['lottery_level'])
88
+                                    ->first();
89
+                if(!$box){
90
+                    $querys[] = $query;
91
+                }
92
+            }
93
+
94
+            $res = LotteryBoxs::insert($querys);
95
+            if($res){
96
+                echo $v.'=======成功'.PHP_EOL;
97
+            } else {
98
+                echo $v.'=======失败'.PHP_EOL;
99
+            }
100
+            $i++;
101
+        }
102
+        echo $i.'个活动同步成功';
103
+    }
104
+}

+ 100 - 0
app/Console/Commands/Vip.php Целия файл

@@ -0,0 +1,100 @@
1
+<?php
2
+
3
+namespace App\Console\Commands;
4
+
5
+use Illuminate\Console\Command;
6
+use App\Models\CorpVip;
7
+use App\Models\AdminVip;
8
+use App\Models\Admin;
9
+
10
+class Vip extends Command
11
+{
12
+    /**
13
+     * The name and signature of the console command.
14
+     *
15
+     * @var string
16
+     */
17
+    protected $signature = 'command:vip';
18
+
19
+    /**
20
+     * The console command description.
21
+     *
22
+     * @var string
23
+     */
24
+    protected $description = '会员信息处理';
25
+
26
+    /**
27
+     * Create a new command instance.
28
+     *
29
+     * @return void
30
+     */
31
+    public function __construct()
32
+    {
33
+        parent::__construct();
34
+    }
35
+
36
+    /**
37
+     * Execute the console command.
38
+     * @return mixed
39
+     */
40
+    public function handle()
41
+    {
42
+        //获取当前可用会员信息
43
+        $vipInfo = AdminVip::where('vip_end_time', '>', time())->get()->toArray();
44
+        if(empty($vipInfo)){
45
+            echo '无当前可用会员数据'.PHP_EOL;
46
+            die;
47
+        }
48
+        $i = 0;
49
+        foreach($vipInfo as $k=>$v){
50
+            //判断管理员是否存在
51
+            $adminInfo = Admin::where('id', $v['admin_id'])->first();
52
+            if(!$adminInfo){
53
+                echo $v['admin_id'].'管理员不存在'.PHP_EOL;
54
+                continue;
55
+            } else {
56
+                $adminInfo = collect($adminInfo)->toArray();
57
+            }
58
+
59
+            //判断是否已经有企业会员记录
60
+            $corpVipInfo = CorpVip::where('corp_id', $adminInfo['corp_id'])->first();
61
+            if($corpVipInfo){
62
+                //已存在则按照规则整合会员
63
+                if($corpVipInfo['vip_level'] == $v['vip_level']){
64
+                    $query = [];
65
+                    $query['vip_start_time'] = time();
66
+                    $query['vip_end_time']   = time()+3600*24*7;
67
+                    CorpVip::where('corp_id', $adminInfo['corp_id'])->update($query);
68
+                    echo $v['admin_id'].'管理员时间叠加'.PHP_EOL;
69
+                } elseif($corpVipInfo['vip_level'] > $v['vip_level']){
70
+                    echo $v['admin_id'].'管理员低级会员无需合并'.PHP_EOL;
71
+                } else {
72
+                    $query = [];
73
+                    $query['vip_level'] = $v['vip_level'];
74
+                    $query['vip_start_time'] = $v['vip_start_time'];
75
+                    $query['vip_end_time']   = $v['vip_end_time'];
76
+                    CorpVip::where('corp_id', $adminInfo['corp_id'])->update($query);
77
+                    echo $v['admin_id'].'管理员高级会员直接替换'.PHP_EOL;
78
+                }
79
+            } else {
80
+                //不存在则直接插入
81
+                $query = [];
82
+                $query['corp_id']       = $adminInfo['corp_id'];
83
+                $query['app_id']        = 1;
84
+                $query['vip_level']     = $v['vip_level'];
85
+                $query['vip_start_time']= time();
86
+                $query['vip_end_time']  = time()+3600*24*7;
87
+                $query['create_time']   = time();
88
+                $query['update_time']   = time();
89
+                $res = CorpVip::insert($query);
90
+                if($res){
91
+                    echo $v['admin_id'].'管理员合并成功'.PHP_EOL;
92
+                } else {
93
+                    echo $v['admin_id'].'管理员合并失败'.PHP_EOL;
94
+                }
95
+            }
96
+            $i++;
97
+        }
98
+        echo '整合管理员'.$i.'个';
99
+    }
100
+}

+ 42 - 0
app/Console/Kernel.php Целия файл

@@ -0,0 +1,42 @@
1
+<?php
2
+
3
+namespace App\Console;
4
+
5
+use Illuminate\Console\Scheduling\Schedule;
6
+use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
7
+
8
+class Kernel extends ConsoleKernel
9
+{
10
+    /**
11
+     * The Artisan commands provided by your application.
12
+     *
13
+     * @var array
14
+     */
15
+    protected $commands = [
16
+        //
17
+    ];
18
+
19
+    /**
20
+     * Define the application's command schedule.
21
+     *
22
+     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
23
+     * @return void
24
+     */
25
+    protected function schedule(Schedule $schedule)
26
+    {
27
+        // $schedule->command('inspire')
28
+        //          ->hourly();
29
+    }
30
+
31
+    /**
32
+     * Register the commands for the application.
33
+     *
34
+     * @return void
35
+     */
36
+    protected function commands()
37
+    {
38
+        $this->load(__DIR__.'/Commands');
39
+
40
+        require base_path('routes/console.php');
41
+    }
42
+}

+ 53 - 0
app/Exceptions/Handler.php Целия файл

@@ -0,0 +1,53 @@
1
+<?php
2
+
3
+namespace App\Exceptions;
4
+
5
+use Exception;
6
+use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
7
+
8
+class Handler extends ExceptionHandler
9
+{
10
+    /**
11
+     * A list of the exception types that are not reported.
12
+     *
13
+     * @var array
14
+     */
15
+    protected $dontReport = [
16
+        //
17
+    ];
18
+
19
+    /**
20
+     * A list of the inputs that are never flashed for validation exceptions.
21
+     *
22
+     * @var array
23
+     */
24
+    protected $dontFlash = [
25
+        'password',
26
+        'password_confirmation',
27
+    ];
28
+
29
+    /**
30
+     * Report or log an exception.
31
+     *
32
+     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
33
+     *
34
+     * @param  \Exception  $exception
35
+     * @return void
36
+     */
37
+    public function report(Exception $exception)
38
+    {
39
+        parent::report($exception);
40
+    }
41
+
42
+    /**
43
+     * Render an exception into an HTTP response.
44
+     *
45
+     * @param  \Illuminate\Http\Request  $request
46
+     * @param  \Exception  $exception
47
+     * @return \Illuminate\Http\Response
48
+     */
49
+    public function render($request, Exception $exception)
50
+    {
51
+        return parent::render($request, $exception);
52
+    }
53
+}

+ 255 - 0
app/Http/Controllers/ActivityController.php Целия файл

@@ -0,0 +1,255 @@
1
+<?php
2
+/**
3
+ * 2018-06-25 韩
4
+ */
5
+
6
+namespace App\Http\Controllers;
7
+
8
+use App\Http\Requests;
9
+use App\Models\VipConfig;
10
+use Illuminate\Http\Request;
11
+
12
+use DB;
13
+use Excel;
14
+use Session;
15
+use App\Common\Api;
16
+use App\Models\Activitys;
17
+use App\Models\Apps;
18
+use App\Models\Corps;
19
+use App\Models\AdminVip;
20
+use App\Models\CorpVip;
21
+
22
+use Qiniu\Auth;
23
+
24
+class ActivityController extends Controller
25
+{
26
+    public function __construct(){
27
+
28
+    }
29
+
30
+    /**
31
+     * 超级管理员获取企业列表
32
+     * 2018-06-26 10:32:00
33
+     * @param Request $request
34
+     * @return string
35
+     */
36
+    public function getCorpList(Request $request){
37
+        try {
38
+            $params = $request->all();
39
+
40
+            $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
41
+
42
+            $keyword = $request->get("keyword");
43
+
44
+            if (is_null($keyword)) {
45
+                $corp_info = Corps::orderByDesc("corp_id")->paginate($page_size);
46
+            } else {
47
+                $corp_info = Corps::where("corp_name", "like", "%" . $keyword . "%")
48
+                    ->orderByDesc("corp_id")->paginate($page_size);
49
+            }
50
+
51
+            $data = Api::page($corp_info);
52
+
53
+            //时间戳转换
54
+            foreach ($data['data'] as $key => $val) {
55
+                $data['data'][$key] = Api::dateFormat($val);
56
+            }
57
+
58
+            return Api::json(config('code.success'), trans('msg.success'), $data);
59
+        }catch(\Exception $e) {
60
+            return Api::serviceError($e);
61
+        }
62
+    }
63
+
64
+    /**
65
+     *  应用列表
66
+     *  corp_id 企业ID
67
+     */
68
+    public function getAppList(Request $request){
69
+        try {
70
+            $res = Apps::get();
71
+
72
+            $data = json_decode($res, true);
73
+
74
+            $params = $request->all();
75
+            if (empty($params['corp_id'])) {
76
+                return Api::json(config('code.params_error'), trans('params.corp_id').trans('msg.params_error'));
77
+            }
78
+            $userInfo = $request->session()->get('userInfo');
79
+            //给超级管理员的企业ID赋值。赋予当前选中的企业ID
80
+            if ($userInfo['is_admin'] == 1) {
81
+                $userInfo['corp_id'] = $params['corp_id'];
82
+                $request->session()->put('userInfo', $userInfo);
83
+            }
84
+
85
+            return Api::json(config('code.success'), trans('msg.success'), $data);
86
+        }catch(\Exception $e) {
87
+            return Api::serviceError($e);
88
+        }
89
+    }
90
+
91
+    /**
92
+     *  获取应用详情
93
+     *  id  int   活动类行ID
94
+     */
95
+    public function getAppInfo(Request $request){
96
+        try {
97
+            $params = $request->all();
98
+
99
+            if (empty($params['app_id'])) {
100
+                return Api::json(config('code.params_error'), trans('params.app_id').trans('msg.params_error'));
101
+            }
102
+
103
+            $data = Apps::where('app_id', $params['app_id'])->first();
104
+
105
+            return Api::json(config('code.success'), trans('msg.success'), $data);
106
+        }catch(\Exception $e) {
107
+            return Api::serviceError($e);
108
+        }
109
+    }
110
+
111
+    /**
112
+     *  获取七牛上传头token
113
+     */
114
+    public function getUploadToken(Request $request){
115
+        try {
116
+            $accessKey = env("QINIU_ACCESS_KEY");
117
+            $secretKey = env("QINIU_SECRET_KEY");
118
+            $auth = new Auth($accessKey, $secretKey);
119
+            $bucket = env("QINIU_BUCKET");
120
+            // 生成上传Token
121
+            $token = $auth->uploadToken($bucket);
122
+
123
+            $data['token'] = $token;
124
+            return Api::json(config('code.success'), trans('msg.success'), $data);
125
+        }catch(\Exception $e) {
126
+            return Api::serviceError($e);
127
+        }
128
+    }
129
+
130
+    /**
131
+     *  获取活动列表
132
+     *  Corp_id int() 企业ID
133
+     *  2018-05-08 16:55 韩
134
+     */
135
+    public function getList(Request $request){
136
+        try {
137
+            $params = $request->all();
138
+
139
+            $keys = array('corp_id');
140
+            foreach ($keys as $key) {
141
+                if (empty($params[$key])) {
142
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_error'));
143
+                }
144
+            }
145
+
146
+            $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
147
+
148
+            $user_info = Session::get('userInfo');
149
+            if (isset($params['keyword']) && !empty($params['keyword'])) {
150
+                $data = Activitys::where('corp_id', $params['corp_id'])
151
+                    ->where('status', '1')
152
+//                    ->where('creator', $user_info['id'])
153
+                    ->where('is_complete_set', '1')
154
+                    ->where('title', 'like', "%" . $params['keyword'] . "%")
155
+                    ->orderByDesc("create_time")->paginate($page_size);
156
+            } else {
157
+                $data = Activitys::where('corp_id', $params['corp_id'])
158
+                    ->where('status', '1')
159
+//                    ->where('creator', $user_info['id'])
160
+                    ->where('is_complete_set', '1')
161
+                    ->orderByDesc("create_time")->paginate($page_size);
162
+            }
163
+
164
+            $data = Api::page($data);
165
+
166
+            foreach ($data['data'] as $k => $v) {
167
+                //管理路由地址
168
+                $app_info = Apps::where('app_id', $v['app_id'])->first()->toArray();
169
+                $data['data'][$k]['admin_url'] = $app_info['admin_url'];
170
+
171
+                //游戏路由地址
172
+                $data['data'][$k]['game_url'] = env('WEB_URL') . '/' . $app_info['app_code'] . '?activity_id=' . $v['activity_id'];
173
+            }
174
+
175
+            //时间戳格式化
176
+            foreach ($data['data'] as $key => $val) {
177
+                $data['data'][$key] = Api::dateFormat($val);
178
+                //活动状态
179
+                if ($val['start_time'] > time()) {
180
+                    $data['data'][$key]['activity_status_text'] = '未开始';
181
+                } elseif ($val['end_time'] < time()) {
182
+                    $data['data'][$key]['activity_status_text'] = '已结束';
183
+                } else {
184
+                    if ($val['is_temp_stop'] == 1) {
185
+                        $data['data'][$key]['activity_status_text'] = '已暂停';
186
+                    } else {
187
+                        $data['data'][$key]['activity_status_text'] = '进行中';
188
+                    }
189
+                }
190
+            }
191
+            return Api::json(config('code.success'), trans('msg.success'), $data);
192
+
193
+        } catch(\Exception $e) {
194
+            return Api::serviceError($e);
195
+        }
196
+    }
197
+
198
+    /**
199
+     * 获取用户信息
200
+     * @param Request $request
201
+     * @return string
202
+     */
203
+    public function getBaseAdmin(Request $request){
204
+        $params = $request->all();
205
+
206
+        $user_info = $request->session()->get('userInfo');
207
+        if($user_info['corp_id'] != 0){
208
+            $user_info['corp_short_name'] = Corps::where('corp_id', $user_info['corp_id'])->value('corp_short_name');
209
+        }
210
+
211
+        if(empty($params['app_id'])){
212
+//            $admin_vip_config = AdminVip::where('admin_id', $user_info['id'])
213
+            $admin_vip_config = CorpVip::where('corp_id', $user_info['corp_id'])
214
+                                ->where('vip_end_time', '>', time())
215
+                                ->orderByDesc('vip_level')
216
+                                ->first();
217
+        } else {
218
+//            $admin_vip_config = AdminVip::where('admin_id', $user_info['id'])
219
+            $admin_vip_config = CorpVip::where('corp_id', $user_info['corp_id'])
220
+                                ->where('vip_end_time', '>', time())
221
+                                ->where('app_id', $params['app_id'])
222
+                                ->orderByDesc('vip_level')
223
+                                ->first();
224
+        }
225
+        if(!empty($admin_vip_config)){
226
+            $vipConfig = VipConfig::where('vip_level', $admin_vip_config['vip_level'])->first();
227
+            $user_info['time_range']      = ceil(($admin_vip_config['vip_end_time']-time())/(3600*24));
228
+            $user_info['vip_name']        = $vipConfig['vip_name'];
229
+            $user_info['vip_end_time']    = date('Y-m-d H:i:s', $admin_vip_config['vip_end_time']);
230
+            $user_info['vip_level']       = $admin_vip_config['vip_level'];
231
+
232
+            //当前用户可创建活动数和已创建且在线的活动数
233
+            $user_info['online_act_num']  = $vipConfig['online_act_num'];
234
+            $user_info['new_online_act']  = Activitys::where('corp_id', $user_info['corp_id'])
235
+                                                    ->where('status', 1)
236
+                                                    ->where('end_time', '>', time())
237
+                                                    ->where('is_complete_set', 1)
238
+                                                    ->count();
239
+        }
240
+
241
+        $user_info['env'] = env('APP_ENV');
242
+        return Api::json(config('code.success'), trans('msg.success'), $user_info);
243
+    }
244
+
245
+//    /**2018-10-29 迁移到DdController
246
+//     * 获取公告列表
247
+//     * @param Request $request
248
+//     * @return string
249
+//     */
250
+//    public function getMessageList(Request $request){
251
+//        $res = Messages::orderByDesc('create_time')->limit(10)->get();
252
+//        return Api::json(config('code.success'), trans('msg.success'), $res);
253
+//    }
254
+}
255
+?>

+ 393 - 0
app/Http/Controllers/Api/ActivityController.php Целия файл

@@ -0,0 +1,393 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Api;
4
+
5
+use Illuminate\Http\Request;
6
+use App\Http\Requests;
7
+use App\Http\Controllers\Controller;
8
+use App\Common\Api;
9
+
10
+use App\Models\Apps;
11
+use App\Models\Activitys;
12
+use App\Models\Corps;
13
+
14
+use Illuminate\Support\Facades\Validator;
15
+use Qiniu\Auth;
16
+use Qiniu\Storage\UploadManager;
17
+
18
+use App\Services\ActivityService;
19
+
20
+use DB;
21
+use Excel;
22
+
23
+class ActivityController extends Controller
24
+{
25
+
26
+    public function __construct(){
27
+        //加载中间键
28
+        $this->middleware('CheckLogin');
29
+        $this->middleware('Logs');
30
+        $this->middleware('CacheClear');
31
+    }
32
+
33
+    //宝箱设置
34
+    const LOTTERY_LEVEL = array(
35
+        'copperPrize'=>1,
36
+        'sliverPrize'=>2,
37
+        'goldPrize'  =>3,
38
+    );
39
+    const USER_UPLOAD = 1;
40
+
41
+    /**
42
+     *  获取活动列表
43
+     *  Corp_id int() 企业ID
44
+     *  2018-05-08 16:55 韩
45
+     */
46
+    public function getActList(Request $request){
47
+        try {
48
+            $params = $request->all();
49
+
50
+            $keys = array('corp_id');
51
+            foreach ($keys as $key) {
52
+                if (empty($params[$key])) {
53
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_error'));
54
+                }
55
+            }
56
+
57
+            $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
58
+
59
+            if (isset($params['keyword']) && !empty($params['keyword'])) {
60
+                $data = Activitys::where('corp_id', $params['corp_id'])
61
+                    ->where('status', '1')
62
+                    ->where('is_complete_set', '1')
63
+                    ->where('title', 'like', "%" . $params['keyword'] . "%")
64
+                    ->orderByDesc("create_time")->paginate($page_size);
65
+            } else {
66
+                $data = Activitys::where('corp_id', $params['corp_id'])
67
+                    ->where('status', '1')
68
+                    ->where('is_complete_set', '1')
69
+                    ->orderByDesc("create_time")->paginate($page_size);
70
+            }
71
+
72
+            $data = Api::page($data);
73
+
74
+            foreach ($data['data'] as $k => $v) {
75
+                //管理路由地址
76
+                $app_info = Apps::where('app_id', $v['app_id'])->first()->toArray();
77
+                $data['data'][$k]['admin_url'] = $app_info['admin_url'];
78
+
79
+                //游戏路由地址
80
+                $data['data'][$k]['game_url'] = env('WEB_URL') . '/' . $app_info['app_code'] . '?activity_id=' . $v['activity_id'];
81
+            }
82
+
83
+            //时间戳格式化
84
+            foreach ($data['data'] as $key => $val) {
85
+                $data['data'][$key] = Api::dateFormat($val);
86
+                //活动状态
87
+                if ($val['start_time'] > time()) {
88
+                    $data['data'][$key]['activity_status_text'] = '未开始';
89
+                } elseif ($val['end_time'] < time()) {
90
+                    $data['data'][$key]['activity_status_text'] = '已结束';
91
+                } else {
92
+                    if ($val['is_temp_stop'] == 1) {
93
+                        $data['data'][$key]['activity_status_text'] = '已暂停';
94
+                    } else {
95
+                        $data['data'][$key]['activity_status_text'] = '进行中';
96
+                    }
97
+                }
98
+            }
99
+            return Api::json(config('code.success'), trans('msg.success'), $data);
100
+
101
+        } catch(\Exception $e) {
102
+            return Api::serviceError($e);
103
+        }
104
+    }
105
+
106
+    /**
107
+     *  获取活动详情
108
+     *  act_id  int  活动ID
109
+     */
110
+    public function getActInfo(Request $request){
111
+        try {
112
+            $params = $request->all();
113
+
114
+            $keys = array('activity_id', 'corp_id');
115
+            foreach ($keys as $key) {
116
+                if (empty($params[$key])) {
117
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_error'));
118
+                }
119
+            }
120
+
121
+            $res = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
122
+
123
+            if ($res) {
124
+                return Api::json(config('code.success'), trans('msg.success'), $res);
125
+            } else {
126
+                return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
127
+            }
128
+        } catch(\Exception $e) {
129
+            return Api::serviceError($e);
130
+        }
131
+    }
132
+
133
+    /**
134
+     *  应用列表
135
+     *  corp_id 企业ID
136
+     */
137
+    public function getAppList(Request $request){
138
+        try {
139
+            $res = Apps::get();
140
+
141
+            $data = json_decode($res, true);
142
+
143
+            $params = $request->all();
144
+            if (empty($params['corp_id'])) {
145
+                return Api::json(config('code.params_error'), trans('msg.params_error'));
146
+            }
147
+            $userInfo = $request->session()->get('userInfo');
148
+            //给超级管理员的企业ID赋值。赋予当前选中的企业ID
149
+            if ($userInfo['is_admin'] == 1) {
150
+                $userInfo['corp_id'] = $params['corp_id'];
151
+                $request->session()->put('userInfo', $userInfo);
152
+            }
153
+
154
+            return Api::json(config('code.success'), trans('msg.success'), $data);
155
+        }catch(\Exception $e) {
156
+            return Api::serviceError($e);
157
+        }
158
+    }
159
+
160
+    /**
161
+     *  获取应用详情
162
+     *  id  int   活动类行ID
163
+     */
164
+    public function getAppInfo(Request $request){
165
+        try {
166
+            $params = $request->all();
167
+
168
+            if (empty($params['app_id'])) {
169
+                return Api::json(config('code.params_error'), trans('msg.params_error'));
170
+            }
171
+
172
+            $data = Apps::where('app_id', $params['app_id'])->first();
173
+
174
+            return Api::json(config('code.success'), trans('msg.success'), $data);
175
+        }catch(\Exception $e) {
176
+            return Api::serviceError($e);
177
+        }
178
+    }
179
+
180
+    /**
181
+     *  超级管理员获取企业列表
182
+     *
183
+     */
184
+    public function getCorpList(Request $request){
185
+        try {
186
+            $params = $request->all();
187
+
188
+            $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
189
+
190
+            $keyword = $request->get("keyword");
191
+
192
+            if (is_null($keyword)) {
193
+                $corp_info = Corps::orderByDesc("corp_id")->paginate($page_size);
194
+            } else {
195
+                $corp_info = Corps::where("corp_name", "like", "%" . $keyword . "%")
196
+                    ->orderByDesc("corp_id")->paginate($page_size);
197
+            }
198
+
199
+            $data = Api::page($corp_info);
200
+
201
+            //时间戳转换
202
+            foreach ($data['data'] as $key => $val) {
203
+                $data['data'][$key] = Api::dateFormat($val);
204
+            }
205
+
206
+            return Api::json(config('code.success'), trans('msg.success'), $data);
207
+        }catch(\Exception $e) {
208
+            return Api::serviceError($e);
209
+        }
210
+    }
211
+
212
+    /**
213
+     *  获取七牛上传头token
214
+     */
215
+    public function getUploadToken(Request $request){
216
+        try {
217
+            $accessKey = env("QINIU_ACCESS_KEY");
218
+            $secretKey = env("QINIU_SECRET_KEY");
219
+            $auth = new Auth($accessKey, $secretKey);
220
+            $bucket = env("QINIU_BUCKET");
221
+            // 生成上传Token
222
+            $token = $auth->uploadToken($bucket);
223
+
224
+            $data['token'] = $token;
225
+            return Api::json(config('code.success'), trans('msg.success'), $data);
226
+        }catch(\Exception $e) {
227
+            return Api::serviceError($e);
228
+        }
229
+    }
230
+
231
+    /**
232
+     * 活动复制
233
+     * @param Request $request
234
+     * @return string
235
+     */
236
+    public function getActCopy(Request $request){
237
+        try {
238
+            $params = $request->all();
239
+
240
+            $keys = array('activity_id');
241
+            foreach ($keys as $key) {
242
+                if (empty($params[$key])) {
243
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
244
+                }
245
+            }
246
+
247
+            $res = ActivityService::copyActivity($params);
248
+
249
+            if ($res) {
250
+                $data['activity_id'] = $res;
251
+                return Api::json(config('code.success'), trans('msg.success'), $data);
252
+            } else {
253
+                return Api::json(config('code.fail'), trans('msg.fail'));
254
+            }
255
+        }catch(\Exception $e) {
256
+            return Api::serviceError($e);
257
+        }
258
+    }
259
+
260
+    /**
261
+     * 活动下架(删除)
262
+     * @param Request $request
263
+     * @return string
264
+     */
265
+    public function postChangeStatus(Request $request){
266
+        try {
267
+            $params = $request->all();
268
+
269
+            $keys = array('activity_id', 'corp_id');
270
+            foreach ($keys as $key) {
271
+                if (empty($params[$key])) {
272
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
273
+                }
274
+            }
275
+
276
+            $res = ActivityService::changeActStatus($params);
277
+
278
+            return Api::json($res['code'], $res['msg']);
279
+        }catch(\Exception $e) {
280
+            return Api::serviceError($e);
281
+        }
282
+    }
283
+
284
+    /**
285
+     * 暂停活动
286
+     * @param Request $request
287
+     * @return string
288
+     */
289
+    public function getActStop(Request $request){
290
+        try {
291
+            $params = $request->all();
292
+
293
+            $keys = array('activity_id', 'corp_id');
294
+            foreach ($keys as $key) {
295
+                if (empty($params[$key])) {
296
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
297
+                }
298
+            }
299
+
300
+            $res = ActivityService::stopActivity($params);
301
+
302
+            return Api::json($res['code'], $res['msg']);
303
+        }catch(\Exception $e) {
304
+            return Api::serviceError($e);
305
+        }
306
+    }
307
+
308
+    /**
309
+     * 新建活动
310
+     * 2018-06-19 17:00:00
311
+     * @param Request $request
312
+     * @return string
313
+     */
314
+    public function postAddAct(Request $request){
315
+        try {
316
+            $params = $request->all();
317
+
318
+            $keys = array('corp_id', 'app_id');
319
+            foreach ($keys as $key) {
320
+                if (empty($params[$key])) {
321
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
322
+                }
323
+            }
324
+
325
+            if($params['activity_id']){
326
+                $res = ActivityService::getConfigs($params['activity_id'], $params['corp_id']);
327
+            } else {
328
+                $res = ActivityService::addAct($params['corp_id'], $params['app_id']);
329
+            }
330
+
331
+            return Api::json($res['code'], $res['msg'], $res['data']);
332
+        }catch(\Exception $e) {
333
+            return Api::serviceError($e);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * 保存活动
339
+     * 2018-06-20 10:25:00
340
+     * @param Request $request
341
+     * @return string
342
+     */
343
+    public function postSaveAct(Request $request){
344
+        try {
345
+            $params = $request->all();
346
+
347
+            $keys = array('activity_id', 'corp_id', 'app_id', 'title', 'start_time', 'end_time');
348
+            foreach ($keys as $key) {
349
+                if (empty($params[$key])) {
350
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
351
+                }
352
+            }
353
+
354
+            //数字不能为小数点  不能为负数
355
+            $int_key = array();
356
+
357
+            $res = ActivityService::saveActivity($params);
358
+
359
+            return Api::json($res['code'], $res['msg'], $res['data']);
360
+        }catch(\Exception $e) {
361
+            return Api::serviceError($e);
362
+        }
363
+    }
364
+
365
+    public function postTest(Request $request){
366
+    /*参数验证测试*/
367
+////        $params = $request->validate([
368
+////            'username'=>'required',
369
+////            'password'=>'required',
370
+////        ]);
371
+//        $validator = Validator::make($request->all(), [
372
+//            'username' => 'required |max:255',
373
+//            'password' => 'required',
374
+//        ]);
375
+//
376
+//        if ($validator->fails()) {
377
+//            $errors = collect($validator->errors())->toArray();
378
+//            $res = current($errors);
379
+//            return Api::json(config('code.success'), trans('msg.success'), $res);
380
+////            return $validator->errors();
381
+//        }
382
+//
383
+//        return Api::json(config('code.success'), trans('msg.success'));
384
+
385
+        return 'xxxx';
386
+    }
387
+}
388
+?>
389
+
390
+
391
+
392
+
393
+

+ 139 - 0
app/Http/Controllers/Api/IndexController.php Целия файл

@@ -0,0 +1,139 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/7/24
6
+ * Time: 15:22
7
+ */
8
+
9
+namespace App\Http\Controllers\Api;
10
+
11
+use App\Http\Controllers\Controller;
12
+use App\Models\Admin;
13
+use App\Models\Corps;
14
+use App\Services\AghApiService;
15
+use Illuminate\Http\Request;
16
+use Illuminate\Support\Facades\DB;
17
+use Illuminate\Support\Facades\Log;
18
+
19
+
20
+class IndexController extends Controller
21
+{
22
+    public function sso(Request $request){
23
+
24
+        //return AghApiService::getInstance()->adminSso();
25
+        $array = [
26
+            "partnerId"=>$request->get("partnerId"),
27
+            "expires"=>$request->get("expires"),
28
+            "nonce"=>$request->get("nonce"),
29
+            "data"=>urlencode($request->get("data")),
30
+        ];
31
+        ksort($array);
32
+        $str ="";
33
+        foreach ($array as $key=>$value){
34
+            $str = $str . $key . '=' . $value . '&';
35
+        }
36
+        $str = substr($str, 0,strlen($str)-1);
37
+        $signature = hash_hmac('SHA256',$str, env("B_API_SECRET_KEY"));
38
+        Log::info(json_encode($array));
39
+        Log::info("signature:".$signature);
40
+
41
+
42
+        try{
43
+            if($signature==$request->get("signature")){
44
+                $data = json_decode(base64_decode($request->get("data")),true);
45
+                $adminUserId = $data["admin_user_id"];
46
+                $aghCorpId = $data["corp_id"];
47
+                $name = $data["admin_name"];
48
+
49
+                $adminUser = Admin::where("admin_user_id",$adminUserId)->first();
50
+                if(empty($adminUser)){
51
+                    $corp = Corps::where("source_id",$aghCorpId)->where("source_type","agh")->first();
52
+                    if($corp){
53
+                        $res = Admin::insert([
54
+                            "username" => "agh_".$adminUserId,
55
+                            "name" => $name,
56
+                            "corp_id" => $corp->corp_id,
57
+                            "is_admin" => 0,
58
+                            "admin_user_id" => $adminUserId,
59
+                            "status" => 1,
60
+                            "create_time" => time(),
61
+                            "update_time" => time(),
62
+                        ]);
63
+                        if($res){
64
+                            $adminUser = Admin::where("admin_user_id",$adminUserId)->first();
65
+                        }
66
+                    }else{
67
+                        $ret = AghApiService::getInstance()->getCorpInfo($aghCorpId);
68
+                        if($ret["errno"]==0){
69
+                            $corpSource = $ret["body"];
70
+                            $query = [];
71
+                            $query['source_id']         = $corpSource['enterpriseId'];
72
+                            $query['source_type']       = 'agh';
73
+                            $query['corp_name']         = $corpSource['fullName'];
74
+                            $query['corp_short_name']   = $corpSource['abbName'];
75
+                            $query['contact_name']      = $corpSource['contact'];
76
+                            $query['contact_phone']     = $corpSource['cellPhone'];
77
+                            $query['contact_email']     = $corpSource['email'];
78
+                            $query['contact_address']   = $corpSource['address'];
79
+                            $query['status']            = $corpSource['state'] == true ? 1 : 0;
80
+                            $query['update_time']       = time();
81
+                            $query["create_time"]       = time();
82
+
83
+                            Corps::insert($query);
84
+
85
+                            $corp = Corps::where("source_id",$aghCorpId)->where("source_type","agh")->first();
86
+                            if($corp){
87
+                                $res = Admin::insert([
88
+                                    "username" => "agh_".$adminUserId,
89
+                                    "name" => $name,
90
+                                    "corp_id" => $corp->corp_id,
91
+                                    "is_admin" => 0,
92
+                                    "admin_user_id" => $adminUserId,
93
+                                    "status" => 1,
94
+                                    "create_time" => time(),
95
+                                    "update_time" => time(),
96
+                                ]);
97
+                                if($res){
98
+                                    $adminUser = Admin::where("admin_user_id",$adminUserId)->first();
99
+                                }
100
+                            }
101
+
102
+                        }
103
+                    }
104
+                }
105
+
106
+                if($adminUser){
107
+                    $corp = Corps::where("corp_id", $adminUser["corp_id"])->first();
108
+
109
+                    DB::table("agh_admin_log")->insert([
110
+                        "admin_id" =>$adminUser["id"],
111
+                        "name" =>$adminUser["name"],
112
+                        "corp_id" =>$corp["corp_id"],
113
+                        "agh_corp_id" =>$corp["source_id"],
114
+                        "corp_name" =>$corp["corp_name"],
115
+                        "first_time" =>$adminUser["create_time"],
116
+                        "create_time" => time()
117
+                    ]);
118
+
119
+                    $request->session()->put('userInfo', $adminUser);
120
+                    $redirect = $request->get("redirect");
121
+                    if(empty($redirect)){
122
+                        return redirect("/manage");
123
+                    }else{
124
+                        header("location:".$redirect);
125
+                    }
126
+
127
+                }
128
+
129
+                return "认证成功,但找不到该企业信息";
130
+            }
131
+        }catch (\Exception $exception){
132
+            Log::info($exception->getTraceAsString());
133
+        }
134
+
135
+        return "认证不通过";
136
+
137
+    }
138
+
139
+}

+ 329 - 0
app/Http/Controllers/Api/LoginController.php Целия файл

@@ -0,0 +1,329 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Api;
4
+
5
+use App\Models\Activitys;
6
+use App\Models\Configs;
7
+use App\Models\Corps;
8
+use App\Models\Departments;
9
+use App\Services\QuestionService;
10
+use App\Services\UserService;
11
+use Illuminate\Http\Request;
12
+use App\Http\Requests;
13
+use App\Http\Controllers\Controller;
14
+use App\Models\Admin;
15
+use App\Common\Api;
16
+
17
+use App\Models\Prizes;
18
+use App\Models\Users;
19
+use App\Models\Lotterys;
20
+use Illuminate\Support\Facades\DB;
21
+use Excel;
22
+
23
+use Qiniu\Auth;
24
+use Qiniu\Storage\UploadManager;
25
+
26
+use App\Services\ActivityService;
27
+use Illuminate\Support\Facades\Redis;
28
+use Psy\Test\CodeCleaner\FunctionContextPassTest;
29
+
30
+class LoginController extends Controller
31
+{
32
+
33
+    public function __construct(){
34
+    }
35
+
36
+    const QUESTION_UPLOAD_FAIL = 'bsb_question_upload_fail:';
37
+    const USER_UPLOAD_FAIL = 'bsb_user_upload_fail:';
38
+
39
+    /**
40
+     *  登录校验
41
+     *  username varchar()
42
+     *  password varchar()
43
+     *  2018-05-08 16:37 韩
44
+     */
45
+    public function Login(Request $request){
46
+        $params = $request->all();
47
+
48
+        $password = md5($params['password']);
49
+        $res = Admin::where('username', $params['username'])
50
+            ->where('password', $password)
51
+            ->where('status', 1)        //1 正常 0 冻结
52
+            ->first();
53
+
54
+        if($res){
55
+            //用户信息缓存
56
+            $request->session()->put('userInfo', $res);
57
+
58
+            $user_admin = collect($res)->toArray();
59
+            return Api::json(config('code.success'), trans('msg.login_success'), $user_admin['is_admin']);
60
+        } else {
61
+            return Api::json(config('code.fail'), trans('msg.login_error'));
62
+        }
63
+    }
64
+
65
+    /**
66
+     *  活动看板
67
+     */
68
+    public function getBoard(Request $request){
69
+        $params = $request->all();
70
+        if(empty($params['activity_id'])){
71
+            return '没参数';
72
+        }
73
+        $data = [];
74
+        $activity_id = $params['activity_id'];
75
+
76
+        $activityConfigs = Configs::where('activity_id', $activity_id)->first();
77
+
78
+        //奖品设置
79
+        $data['prizes']['data'] = Prizes::where('activity_id', $activity_id)->get()->toArray();
80
+        $data['prizes']['is_open_prize'] = $activityConfigs['is_open_prize'];
81
+
82
+        //人员情况
83
+        $user_all = Users::where('activity_id', $activity_id)->count();                                                                      //总人数
84
+        $user_binding = Users::where('activity_id', $activity_id)->where('open_id', '!=', null)->where('open_id', '!=', '')->count();       //绑定人数
85
+        $user_blockade = Users::where('activity_id', $activity_id)->where('is_blockade_success', '1')->count();                              //必答成功人数
86
+        $data['users']['user_all']      = $user_all;
87
+        $data['users']['user_binding']  = $user_binding;
88
+        $data['users']['user_blockade'] = $user_blockade;
89
+        $data['users']['user_online']   = intval(Redis::get('bs_online:'.$activity_id));
90
+
91
+        //活动数据
92
+        $activity_info = Configs::where('activity_id', $activity_id)->first()->toArray();
93
+        $data['activity_info'] = $activity_info;
94
+
95
+        //抽奖情况
96
+        $copper_complete    = Users::where('activity_id', $activity_id)->where('knowledge_money', '>=', $activity_info['copper_box_km'])->count();
97
+        $silver_complete    = Users::where('activity_id', $activity_id)->where('knowledge_money', '>=', $activity_info['silver_box_km'])->count();
98
+        $gold_complete      = Users::where('activity_id', $activity_id)->where('knowledge_money', '>=', $activity_info['gold_box_km'])->count();
99
+
100
+        $copper_use     = Lotterys::where('activity_id', $activity_id)->where('lottery_level', 1)->count();
101
+        $silver_use     = Lotterys::where('activity_id', $activity_id)->where('lottery_level', 2)->count();
102
+        $gold_use       = Lotterys::where('activity_id', $activity_id)->where('lottery_level', 3)->count();
103
+
104
+        $data['completes']['copper']['complete']    = $copper_complete;
105
+        $data['completes']['copper']['use']         = $copper_use;
106
+        $data['completes']['copper']['unuse']       = $copper_complete - $copper_use;
107
+        $data['completes']['silver']['complete']    = $silver_complete;
108
+        $data['completes']['silver']['use']         = $silver_use;
109
+        $data['completes']['silver']['unuse']       = $silver_complete - $silver_use;
110
+        $data['completes']['gold']['complete']      = $gold_complete;
111
+        $data['completes']['gold']['use']           = $gold_use;
112
+        $data['completes']['gold']['unuse']         = $gold_complete - $gold_use;
113
+
114
+        //单位参与率排行
115
+        $department_user_info = DB::select("select count(*) as user_num,sum(is_blockade_success) as sum_join,avg(knowledge_money) as avg_km,department_id
116
+                                          from bs_users where activity_id={$activity_id} and department_id>0 and status=1 group by department_id");
117
+
118
+        $department_user_info = json_decode(json_encode($department_user_info), true);
119
+        $joins = [];
120
+        $user_nums = [];
121
+        $avg_kms = [];
122
+        foreach($department_user_info as $k=>$v){
123
+            $department_user_info[$k]['department_name'] = Departments::where('department_id', $v['department_id'])->value('department_name');
124
+            $department_user_info[$k]['join'] = $v['user_num'] != 0 ? $v['sum_join']/$v['user_num']*100 : 0;
125
+            $joins[] = $v['sum_join']/$v['user_num'];
126
+            $user_nums[] = $v['user_num'];
127
+            $avg_kms[] = $v['avg_km'];
128
+        }
129
+
130
+        $kms = $department_user_info;
131
+        array_multisort($joins,SORT_DESC,$user_nums,SORT_DESC,$department_user_info);
132
+        $data['departments']['data'] = $department_user_info;
133
+        $data['departments']['open_department_top'] = $activityConfigs['open_department_top'];
134
+
135
+        //单位知识币排行
136
+        array_multisort($avg_kms,SORT_DESC,$user_nums,SORT_DESC,$kms);
137
+        $data['avg_km'] = $kms;
138
+
139
+        //个人知识币排行
140
+        $user_km = Users::where('activity_id', $activity_id)->where('status', 1)->where('is_blockade_success', 1)->orderBy('knowledge_money', 'desc')->limit(100)->get()->toArray();
141
+        foreach ($user_km as $k=>$v) {
142
+            $user_km[$k]['department_name'] = Departments::where('department_id', $v['department_id'])->value('department_name');
143
+        }
144
+        $data['user_km'] = $user_km;
145
+
146
+        return view('board', ['data'=>$data]);
147
+    }
148
+
149
+    /**
150
+     *  看板下载
151
+     */
152
+    public function getDownload(Request $request){
153
+        $params = $request->all();
154
+
155
+        if(empty($params['activity_id']) || empty($params['type'])){
156
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
157
+        }
158
+
159
+        if($params['type'] == 'join') {
160
+            $joins_info = Users::where('activity_id', $params['activity_id'])->where('status', 1)->where('is_blockade_success', 1)->orderBy('blockade_success_time', 'desc')->get()->toArray();
161
+
162
+            $data = [];
163
+            $res = [];
164
+            $joins_info = json_decode(json_encode($joins_info), true);
165
+            foreach ($joins_info as $k => $v) {
166
+                $res['name'] = $v['name'];
167
+                $res['department_name'] = Departments::where('department_id', $v['department_id'])->value('department_name');
168
+                $res['knowledge_money'] = $v['knowledge_money'];
169
+                $res['blockade_success_time'] = date('Y-m-d H:i:s', $v['blockade_success_time']);
170
+                $data[] = $res;
171
+            }
172
+            $hands = array('姓名', '部门', '知识币', '必答完成时间');
173
+            array_unshift($data, $hands);
174
+
175
+            Excel::create('参与情况', function ($excel) use ($data) {
176
+                $excel->sheet('join', function ($sheet) use ($data) {
177
+                    $sheet->rows($data);
178
+                });
179
+            })->export('xlsx');
180
+        } elseif($params['type'] == 'lottery') {
181
+            $lotterys = Lotterys::where('activity_id', $params['activity_id'])->orderBy('lottery_time', 'desc')->get()->toArray();
182
+
183
+            $data = [];
184
+            $res = [];
185
+            $lotterys = json_decode(json_encode($lotterys), true);
186
+            foreach ($lotterys as $k => $v) {
187
+                $userInfo = Users::where('user_id', $v['user_id'])->first()->toArray();
188
+                $res['name'] = $userInfo['name'];
189
+                $res['department_name'] = Departments::where('department_id', $userInfo['department_id'])->value('department_name');
190
+                $res['knowledge_money'] = $v['prize_name'];
191
+                $res['blockade_success_time'] = $v['lottery_time'];
192
+                $data[] = $res;
193
+            }
194
+            $hands = array('姓名', '部门', '获得奖品', '抽奖时间');
195
+            array_unshift($data, $hands);
196
+
197
+            Excel::create('抽奖情况', function ($excel) use ($data) {
198
+                $excel->sheet('lottery', function ($sheet) use ($data) {
199
+                    $sheet->rows($data);
200
+                });
201
+            })->export('xlsx');
202
+        } else {
203
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
204
+        }
205
+
206
+    }
207
+
208
+    /**
209
+     *  下载模板
210
+     */
211
+    public function getDownloadModel(Request $request){
212
+        $params = $request->all();
213
+
214
+        if(empty($params['type'])){
215
+            return Api::json(config('code.params_error'), trans('params.type').trans('msg.params_not_null'));
216
+        } else {
217
+            if($params['type'] == 'user'){
218
+                $url = '/model/人员模板.xlsx';           //人员导入模板
219
+            } else {
220
+                $url = '/model/题库模板.xlsx';           //题库导入模板
221
+            }
222
+            header('location:/manage'.$url);
223
+        }
224
+    }
225
+
226
+    /**
227
+     * 获取用户信息
228
+     * @param Request $request
229
+     * @return string
230
+     */
231
+    public function getBaseAdmin(Request $request){
232
+        $user_info = $request->session()->get('userInfo');
233
+        if($user_info['corp_id'] != 0){
234
+            $user_info['corp_short_name'] = Corps::where('corp_id', $user_info['corp_id'])->value('corp_short_name');
235
+        }
236
+
237
+        return Api::json(config('code.success'), trans('msg.success'), $user_info);
238
+    }
239
+
240
+    /**
241
+     *  退出登录
242
+     */
243
+    public function loginOut(Request $request){
244
+        $request->session()->forget('userInfo');
245
+
246
+        return redirect('manage');
247
+//        return Api::json(config('code.success'), trans('msg.success'));
248
+    }
249
+
250
+    /**
251
+     * 下载上传失败的数据(优化)
252
+     * 2018-07-02 15;00:00
253
+     * @param Request $request
254
+     * @return string
255
+     */
256
+    public function getErrorUpload(Request $request){
257
+        try {
258
+            $params = $request->all();
259
+            $keys = array('corp_id', 'activity_id', 'type');
260
+            foreach ($keys as $key) {
261
+                if (empty($params[$key])) {
262
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
263
+                }
264
+            }
265
+
266
+            $actInfo = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
267
+            if (!$actInfo) {
268
+                return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
269
+            }
270
+
271
+            $data = [];
272
+            if($params['type'] == 'user'){
273
+                $data = Redis::get(self::USER_UPLOAD_FAIL.$params['activity_id']);
274
+                $data = json_decode($data, true);
275
+                if(empty($data)) return Api::json(config('code.fail'), '无错误上传数据');
276
+
277
+                UserService::downloadUserExcel($data);
278
+            } elseif($params['type'] == 'question') {
279
+                $data = Redis::get(self::QUESTION_UPLOAD_FAIL.$params['activity_id']);
280
+                $data = json_decode($data, true);
281
+                if(empty($data)) return Api::json(config('code.fail'), '无错误上传数据');
282
+
283
+                QuestionService::downloadQuestionExcel($data);
284
+            }
285
+        }catch(\Exception $e) {
286
+            return Api::serviceError($e);
287
+        }
288
+    }
289
+
290
+
291
+    /**
292
+     *  获取七牛上传头token
293
+     */
294
+    public function getUploadToken(Request $request){
295
+        try {
296
+            $accessKey = env("QINIU_ACCESS_KEY");
297
+            $secretKey = env("QINIU_SECRET_KEY");
298
+            $auth = new Auth($accessKey, $secretKey);
299
+            $bucket = env("QINIU_BUCKET");
300
+            // 生成上传Token
301
+            $token = $auth->uploadToken($bucket);
302
+
303
+            $data['token'] = $token;
304
+            return Api::json(config('code.success'), trans('msg.success'), $data);
305
+        }catch(\Exception $e) {
306
+            return Api::serviceError($e);
307
+        }
308
+    }
309
+
310
+    /**
311
+     * 测试方法
312
+     * @param Request $request
313
+     * @return string
314
+     */
315
+    public function test(Request $request){
316
+        $str = '韩\u202e乐1552\u202d8333321\u202ccc';
317
+        $str = Api::unicode_decode($str);
318
+//        $pattern = "/[\x{007f}-\x{009f}]|\x{00ad}|[\x{0483}-\x{0489}]|[\x{0559}-\x{055a}]|\x{058a}|[\x{0591}-\x{05bd}]|\x{05bf}|[\x{05c1}-\x{05c2}]|[\x{05c4}-\x{05c7}]|[\x{0606}-\x{060a}]|[\x{063b}-\x{063f}]|\x{0674}|[\x{06e5}-\x{06e6}]|\x{070f}|[\x{076e}-\x{077f}]|\x{0a51}|\x{0a75}|\x{0b44}|[\x{0b62}-\x{0b63}]|[\x{0c62}-\x{0c63}]|[\x{0ce2}-\x{0ce3}]|[\x{0d62}-\x{0d63}]|\x{135f}|[\x{200b}-\x{200f}]|[\x{2028}-\x{202e}]|\x{2044}|\x{2071}|[\x{f701}-\x{f70e}]|[\x{f710}-\x{f71a}]|\x{fb1e}|[\x{fc5e}-\x{fc62}]|\x{feff}|\x{fffc}/u";
319
+//        $str = preg_replace($pattern, '', $str);
320
+//        return $str;
321
+//        $str_arr = preg_split('/(?<!^)(?!$)/u', $str );
322
+//        $str_arr = preg_match_all("/./u", $str, $arr);
323
+//        foreach()
324
+        return $str;
325
+    }
326
+
327
+
328
+}
329
+?>

+ 93 - 0
app/Http/Controllers/Api/PrizeController.php Целия файл

@@ -0,0 +1,93 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Api;
4
+
5
+use App\Common\Api;
6
+use Illuminate\Http\Request;
7
+use App\Http\Controllers\Controller;
8
+
9
+use App\Models\Prizes;
10
+use App\Models\Lotterys;
11
+use App\Services\PrizeService;
12
+
13
+class PrizeController extends Controller
14
+{
15
+    public function __construct()
16
+    {
17
+        //加载中间键
18
+        $this->middleware('CheckLogin');
19
+        $this->middleware('Logs');
20
+        $this->middleware('CacheClear');
21
+    }
22
+
23
+    /**
24
+     *  宝箱——添加/修改奖品
25
+     */
26
+    public function postPrize(Request $request){
27
+        try {
28
+            $params = $request->all();
29
+
30
+            $keys = array('activity_id', 'corp_id', 'lottery_level', 'prize_name', 'prize_day_rule', 'prize_count', 'prize_weights', 'prize_image_url');
31
+            foreach ($keys as $key) {
32
+                if (!isset($params[$key])) {
33
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
34
+                }
35
+            }
36
+
37
+            $res = PrizeService::prizeDetail($params);
38
+
39
+            return Api::json($res['code'], $res['msg'], $res['data']);
40
+        }catch(\Exception $e) {
41
+            return Api::serviceError($e);
42
+        }
43
+    }
44
+
45
+    /**
46
+     * 获取宝箱内的奖品列表
47
+     * @param Request $request
48
+     * @return string
49
+     */
50
+    public function getPrizeList(Request $request){
51
+        try {
52
+            $params = $request->all();
53
+
54
+            $keys = array('activity_id', 'lottery_level', 'corp_id');
55
+            foreach ($keys as $key) {
56
+                if (empty($params[$key])) {
57
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
58
+                }
59
+            }
60
+
61
+            $res = PrizeService::getPrizeList($params['corp_id'], $params['activity_id'], $params['lottery_level']);
62
+
63
+            return Api::json($res['code'], $res['msg'], $res['data']);
64
+        }catch(\Exception $e) {
65
+            return Api::serviceError($e);
66
+        }
67
+    }
68
+
69
+    /**
70
+     * 奖品删除
71
+     * @param Request $request
72
+     * @return string
73
+     */
74
+    public function postPrizeDelete(Request $request){
75
+        try {
76
+            $params = $request->all();
77
+
78
+            $keys = array('activity_id', 'lottery_level', 'corp_id', 'prize_id');
79
+            foreach ($keys as $key) {
80
+                if (empty($params[$key])) {
81
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
82
+                }
83
+            }
84
+
85
+            $res = PrizeService::prizeDelete($params);
86
+
87
+            return Api::json($res['code'], $res['msg'], $res['data']);
88
+        }catch(\Exception $e) {
89
+            return Api::serviceError($e);
90
+        }
91
+    }
92
+}
93
+?>

+ 254 - 0
app/Http/Controllers/Api/QuestionController.php Целия файл

@@ -0,0 +1,254 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Api;
4
+
5
+use App\Models\Configs;
6
+use Illuminate\Http\Request;
7
+use App\Http\Requests;
8
+use App\Http\Controllers\Controller;
9
+use App\Common\Api;
10
+
11
+use App\Models\Questions;
12
+
13
+use DB;
14
+use Excel;
15
+use Storage;
16
+use Illuminate\Support\Facades\Redis;
17
+use App\Services\ActivityService;
18
+use App\Services\QuestionService;
19
+
20
+class QuestionController extends Controller
21
+{
22
+
23
+    public function __construct(){
24
+        //加载中间键
25
+        $this->middleware('CheckLogin');
26
+        $this->middleware('Logs');
27
+        $this->middleware('CacheClear');
28
+    }
29
+
30
+    const QUESTION_UPLOAD = 1;
31
+    const QUESTION_UPLOAD_KEY = 'bsb_question_upload:';        //题目上传到redis的key
32
+
33
+    /**
34
+     *  活动配置——题库上传(题目)
35
+     */
36
+    public function postActQuestion(Request $request){
37
+        try {
38
+            $params = $request->all();
39
+
40
+            $keys = array('activity_id', 'corp_id', 'category_name');
41
+            foreach ($keys as $key) {
42
+                if (empty($params[$key])) {
43
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
44
+                }
45
+            }
46
+
47
+            if ($request->isMethod("post")) {
48
+                $activity_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
49
+                if (!$activity_info) {
50
+                    return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
51
+                }
52
+
53
+                if (!empty($_FILES['question'])) {
54
+                    $filePath = $_FILES['question']['tmp_name'];
55
+                    Excel::load($filePath, function ($reader) {
56
+                        $reader = $reader->getSheet(0);
57
+                        $res = $reader->toArray();
58
+
59
+                        //去掉无用表头
60
+                        foreach ($res as $k=>$v) {
61
+                            unset($res[$k]);
62
+                            if(Api::trimAll($v[0]) == '题目标题' && Api::trimAll($v['1']) == 'A选项' && Api::trimAll($v[2]) == 'B选项' && Api::trimAll($v[3]) == 'C选项' && Api::trimAll($v['4']) == 'D选项' && Api::trimAll($v[5]) == '答案'){
63
+                                break;
64
+                            }
65
+                        }
66
+
67
+                        //去掉excel表格的空数据
68
+                        $res = collect($res)->filter(function($value){
69
+                            return !is_null($value[0]) || !is_null($value[1]) || !is_null($value[2]) || !is_null($value[3]) || !is_null($value[4]) || !is_null($value[5]);
70
+                        });
71
+
72
+                        if (empty($res)) {
73
+                            print_r(Api::json(config('code.fail'), trans('msg.question_not_exist')));
74
+                            exit;
75
+                        }
76
+
77
+                        //存入redis
78
+                        Redis::set(self::QUESTION_UPLOAD_KEY.$_REQUEST['activity_id'], json_encode($res), 'EX', 3600);
79
+                    });
80
+
81
+                    //从redis获取数据
82
+                    $data = Redis::get(self::QUESTION_UPLOAD_KEY.$params['activity_id']);
83
+                    $result = QuestionService::questionUpload(json_decode($data, true), $params);
84
+
85
+                    if($result['code'] != 0){
86
+                        return Api::json(config('code.upload_fail'), trans('msg.upload_fail'));
87
+                    }
88
+
89
+                    //文件保存
90
+                    $newPath = base_path('storage/uploads/' . date('Ymd'));
91
+                    if (!is_dir($newPath)) {
92
+                        mkdir($newPath);
93
+                    }
94
+                    $file = $request->file('question');
95
+                    $file->move($newPath, date('His') . $_FILES['question']['name']);
96
+
97
+                    //修改人员上传状态
98
+                    $query_config['is_question_upload'] = self::QUESTION_UPLOAD;
99
+                    Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->update($query_config);
100
+
101
+                    return Api::json($result['code'], $result['msg'], $result['data']);
102
+                } else {
103
+                    return Api::json(config('code.params_error'), trans('msg.params_not_null'));
104
+                }
105
+            }
106
+        }catch(\Exception $e) {
107
+            return Api::serviceError($e);
108
+        }
109
+    }
110
+
111
+    /**
112
+     * 获取题库内的题目列表
113
+     * 2018-06-21 10:00:00
114
+     * @param Request $request
115
+     * @return string
116
+     */
117
+    public function getQuestionsList(Request $request){
118
+        try {
119
+            $params = $request->all();
120
+
121
+            $keys = array('corp_id', 'category_id', 'activity_id');
122
+            foreach ($keys as $key) {
123
+                if (empty($params[$key])) {
124
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
125
+                }
126
+            }
127
+
128
+            $category_info = QuestionService::getCategoryInfo($params['activity_id'], $params['corp_id'], $params['category_id']);
129
+
130
+            if (!$category_info) {
131
+                return Api::json(config('code.category_not_exist'), trans('msg.category_not_exist'));
132
+            }
133
+
134
+            $keyword = empty($params['keyword']) ? '' : $params['keyword'];
135
+            $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
136
+
137
+            $sql = Questions::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('category_id', $params['category_id'])->where('status', 1);
138
+            if (!empty($params['keyword'])) {
139
+                $sql = $sql->where("question_title", "like", "%" . $keyword . "%");
140
+            }
141
+
142
+            $questions = $sql->orderByDesc('create_time')->paginate($page_size);
143
+
144
+            $data = Api::page($questions);
145
+
146
+            //时间戳转换
147
+            foreach ($data['data'] as $key => $val) {
148
+                $data['data'][$key] = Api::dateFormat($val);
149
+                $data['data'][$key]['question_options'] = unserialize($val['question_options']);
150
+            }
151
+
152
+            return Api::json(config('code.success'), trans('msg.success'), $data);
153
+        }catch(\Exception $e) {
154
+            return Api::serviceError($e);
155
+        }
156
+    }
157
+
158
+    /**
159
+     * 获取题库列表
160
+     * 2018-06-21 10:00:00
161
+     * @param Request $request
162
+     * @return string
163
+     */
164
+    public function getCategoryList(Request $request){
165
+        try {
166
+            $params = $request->all();
167
+
168
+            $keys = array('corp_id', 'activity_id');
169
+            foreach ($keys as $key) {
170
+                if (empty($params[$key])) {
171
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
172
+                }
173
+            }
174
+
175
+            $res = QuestionService::getCategoryList($params);
176
+
177
+            return Api::json($res['code'], $res['msg'], $res['data']);
178
+        }catch(\Exception $e) {
179
+            return Api::serviceError($e);
180
+        }
181
+    }
182
+
183
+    /**
184
+     * 修改单个题目
185
+     * @param Request $request
186
+     * @return string
187
+     */
188
+    public function postQuestionModify(Request $request){
189
+        try {
190
+            $params = $request->all();
191
+
192
+            $keys = array('corp_id', 'activity_id', 'category_id');
193
+            foreach ($keys as $key) {
194
+                if (empty($params[$key])) {
195
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
196
+                }
197
+            }
198
+
199
+            $res = QuestionService::questionModify($params);
200
+            return Api::json($res['code'], $res['msg'], $res['data']);
201
+        } catch (\Exception $e) {
202
+            return Api::serviceError($e);
203
+        }
204
+    }
205
+
206
+    /**
207
+     * 修改题库名
208
+     * @param Request $request
209
+     * @return string
210
+     */
211
+    public function postSaveCategory(Request $request){
212
+        try {
213
+            $params = $request->all();
214
+
215
+            $keys = array('corp_id', 'activity_id', 'category_id', 'category_name');
216
+            foreach ($keys as $key) {
217
+                if (empty($params[$key])) {
218
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
219
+                }
220
+            }
221
+
222
+            $res = QuestionService::saveCategory($params);
223
+            return Api::json($res['code'], $res['msg'], $res['data']);
224
+        } catch (\Exception $e) {
225
+            return Api::serviceError($e);
226
+        }
227
+    }
228
+
229
+    /**
230
+     * 删除题目
231
+     * 2018-06-22 10:24:00
232
+     * @param Request $request
233
+     * @return string
234
+     */
235
+    public function postDelQuestion(Request $request){
236
+        try {
237
+            $params = $request->all();
238
+
239
+            $keys = array('corp_id', 'activity_id', 'category_id', 'question_id');
240
+            foreach ($keys as $key) {
241
+                if (empty($params[$key])) {
242
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
243
+                }
244
+            }
245
+
246
+            $res = QuestionService::delQuestion($params);
247
+
248
+            return Api::json($res['code'], $res['msg'], $res['data']);
249
+        } catch (\Exception $e) {
250
+            return Api::serviceError($e);
251
+        }
252
+    }
253
+}
254
+?>

+ 201 - 0
app/Http/Controllers/Api/UserController.php Целия файл

@@ -0,0 +1,201 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Api;
4
+
5
+use Illuminate\Support\Facades\Log;
6
+use App\Common\Api;
7
+use App\Models\Departments;
8
+use Illuminate\Http\Request;
9
+use App\Http\Controllers\Controller;
10
+
11
+use App\Models\Users;
12
+use App\Models\Configs;
13
+use App\Services\ActivityService;
14
+use App\Services\UserService;
15
+
16
+use Illuminate\Support\Facades\Redis;
17
+use Excel;
18
+
19
+class UserController extends Controller
20
+{
21
+    public function __construct(){
22
+        //加载中间键
23
+        $this->middleware('CheckLogin');
24
+        $this->middleware('Logs');
25
+        $this->middleware('CacheClear');
26
+    }
27
+
28
+    const USER_UPLOAD = 1;
29
+    const USER_UPLOAD_KEY = 'bsb_user_upload:';
30
+
31
+    /**
32
+     * 用户上传接口
33
+     * @param Request $request
34
+     * @return string
35
+     */
36
+    public function postUserUpload(Request $request){
37
+        try{
38
+            ini_set('memory_limit', '256M');
39
+            set_time_limit(0);
40
+
41
+            $params = $request->all();
42
+            $keys = array('corp_id', 'activity_id');
43
+            foreach($keys as $key){
44
+                if(empty($params[$key])){
45
+                    return Api::json(config('code.params_error'), trans('params.'.$key).trans('msg.params_not_null'));
46
+                }
47
+            }
48
+
49
+            if($request->isMethod('post')){
50
+                //活动存在性判断
51
+                $activity_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
52
+                if(!$activity_info){
53
+                    return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
54
+                }
55
+
56
+                //表单校验
57
+                if(empty($_FILES['user'])){
58
+                    return Api::json(config('code.fail'), trans('msg.excel_not_exist'));
59
+                }
60
+
61
+                //读取excel存入redis
62
+                $filePath = $_FILES['user']['tmp_name'];
63
+
64
+                Excel::load($filePath, function ($reader) {
65
+                    $reader = $reader->getSheet(0);
66
+                    $res = $reader->toArray();
67
+
68
+                    foreach ($res as $k=>$v) {
69
+                        unset($res[$k]);
70
+                        if($v[0] == '姓名' && $v['1'] == '部门' && $v[2] == '手机号码'){
71
+                            break;
72
+                        }
73
+                    }
74
+
75
+                    //去掉excel表格的空数据
76
+                    $res = collect($res)->filter(function($value){
77
+                        return !is_null($value[0]) || !is_null($value[1]) || !is_null($value[2]);
78
+                    });
79
+
80
+                    //表单内容校验
81
+                    if(empty($res)){
82
+                        print_r(Api::json(config('code.fail'), trans('msg.user_not_exist')));
83
+                        exit;
84
+                    }
85
+
86
+                    $res = json_encode($res);
87
+                    Redis::set(self::USER_UPLOAD_KEY.$_REQUEST['activity_id'], $res, 'EX', 3600);
88
+                });
89
+
90
+                //数据处理入库
91
+                $res = Redis::get(self::USER_UPLOAD_KEY.$params['activity_id']);
92
+                $res = json_decode($res, true);
93
+                $result = UserService::userUpload($res, $params['activity_id'], $params['corp_id']);
94
+
95
+                //入库成功则保存文件
96
+                if($result['code'] == 0){
97
+                    $newPath = base_path('storage/uploads/' . date('Ymd'));
98
+                    if (!is_dir($newPath)) {
99
+                        mkdir($newPath);
100
+                    }
101
+                    $file = $request->file('user');
102
+                    $file->move($newPath, date('His') . $_FILES['user']['name']);
103
+
104
+                    //修改人员上传状态
105
+                    Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->update(['is_user_upload'=>1]);
106
+                }
107
+
108
+                return Api::json($result['code'], $result['msg'], $result['data']);
109
+            } else {
110
+                return Api::json(config('code.fail'), trans('msg.method_no'));
111
+            }
112
+        } catch(\Exception $e) {
113
+            Log::info($e);
114
+            return Api::json(config('code.service_error'), '上传失败,请检测文件格式或文件是否加密!!');
115
+        }
116
+    }
117
+
118
+    /**
119
+     * 获取活动人员列表
120
+     * @param Request $request
121
+     * @return string
122
+     */
123
+    public function getUserList(Request $request){
124
+        try {
125
+            $params = $request->all();
126
+
127
+            $keys = array('activity_id', 'corp_id');
128
+            foreach ($keys as $key) {
129
+                if (empty($params[$key])) {
130
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
131
+                }
132
+            }
133
+
134
+            $pageSize = empty($params['page_size']) ? 10 : $params['page_size'];
135
+
136
+            $keyword = $request->get("keyword");
137
+
138
+            if (is_null($keyword)) {
139
+                $userInfo = Users::where('activity_id', $params['activity_id'])
140
+                                ->where('corp_id', $params['corp_id'])
141
+                                ->where('status', 1)                                    //人员状态  0 无效 1 有效
142
+                                ->orderByDesc("create_time")->paginate($pageSize);
143
+            } else {
144
+                $department_like = Departments::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where("department_name", "like", "%" . $keyword . "%")->pluck('department_id');
145
+
146
+                $sql = Users::where('activity_id', $params['activity_id'])
147
+                            ->where('corp_id', $params['corp_id'])
148
+                            ->where('status', 1)                                    //人员状态  0 无效 1 有效
149
+                            ->where("name", "like", "%" . $keyword . "%");
150
+                if(count($department_like)>0){
151
+                    $sql = $sql->orwhereIn("department_id", $department_like);
152
+                }
153
+
154
+                $userInfo = $sql ->orderByDesc("create_time")->paginate($pageSize);
155
+            }
156
+
157
+            $data = Api::page($userInfo);
158
+
159
+            //时间戳转换
160
+            foreach ($data['data'] as $key => $val) {
161
+                $data['data'][$key] = Api::dateFormat($val);
162
+                $department_name = Departments::where('department_id', $val['department_id'])->value('department_name');
163
+                $data['data'][$key]['department_name'] = $department_name?$department_name:'无部门';
164
+            }
165
+
166
+            //获取部门信息
167
+            $data['department_info'] = ActivityService::getUsersCount($params['corp_id'], $params['activity_id']);
168
+
169
+            return Api::json(config('code.success'), trans('msg.success'), $data);
170
+        }catch(\Exception $e) {
171
+            return Api::serviceError($e);
172
+        }
173
+    }
174
+
175
+    /**
176
+     * 删除人员(软删除)
177
+     * 2018-06-20 18:00:00
178
+     * @param Request $request
179
+     * @return string
180
+     */
181
+    public function postDelUser(Request $request){
182
+        try{
183
+            $params = $request->all();
184
+
185
+            $keys = array('activity_id', 'corp_id', 'user_id');
186
+            foreach ($keys as $key) {
187
+                if (empty($params[$key])) {
188
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
189
+                }
190
+            }
191
+
192
+            $res = UserService::delUser($params);
193
+
194
+            return Api::json($res['code'], $res['msg'], $res['data']);
195
+        }catch(\Exception $e) {
196
+            return Api::serviceError($e);
197
+        }
198
+    }
199
+
200
+}
201
+?>

+ 32 - 0
app/Http/Controllers/Auth/ForgotPasswordController.php Целия файл

@@ -0,0 +1,32 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Auth;
4
+
5
+use App\Http\Controllers\Controller;
6
+use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
7
+
8
+class ForgotPasswordController extends Controller
9
+{
10
+    /*
11
+    |--------------------------------------------------------------------------
12
+    | Password Reset Controller
13
+    |--------------------------------------------------------------------------
14
+    |
15
+    | This controller is responsible for handling password reset emails and
16
+    | includes a trait which assists in sending these notifications from
17
+    | your application to your users. Feel free to explore this trait.
18
+    |
19
+    */
20
+
21
+    use SendsPasswordResetEmails;
22
+
23
+    /**
24
+     * Create a new controller instance.
25
+     *
26
+     * @return void
27
+     */
28
+    public function __construct()
29
+    {
30
+        $this->middleware('guest');
31
+    }
32
+}

+ 39 - 0
app/Http/Controllers/Auth/LoginController.php Целия файл

@@ -0,0 +1,39 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Auth;
4
+
5
+use App\Http\Controllers\Controller;
6
+use Illuminate\Foundation\Auth\AuthenticatesUsers;
7
+
8
+class LoginController extends Controller
9
+{
10
+    /*
11
+    |--------------------------------------------------------------------------
12
+    | Login Controller
13
+    |--------------------------------------------------------------------------
14
+    |
15
+    | This controller handles authenticating users for the application and
16
+    | redirecting them to your home screen. The controller uses a trait
17
+    | to conveniently provide its functionality to your applications.
18
+    |
19
+    */
20
+
21
+    use AuthenticatesUsers;
22
+
23
+    /**
24
+     * Where to redirect users after login.
25
+     *
26
+     * @var string
27
+     */
28
+    protected $redirectTo = '/home';
29
+
30
+    /**
31
+     * Create a new controller instance.
32
+     *
33
+     * @return void
34
+     */
35
+    public function __construct()
36
+    {
37
+        $this->middleware('guest')->except('logout');
38
+    }
39
+}

+ 72 - 0
app/Http/Controllers/Auth/RegisterController.php Целия файл

@@ -0,0 +1,72 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Auth;
4
+
5
+use App\User;
6
+use App\Http\Controllers\Controller;
7
+use Illuminate\Support\Facades\Hash;
8
+use Illuminate\Support\Facades\Validator;
9
+use Illuminate\Foundation\Auth\RegistersUsers;
10
+
11
+class RegisterController extends Controller
12
+{
13
+    /*
14
+    |--------------------------------------------------------------------------
15
+    | Register Controller
16
+    |--------------------------------------------------------------------------
17
+    |
18
+    | This controller handles the registration of new users as well as their
19
+    | validation and creation. By default this controller uses a trait to
20
+    | provide this functionality without requiring any additional code.
21
+    |
22
+    */
23
+
24
+    use RegistersUsers;
25
+
26
+    /**
27
+     * Where to redirect users after registration.
28
+     *
29
+     * @var string
30
+     */
31
+    protected $redirectTo = '/home';
32
+
33
+    /**
34
+     * Create a new controller instance.
35
+     *
36
+     * @return void
37
+     */
38
+    public function __construct()
39
+    {
40
+        $this->middleware('guest');
41
+    }
42
+
43
+    /**
44
+     * Get a validator for an incoming registration request.
45
+     *
46
+     * @param  array  $data
47
+     * @return \Illuminate\Contracts\Validation\Validator
48
+     */
49
+    protected function validator(array $data)
50
+    {
51
+        return Validator::make($data, [
52
+            'name' => 'required|string|max:255',
53
+            'email' => 'required|string|email|max:255|unique:users',
54
+            'password' => 'required|string|min:6|confirmed',
55
+        ]);
56
+    }
57
+
58
+    /**
59
+     * Create a new user instance after a valid registration.
60
+     *
61
+     * @param  array  $data
62
+     * @return \App\User
63
+     */
64
+    protected function create(array $data)
65
+    {
66
+        return User::create([
67
+            'name' => $data['name'],
68
+            'email' => $data['email'],
69
+            'password' => Hash::make($data['password']),
70
+        ]);
71
+    }
72
+}

+ 39 - 0
app/Http/Controllers/Auth/ResetPasswordController.php Целия файл

@@ -0,0 +1,39 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Auth;
4
+
5
+use App\Http\Controllers\Controller;
6
+use Illuminate\Foundation\Auth\ResetsPasswords;
7
+
8
+class ResetPasswordController extends Controller
9
+{
10
+    /*
11
+    |--------------------------------------------------------------------------
12
+    | Password Reset Controller
13
+    |--------------------------------------------------------------------------
14
+    |
15
+    | This controller is responsible for handling password reset requests
16
+    | and uses a simple trait to include this behavior. You're free to
17
+    | explore this trait and override any methods you wish to tweak.
18
+    |
19
+    */
20
+
21
+    use ResetsPasswords;
22
+
23
+    /**
24
+     * Where to redirect users after resetting their password.
25
+     *
26
+     * @var string
27
+     */
28
+    protected $redirectTo = '/home';
29
+
30
+    /**
31
+     * Create a new controller instance.
32
+     *
33
+     * @return void
34
+     */
35
+    public function __construct()
36
+    {
37
+        $this->middleware('guest');
38
+    }
39
+}

+ 13 - 0
app/Http/Controllers/Controller.php Целия файл

@@ -0,0 +1,13 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use Illuminate\Foundation\Bus\DispatchesJobs;
6
+use Illuminate\Routing\Controller as BaseController;
7
+use Illuminate\Foundation\Validation\ValidatesRequests;
8
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
9
+
10
+class Controller extends BaseController
11
+{
12
+    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
13
+}

+ 169 - 0
app/Http/Controllers/DdController.php Целия файл

@@ -0,0 +1,169 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * 超级管理员-管理爱答题
5
+ * User: guanxl
6
+ * Date: 2018/7/4
7
+ * Time: 11:45
8
+ */
9
+
10
+namespace App\Http\Controllers;
11
+
12
+use App\Http\Requests;
13
+use App\Services\DdService;
14
+use Illuminate\Http\Request;
15
+use App\Common\Api;
16
+use DB;
17
+
18
+use App\Models\Messages;
19
+use App\Models\AdminVip;
20
+use App\Models\Admin;
21
+use App\Models\Apps;
22
+use App\Models\Activitys;
23
+use App\Models\Configs;
24
+use App\Models\CorpVip;
25
+use App\Services\QuestionService;
26
+
27
+class DdController extends Controller
28
+{
29
+    /**
30
+     * 获取公告列表
31
+     * @param Request $request
32
+     * @return string
33
+     */
34
+    public function getMessageList(Request $request){
35
+        $res = Messages::orderByDesc('create_time')->limit(10)->where('status', 1)->get();
36
+        return Api::json(config('code.success'), trans('msg.success'), $res);
37
+    }
38
+
39
+    /**
40
+     * DD会员开通及初始活动创建
41
+     * @param Request $request
42
+     * @return string
43
+     */
44
+    public function openVip(Request $request){
45
+        $adminId = $request->get('admin_id');
46
+        if(empty($adminId)){
47
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
48
+        }
49
+
50
+        //默认参数赋值
51
+        $appId          = 1;
52
+        $authType       = 'dingtalk_add';
53
+        $clientType     = 'dingtalk';
54
+        $title          = '叮当答题初体验(示例活动)';
55
+        $sponsor_corp   = '本活动解释权归迷倒万千少男少女的答题君所有';
56
+        $extendConfigs  = '{"must_question_num":2,"must_answer_wrong_num":1,"must_answer_success_km":100,"blockade_question_num":3,"blockade_answer_wrong_num":1,"blockade_answer_success_km":30,"pk_question_num":3,"pk_last_double":1,"pk_kms":"10\/20\/50","must_category_ids":"","blockade_category_ids":"","pk_category_ids":"","top_prize_num":3,"top_prize_text":"\u6392\u884c\u524d3\u540d\u8fd8\u53ef\u83b7\u5f97\u989d\u5916\u5956\u52b1\uff01","top_prize_open":1,"blockade_answer_count_down":10,"must_answer_count_down":10}';
57
+
58
+        $adminInfo = Admin::where('id', $adminId)->where('status', 1)->first();
59
+
60
+        if(!$adminInfo){
61
+            return Api::json(config('code.fail'), trans('msg.admin_not_exist'));
62
+        }
63
+
64
+        //管理员VIP开通记录
65
+        $adminCorpId = Admin::where('id', $adminId)->value('corp_id');
66
+        $vipInfo = CorpVip::where('corp_id', $adminCorpId)->first();
67
+        if(!$vipInfo){
68
+            //未开通过的企业赋予七天体验版VIP
69
+            $query = [];
70
+            $query['corp_id']   = $adminCorpId;
71
+            $query['app_id']    = $appId;                                                                               //默认为爱答题,后续若新增新的应用,需要在管理员表表明管理员所属应用
72
+            $query['vip_level'] = 1;
73
+            $query['vip_start_time'] = time();
74
+            $query['vip_end_time']   = time()+3600*24*7;                                                                //赋予七天免费版VIP
75
+            $query['create_time'] = time();
76
+            $query['update_time'] = time();
77
+
78
+            $res = CorpVip::insert($query);
79
+            if(!$res){
80
+                return Api::json(config('code.fail'), '会员开通失败');
81
+            }
82
+        }
83
+
84
+        //活动创建记录
85
+        $activityInfo = Activitys::where('creator', $adminId)->first();
86
+        if(!$activityInfo){
87
+            $vipInfo = CorpVip::where('corp_id', $adminCorpId)->first();
88
+            if($vipInfo['vip_end_time'] <= time()){
89
+                return Api::arr(config('code.fail'), trans('msg.vip_time_out'));
90
+            }
91
+
92
+            //获取应用默认数据
93
+            $app_info = Apps::where('app_id', $appId)->value('default_data');
94
+            $default_data = json_decode($app_info, true);
95
+
96
+            //activitys表参数拼接
97
+            $query = [];
98
+            $query['corp_id']       = $adminInfo['corp_id'];
99
+            $query['app_id']        = $appId;
100
+            $query['create_time']   = time();
101
+            $query['update_time']   = time();
102
+            $query['title']         = $title;
103
+            $query['logo']          = $default_data['logo'];
104
+            $query['regulation']    = $default_data['regulation'];
105
+            $query['is_jobtime_limit'] = $default_data['is_jobtime_limit'];
106
+            $query['jobtimes']      = $default_data['jobtimes'];
107
+            $query['start_time']    = strtotime(date('Y-m-d'));
108
+            $query['end_time']      = strtotime(date('Y-m-d'))+30*3600*24;
109
+            $query['auth_type']     = $authType;
110
+            $query['client_type']   = $clientType;
111
+            $query['creator']       = $adminId;
112
+            $query['is_complete_set'] = 1;
113
+            $query['activity_type'] = $vipInfo['vip_level'] == 1 ? 1 : 2;           //根据企业会员状态赋予活动收费状态
114
+
115
+            //企业VIP信息
116
+            $vip_level = CorpVip::where('corp_id', $adminCorpId)->value('vip_level');
117
+            $query['vip_level']     = $vip_level;                                                                           //活动vip等级,用于手机端权限控制
118
+
119
+            $activity_res = Activitys::insertGetId($query);
120
+
121
+            //configs表参数拼接
122
+            $configQuery = [];
123
+            $categoryRes = QuestionService::addDefault($activity_res);                                                  //添加默认题库
124
+            if(!$categoryRes){
125
+                return Api::arr($categoryRes['code'], $categoryRes['msg']);
126
+            } else {
127
+                $extendConfig = json_decode($extendConfigs, true);
128
+                $extendConfig['must_category_ids']      = $categoryRes['data']['category_id'];
129
+                $extendConfig['blockade_category_ids']  = $categoryRes['data']['category_id'];
130
+                $extendConfig['pk_category_ids']        = $categoryRes['data']['category_id'];
131
+                $configQuery['extend_configs'] = json_encode($extendConfig);
132
+            }
133
+            $configQuery['activity_id']         = $activity_res;
134
+            $configQuery['corp_id']             = $adminInfo['corp_id'];
135
+            $configQuery['top_banner']          = $default_data['top_banner'];
136
+            $configQuery['home_background']     = $default_data['home_background'];
137
+            $configQuery['mark_background']     = $default_data['mark_background'];
138
+            $configQuery['count_down_background'] = $default_data['count_down_background'];
139
+            $configQuery['sponsor_corp']        = $sponsor_corp;
140
+            $configQuery['prize_banner']        = '//s1-hn.aghcdn.com/management/20181025/069cc3cd0b76a7e1ec194b97946a62052d31d143.png';
141
+            $configQuery['copper_box_km']       = $default_data['copper_box_km'];
142
+            $configQuery['silver_box_km']       = $default_data['silver_box_km'];
143
+            $configQuery['gold_box_km']         = $default_data['gold_box_km'];
144
+            $configQuery['is_open_prize']       = 1;                                                                        //默认开启抽奖
145
+            $configQuery['open_department_top'] = $default_data['open_department_top'];                                     //默认不开启单位排行
146
+            $configQuery['level_star_config']   = json_encode($default_data['level_star_config']);                          //段位的默认配置
147
+            $configQuery['update_time']         = time();
148
+            $configQuery['create_time']         = time();
149
+
150
+            $config_res = Configs::insert($configQuery);
151
+
152
+            //添加示例宝箱
153
+            $box_res = DdService::ExampleActBox($activity_res, $adminInfo['corp_id']);
154
+
155
+            if($activity_res && $config_res && $box_res) {
156
+                //清理并生成题库缓存
157
+                $questions_cache = env('WEB_URL').'/brainstorming/console/cache/question?activity_id='.$activity_res;
158
+                $config_cache = env('WEB_URL').'/brainstorming/console/cache/config?activity_id='.$activity_res;
159
+                Api::curl($config_cache);
160
+                Api::curl($questions_cache);
161
+
162
+                return Api::json(config('code.success'), trans('msg.success'));
163
+            } else {
164
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
165
+            }
166
+        }
167
+//        return Api::json(config('code.success'), trans('msg.success'));
168
+    }
169
+}

+ 42 - 0
app/Http/Controllers/LogApiController.php Целия файл

@@ -0,0 +1,42 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanle
5
+ * Date: 2018/10/19
6
+ * Time: 12:43
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Common\Curl;
12
+use App\Common\Api;
13
+use Illuminate\Http\Request;
14
+
15
+class LogApiController extends Controller
16
+{
17
+    public function __construct(){}
18
+
19
+    /**
20
+     * 日志收集接口
21
+     * @param Request $request
22
+     * @return string
23
+     */
24
+    public function getLogCollect(Request $request){
25
+        $params = $request->all();
26
+
27
+        if(empty(env('APP_LOG_URL')) || !env('APP_LOG_URL')){
28
+            return Api::json(config('code.success'), trans('msg.success'));
29
+        }
30
+
31
+        $url = env('APP_LOG_URL').'/log/collect?admin_id='.$params['admin_id'].'&event='.$params['event'];
32
+        $curl = new Curl($url);
33
+        $res = json_decode($curl->httpGet(), true);
34
+
35
+        if($res) {
36
+            return Api::json($res['error'], $res['message']);
37
+        } else {
38
+            return Api::json(config('code.fail'), trans('msg.fail'));
39
+        }
40
+    }
41
+}
42
+?>

+ 152 - 0
app/Http/Controllers/LoginController.php Целия файл

@@ -0,0 +1,152 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use Illuminate\Http\Request;
6
+use App\Http\Requests;
7
+use App\Http\Controllers\Controller;
8
+use App\Common\Api;
9
+
10
+use App\Services\AghApiService;
11
+use App\Models\Admin;
12
+use Illuminate\Support\Facades\Log;
13
+use Illuminate\Support\Facades\Redis;
14
+
15
+class LoginController extends Controller
16
+{
17
+
18
+    public function __construct(){
19
+    }
20
+
21
+    /**
22
+     *  登良
23
+     */
24
+    public function LoginIndex(Request $request){
25
+        $user_info = $request->session()->get('userInfo');
26
+        if(!is_null($user_info)) {
27
+            if ($user_info['is_admin'] == 1) {
28
+                //超管跳转
29
+                return redirect('manage/super');
30
+            } else {
31
+                //普通管理员跳转
32
+                //钉钉和微信跳转区分
33
+                if(env('APP_ENV') != "dingtalk") {
34
+                    if (empty($user_info['admin_user_id'])) {
35
+                        return redirect('manage/static/index.html#/Gameindex');
36
+                    } else {
37
+                        return redirect('manage/static/index.html#/Gamecenter');
38
+                    }
39
+                } else {
40
+                    return redirect('manage/static/index.html#/dingtalk');
41
+                }
42
+            }
43
+        }
44
+        return redirect('manage/static/index.html#/Login');
45
+    }
46
+
47
+    /**
48
+     *  登录校验
49
+     *  username varchar()
50
+     *  password varchar()
51
+     *  2018-05-08 16:37 韩
52
+     */
53
+    public function checkLogin(Request $request){
54
+        $params = $request->all();
55
+
56
+        $password = md5($params['password']);
57
+        $res = Admin::where('username', $params['username'])
58
+            ->where('password', $password)
59
+            ->where('status', 1)        //1 正常 0 冻结
60
+            ->first();
61
+
62
+        if($res){
63
+            //用户信息缓存
64
+            $request->session()->put('userInfo', $res);
65
+
66
+            Log::debug($res);
67
+
68
+            $user_admin = collect($res)->toArray();
69
+            return Api::json(config('code.success'), trans('msg.login_success'), $user_admin['is_admin']);
70
+        } else {
71
+            return Api::json(config('code.fail'), trans('msg.login_error'));
72
+        }
73
+    }
74
+
75
+    /**
76
+     * 获取用户信息
77
+     * @param Request $request
78
+     * @return string
79
+     */
80
+    public function getBaseAdmin(Request $request){
81
+        $user_info = $request->session()->get('userInfo');
82
+        if($user_info['corp_id'] != 0){
83
+            $user_info['corp_short_name'] = Corps::where('corp_id', $user_info['corp_id'])->value('corp_short_name');
84
+        }
85
+
86
+        return Api::json(config('code.success'), trans('msg.success'), $user_info);
87
+    }
88
+
89
+    /**
90
+     *  退出登录
91
+     */
92
+    public function logout(Request $request){
93
+        $request->session()->forget('userInfo');
94
+
95
+        return redirect('manage');
96
+//        return Api::json(config('code.success'), trans('msg.success'));
97
+    }
98
+
99
+    /**
100
+     * 单点登录接口
101
+     * @param Request $request
102
+     * @return string
103
+     */
104
+    public function sso(Request $request){
105
+        $params = $request->all();
106
+
107
+        $token = $params['token'];
108
+        $redirect = empty($params['redirect'])?'':$params['redirect'];
109
+        if(empty($token)){
110
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
111
+        }
112
+
113
+        $adminId = Redis::get('b_sso_token:'.$token);
114
+        if($adminId){
115
+            $adminInfo = Admin::where('id', $adminId)->where('status', 1)->first();
116
+            if(!empty($adminInfo)){
117
+                $request->session()->put('userInfo', $adminInfo);
118
+                if(empty($redirect)){
119
+                    return redirect("/manage");
120
+                } else {
121
+                    header("location:".$redirect);
122
+                }
123
+            } else {
124
+                return '认证失败';
125
+            }
126
+        } else {
127
+            return '认证失败';
128
+        }
129
+    }
130
+
131
+    /**
132
+     * cookie写入接口
133
+     * @param Request $request
134
+     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
135
+     */
136
+    public function setCookie(Request $request){
137
+        $activityId = $request->get('activity_id');
138
+        $username = $request->get('username');
139
+        $name = $request->get('name');
140
+//        $adminInfo = $request->session()->get('userInfo');
141
+
142
+        setcookie('oauth_open_id', $username, 0, "/", env("COOKIE_DOMAIN"));
143
+        setcookie('oauth_avatar', '', 0, "/", env("COOKIE_DOMAIN"));
144
+        setcookie('oauth_nickname', $name, 0, "/", env("COOKIE_DOMAIN"));
145
+        setcookie('oauth_platform', 'wechat', 0, "/", env("COOKIE_DOMAIN"));
146
+        setcookie('oauth_guid', $username, 0, "/", env("COOKIE_DOMAIN"));
147
+        setcookie('oauth_gcorp_id', '', 0, "/", env("COOKIE_DOMAIN"));
148
+
149
+        return redirect(env('WEB_URL').'/brainstorming?activity_id='.$activityId);
150
+    }
151
+}
152
+?>

+ 279 - 0
app/Http/Controllers/PayController.php Целия файл

@@ -0,0 +1,279 @@
1
+<?php
2
+/**
3
+ * 2018-07-25 韩
4
+ */
5
+
6
+namespace App\Http\Controllers;
7
+
8
+use App\Models\Corps;
9
+use Illuminate\Http\Request;
10
+
11
+use DB;
12
+use Illuminate\Support\Facades\Redis;
13
+use Pay;
14
+use Log;
15
+use Mail;
16
+use App\Common\Api;
17
+use App\Models\Orders;
18
+use App\Models\AdminVip;
19
+use App\Models\Activitys;
20
+use App\Models\VipConfig;
21
+use App\Models\Admin;
22
+use App\Models\CorpVip;
23
+
24
+class PayController extends Controller
25
+{
26
+    public function __construct()
27
+    {
28
+
29
+    }
30
+
31
+    /**
32
+     * 微信支付获取二维码URL并下单
33
+     * @param Request $request
34
+     * @return mixed
35
+     */
36
+    public function wechatPay(Request $request){
37
+        $params = $request->all();
38
+
39
+        $userInfo = $request->session()->get('userInfo')->toArray();
40
+        //若会员等级不在配置表中存在,则视为违规请求
41
+        $vip_config = VipConfig::where('vip_level', $params['vip_level'])->first();
42
+        if(!$vip_config){
43
+            return Api::json(config('code.fail'), trans('msg.vip_not_exist'));
44
+        }
45
+
46
+        //配置参数
47
+        $order = [];
48
+        $order['out_trade_no']  = date('YmdHis').uniqid();
49
+        $price = $vip_config['price'];
50
+        $order['total_fee'] = $price * $params['months'];
51
+
52
+//        //该管理员若存在已生效会员且未到期,则无法购买低版本会员
53
+//        $adminVip = AdminVip::where('app_id', $params['app_id'])->where('admin_id', $userInfo['id'])->first();
54
+//        if($adminVip){
55
+//            if($adminVip['vip_level'] > $params['vip_level'] && $adminVip['vip_end_time'] > time()) {
56
+//                return Api::json(config('code.fail'), trans('msg.vip_not_reduce'));
57
+//            }
58
+//        }
59
+        //该企业若存在已生效会员且未到期,则无法购买低版本会员
60
+        $CorpVip = CorpVip::where('app_id', $params['app_id'])->where('corp_id', $userInfo['corp_id'])->first();
61
+        if($CorpVip){
62
+            if($CorpVip['vip_level'] > $params['vip_level'] && $CorpVip['vip_end_time'] > time()) {
63
+                return Api::json(config('code.fail'), trans('msg.vip_not_reduce'));
64
+            }
65
+        }
66
+
67
+        if($params['vip_level'] == 1){
68
+            $order_info = Orders::where('admin_id', $userInfo['id'])
69
+                                ->where('app_id', $params['app_id'])
70
+                                ->where('vip_level', $params['vip_level'])
71
+                                ->where('status', 1)
72
+                                ->first();
73
+            if($order_info){
74
+                return Api::json(config('code.fail'), trans('msg.vip_buy_again'));
75
+            }
76
+            $order['body']      = env('APP_NAME').'体验版('.$params['months'].'个月)';
77
+        } elseif($params['vip_level'] == 10) {
78
+            $order['body']      = env('APP_NAME').'专业版('.$params['months'].'个月)';
79
+        }
80
+
81
+        //获取支付相关参数
82
+        $result = Pay::wechat()->scan($order);
83
+
84
+        //业务结果成功时订单入库
85
+        if($result['result_code'] == 'SUCCESS') {
86
+            //订单入库
87
+            $query = [];
88
+            $query['admin_id']  = $userInfo['id'];
89
+            $query['corp_id']   = $userInfo['corp_id'];
90
+            $query['app_id']    = $params['app_id'];
91
+            $query['vip_level'] = $params['vip_level'];
92
+            $query['months']    = $params['months'];
93
+            $query['money']     = $order['total_fee'];
94
+            $query['order_id']  = $order['out_trade_no'];
95
+            $query['create_time'] = time();
96
+            $query['update_time'] = time();
97
+            $res = Orders::insert($query);
98
+            if (!$res) {
99
+                return Api::json(config('code.fail'), trans('msg.sql_error'));
100
+            }
101
+
102
+            $data['order_id'] = $order['out_trade_no'];
103
+            $data['code_url'] = $result['code_url'];
104
+            return Api::json(config('code.success'), trans('msg.success'), $data);
105
+        } else {
106
+            return Api::json(config('code.service_error'), trans('msg.service_error'));
107
+        }
108
+    }
109
+
110
+    /**
111
+     * 支付通知接口
112
+     * @param Request $request
113
+     * @return mixed
114
+     */
115
+    public function wechatPayNotify(Request $request){
116
+        $pay = Pay::wechat();
117
+
118
+        try{
119
+            $data = $pay->verify(); // 是的,验签就这么简单!
120
+
121
+            Log::debug('Wechat notify', $data->all());
122
+            //订单状态修改
123
+            $order_info = Orders::where('order_id', $data['out_trade_no'])->first();
124
+            if($order_info['status'] == 0){
125
+                self::orderDetail($order_info['order_id']);
126
+            }
127
+        } catch (Exception $e) {
128
+            // $e->getMessage();
129
+        }
130
+
131
+        return $pay->success();         // laravel 框架中请直接 `return $pay->success()`
132
+    }
133
+
134
+    /**
135
+     * 获取订单支付状态
136
+     * @param Request $request
137
+     * @return string
138
+     */
139
+    public function getOrderStatus(Request $request){
140
+        $params = $request->all();
141
+        if(empty($params['order_id'])){
142
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
143
+        }
144
+
145
+        $order_info = Orders::where('order_id', $params['order_id'])->first();
146
+        if($order_info) {
147
+            //若订单状态为0(未支付),则获取微信订单状态
148
+            if($order_info['status'] == 0){
149
+                //查询订单状态  参数对照:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2
150
+                $order_query = Pay::wechat()->find($params['order_id']);
151
+                if($order_query['trade_state'] == 'SUCCESS'){                    //SUCCESS 支付成功
152
+                    self::orderDetail($params['order_id']);
153
+
154
+                    $data['status'] = 1;
155
+                } else {
156
+                    $data['status'] = $order_info['status'];
157
+                }
158
+            } else {
159
+                $data['status'] = $order_info['status'];
160
+            }
161
+            return Api::json(config('code.success'), trans('msg.success'), $data);
162
+        } else {
163
+            return Api::json(config('code.fail'), trans('msg.order_not_exist'));
164
+        }
165
+    }
166
+
167
+    /**
168
+     * 获取历史订单
169
+     * @param Request $request
170
+     * @return string
171
+     */
172
+    public function getHistoryOrders(Request $request){
173
+        $params = $request->all();
174
+
175
+        $userInfo = $request->session()->get('userInfo');
176
+        $userInfo = collect($userInfo)->toArray();
177
+
178
+        $page_size = empty($params['page_size'])?10:$params['page_size'];
179
+
180
+        $res = Orders::where('corp_id', $userInfo['corp_id'])
181
+                    ->where('admin_id', $userInfo['id'])
182
+                    ->where('status', 1)
183
+                    ->paginate($page_size);
184
+        foreach($res as $k=>$v){
185
+            $vipConfig = VipConfig::where('vip_level', $v['vip_level'])->first();
186
+            $res[$k]['vip_name']    = $vipConfig['vip_name'];
187
+            $res[$k]['money']       = $v['money']/100;
188
+            $res[$k]['price']       = $vipConfig['price']/100;
189
+            $res[$k]['cost_price']  = $vipConfig['cost_price']/100;
190
+            $res[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
191
+            $res[$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']);
192
+        }
193
+
194
+        $res = Api::dateFormat($res);
195
+        $data = Api::page($res);
196
+        return Api::json(config('code.success'), trans('msg.success'), $data);
197
+    }
198
+
199
+    /**
200
+     * 获取VIP配置
201
+     * @param Request $request
202
+     * @return string
203
+     */
204
+    public function getVipConfig(Request $request){
205
+        $res = VipConfig::get()->toArray();
206
+        foreach($res as $k=>$v){
207
+            $res[$k]['price'] = $v['price']/100;
208
+            $res[$k]['cost_price'] = $v['cost_price']/100;
209
+        }
210
+        return Api::json(config('code.success'), trans('msg.success'), $res);
211
+    }
212
+
213
+    /**
214
+     * 订单处理
215
+     * @param $order_id
216
+     * @return bool
217
+     */
218
+    public function orderDetail($order_id){
219
+        $order_info = Orders::where('order_id', $order_id)->first();
220
+        //支付成功,修改订单及相关记录状态
221
+        Orders::where('order_id', $order_id)->update(['status'=>1,'update_time'=>time()]);
222
+        $is_admin_vip = AdminVip::where('app_id', $order_info['app_id'])->where('admin_id', $order_info['admin_id'])->first();
223
+        $result = Redis::setnx($order_id, 1);                                                                           //流程控制,确保不会二次修改订单
224
+        if($result) {
225
+            Redis::expire($order_id, 3600);
226
+            if (!$is_admin_vip) {
227
+                //同步订单信息到AdminVip表
228
+                $query = [];
229
+                $query['admin_id'] = $order_info['admin_id'];
230
+                $query['app_id'] = $order_info['app_id'];
231
+                $query['vip_level'] = $order_info['vip_level'];
232
+                $query['vip_start_time'] = $order_info['create_time'];
233
+                $query['vip_end_time'] = $order_info['create_time'] + ($order_info['months'] * 30 * 3600 * 24);
234
+                $query['create_time'] = time();
235
+                $query['update_time'] = time();
236
+                AdminVip::insert($query);
237
+            } else {
238
+                $query = [];
239
+                if ($is_admin_vip['vip_level'] == $order_info['vip_level']) {
240
+                    if ($is_admin_vip['vip_end_time'] > time()) {
241
+                        $query['vip_end_time'] = $is_admin_vip['vip_end_time'] + ($order_info['months'] * 30 * 3600 * 24);
242
+                    } else {
243
+                        $query['vip_end_time'] = time() + ($order_info['months'] * 30 * 3600 * 24);
244
+                    }
245
+                } else {
246
+                    $query['vip_start_time'] = time();
247
+                    $query['vip_end_time'] = time() + ($order_info['months'] * 30 * 3600 * 24);
248
+                }
249
+                $query['vip_level'] = $order_info['vip_level'];
250
+                AdminVip::where('app_id', $order_info['app_id'])->where('admin_id', $order_info['admin_id'])->update($query);
251
+            }
252
+            //更新活动表中该管理员创建的活动的vip_level
253
+            if (!$is_admin_vip || $is_admin_vip['vip_level'] < $order_info['vip_level']) {
254
+                Activitys::where('corp_id', $order_info['corp_id'])->where('creator', $order_info['admin_id'])->where('app_id', $order_info['app_id'])->update(['vip_level' => $order_info['vip_level']]);
255
+            }
256
+
257
+            //发送邮件通知
258
+            $corp_info = Corps::where('corp_id', $order_info['corp_id'])->first();
259
+            $admin_info = Admin::where('id', $order_info['admin_id'])->first();
260
+            $vip_config_info = VipConfig::where('vip_level', $order_info['vip_level'])->first();
261
+            $content="购买公司:".$corp_info['corp_name']."\n"
262
+                .'购买用户:'.$admin_info['name']."\n"
263
+                .'会员等级:'.$vip_config_info['vip_name']."\n"
264
+                .'购买期限:'.$order_info['months']."个月\n"
265
+                .'付款金额:'.($order_info['money']/100)."元\n"
266
+                .'订 单 号:'.$order_info['order_id']."\n";
267
+            Log::info($content);
268
+            Mail::raw("$content",function ($message){
269
+                $mail_receive = collect(config('mail.mail_receive'))->toArray();
270
+                foreach($mail_receive as $k=>$v){
271
+                    $message->to($k, $v)->subject('会员购买通知');
272
+                }
273
+            });
274
+        }
275
+
276
+        return true;
277
+    }
278
+}
279
+?>

+ 453 - 0
app/Http/Controllers/SuperAdmin/BrainstormingController.php Целия файл

@@ -0,0 +1,453 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * 超级管理员-管理爱答题
5
+ * User: guanxl
6
+ * Date: 2018/7/4
7
+ * Time: 11:45
8
+ */
9
+
10
+namespace App\Http\Controllers\SuperAdmin;
11
+
12
+use App\Http\Controllers\Controller;
13
+use App\Http\Requests;
14
+use App\Models\Admin;
15
+use App\Models\BlockadeAnswer;
16
+use App\Models\Blockades;
17
+use App\Models\Categorys;
18
+use App\Models\Configs;
19
+use App\Models\Departments;
20
+use App\Models\KnowledgeRecords;
21
+use App\Models\Lotterys;
22
+use App\Models\PkAnswer;
23
+use App\Models\PkRooms;
24
+use App\Models\Prizes;
25
+use App\Models\Questions;
26
+use App\Models\Messages;
27
+use Illuminate\Http\Request;
28
+
29
+use App\Common\Api;
30
+use App\Models\Corps;
31
+use App\Models\Users;
32
+use App\Models\Apps;
33
+use App\Models\Activitys;
34
+use App\Services\ActivityService;
35
+use Illuminate\Support\Facades\Redis;
36
+use Illuminate\Support\Facades\Storage;
37
+use DB;
38
+
39
+class BrainstormingController extends Controller
40
+{
41
+    /**
42
+     * 爱答题企业列表
43
+     * @return string
44
+     */
45
+    public function corpList(Request $request){
46
+        $params = $request->all();
47
+
48
+        $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
49
+
50
+        $keyword = $request->get("keyword");
51
+
52
+        if (is_null($keyword)) {
53
+            $corpInfos = Corps::orderBy("corp_id")->paginate($page_size);
54
+        } else {
55
+            $corpInfos = Corps::where("corp_name", "like", "%" . $keyword . "%")
56
+                ->orderBy("corp_id")->paginate($page_size);
57
+        }
58
+
59
+        //数据处理
60
+        foreach($corpInfos as $k=>$corpInfo){
61
+            if($corpInfo['source_type'] == 'agh'){
62
+                $corpInfos[$k]['source_type'] = '爱关怀';
63
+            }
64
+            $corpInfos[$k]['has_wesuit'] = $corpInfo['has_wesuit'] == 0 ? '未开启':'已开启';
65
+
66
+            $corpInfos[$k]['activity_num'] = Activitys::where('corp_id', $corpInfo['corp_id'])->where('status', 1)->where('is_complete_set', 1)->count();
67
+        }
68
+
69
+        $corpInfos->withPath("list?keyword=".$keyword);
70
+
71
+        return view("superadmin.brainstorming.corp_list", ['data'=>$corpInfos]);
72
+    }
73
+
74
+    /**
75
+     * 爱答题活动列表
76
+     * @return string
77
+     */
78
+    public function activityList(Request $request){
79
+        $params = $request->all();
80
+
81
+        $keyword = isset($params['keyword'])?$params['keyword']:'';
82
+        $corp_id = isset($params['corp_id'])?$params['corp_id']:0;
83
+        $page_size = empty($params['page_size']) ? 15 : $params['page_size'];
84
+
85
+        $sql = Activitys::where('status', '1')->where('is_complete_set', '1')->orderByDesc("create_time");
86
+        if(isset($params['corp_id']) && !empty($params['corp_id'])){
87
+            $sql = $sql->where('corp_id', $params['corp_id']);
88
+        }
89
+
90
+        if (isset($params['keyword']) && !empty($params['keyword'])) {
91
+            $sql = $sql->where('title', 'like', "%" . $params['keyword'] . "%");
92
+        }
93
+
94
+        $data = $sql->paginate($page_size);
95
+
96
+        //企业信息
97
+        $corpIds = $data->pluck("corp_id");
98
+        $corpNames = Corps::whereIn("corp_id",$corpIds)->pluck("corp_name","corp_id");
99
+        //时间戳格式化
100
+        foreach ($data as $key => $val) {
101
+            //活动状态
102
+            if ($val['start_time'] > time()) {
103
+                $data[$key]['activity_status_text'] = '未开始';
104
+            } elseif ($val['end_time'] < time()) {
105
+                $data[$key]['activity_status_text'] = '已结束';
106
+            } else {
107
+                if ($val['is_temp_stop'] == 1) {
108
+                    $data[$key]['activity_status_text'] = '已暂停';
109
+                } else {
110
+                    $data[$key]['activity_status_text'] = '进行中';
111
+                }
112
+            }
113
+            $data[$key]['start_time'] = date('Y-m-d H:i', $val['start_time']);
114
+            $data[$key]['end_time'] = date('Y-m-d H:i', $val['end_time']);
115
+            $data[$key]['corp_name'] = $corpNames[$val['corp_id']];
116
+
117
+            //管理路由地址
118
+            $app_info = Apps::where('app_id', $val['app_id'])->first()->toArray();
119
+            $data[$key]['admin_url'] = $app_info['admin_url'];
120
+
121
+            //游戏路由地址
122
+            $data[$key]['game_url'] = env('WEB_URL') . '/' . $app_info['app_code'] . '?activity_id=' . $val['activity_id'];
123
+        }
124
+
125
+        //分页
126
+        $data->withPath("list?keyword=".$keyword.'&corp_id='.$corp_id);
127
+
128
+        return view("superadmin.brainstorming.activity_list", ['data'=>$data]);
129
+    }
130
+
131
+    /**
132
+     * 活动新增
133
+     */
134
+    public function activityAdd(Request $request){
135
+        $params = $request->all();
136
+
137
+        $app_id = 1;
138
+        $keys = array('corp_id');
139
+        foreach ($keys as $key) {
140
+            if (empty($params[$key])) {
141
+                return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
142
+            }
143
+        }
144
+
145
+//        $res = ActivityService::addAct($params['corp_id'], $app_id);
146
+
147
+        return redirect(env('WEB_URL')."/manage/static/index.html#/Configger?app_id=1&corp_id=".$params['corp_id']);
148
+    }
149
+
150
+    /**
151
+     * 爱答题活动回收站
152
+     */
153
+    public function activityRecycle(Request $request){
154
+        $params = $request->all();
155
+
156
+        $keyword = isset($params['keyword'])?$params['keyword']:'';
157
+        $corp_id = isset($params['corp_id'])?$params['corp_id']:0;
158
+        $page_size = empty($params['page_size']) ? 15 : $params['page_size'];
159
+
160
+        $sql = Activitys::where('status', '0')->where('is_complete_set', '1')->orderByDesc("create_time");
161
+        if(isset($params['corp_id']) && !empty($params['corp_id'])){
162
+            $sql = $sql->where('corp_id', $params['corp_id']);
163
+        }
164
+
165
+        if (isset($params['keyword']) && !empty($params['keyword'])) {
166
+            $sql = $sql->where('title', 'like', "%" . $params['keyword'] . "%");
167
+        }
168
+
169
+        $data = $sql->paginate($page_size);
170
+
171
+        //企业信息
172
+        $corpIds = $data->pluck("corp_id");
173
+        $corpNames = Corps::whereIn("corp_id",$corpIds)->pluck("corp_name","corp_id");
174
+
175
+        //时间戳格式化
176
+        foreach ($data as $key => $val) {
177
+            $data[$key]['start_time'] = date('Y-m-d H:i', $val['start_time']);
178
+            $data[$key]['end_time'] = date('Y-m-d H:i', $val['end_time']);
179
+            $data[$key]['corp_name'] = $corpNames[$val['corp_id']];
180
+
181
+            //管理路由地址
182
+            $app_info = Apps::where('app_id', $val['app_id'])->first()->toArray();
183
+            $data[$key]['admin_url'] = $app_info['admin_url'];
184
+
185
+            //游戏路由地址
186
+            $data[$key]['game_url'] = env('WEB_URL') . '/' . $app_info['app_code'] . '?activity_id=' . $val['activity_id'];
187
+        }
188
+
189
+        //分页
190
+        $data->withPath("recycle?keyword=".$keyword.'&corp_id='.$corp_id);
191
+
192
+        return view("superadmin.brainstorming.activity_recycle", ['data'=>$data]);
193
+    }
194
+
195
+    /**
196
+     * 活动二维码弹框页面
197
+     * @param Request $request
198
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
199
+     */
200
+    public function imageUrl(Request $request){
201
+        return view("superadmin.brainstorming.image_url", ['data'=>'']);
202
+    }
203
+
204
+    /**
205
+     * 修改活动收费状态 1 免费限制人数 2 收费不限人数
206
+     * @param Request $request
207
+     * @return array|string
208
+     */
209
+    public function postChangeActivityType(Request $request){
210
+        $params = $request->all();
211
+        if(!isset($params['activity_id']) || empty($params['activity_id'])){
212
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
213
+        }
214
+        $activity_info = Activitys::where('activity_id', $params['activity_id'])->first();
215
+        if(!$activity_info){
216
+            return Api::json(config('code.fail'), trans('msg.activity_not_exist'));
217
+        }
218
+
219
+        $res = Activitys::where('activity_id', $params['activity_id'])->update(['activity_type'=> 2]);
220
+        if($res){
221
+            return Api::json(config('code.success'), trans('msg.success'));
222
+        } else {
223
+            Api::json(config('code.fail'), trans('msg.fail'));
224
+        }
225
+        return $params;
226
+    }
227
+
228
+    /**
229
+     * 超管看板
230
+     * @param Request $request
231
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
232
+     */
233
+    public function board(){
234
+        $data = [];
235
+        $data['user_online_count']      = Redis::get('bs_online');
236
+        $data['activity_active_count']  = Activitys::where('end_time', '>', time())->where('start_time', '<', time())->where('status', 1)->where('is_complete_set', 1)->count();
237
+        $data['activity_active']        = Activitys::where('end_time', '>', time())->where('start_time', '<', time())->where('status', 1)->where('is_complete_set', 1)->orderByDesc('update_time')->get();
238
+        $data['activity_end']           = Activitys::where('end_time', '<', time())->where('status', 1)->where('is_complete_set', 1)->orderByDesc('end_time')->limit(10)->get();
239
+
240
+        foreach($data['activity_active'] as $k=>$v){
241
+            $data['activity_active'][$k]['user_count']  = Users::where('activity_id', $v['activity_id'])->where('status', 1)->count();
242
+            $data['activity_active'][$k]['user_join']   = Users::where('activity_id', $v['activity_id'])->where('status', 1)->where('platform', '!=', NULL)->count();
243
+
244
+            $user_online = Redis::get('bs_online:'.$v['activity_id']);
245
+            $data['activity_active'][$k]['user_online'] = $user_online?$user_online:0;
246
+
247
+            $data['activity_active'][$k]['must_success']        = Users::where('activity_id', $v['activity_id'])->where('status', 1)->where('is_blockade_success', 1)->count();
248
+            $data['activity_active'][$k]['blockade_num']        = Blockades::where('activity_id', $v['activity_id'])->count();
249
+            $data['activity_active'][$k]['pk_num']              = PkRooms::where('activity_id', $v['activity_id'])->count();
250
+            $data['activity_active'][$k]['corp_short_name']     = Corps::where('corp_id', $v['corp_id'])->value('corp_short_name');
251
+        }
252
+
253
+        foreach($data['activity_end'] as $k=>$v){
254
+            $data['activity_end'][$k]['user_count']  = Users::where('activity_id', $v['activity_id'])->where('status', 1)->count();
255
+            $data['activity_end'][$k]['user_join']   = Users::where('activity_id', $v['activity_id'])->where('status', 1)->where('platform', '!=', NULL)->count();
256
+            $data['activity_end'][$k]['must_success']= Users::where('activity_id', $v['activity_id'])->where('status', 1)->where('is_blockade_success', 1)->count();
257
+            $data['activity_end'][$k]['blockade_num']= Blockades::where('activity_id', $v['activity_id'])->count();
258
+            $data['activity_end'][$k]['pk_num']      = PkRooms::where('activity_id', $v['activity_id'])->count();
259
+            $data['activity_end'][$k]['corp_short_name'] = Corps::where('corp_id', $v['corp_id'])->value('corp_short_name');
260
+        }
261
+
262
+        $data['source'] = $_SERVER['HTTP_USER_AGENT'];
263
+
264
+        return view("superadmin.brainstorming.board", ['data'=>$data]);
265
+    }
266
+
267
+    /**
268
+     * 活动复制
269
+     */
270
+    public function activityCopy(Request $request){
271
+        $params = $request->all();
272
+
273
+        $keys = array('activity_id', 'corp_id', 'app_id');
274
+        foreach ($keys as $key) {
275
+            if (empty($params[$key])) {
276
+                return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
277
+            }
278
+        }
279
+
280
+        $res = ActivityService::copyActivity($params);
281
+
282
+        return redirect(env('WEB_URL')."/manage/static/index.html#/Gamemove?activity_id=".$res."&corp_id=".$params['corp_id']."&app_id=".$params['app_id']."&index=2");
283
+    }
284
+
285
+    public function getChangeAdminIndex(Request $request){
286
+        $params = $request->all();
287
+        $activityId     = $params['activity_id'];
288
+        $activityInfo   = ActivityService::getActivityInfo($activityId);
289
+        $corpInfo       = Corps::where('corp_id', $activityInfo['corp_id'])->first();
290
+        $adminInfo      = Admin::where('id', $activityInfo['creator'])->first();
291
+        $data['title']      = $activityInfo['title'];
292
+        $data['corp_name']  = $corpInfo['corp_name'];
293
+        $data['username']   = $adminInfo['username'];
294
+        $data['activity_id'] = $activityId;
295
+        return view("superadmin.brainstorming.admin_change", ['data' => $data]);
296
+    }
297
+
298
+    /**
299
+     * 活动转移
300
+     * @param Request $request
301
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
302
+     */
303
+    public function postChangeAdmin(Request $request){
304
+        $params = $request->all();
305
+
306
+        $activityId = $params['activity_id'];
307
+        $admin_new  = $params['admin_new'];
308
+
309
+        //活动信息
310
+        $activityInfo = ActivityService::getActivityInfo($activityId);
311
+        if(!$activityInfo){
312
+            return Api::json(config('code.fail'), trans('msg.activity_not_exist'));
313
+        }
314
+
315
+        //新管理员信息
316
+        $adminInfo = Admin::where('username', $admin_new)->where('status', 1)->first();
317
+        if(!$adminInfo){
318
+            return Api::json(config('code.fail'), trans('msg.admin_not_exist'));
319
+        }
320
+
321
+        $activity_res   = Activitys::where('activity_id', $activityId)->update(['creator'=>$adminInfo['id'], 'corp_id'=>$adminInfo['corp_id']]);
322
+
323
+        if($activityInfo['corp_id'] != $adminInfo['corp_id']) {
324
+            $config_res     = Configs::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
325
+            $user_res       = Users::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
326
+            $category_res   = Categorys::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
327
+            $question_res   = Questions::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
328
+            $blockades_res  = Blockades::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
329
+            $blockades_answer_res = BlockadeAnswer::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
330
+            $department_res = Departments::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
331
+            $knowledge_res  = KnowledgeRecords::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
332
+            $pk_room_res    = PkRooms::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
333
+            $pk_answer_res  = PkAnswer::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
334
+            $lottery_res    = Lotterys::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
335
+            $prize_res      = Prizes::where('activity_id', $activityId)->update(['corp_id' => $adminInfo['corp_id']]);
336
+
337
+            if($config_res && $user_res && $category_res && $question_res && $blockades_res && $blockades_answer_res && $department_res && $knowledge_res && $pk_room_res && $pk_answer_res && $lottery_res && $prize_res){
338
+                return Api::json(config('code.success'), trans('msg.success'));
339
+            }
340
+        }
341
+
342
+        if($activity_res){
343
+            return Api::json(config('code.success'), trans('msg.success'));
344
+        } else {
345
+            return Api::json(config('code.fail'), trans('msg.sql_error'));
346
+        }
347
+    }
348
+
349
+    /**
350
+     * 公告发布
351
+     * @param Request $request
352
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
353
+     */
354
+    public function notice(Request $request){
355
+        if($request->isMethod('post')){
356
+            if(!empty($_FILES['file']['tmp_name'])) {
357
+                $file 	= $request->file('file');
358
+                $name   = $file->getClientOriginalName();//得到图片名;
359
+                $ext    = $file->getClientOriginalExtension();//得到图片后缀;
360
+
361
+                $fileName = md5(uniqid($name));
362
+                $fileName = $fileName.'.'.$ext;//生成新的的文件名
363
+                Storage::disk('public')->put($fileName,file_get_contents($file->getRealPath()));
364
+
365
+                $data = [
366
+                    'src' => env('WEB_URL').'/manage/uploads/'.$fileName,
367
+                    'title' => '',
368
+                ];
369
+                return response()->json([
370
+                    'code' => 0,
371
+                    'msg' => '',
372
+                    'data' => $data
373
+                ]);
374
+            }
375
+        } else {
376
+            $params = $request->all();
377
+            if(empty($params['message_id'])) {
378
+                if(isset($params['title']) && isset($params['content'])) {
379
+                    //新增公告
380
+                    $query = [];
381
+                    $query['title'] = $params['title'];
382
+                    $query['content'] = $params['content'];
383
+                    $query['create_time'] = time();
384
+
385
+                    Messages::insert($query);
386
+
387
+                    return redirect('/manage/super/brainstorming/notice/list');
388
+                } else {
389
+                    return view("superadmin.brainstorming.notice");
390
+                }
391
+            } else {
392
+               if(isset($params['title']) && isset($params['content'])) {
393
+                   //编辑公告
394
+                   $query = [];
395
+                   $query['title'] = $params['title'];
396
+                   $query['content'] = $params['content'];
397
+
398
+                   Messages::where('ID', $params['message_id'])->update($query);
399
+
400
+                   return redirect('/manage/super/brainstorming/notice/list');
401
+               } else {
402
+                   $data = Messages::where('ID', $params['message_id'])->where('status', 1)->first();
403
+                   return view("superadmin.brainstorming.notice", ['data' => $data]);
404
+               }
405
+            }
406
+        }
407
+    }
408
+
409
+    /**
410
+     * 公告列表
411
+     * @param Request $request
412
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
413
+     */
414
+    public function noticeList(Request $request){
415
+        $params = $request->all();
416
+
417
+        $keyword = isset($params['keyword'])?$params['keyword']:'';
418
+        $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
419
+
420
+        if(empty($keyword)){
421
+            $sql = Messages::where('status', 1);
422
+        } else {
423
+            $sql = Messages::where('status', 1)->where('title', 'like', "%".$keyword."%");
424
+        }
425
+
426
+        $data = $sql->orderByDesc('create_time')->paginate($page_size);
427
+
428
+        //分页
429
+        $data->withPath("list?keyword=".$keyword);
430
+
431
+        return view("superadmin.brainstorming.notice_list", ['data'=>$data]);
432
+    }
433
+
434
+    /**
435
+     * 公告删除
436
+     * @param Request $request
437
+     * @return string
438
+     */
439
+    public function noticeDelete(Request $request){
440
+        $params = $request->all();
441
+
442
+        if(empty($params['message_id'])){
443
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
444
+        }
445
+
446
+        $res = Messages::where('ID', $params['message_id'])->update(['status'=>0]);
447
+        if($res){
448
+            return Api::json(config('code.success'), trans('msg.success'));
449
+        } else {
450
+            return Api::json(config('code.fail'), trans('msg.sql_error'));
451
+        }
452
+    }
453
+}

+ 77 - 0
app/Http/Controllers/SuperAdmin/GamesController.php Целия файл

@@ -0,0 +1,77 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * 超级管理员-管理爱答题
5
+ * User: hanl
6
+ * Date: 2018/9/14
7
+ * Time: 11:45
8
+ */
9
+
10
+namespace App\Http\Controllers\SuperAdmin;
11
+
12
+use Illuminate\Http\Request;
13
+use App\Http\Controllers\Controller;
14
+use Illuminate\Support\Facades\Redis;
15
+use DB;
16
+use Excel;
17
+use App\Common\Api;
18
+
19
+class GamesController extends Controller
20
+{
21
+    //中秋寄相思活动列表
22
+    public function autumnList(Request $request){
23
+        $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
24
+
25
+        $keyword = $request->get("keyword");
26
+
27
+        if (is_null($keyword)) {
28
+            $data = DB::table('topic_e16_zq_corps')->orderBy("corp_id")->paginate($page_size);
29
+        } else {
30
+            $data = DB::table('topic_e16_zq_corps')->where("corp_name", "like", "%" . $keyword . "%")->orderBy("corp_id")->paginate($page_size);
31
+        }
32
+
33
+        $data->withPath("list?keyword=".$keyword);
34
+        return view("superadmin.games.autumn.list", ['data'=>$data]);
35
+    }
36
+
37
+    public function autumnUserUpload(Request $request){
38
+        $params = $request->all();
39
+        $corp_id = $params['corp_id'];
40
+
41
+        if($request->isMethod('post')){
42
+            $filePath = $_FILES['file']['tmp_name'];
43
+            Excel::load($filePath, function ($reader) {
44
+                $reader = $reader->getSheet(0);
45
+                $res = $reader->toArray();
46
+                if($res[0][0] != '姓名' || $res[0][1] != '电话号码'){
47
+                    print_r(Api::json(config('code.fail'), '文件错误'));
48
+                    exit;
49
+                }
50
+                unset($res[0]);
51
+
52
+                $res = json_encode($res);
53
+                Redis::set('autumn_user_load', $res);
54
+            });
55
+
56
+            $data = Redis::get('autumn_user_load');
57
+            $userData = json_decode($data, true);
58
+
59
+            foreach($userData as $k=>$v){
60
+                $userQuery = [];
61
+                $userQuery['corp_id']   = $corp_id;
62
+                $userQuery['realname']  = $v[0];
63
+                $userQuery['phone']     = $v[1];
64
+                $userQuery['create_time'] = time();
65
+
66
+                $repeat_res = DB::table('topic_e16_zq_user')->where('corp_id', $corp_id)->where('phone', $v[1])->first();
67
+                if($repeat_res){
68
+                    DB::table('topic_e16_zq_user')->where('corp_id', $corp_id)->where('phone', $v[1])->update($userQuery);
69
+                } else {
70
+                    DB::table('topic_e16_zq_user')->insert($userQuery);
71
+                }
72
+            }
73
+
74
+            return Api::json(config('code.success'), trans('msg.success'));
75
+        }
76
+    }
77
+}

+ 208 - 0
app/Http/Controllers/SuperAdmin/LogController.php Целия файл

@@ -0,0 +1,208 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * 超级管理员-管理爱答题
5
+ * User: hanl
6
+ * Date: 2018/9/14
7
+ * Time: 11:45
8
+ */
9
+
10
+namespace App\Http\Controllers\SuperAdmin;
11
+
12
+use App\Models\Admin;
13
+use App\Models\Corps;
14
+use App\Services\LogService;
15
+use Illuminate\Http\Request;
16
+use App\Http\Controllers\Controller;
17
+use DB;
18
+use Excel;
19
+use App\Common\Api;
20
+
21
+class LogController extends Controller
22
+{
23
+
24
+    /**
25
+     * 获取日志统计数据
26
+     * @param Request $request
27
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
28
+     */
29
+    public function event(Request $request)
30
+    {
31
+        //参数处理
32
+        $params = $request->all();
33
+
34
+        $res = LogService::eventCount($params);
35
+
36
+        $keyCorp   = empty($params['keyword_corp']) ?''                 :$params['keyword_corp'];
37
+        $keyAdmin  = empty($params['keyword_admin'])?''                 :$params['keyword_admin'];
38
+        $startTime = empty($params['start_time'])   ?time()-3600*24*7   :strtotime($params['start_time']);
39
+        $endTime   = empty($params['end_time'])     ?time()-3600*24     :strtotime($params['end_time']);
40
+        $type = '';
41
+        if(!empty($keyCorp) || !empty($keyAdmin)){
42
+            $type = 'corp';
43
+        } else {
44
+            $type = 'all';
45
+        }
46
+
47
+        return view("superadmin.log.event", ['data' => $res['data'], 'type'=>$type, 'start_time'=>$startTime, 'end_time'=>$endTime]);
48
+    }
49
+
50
+    /**
51
+     * 访问统计数据下载
52
+     * @param Request $request
53
+     */
54
+    public function logDownload(Request $request){
55
+        $params = $request->all();
56
+
57
+        $res = LogService::eventCount($params);
58
+        $data = $res['data'];
59
+
60
+        if(!empty($params['keyword_corp']) || !empty($params['keyword_admin'])){
61
+            $hands = array('访问人', '事件名称', '访问时间');
62
+            array_unshift($data, $hands);
63
+
64
+            Excel::create('访问详情'.date('YmdHis'), function ($excel) use ($data) {
65
+                $excel->sheet('corp_visit', function ($sheet) use ($data) {
66
+                    $tot = count($data);
67
+                    $sheet->setWidth(array(
68
+                        'A'     =>  15,
69
+                        'B'     =>  15,
70
+                        'C'     =>  25,
71
+                    ))->rows($data)->setFontSize(12);
72
+
73
+                    $sheet->setStyle([
74
+                        'font' => [
75
+                            'size' => 12,
76
+                            'bold' => false,
77
+                        ]
78
+                    ])->cells('A1:C1', function($cells){                                                               //设置单元格格式
79
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
80
+                        $cells->setFontWeight('bold');                                                                  //粗体
81
+                        $cells->setBackground('#92D050');                                                               //底色
82
+                    })->cells('A1:C'.$tot, function($cells){
83
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
84
+                    });
85
+                });
86
+            })->export('xlsx');
87
+        } else {
88
+            $hands = array('企业简称', '爱关怀企业ID', '企业注册时间', '访问次数');
89
+            array_unshift($data, $hands);
90
+
91
+            Excel::create('企业访问详情'.date('YmdHis'), function ($excel) use ($data) {
92
+                $excel->sheet('all_corp_visit', function ($sheet) use ($data) {
93
+                    $tot = count($data);
94
+                    $sheet->setWidth(array(
95
+                        'A'     =>  15,
96
+                        'B'     =>  15,
97
+                        'C'     =>  25,
98
+                        'D'     =>  25,
99
+                    ))->rows($data)->setFontSize(12);
100
+
101
+                    $sheet->setStyle([
102
+                        'font' => [
103
+                            'size' => 12,
104
+                            'bold' => false,
105
+                        ]
106
+                    ])->cells('A1:D1', function($cells){                                                               //设置单元格格式
107
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
108
+                        $cells->setFontWeight('bold');                                                                  //粗体
109
+                        $cells->setBackground('#92D050');                                                               //底色
110
+                    })->cells('A1:D'.$tot, function($cells){
111
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
112
+                    });
113
+                });
114
+            })->export('xlsx');
115
+        }
116
+    }
117
+
118
+    /**
119
+     * 获取订单列表
120
+     * @param Request $request
121
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
122
+     */
123
+    public function order(Request $request){
124
+        $params = $request->all();
125
+
126
+        $params['order_start_time'] = empty($params['order_start_time'])?time()-3600*24*7:strtotime($params['order_start_time']);
127
+        $params['order_end_time']   = empty($params['order_end_time'])  ?time()-3600*24  :strtotime($params['order_end_time']);
128
+        $params['vip_start_time']   = empty($params['vip_start_time'])  ?strtotime('2018-01-01'):strtotime($params['vip_start_time']);
129
+        $params['vip_end_time']     = empty($params['vip_end_time'])    ?time()+3600*24*365*5  :strtotime($params['vip_end_time']);
130
+
131
+        $data = LogService::orderList($params);
132
+
133
+        $res['data'] = $data;
134
+        $res['order_start_time'] = $params['order_start_time'];
135
+        $res['order_end_time']   = $params['order_end_time'];
136
+        $res['vip_start_time']   = $params['vip_start_time'];
137
+        $res['vip_end_time']     = $params['vip_end_time'];
138
+
139
+        return view("superadmin.log.order", ['data' => $res]);
140
+    }
141
+
142
+    /**
143
+     * 订单信息下载
144
+     * @param Request $request
145
+     */
146
+    public function orderDownload(Request $request){
147
+        $params = $request->all();
148
+
149
+        $params['order_start_time'] = empty($params['order_start_time'])?time()-3600*24*7:strtotime($params['order_start_time']);
150
+        $params['order_end_time']   = empty($params['order_end_time'])  ?time()-3600*24  :strtotime($params['order_end_time']);
151
+        $params['vip_start_time']   = empty($params['vip_start_time'])  ?strtotime('2018-01-01'):strtotime($params['vip_start_time']);
152
+        $params['vip_end_time']     = empty($params['vip_end_time'])    ?time()+3600*24*365*5  :strtotime($params['vip_end_time']);
153
+
154
+        $res = LogService::orderList($params);
155
+        $res = collect($res)->toArray();
156
+
157
+        $data = [];
158
+        foreach($res as $k=>$v){
159
+            $data[$k]['corp_name'] = $v['corp_name'];
160
+            $data[$k]['admin_name'] = $v['admin_name'];
161
+            switch ($v['vip_level']){
162
+                case 1:
163
+                    $data[$k]['vip_name'] = '体验版';
164
+                    break;
165
+                case 10:
166
+                    $data[$k]['vip_name'] = '专业版';
167
+                break;
168
+                case 100:
169
+                    $data[$k]['vip_name'] = '企业版';
170
+                    break;
171
+            }
172
+            $data[$k]['months'] = $v['months'].'个月';
173
+            $data[$k]['prices'] = ($v['money']/100).'元';
174
+            $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
175
+            $data[$k]['vip_end_time'] = date('Y-m-d H:i:s', $v['create_time']+3600*24*30*$v['months']);
176
+        }
177
+
178
+        $hands = ['公司名称', '管理员名称','会员版本', '购买期限', '支付金额', '下单时间', '订单到期时间'];
179
+        array_unshift($data, $hands);
180
+
181
+        Excel::create('企业订单'.date('YmdHis'), function ($excel) use ($data) {
182
+            $excel->sheet('all_corp_visit', function ($sheet) use ($data) {
183
+                $tot = count($data);
184
+                $sheet->setWidth(array(
185
+                    'A'     =>  25,
186
+                    'B'     =>  25,
187
+                    'C'     =>  25,
188
+                    'D'     =>  25,
189
+                    'E'     =>  25,
190
+                    'F'     =>  25,
191
+                ))->rows($data)->setFontSize(12);
192
+
193
+                $sheet->setStyle([
194
+                    'font' => [
195
+                        'size' => 12,
196
+                        'bold' => false,
197
+                    ]
198
+                ])->cells('A1:F1', function($cells){                                                               //设置单元格格式
199
+                    $cells->setAlignment('center');                                                                 //文本对齐方式
200
+                    $cells->setFontWeight('bold');                                                                  //粗体
201
+                    $cells->setBackground('#92D050');                                                               //底色
202
+                })->cells('A1:F'.$tot, function($cells){
203
+                    $cells->setAlignment('center');                                                                 //文本对齐方式
204
+                });
205
+            });
206
+        })->export('xlsx');
207
+    }
208
+}

+ 183 - 0
app/Http/Controllers/SuperAdminController.php Целия файл

@@ -0,0 +1,183 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/7/3
6
+ * Time: 17:39
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Http\Controllers\Controller;
12
+use App\Models\CorpVip;
13
+use App\Models\VipConfig;
14
+use Illuminate\Http\Request;
15
+
16
+use App\Common\Api;
17
+use App\Models\Corps;
18
+use App\Models\Activitys;
19
+use App\Models\Admin;
20
+
21
+class SuperAdminController extends Controller
22
+{
23
+    public function index(){
24
+        return view("superadmin.index");
25
+    }
26
+
27
+    public function home(){
28
+        return redirect("/manage/super/brainstorming/board");
29
+    }
30
+
31
+    /**
32
+     * 企业管理
33
+     * @param Request $request
34
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
35
+     */
36
+    public function corp(Request $request){
37
+        $params = $request->all();
38
+
39
+        $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
40
+
41
+        $keyword = $request->get("keyword");
42
+
43
+        if (is_null($keyword)) {
44
+            $corpInfos = Corps::orderBy("corp_id")->paginate($page_size);
45
+        } else {
46
+            $corpInfos = Corps::where("corp_name", "like", "%" . $keyword . "%")
47
+                ->orderBy("corp_id")->paginate($page_size);
48
+        }
49
+
50
+        //数据处理
51
+        foreach($corpInfos as $k=>$corpInfo){
52
+            if($corpInfo['source_type'] == 'agh'){
53
+                $corpInfos[$k]['source_type'] = '爱关怀';
54
+            }
55
+            $corpInfos[$k]['has_wesuit'] = $corpInfo['has_wesuit'] == 0 ? '未开启':'已开启';
56
+
57
+            $corpInfos[$k]['activity_num'] = Activitys::where('corp_id', $corpInfo['corp_id'])->where('status', 1)->where('is_complete_set', 1)->count();
58
+        }
59
+
60
+        $corpInfos->withPath("corp?keyword=".$keyword);
61
+
62
+        return view("superadmin.corp_manage", ['data'=>$corpInfos]);
63
+    }
64
+
65
+    /**
66
+     * 新增企业
67
+     * @param Request $request
68
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
69
+     */
70
+    public function corpAdd(Request $request){
71
+        if($request->isMethod('post')){
72
+            $params = $request->all();
73
+
74
+            $query = [];
75
+            $query['corp_name']         = $params['corp_name'];
76
+            $query['corp_short_name']   = $params['corp_short_name'];
77
+            $query['contact_name']      = $params['contact_name'];
78
+            $query['contact_phone']     = $params['contact_phone'];
79
+            $query['contact_email']     = $params['contact_email'];
80
+            $query['contact_address']   = $params['contact_address'];
81
+            $query['update_time']       = time();
82
+            $query['create_time']       = time();
83
+            $res = Corps::insert($query);
84
+            if($res){
85
+                return Api::json(config('code.success'), trans('msg.success'));
86
+            } else {
87
+                return Api::json(config('code.fail'), trans('msg.fail'));
88
+            }
89
+
90
+        } else {
91
+            return view("superadmin.corp_add");
92
+        }
93
+    }
94
+
95
+    /**
96
+     * 管理员管理
97
+     * @param Request $request
98
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
99
+     */
100
+    public function adminAdd(Request $request){
101
+        $params = $request->all();
102
+        if($request->isMethod('post')){
103
+            $query = [];
104
+            $query['name']          = $params['name'];
105
+            $query['username']      = $params['username'];
106
+            $query['password']      = md5($params['password']);
107
+            $query['is_admin']      = $params['is_admin'];
108
+            $query['corp_id']       = $params['corp_id'];
109
+            $query['status']        = 1;
110
+            $query['update_time']   = time();
111
+            $query['create_time']   = time();
112
+
113
+            $userNameRepeat = Admin::where('username', $params['username'])->first();
114
+            if($userNameRepeat){
115
+                return Api::json(config('code.fail'), '账号已存在,请重新输入!');
116
+            }
117
+
118
+            $res = Admin::insert($query);
119
+            if($res){
120
+                return Api::json(config('code.success'), trans('msg.success'));
121
+            } else {
122
+                return Api::json(config('code.fail'), trans('msg.fail'));
123
+            }
124
+
125
+        } else {
126
+            $corp_id = $params['corp_id'];
127
+            $admins = Admin::where('corp_id', $corp_id)->get();
128
+            $data['corp_id'] = $corp_id;
129
+            $data['admins'] = $admins;
130
+
131
+            return view("superadmin.admin_add", ['data'=>$data]);
132
+        }
133
+    }
134
+
135
+    /**
136
+     * 会员设置
137
+     * @param Request $request
138
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
139
+     */
140
+    public function vipSet(Request $request){
141
+        $params = $request->all();
142
+        if(isset($params['vip_time_set']) && !empty($params['vip_time_set'])){
143
+            $vipInfo = CorpVip::where('corp_id', $params['corp_id'])->first();
144
+            if($vipInfo){
145
+                CorpVip::where('corp_id', $params['corp_id'])->update(['vip_end_time'=>strtotime($params['vip_time_set']) + 3600*24 -1, 'vip_level'=>$params['vip_level']]);
146
+            } else {
147
+                $query = [];
148
+                $query['corp_id'] = $params['corp_id'];
149
+                $query['app_id'] = 1;
150
+                $query['vip_level'] = $params['vip_level'];
151
+                $query['vip_start_time'] = time();
152
+                $query['vip_end_time'] = strtotime($params['vip_time_set']) + 3600*24 -1;
153
+                $query['update_time'] = $query['create_time'] = time();
154
+                CorpVip::insert($query);
155
+            }
156
+            //修改该企业已有活动的收费状态(体验版升级为其他版本时修改状态)
157
+            $vipInfo = CorpVip::where('corp_id', $params['corp_id'])->first();
158
+            if($vipInfo['vip_level'] != 1){
159
+                Activitys::where('corp_id', $params['corp_id'])->where('activity_type', 1)->update(['activity_type'=>2]);
160
+            }
161
+            return Api::json(config('code.success'), trans('msg.success'));
162
+        } else {
163
+            $corpInfo = Corps::where('corp_id', $params['corp_id'])->first();
164
+            if(!$corpInfo){
165
+                return Api::json(config('code.fail'), '企业不存在');
166
+            }
167
+            $vipInfo = CorpVip::where('corp_id', $params['corp_id'])->first();
168
+            $data = [];
169
+            $data['corp_id'] = $params['corp_id'];
170
+            $data['vipConfigs'] = VipConfig::get();
171
+            if($vipInfo) {
172
+                $data['corp_name'] = $corpInfo['corp_name'];
173
+                $data['vip_end_time'] = $vipInfo['vip_end_time'];
174
+                $data['vip_name'] = VipConfig::where('vip_level', $vipInfo['vip_level'])->value('vip_name');
175
+                $data['online_user_num'] = VipConfig::where('vip_level', $vipInfo['vip_level'])->value('online_user_num');
176
+            } else {
177
+                $data['corp_name'] = $corpInfo['corp_name'];
178
+                $data['vip_name'] = '非会员';
179
+            }
180
+            return view("superadmin.vip_set", ['data'=>$data]);
181
+        }
182
+    }
183
+}

+ 673 - 0
app/Http/Controllers/brainstorming/ActivityController.php Целия файл

@@ -0,0 +1,673 @@
1
+<?php
2
+/**
3
+ * 2018-06-25 韩
4
+ */
5
+
6
+namespace App\Http\Controllers\brainstorming;
7
+
8
+use App\Http\Requests;
9
+use App\Models\Lottery;
10
+use App\Models\LotteryBoxs;
11
+use Illuminate\Http\Request;
12
+use App\Http\Controllers\Controller;
13
+
14
+use DB;
15
+use Excel;
16
+use App\Common\Api;
17
+use App\Models\Users;
18
+use App\Models\Configs;
19
+use App\Models\Lotterys;
20
+use App\Models\Prizes;
21
+use App\Models\Departments;
22
+use App\Models\PkRooms;
23
+use App\Models\KnowledgeRecords;
24
+use App\Models\Blockades;
25
+
26
+use App\Services\ActivityService;
27
+use App\Services\UserService;
28
+use App\Services\QuestionService;
29
+use Illuminate\Support\Facades\Redis;
30
+use Illuminate\Support\Facades\Log;
31
+
32
+class ActivityController extends Controller
33
+{
34
+    public function __construct(){
35
+
36
+    }
37
+
38
+    const QUESTION_UPLOAD_FAIL = 'bsb_question_upload_fail:';
39
+    const USER_UPLOAD_FAIL = 'bsb_user_upload_fail:';
40
+
41
+    /**
42
+     * 新建活动并获取默认配置
43
+     * @param Request $request
44
+     * @return string
45
+     */
46
+    public function postAdd(Request $request){
47
+        try {
48
+            $params = $request->all();
49
+
50
+            $keys = array('corp_id', 'app_id');
51
+            foreach ($keys as $key) {
52
+                if (empty($params[$key])) {
53
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
54
+                }
55
+            }
56
+
57
+            if(!empty($params['activity_id'])){
58
+                $res = ActivityService::getConfigs($params['activity_id'], $params['corp_id']);
59
+            } else {
60
+                $res = ActivityService::addAct($params['corp_id'], $params['app_id']);
61
+            }
62
+
63
+            return Api::json($res['code'], $res['msg'], $res['data']);
64
+        }catch(\Exception $e) {
65
+            return Api::serviceError($e);
66
+        }
67
+    }
68
+
69
+    /**
70
+     * 保存活动
71
+     * 2018-06-20 10:25:00
72
+     * @param Request $request
73
+     * @return string
74
+     */
75
+    public function postSave(Request $request){
76
+        try {
77
+            $params = $request->all();
78
+
79
+            $keys = array('activity_id', 'corp_id', 'app_id', 'title', 'start_time', 'end_time');
80
+            foreach ($keys as $key) {
81
+                if (empty($params[$key])) {
82
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
83
+                }
84
+            }
85
+
86
+            $res = ActivityService::saveActivity($params);
87
+
88
+            return Api::json($res['code'], $res['msg'], $res['data']);
89
+        }catch(\Exception $e) {
90
+            return Api::serviceError($e);
91
+        }
92
+    }
93
+
94
+    /**
95
+     * 暂停活动
96
+     * @param Request $request
97
+     * @return string
98
+     */
99
+    public function postPause(Request $request){
100
+        try {
101
+            $params = $request->all();
102
+
103
+            $keys = array('activity_id', 'corp_id');
104
+            foreach ($keys as $key) {
105
+                if (empty($params[$key])) {
106
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
107
+                }
108
+            }
109
+
110
+            $res = ActivityService::stopActivity($params);
111
+
112
+            return Api::json($res['code'], $res['msg']);
113
+        }catch(\Exception $e) {
114
+            return Api::serviceError($e);
115
+        }
116
+    }
117
+
118
+    /**
119
+     * 活动下架(删除)
120
+     * @param Request $request
121
+     * @return string
122
+     */
123
+    public function postDelete(Request $request){
124
+        try {
125
+            $params = $request->all();
126
+
127
+            $keys = array('activity_id');
128
+            foreach ($keys as $key) {
129
+                if (empty($params[$key])) {
130
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
131
+                }
132
+            }
133
+
134
+            $res = ActivityService::changeActStatus($params);
135
+
136
+            return Api::json($res['code'], $res['msg']);
137
+        }catch(\Exception $e) {
138
+            return Api::serviceError($e);
139
+        }
140
+    }
141
+
142
+    /**
143
+     * 活动复制
144
+     * @param Request $request
145
+     * @return string
146
+     */
147
+    public function postCopy(Request $request){
148
+        try {
149
+            $params = $request->all();
150
+
151
+            $keys = array('activity_id');
152
+            foreach ($keys as $key) {
153
+                if (empty($params[$key])) {
154
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
155
+                }
156
+            }
157
+
158
+            $res = ActivityService::copyActivity($params);
159
+
160
+            if ($res) {
161
+                $data['activity_id'] = $res;
162
+                return Api::json(config('code.success'), trans('msg.success'), $data);
163
+            } else {
164
+                return Api::json(config('code.fail'), trans('msg.fail'));
165
+            }
166
+        }catch(\Exception $e) {
167
+            return Api::serviceError($e);
168
+        }
169
+    }
170
+
171
+    /**
172
+     * 下载上传失败的数据
173
+     * @param Request $request
174
+     * @return string
175
+     */
176
+    public function getErrorUpload(Request $request){
177
+        try {
178
+            $params = $request->all();
179
+            $keys = array('corp_id', 'activity_id', 'type');
180
+            foreach ($keys as $key) {
181
+                if (empty($params[$key])) {
182
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
183
+                }
184
+            }
185
+
186
+            $actInfo = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
187
+            if (!$actInfo) {
188
+                return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
189
+            }
190
+
191
+            $data = [];
192
+            if($params['type'] == 'user'){
193
+                $data = Redis::get(self::USER_UPLOAD_FAIL.$params['activity_id']);
194
+                $data = json_decode($data, true);
195
+                if(empty($data)) return Api::json(config('code.fail'), '无错误上传数据');
196
+
197
+                UserService::downloadUserExcel($data);
198
+            } elseif($params['type'] == 'question') {
199
+                $data = Redis::get(self::QUESTION_UPLOAD_FAIL.$params['activity_id']);
200
+                $data = json_decode($data, true);
201
+                if(empty($data)) return Api::json(config('code.fail'), '无错误上传数据');
202
+
203
+                QuestionService::downloadQuestionExcel($data);
204
+            }
205
+        }catch(\Exception $e) {
206
+            return Api::serviceError($e);
207
+        }
208
+    }
209
+
210
+    /**
211
+     *  活动看板
212
+     */
213
+    public function getBoard(Request $request){
214
+        $params = $request->all();
215
+        $activity_id = $params['activity_id'];
216
+        if(empty($activity_id) || !isset($activity_id)){
217
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
218
+        }
219
+        //概况
220
+        $data = [];
221
+        $data['time'] = date('Y-m-d H:i:s');
222
+        $data['users']['total'] = Users::where('activity_id', $activity_id)->where('status', 1)->count();
223
+        $data['users']['join'] = Users::where('activity_id', $activity_id)->where('status', 1)->where('platform', '!=', NULL)->count();
224
+        $data['users']['is_blockade_success'] = Users::where('activity_id', $activity_id)->where('status', 1)->where('is_blockade_success', 1)->count();
225
+        $userLotterys = Lotterys::where('activity_id', $activity_id)->groupBy('user_id')->get();
226
+        $data['users']['prize'] = count($userLotterys);
227
+        $data['users']['blockades'] = Blockades::where('activity_id', $activity_id)->count();
228
+        $data['users']['user_online']   = intval(Redis::get('bs_online:'.$activity_id));
229
+
230
+        //奖品情况
231
+        $data['prize'] = Prizes::where('activity_id', $activity_id)->get()->toArray();
232
+        $data['prize_counts'] = 0;
233
+        $data['day_counts'] = 0;
234
+        $data['total_counts'] = 0;
235
+        foreach($data['prize'] as $k=>$v){
236
+            $key = 'bs_prize_count:'.$v['prize_id'].':'.date('Ymd');
237
+            if(Redis::exists($key)){
238
+                $data['prize'][$k]['day_count'] = $v['prize_day_rule']- Redis::get($key);
239
+            } else {
240
+                $data['prize'][$k]['day_count'] = 0;
241
+            }
242
+            $data['prize_counts'] += $v['prize_count'];
243
+            $data['day_counts'] += $data['prize'][$k]['day_count'];
244
+            $data['total_counts'] += $v['prize_grant_count'];
245
+
246
+            $data['prize'][$k]['lottery_name'] = LotteryBoxs::where('activity_id', $activity_id)->where('lottery_level', $v['lottery_level'])->value('lottery_name');
247
+        }
248
+
249
+        //知识币情况
250
+        $boxConfigs = LotteryBoxs::where('activity_id', $activity_id)->where('status', 1)->get();
251
+        $data['user_knowledge_success'] = 0;
252
+        $data['prize_count'] = 0;
253
+        $data['money'] = [];
254
+        foreach($boxConfigs as $k=>$v){
255
+            $data['money'][$v['open_rule']]['user_success'] = Users::where('activity_id', $activity_id)->where('status', 1)->where('knowledge_money', '>=', $v['open_rule'])->count();
256
+            $data['money'][$v['open_rule']]['prize'] = Lotterys::where('activity_id', $activity_id)->where('lottery_level', $v['lottery_level'])->count();
257
+            if($data['money'][$v['open_rule']]['user_success'] != 0){
258
+                $data['money'][$v['open_rule']]['proportion'] = sprintf("%.2f", $data['money'][$v['open_rule']]['prize'] / $data['money'][$v['open_rule']]['user_success']);
259
+            } else {
260
+                $data['money'][$v['open_rule']]['proportion'] = 0;
261
+            }
262
+            $data['prize_count'] += $data['money'][$v['open_rule']]['prize'];                       //总抽奖人数
263
+        }
264
+        if(!empty($data['money'])){
265
+            ksort($data['money']);
266
+        }
267
+        $data['user_knowledge_success'] = reset($data['money'])['user_success'];                    //知识币完成人数
268
+
269
+        //个人排行
270
+        $pkData = Redis::zRevrangebyscore('bs_top:users:pk:'.$params['activity_id'],"+inf", "-inf");
271
+        $topUserInfos = Users::where('activity_id', $params['activity_id'])->where('status', 1)->get()->toArray();
272
+        if(!empty($pkData)) {
273
+            $userDatas = [];
274
+            foreach($topUserInfos as $k=>$v){
275
+                $userDatas[$v['user_id']] = $v;
276
+            }
277
+            foreach ($pkData as $k => $v) {
278
+                $pkData[$k] = $userDatas[$v];
279
+            }
280
+            $data['top']['user']['pk'] = json_decode(json_encode($pkData), true);
281
+        } else {
282
+            $data['top']['user']['pk'] = [];
283
+        }
284
+
285
+
286
+        $sql = Users::where('activity_id', $activity_id)->where('status', 1)->orderByDesc('knowledge_money')->limit(100);
287
+        $data['top']['user']['knowledge_money'] = $sql->get();
288
+
289
+        $levelStarConfig = Configs::where('activity_id', $params['activity_id'])->value('level_star_config');
290
+        $levelStarConfig = json_decode($levelStarConfig, true);
291
+        $departmentInfo = Departments::where('activity_id', $params['activity_id'])->pluck('department_name', 'department_id')->toArray();
292
+        if(!empty($data['top']['user']['knowledge_money'])) {
293
+            foreach ($data['top']['user']['knowledge_money'] as $k=>$v) {
294
+                $data['top']['user']['knowledge_money'][$k]['department_name'] = $v['department_id'] == 0 ? '' : $departmentInfo[$v['department_id']];
295
+            }
296
+        }
297
+
298
+        if(!empty($data['top']['user']['pk'])) {
299
+            foreach ($data['top']['user']['pk'] as $k=>$v) {
300
+                $data['top']['user']['pk'][$k]['department_name'] = $v['department_id'] == 0 ? '' : $departmentInfo[$v['department_id']];
301
+                $data['top']['user']['pk'][$k]['level_name'] = $levelStarConfig[$v['user_level']]['name'];
302
+            }
303
+            $data['top']['user']['pk'] = collect($data['top']['user']['pk'])->take(100);
304
+        }
305
+
306
+        //部门排行(参与率)
307
+        $deparments = Departments::where('activity_id', $activity_id)->where('status', 1)->get()->toArray();
308
+        if($deparments) {
309
+            $result = Users::where('activity_id', $params['activity_id'])
310
+                            ->select(DB::raw('count(user_id) as count, department_id, sum(is_blockade_success) as success_num, sum(knowledge_money) as moneys'))
311
+                            ->where('status', 1)
312
+                            ->where('department_id', '!=', 0)
313
+                            ->groupBy('department_id')
314
+                            ->get()->toArray();
315
+            foreach($result as $k=>$v){
316
+                if(isset($departmentInfo[$v['department_id']])) {
317
+                    $result[$k]['department_name'] = $departmentInfo[$v['department_id']];
318
+                } else {
319
+                    $result[$k]['department_name'] = '';
320
+                }
321
+            }
322
+            //参与率、知识币、平均知识币
323
+            $departmentRes = collect($result)->reduce(function($departmentRes, $item){
324
+                if($item['count'] != 0) {
325
+                    $departmentRes['department_join'][$item["department_name"]] = sprintf("%.2f", $item["success_num"] / $item["count"]);
326
+                    $departmentRes['department_knowledge'][$item["department_name"]]['avg']   = round($item['moneys']/$item["count"]);
327
+                } else {
328
+                    $departmentRes['department_join'][$item["department_name"]] = 0;
329
+                    $departmentRes['department_knowledge'][$item["department_name"]]['avg']   = $item['moneys'];
330
+                }
331
+
332
+                $departmentRes['department_knowledge'][$item["department_name"]]['count'] = $item['moneys'];
333
+
334
+                return $departmentRes;
335
+            });
336
+
337
+            $data['top']['department_knowledge']    = $departmentRes['department_knowledge'];
338
+            $data['top']['department_join']         = $departmentRes['department_join'];
339
+
340
+            arsort($data['top']['department_knowledge']);
341
+            arsort($data['top']['department_join']);
342
+        }
343
+
344
+        //游戏数据
345
+        $data['must']['total'] = Blockades::where('activity_id', $activity_id)->where('is_first', 1)->count();
346
+        $data['must']['question_count'] = Blockades::where('activity_id', $activity_id)->where('is_first', 1)->sum('question_count');
347
+        $must_success = Blockades::where('activity_id', $activity_id)->where('is_first', 1)->where('is_success', 1)->count();
348
+        if($data['must']['total'] != 0) {
349
+            $data['must']['success'] = sprintf("%.2f", $must_success / $data['must']['total']);
350
+        } else {
351
+            $data['must']['success'] = 0;
352
+        }
353
+
354
+        $data['blockade']['total'] = Blockades::where('activity_id', $activity_id)->where('is_first', 0)->count();
355
+        $data['blockade']['question_count'] = Blockades::where('activity_id', $activity_id)->where('is_first', 0)->sum('question_count');
356
+        $blockade_success = Blockades::where('activity_id', $activity_id)->where('is_first', 0)->where('is_success', 1)->count();
357
+        if($data['blockade']['total'] != 0) {
358
+            $data['blockade']['success'] = sprintf("%.2f", $blockade_success / $data['blockade']['total']);
359
+        } else {
360
+            $data['blockade']['success'] = 0;
361
+        }
362
+
363
+        $data['pk']['total'] = PkRooms::where('activity_id', $activity_id)->count();
364
+        $pk_question_ids = PkRooms::where('activity_id', $activity_id)->pluck('question_ids');
365
+        $data['pk']['question_count'] = 0;
366
+        foreach($pk_question_ids as $v){
367
+            $ids = explode(',', $v);
368
+            $data['pk']['question_count'] += count($ids);
369
+        }
370
+        $data['pk']['unstart'] = PkRooms::where('activity_id', $activity_id)->whereIn('status', [1,2])->count();
371
+        $data['pk']['records'] = KnowledgeRecords::where('activity_id', $activity_id)->where('get_mode', 'pk')->where('money', '>', 0)->sum('money');
372
+
373
+        $data['configs'] = ActivityService::getActivityConfig($activity_id);
374
+        $data['activity_id'] = $activity_id;
375
+
376
+        return view('board', ['data'=>$data]);
377
+    }
378
+
379
+    /**
380
+     *  看板下载
381
+     */
382
+    public function getBoardDownload(Request $request){
383
+        set_time_limit(0);
384
+        ignore_user_abort(true);
385
+
386
+        $params = $request->all();
387
+
388
+        $keys = array('activity_id');
389
+        foreach($keys as $key){
390
+            if(empty($params[$key])){
391
+                return Api::json(config('code.params_error'), trans('params.'.$key).trans('msg.params_error'));
392
+            }
393
+        }
394
+
395
+        $activity_info = ActivityService::getActivityInfo($params['activity_id']);
396
+        $departmentInfo = Departments::where('activity_id', $params['activity_id'])->pluck('department_name', 'department_id')->toArray();
397
+
398
+        if($params['type'] == 'join') {
399
+            $joins_info = Users::where('activity_id', $params['activity_id'])->where('status', 1)->orderByDesc('knowledge_money')->orderByDesc('blockade_success_time')->get()->toArray();
400
+
401
+            $data = [];
402
+            $res = [];
403
+            $joins_info = json_decode(json_encode($joins_info), true);
404
+
405
+            foreach ($joins_info as $k => $v) {
406
+                $res['name'] = $v['name'];
407
+                if($v['department_id'] != 0) {
408
+                    $res['department_name'] = $departmentInfo[$v['department_id']];
409
+                } else {
410
+                    $res['department_name'] = '';
411
+                }
412
+                if(substr($activity_info['auth_type'],-3) == 'add'){
413
+                    $res['guid'] = $v['open_id'];
414
+                } else {
415
+                    $res['guid'] = $v['guid'];
416
+                }
417
+                $res['knowledge_money'] = $v['knowledge_money'];
418
+                $res['blockade_success_time'] = empty($v['blockade_success_time'])?'未完成':date('Y-m-d H:i:s', $v['blockade_success_time']);
419
+                $data[] = $res;
420
+            }
421
+            $hands = array('姓名', '部门', '唯一标识', '知识币', '必答完成时间');
422
+            array_unshift($data, $hands);
423
+
424
+            Excel::create('参与情况', function ($excel) use ($data) {
425
+                $excel->sheet('join', function ($sheet) use ($data) {
426
+                    $tot = count($data);
427
+                    $sheet->setWidth(array(
428
+                        'A'     =>  15,
429
+                        'B'     =>  15,
430
+                        'C'     =>  25,
431
+                        'D'     =>  15,
432
+                        'E'     =>  25,
433
+                    ))->rows($data)->setFontSize(12);
434
+
435
+                    $sheet->setStyle([
436
+                        'font' => [
437
+                            'size' => 12,
438
+                            'bold' => false,
439
+                        ]
440
+                    ])->cells('A1:E1', function($cells){                                                               //设置单元格格式
441
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
442
+                        $cells->setFontWeight('bold');                                                                  //粗体
443
+                        $cells->setBackground('#92D050');                                                               //底色
444
+                    })->cells('A1:E'.$tot, function($cells){
445
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
446
+                    });
447
+                });
448
+            })->export('xlsx');
449
+        } elseif($params['type'] == 'lottery') {
450
+            DB::enableQueryLog();
451
+            $lotterys = DB::table('bs_user_lotterys')
452
+                            -> leftJoin('bs_prizes','bs_user_lotterys.prize_id','=','bs_prizes.prize_id')
453
+                            -> leftJoin('bs_users','bs_user_lotterys.user_id','=','bs_users.user_id')
454
+                            -> select('bs_users.name','bs_users.department_id','bs_users.guid','bs_user_lotterys.prize_name','bs_user_lotterys.lottery_time','bs_prizes.prize_id')
455
+                            -> where('bs_user_lotterys.activity_id','=',$params['activity_id'])
456
+                            -> orderBy('bs_user_lotterys.lottery_time','desc')
457
+                            -> get()
458
+                            -> toArray();
459
+            Log::info(DB::getQueryLog());
460
+
461
+//            $lotterys = Lotterys::where('activity_id', $params['activity_id']) ->orderBy('lottery_time', 'desc')->get()->toArray();
462
+
463
+            $data = [];
464
+            $res = [];
465
+            $lotterys = json_decode(json_encode($lotterys), true);
466
+            foreach ($lotterys as $k => $v) {
467
+//                $prizeStatus = Prizes::where('prize_id', $v['prize_id'])->value('status');
468
+                if (!$v['prize_id']) {
469
+                    continue;
470
+                }
471
+//                $userInfo = Users::where('user_id', $v['user_id'])->first()->toArray();
472
+                $res['name'] = $v['name'];
473
+                if($v['department_id'] != 0) {
474
+                    $res['department_name'] = $departmentInfo[$v['department_id']];
475
+                } else {
476
+                    $res['department_name'] = '';
477
+                }
478
+                $res['guid'] = $v['guid'];
479
+                $res['prize_name'] = $v['prize_name'];
480
+                $res['lottery_time'] = $v['lottery_time'];
481
+                $data[] = $res;
482
+            }
483
+            $hands = array('姓名', '部门', '手机号码/ID', '获得奖品', '抽奖时间');
484
+            array_unshift($data, $hands);
485
+
486
+            Excel::create('抽奖情况', function ($excel) use ($data) {
487
+                $excel->sheet('lottery', function ($sheet) use ($data) {
488
+                    $tot = count($data);
489
+                    $sheet->setWidth(array(
490
+                        'A' => 15,
491
+                        'B' => 15,
492
+                        'C' => 25,
493
+                        'D' => 15,
494
+                        'E' => 25,
495
+                    ))->rows($data)->setFontSize(12);
496
+
497
+                    $sheet->setStyle([
498
+                        'font' => [
499
+                            'size' => 12,
500
+                            'bold' => false,
501
+                        ]
502
+                    ])->cells('A1:E1', function ($cells) {                                                               //设置单元格格式
503
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
504
+                        $cells->setFontWeight('bold');                                                                  //粗体
505
+                        $cells->setBackground('#92D050');                                                               //底色
506
+                    })->cells('A1:E' . $tot, function ($cells) {
507
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
508
+                    });
509
+                });
510
+            })->export('xlsx');
511
+        } elseif ($params['type'] == 'pk'){
512
+//            $result = DB::select("select department_id,guid,`name`,user_level,user_star,pk_lost_count,pk_win_count,pk_draw_count from bs_users as b where status=1 and activity_id=".$params['activity_id']." ORDER BY b.user_level desc,b.user_star desc");
513
+//            $res = json_decode(json_encode($result), true);
514
+            ini_set('memory_limit', '256M');
515
+            set_time_limit(0);
516
+
517
+            //获取配置信息
518
+            $levelStarConfig = Configs::where('activity_id', $params['activity_id'])->value('level_star_config');
519
+            $levelStarConfig = json_decode($levelStarConfig, true);
520
+
521
+            $pkData = Redis::zRevrangebyscore('bs_top:users:pk:'.$params['activity_id'],"+inf", "-inf");
522
+            $topUserInfos = Users::where('activity_id', $params['activity_id'])->get();
523
+            if(!empty($pkData)) {
524
+                $userDatas = [];
525
+                foreach($topUserInfos as $k=>$v){
526
+                    $userDatas[$v['user_id']] = $v;
527
+                }
528
+                foreach ($pkData as $k => $v) {
529
+                    $pkData[$k] = $userDatas[$v];
530
+                }
531
+                unset($userDatas);
532
+                unset($topUserInfos);
533
+                $pkData = collect($pkData)->toArray();
534
+
535
+                $data = [];
536
+                foreach($pkData as $k=>$v){
537
+                    $data[$k]['name'] = $v['name'];
538
+                    if($v['department_id'] != 0) {
539
+                        $departmentName = $departmentInfo[$v['department_id']];
540
+                    } else {
541
+                        $departmentName = '';
542
+                    }
543
+                    $data[$k]['department_name'] = !$departmentName ? '': $departmentName;
544
+                    $data[$k]['guid']       = $v['guid'];
545
+                    $data[$k]['top']        = $k+1;
546
+                    $data[$k]['level_name'] = $levelStarConfig[$v['user_level']]['name'];
547
+                    $data[$k]['star_num']   = $v['user_star'];
548
+                    $data[$k]['pk_total']   = $v['pk_lost_count'] + $v['pk_win_count'] + $v['pk_draw_count'];
549
+                    $data[$k]['pk_win']     = $v['pk_win_count'];
550
+                    $data[$k]['pk_lost']    = $v['pk_lost_count'];
551
+                    $data[$k]['pk_draw']    = $v['pk_draw_count'];
552
+                    $data[$k]['blockade_success'] = empty($v['is_blockade_success_copy'])?'未参与':'参与';
553
+                    $data[$k]['knowledge_money'] = $v['knowledge_money'];
554
+                }
555
+                unset($pkData);
556
+            } else {
557
+                $data = [];
558
+            }
559
+
560
+            $hands = array('姓名', '部门', '手机号码/ID', '排名', '段位', '星数', 'PK场数', '胜场', '负场', '平局','是否参与','知识币');
561
+            array_unshift($data, $hands);
562
+
563
+            Excel::create('PK情况', function ($excel) use ($data) {
564
+                $excel->sheet('lottery', function ($sheet) use ($data) {
565
+                    $tot = count($data);
566
+                    $sheet->setWidth(array(
567
+                        'A' => 15,
568
+                        'B' => 15,
569
+                        'C' => 25,
570
+                        'D' => 25,
571
+                        'E' => 15,
572
+                        'F' => 25,
573
+                        'G' => 25,
574
+                        'H' => 25,
575
+                        'I' => 25,
576
+                        'J' => 25,
577
+                        'K' => 25,
578
+                        'L' => 25,
579
+                    ))->rows($data)->setFontSize(12);
580
+
581
+                    $sheet->setStyle([
582
+                        'font' => [
583
+                            'size' => 12,
584
+                            'bold' => false,
585
+                        ]
586
+                    ])->cells('A1:L1', function ($cells) {                                                             //设置单元格格式
587
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
588
+                        $cells->setFontWeight('bold');                                                                  //粗体
589
+                        $cells->setBackground('#92D050');                                                               //底色
590
+                    })->cells('A1:L' . $tot, function ($cells) {
591
+                        $cells->setAlignment('center');                                                                 //文本对齐方式
592
+                    });
593
+                });
594
+            })->export('xlsx');
595
+        } else {
596
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
597
+        }
598
+
599
+    }
600
+
601
+    /**
602
+     *  下载模板
603
+     */
604
+    public function getDownloadModel(Request $request){
605
+        $params = $request->all();
606
+
607
+        if(empty($params['type'])){
608
+            return Api::json(config('code.params_error'), trans('params.type').trans('msg.params_not_null'));
609
+        } else {
610
+            if($params['type'] == 'user'){
611
+                $url = '/model/人员模板.xlsx';           //人员导入模板
612
+            } else {
613
+                $url = '/model/题库模板.xlsx';           //题库导入模板
614
+            }
615
+            header('location:/manage'.$url);
616
+        }
617
+    }
618
+
619
+    /**
620
+     * 获取获奖情况(发奖使用)
621
+     * @param Request $request
622
+     * @return string
623
+     */
624
+    public function getPrizeUsers(Request $request){
625
+        $params = $request->all();
626
+
627
+        $keys = array('activity_id');
628
+        foreach($keys as $key){
629
+            if(empty($params[$key])){
630
+                return Api::json(config('code.params_error'), trans('params.'.$key).trans('msg.params_error'));
631
+            }
632
+        }
633
+
634
+        $lotterys = Lotterys::where('activity_id', $params['activity_id'])->orderBy('prize_id', 'desc')->get()->toArray();
635
+
636
+        $data = [];
637
+        $res = [];
638
+        $lotterys = json_decode(json_encode($lotterys), true);
639
+        foreach ($lotterys as $k => $v) {
640
+            $userInfo = Users::where('user_id', $v['user_id'])->first()->toArray();
641
+            $res['name']            = $userInfo['name'];
642
+            $res['avatar']          = $userInfo['avatar'];
643
+            $res['department_name'] = Departments::where('department_id', $userInfo['department_id'])->value('department_name');
644
+            $res['prize_name']      = $v['prize_name'];
645
+            $res['prize_image']     = $v['prize_image_url'];
646
+            $res['blockade_success_time'] = $v['lottery_time'];
647
+            $data[] = $res;
648
+        }
649
+
650
+        return view('user_prize', ['data'=>$data]);
651
+    }
652
+
653
+    /**
654
+     * 修改PK段位配置
655
+     * @param Request $request
656
+     * @return string
657
+     */
658
+    public function postModifyLevelConfig(Request $request){
659
+        $params = $request->all();
660
+
661
+        $keys = array('activity_id', 'level_one', 'level_two', 'level_three', 'level_four', 'level_five', 'level_six');
662
+        foreach($keys as $key){
663
+            if(empty($params[$key])){
664
+                return Api::json(config('code.params_error'), $key .trans('msg.params_error'));
665
+            }
666
+        }
667
+
668
+        $res = ActivityService::modifyLevelConfig($params);
669
+
670
+        return Api::json($res['code'], $res['msg'], $res['data']);
671
+    }
672
+}
673
+?>

+ 164 - 0
app/Http/Controllers/brainstorming/PrizeController.php Целия файл

@@ -0,0 +1,164 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\brainstorming;
4
+
5
+use App\Common\Api;
6
+use App\Models\LotteryBoxs;
7
+use App\Services\ActivityService;
8
+use Illuminate\Http\Request;
9
+use App\Http\Controllers\Controller;
10
+
11
+use App\Services\PrizeService;
12
+
13
+class PrizeController extends Controller
14
+{
15
+    public function __construct()
16
+    {
17
+        //加载中间键
18
+//        $this->middleware('CheckLogin');
19
+//        $this->middleware('Logs');
20
+//        $this->middleware('CacheClear');
21
+    }
22
+
23
+    /**
24
+     *  宝箱——添加/修改奖品
25
+     */
26
+    public function postSave(Request $request){
27
+        try {
28
+            $params = $request->all();
29
+
30
+            $keys = array('activity_id', 'corp_id', 'lottery_level', 'prize_name', 'prize_day_rule', 'prize_count', 'prize_weights', 'prize_image_url');
31
+            foreach ($keys as $key) {
32
+                if (empty($params[$key])) {
33
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
34
+                }
35
+            }
36
+
37
+            $res = PrizeService::prizeDetail($params);
38
+
39
+            return Api::json($res['code'], $res['msg'], $res['data']);
40
+        }catch(\Exception $e) {
41
+            return Api::serviceError($e);
42
+        }
43
+    }
44
+
45
+    /**
46
+     * 获取宝箱内的奖品列表
47
+     * @param Request $request
48
+     * @return string
49
+     */
50
+    public function getList(Request $request){
51
+        try {
52
+            $params = $request->all();
53
+
54
+            $keys = array('activity_id', 'lottery_level', 'corp_id');
55
+            foreach ($keys as $key) {
56
+                if (empty($params[$key])) {
57
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
58
+                }
59
+            }
60
+
61
+            $res = PrizeService::getPrizeList($params['corp_id'], $params['activity_id'], $params['lottery_level']);
62
+
63
+            return Api::json($res['code'], $res['msg'], $res['data']);
64
+        }catch(\Exception $e) {
65
+            return Api::serviceError($e);
66
+        }
67
+    }
68
+
69
+    /**
70
+     * 奖品删除或冻结
71
+     * @param Request $request
72
+     * @return string
73
+     */
74
+    public function postSoldOut(Request $request){
75
+        try {
76
+            $params = $request->all();
77
+
78
+            $keys = array('activity_id', 'lottery_level', 'corp_id', 'prize_id', 'status');
79
+            foreach ($keys as $key) {
80
+                if (empty($params[$key]) && $params[$key] != 0) {
81
+                    return Api::json(config('code.params_error'), $key.trans('msg.params_not_null'));
82
+                }
83
+                //status只允许0 删除 2 冻结  其他则视为参数错误
84
+                if($params['status'] && !in_array($params['status'], array(0,2))){
85
+                    return Api::json(config('code.params_error'), trans('msg.params_error'));
86
+                }
87
+            }
88
+
89
+            $res = PrizeService::prizeSoldOut($params);
90
+
91
+            return Api::json($res['code'], $res['msg'], $res['data']);
92
+        }catch(\Exception $e) {
93
+            return Api::serviceError($e);
94
+        }
95
+    }
96
+
97
+    /**
98
+     * 默认宝箱数据生成
99
+     * @param Request $request
100
+     * @return string
101
+     */
102
+    public function postBoxDefault(Request $request){
103
+        $params = $request->all();
104
+        if(empty($params['activity_id']) || empty($params['corp_id'])){
105
+            return Api::json(config('code.params_error'), trans('msg.params_error'));
106
+        }
107
+
108
+        $activityInfo = ActivityService::getActivityInfo($params['activity_id']);
109
+        if(!$activityInfo){
110
+            return Api::json(config('code.fail'), trans('msg.activity_not_exist'));
111
+        }
112
+
113
+        //获取活动宝箱信息
114
+        $res = PrizeService::getLotteryBoxs($params);
115
+        if(empty($res['data'])){
116
+            //插入默认宝箱
117
+            $result = PrizeService::defaultBox($params, true);
118
+            if($result['code'] == 0){
119
+                return Api::json($result['code'], $result['msg'], $result['data']);
120
+            } else {
121
+                return Api::json($result['code'], $result['msg']);
122
+            }
123
+        } else {
124
+            return Api::json(config('code.success'), trans('msg.success'), $res['data']);
125
+        }
126
+    }
127
+
128
+//    /**
129
+//     * 宝箱状态修改
130
+//     * @param Request $request
131
+//     * @return string
132
+//     */
133
+//    public function postBoxStatus(Request $request){
134
+//        $params = $request->all();
135
+//        $keys = array('activity_id', 'lottery_level', 'corp_id', 'status');
136
+//        foreach ($keys as $key) {
137
+//            if (empty($params[$key]) && $params[$key] != 0) {
138
+//                return Api::json(config('code.params_error'), $key.trans('msg.params_not_null'));
139
+//            }
140
+//            //status只允许0 删除 2 冻结  其他则视为参数错误
141
+//            if($params['status'] && !in_array($params['status'], array(0,1))){
142
+//                return Api::json(config('code.params_error'), trans('msg.params_error'));
143
+//            }
144
+//        }
145
+//
146
+//        $box = LotteryBoxs::where('activity_id', $params['activity_id'])
147
+//            ->where('corp_id',$params['corp_id'])
148
+//            ->where('lottery_level', $params['lottery_level'])->first();
149
+//
150
+//        if(!$box){
151
+//            return Api::json(config('code.fail'), '宝箱不存在');
152
+//        }
153
+//        $res = LotteryBoxs::where('activity_id', $params['activity_id'])
154
+//                            ->where('corp_id',$params['corp_id'])
155
+//                            ->where('lottery_level', $params['lottery_level'])
156
+//                            ->update(['status'=>$params['status'], 'update_time'=>time()]);
157
+//        if($res){
158
+//            return Api::json(config('code.success'), trans('msg.success'));
159
+//        } else {
160
+//            Api::json(config('code.sql_error'), trans('msg.sql_error'));
161
+//        }
162
+//    }
163
+}
164
+?>

+ 317 - 0
app/Http/Controllers/brainstorming/QuestionController.php Целия файл

@@ -0,0 +1,317 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\brainstorming;
4
+
5
+use App\Models\Configs;
6
+use Illuminate\Http\Request;
7
+use App\Http\Requests;
8
+use App\Http\Controllers\Controller;
9
+use App\Common\Api;
10
+
11
+use App\Models\Questions;
12
+
13
+use DB;
14
+use Excel;
15
+use Storage;
16
+use Illuminate\Support\Facades\Redis;
17
+use App\Services\ActivityService;
18
+use App\Services\QuestionService;
19
+
20
+class QuestionController extends Controller
21
+{
22
+
23
+    public function __construct(){
24
+        //加载中间键
25
+//        $this->middleware('CheckLogin');
26
+//        $this->middleware('Logs');
27
+//        $this->middleware('CacheClear');
28
+    }
29
+
30
+    const QUESTION_UPLOAD = 1;
31
+    const QUESTION_UPLOAD_KEY = 'bsb_question_upload:';        //题目上传到redis的key
32
+
33
+    /**
34
+     *  活动配置——题库上传(题目)
35
+     */
36
+    public function postUpload(Request $request){
37
+        try {
38
+            $params = $request->all();
39
+
40
+            $keys = array('activity_id', 'corp_id', 'category_name');
41
+            foreach ($keys as $key) {
42
+                if (empty($params[$key])) {
43
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
44
+                }
45
+            }
46
+
47
+            if ($request->isMethod("post")) {
48
+                $activity_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
49
+                if (!$activity_info) {
50
+                    return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
51
+                }
52
+
53
+                if (!empty($_FILES['question'])) {
54
+                    $filePath = $_FILES['question']['tmp_name'];
55
+                    Excel::load($filePath, function ($reader) {
56
+                        $reader = $reader->getSheet(0);
57
+                        $res = $reader->toArray();
58
+
59
+                        //去掉无用表头
60
+                        foreach ($res as $k=>$v) {
61
+                            unset($res[$k]);
62
+                            if(Api::trimAll($v[0]) == '题目标题' && Api::trimAll($v['1']) == 'A选项' && Api::trimAll($v[2]) == 'B选项' && Api::trimAll($v[3]) == 'C选项' && Api::trimAll($v['4']) == 'D选项' && Api::trimAll($v[5]) == '答案'){
63
+                                break;
64
+                            }
65
+                        }
66
+
67
+                        //去掉excel表格的空数据
68
+                        $res = collect($res)->filter(function($value){
69
+                            return !is_null($value[0]) || !is_null($value[1]) || !is_null($value[2]) || !is_null($value[3]) || !is_null($value[4]) || !is_null($value[5]);
70
+                        });
71
+
72
+                        //如果无正确数据。则返回上传文件为空
73
+                        if (empty($res)) {
74
+                            print_r(Api::json(config('code.fail'), trans('msg.question_not_exist')));
75
+                            exit;
76
+                        }
77
+
78
+                        //去除空格和不可见unicode编码
79
+                        $result = [];
80
+                        foreach($res as $key=>$val){
81
+//                            $result[$key][0] = Api::trimAll($val[0]);
82
+//                            $result[$key][1] = Api::trimAll($val[1]);
83
+//                            $result[$key][2] = Api::trimAll($val[2]);
84
+//                            $result[$key][3] = Api::trimAll($val[3]);
85
+//                            $result[$key][4] = Api::trimAll($val[4]);
86
+                            $result[$key][0] = $val[0];
87
+                            $result[$key][1] = $val[1];
88
+                            $result[$key][2] = $val[2];
89
+                            $result[$key][3] = $val[3];
90
+                            $result[$key][4] = $val[4];
91
+                            $result[$key][5] = Api::trimUnicode($val[5]);
92
+                        }
93
+
94
+                        //存入redis
95
+                        Redis::set(self::QUESTION_UPLOAD_KEY.$_REQUEST['activity_id'], json_encode($result), 'EX', 3600);
96
+                    });
97
+
98
+                    //从redis获取数据
99
+                    $data = Redis::get(self::QUESTION_UPLOAD_KEY.$params['activity_id']);
100
+                    $result = QuestionService::questionUpload(json_decode($data, true), $params);
101
+
102
+                    if($result['code'] != 0){
103
+                        return Api::json(config('code.upload_fail'), '上传失败,请检查数据格式是否正确');
104
+                    }
105
+
106
+                    //文件保存
107
+                    $newPath = base_path('storage/uploads/' . date('Ymd'));
108
+                    if (!is_dir($newPath)) {
109
+                        mkdir($newPath);
110
+                    }
111
+                    $file = $request->file('question');
112
+                    $file->move($newPath, date('His') . $_FILES['question']['name']);
113
+
114
+                    //修改人员上传状态
115
+                    $query_config['is_question_upload'] = self::QUESTION_UPLOAD;
116
+                    Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->update($query_config);
117
+
118
+                    return Api::json($result['code'], $result['msg'], $result['data']);
119
+                } else {
120
+                    return Api::json(config('code.params_error'), trans('msg.params_not_null'));
121
+                }
122
+            }
123
+        }catch(\Exception $e) {
124
+            return Api::serviceError($e);
125
+        }
126
+    }
127
+
128
+    /**
129
+     * 获取题库内的题目列表
130
+     * 2018-06-21 10:00:00
131
+     * @param Request $request
132
+     * @return string
133
+     */
134
+    public function getList(Request $request){
135
+        try {
136
+            $params = $request->all();
137
+
138
+            $keys = array('category_id', 'activity_id');
139
+            foreach ($keys as $key) {
140
+                if (empty($params[$key])) {
141
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
142
+                }
143
+            }
144
+
145
+            $category_info = QuestionService::getCategoryInfo($params['activity_id'], $params['category_id']);
146
+
147
+            if (!$category_info) {
148
+                return Api::json(config('code.category_not_exist'), trans('msg.category_not_exist'));
149
+            }
150
+
151
+            $keyword = empty($params['keyword']) ? '' : $params['keyword'];
152
+            $page_size = empty($params['page_size']) ? 10 : $params['page_size'];
153
+
154
+            $sql = Questions::where('activity_id', $params['activity_id'])->where('category_id', $params['category_id'])->where('status', 1);
155
+            if (!empty($params['keyword'])) {
156
+                $sql = $sql->where("question_title", "like", "%" . $keyword . "%");
157
+            }
158
+
159
+            $questions = $sql->orderByDesc('create_time')->paginate($page_size);
160
+
161
+            $data = Api::page($questions);
162
+
163
+            //时间戳转换
164
+            foreach ($data['data'] as $key => $val) {
165
+                $data['data'][$key] = Api::dateFormat($val);
166
+                $data['data'][$key]['question_options'] = unserialize($val['question_options']);
167
+            }
168
+
169
+            return Api::json(config('code.success'), trans('msg.success'), $data);
170
+        }catch(\Exception $e) {
171
+            return Api::serviceError($e);
172
+        }
173
+    }
174
+
175
+    /**
176
+     * 获取题库列表
177
+     * 2018-06-21 10:00:00
178
+     * @param Request $request
179
+     * @return string
180
+     */
181
+    public function getCategoryList(Request $request){
182
+        try {
183
+            $params = $request->all();
184
+
185
+            $keys = array('corp_id', 'activity_id');
186
+            foreach ($keys as $key) {
187
+                if (empty($params[$key])) {
188
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
189
+                }
190
+            }
191
+
192
+            $res = QuestionService::getCategoryList($params);
193
+
194
+            return Api::json($res['code'], $res['msg'], $res['data']);
195
+        }catch(\Exception $e) {
196
+            return Api::serviceError($e);
197
+        }
198
+    }
199
+
200
+    /**
201
+     * 修改单个题目
202
+     * @param Request $request
203
+     * @return string
204
+     */
205
+    public function postModify(Request $request){
206
+        try {
207
+            $params = $request->all();
208
+
209
+            $keys = array('corp_id', 'activity_id', 'category_id');
210
+            foreach ($keys as $key) {
211
+                if (empty($params[$key])) {
212
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
213
+                }
214
+            }
215
+
216
+            $res = QuestionService::questionModify($params);
217
+            return Api::json($res['code'], $res['msg'], $res['data']);
218
+        } catch (\Exception $e) {
219
+            return Api::serviceError($e);
220
+        }
221
+    }
222
+
223
+    /**
224
+     * 修改题库名
225
+     * @param Request $request
226
+     * @return string
227
+     */
228
+    public function postCategoryModify(Request $request){
229
+        try {
230
+            $params = $request->all();
231
+
232
+            $keys = array('corp_id', 'activity_id', 'category_id', 'category_name');
233
+            foreach ($keys as $key) {
234
+                if (empty($params[$key])) {
235
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
236
+                }
237
+            }
238
+
239
+            $res = QuestionService::saveCategory($params);
240
+            return Api::json($res['code'], $res['msg'], $res['data']);
241
+        } catch (\Exception $e) {
242
+            return Api::serviceError($e);
243
+        }
244
+    }
245
+
246
+    /**
247
+     * 删除题目
248
+     * 2018-06-22 10:24:00
249
+     * @param Request $request
250
+     * @return string
251
+     */
252
+    public function postDelete(Request $request){
253
+        try {
254
+            $params = $request->all();
255
+
256
+            $keys = array('corp_id', 'activity_id', 'category_id', 'question_id');
257
+            foreach ($keys as $key) {
258
+                if (empty($params[$key])) {
259
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
260
+                }
261
+            }
262
+
263
+            $res = QuestionService::delQuestion($params);
264
+
265
+            return Api::json($res['code'], $res['msg'], $res['data']);
266
+        } catch (\Exception $e) {
267
+            return Api::serviceError($e);
268
+        }
269
+    }
270
+
271
+    /**
272
+     * 添加默认题库
273
+     * @param Request $request
274
+     * @return string
275
+     */
276
+    public function postDefault(Request $request){
277
+        try {
278
+            $params = $request->all();
279
+
280
+            $keys = array('activity_id');
281
+            foreach ($keys as $key) {
282
+                if (empty($params[$key])) {
283
+                    return Api::json(config('code.params_error'), trans('params.' . $key) . trans('msg.params_not_null'));
284
+                }
285
+            }
286
+            $res = QuestionService::addDefault($params['activity_id']);
287
+
288
+            return Api::json($res['code'], $res['msg'], $res['data']);
289
+        } catch (\Exception $e) {
290
+            return Api::serviceError($e);
291
+        }
292
+    }
293
+
294
+    /**
295
+     * 删除题库(只允许在活动未发布状态下删除)
296
+     * @param Request $request
297
+     * @return string
298
+     */
299
+    public function postDelCategory(Request $request){
300
+        try {
301
+            $params = $request->all();
302
+
303
+            $keys = array('activity_id', 'category_id');
304
+            foreach ($keys as $key) {
305
+                if (empty($params[$key])) {
306
+                    return Api::json(config('code.params_error'), $key . trans('msg.params_not_null'));
307
+                }
308
+            }
309
+            $res = QuestionService::delCategory($params['activity_id'], $params['category_id']);
310
+
311
+            return Api::json($res['code'], $res['msg'], $res['data']);
312
+        } catch (\Exception $e) {
313
+            return Api::serviceError($e);
314
+        }
315
+    }
316
+}
317
+?>

+ 268 - 0
app/Http/Controllers/brainstorming/UserController.php Целия файл

@@ -0,0 +1,268 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\brainstorming;
4
+
5
+use App\Common\Api;
6
+use App\Models\Departments;
7
+use Illuminate\Http\Request;
8
+use App\Http\Controllers\Controller;
9
+use Illuminate\Support\Facades\Log;
10
+
11
+use App\Models\Users;
12
+use App\Models\Configs;
13
+use App\Services\ActivityService;
14
+use App\Services\UserService;
15
+
16
+use Illuminate\Support\Facades\Redis;
17
+use Excel;
18
+
19
+class UserController extends Controller
20
+{
21
+    public function __construct(){
22
+        //加载中间键
23
+//        $this->middleware('CheckLogin');
24
+//        $this->middleware('Logs');
25
+//        $this->middleware('CacheClear');
26
+    }
27
+
28
+    const USER_UPLOAD = 1;
29
+    const USER_UPLOAD_KEY = 'bsb_user_upload:';
30
+
31
+    /**
32
+     * 用户上传接口
33
+     * @param Request $request
34
+     * @return string
35
+     */
36
+    public function postUpload(Request $request){
37
+        try{
38
+            ini_set('memory_limit', '256M');
39
+            set_time_limit(0);
40
+
41
+            $params = $request->all();
42
+            $keys = array('corp_id', 'activity_id');
43
+            foreach($keys as $key){
44
+                if(empty($params[$key])){
45
+                    return Api::json(config('code.params_error'), trans('params.'.$key).trans('msg.params_not_null'));
46
+                }
47
+            }
48
+
49
+            if($request->isMethod('post')){
50
+                //活动存在性判断
51
+                $activity_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
52
+                if(!$activity_info){
53
+                    return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
54
+                }
55
+
56
+                //表单校验
57
+                if(empty($_FILES['user'])){
58
+                    return Api::json(config('code.fail'), trans('msg.excel_not_exist'));
59
+                }
60
+
61
+                //读取excel存入redis
62
+                $filePath = $_FILES['user']['tmp_name'];
63
+
64
+                Excel::load($filePath, function ($reader) {
65
+                    $reader = $reader->getSheet(0);
66
+                    $res = $reader->toArray();
67
+
68
+                    $is_hand = 0;
69
+                    foreach ($res as $k=>$v) {
70
+                        unset($res[$k]);
71
+                        if($v[0] == '姓名' && $v['1'] == '部门' && $v[2] == '手机号码/ID号'){
72
+                            $is_hand = 1;
73
+                            break;
74
+                        }
75
+                    }
76
+
77
+                    //去掉excel表格的空数据
78
+                    $res = collect($res)->filter(function($value){
79
+                        return !is_null($value[0]) || !is_null($value[1]) || !is_null($value[2]);
80
+                    });
81
+                    $res = collect($res)->toArray();
82
+
83
+                    //表单内容校验
84
+                    if(empty($res)){
85
+                        if($is_hand == 1) {
86
+                            print_r(Api::json(config('code.fail'), trans('msg.user_not_exist')));
87
+                            exit;
88
+                        } else {
89
+                            print_r(Api::json(config('code.fail'), trans('msg.fail_type_exist')));
90
+                            exit;
91
+                        }
92
+                    }
93
+
94
+                    //去除空格和不可见unicode编码
95
+                    $result = [];
96
+                    foreach($res as $key=>$val){
97
+//                        $result[$key][0] = Api::trimUnicode($val[0]);
98
+//                        $result[$key][1] = Api::trimUnicode($val[1]);
99
+//                        $result[$key][2] = Api::trimUnicode($val[2]);
100
+
101
+                        $result[$key][0] = $val[0];
102
+                        $result[$key][1] = $val[1];
103
+                        $result[$key][2] = Api::trimUnicode($val[2]);
104
+                    }
105
+
106
+                    $res = json_encode($result);
107
+                    Redis::set(self::USER_UPLOAD_KEY.$_REQUEST['activity_id'], $res, 'EX', 3600);
108
+                });
109
+
110
+                //数据处理入库
111
+                $res = Redis::get(self::USER_UPLOAD_KEY.$params['activity_id']);
112
+                $res = json_decode($res, true);
113
+                $result = UserService::userUpload($res, $params['activity_id'], $params['corp_id']);
114
+
115
+                //入库成功则保存文件
116
+                if($result['code'] == 0){
117
+                    $newPath = base_path('storage/uploads/' . date('Ymd'));
118
+                    if (!is_dir($newPath)) {
119
+                        mkdir($newPath);
120
+                    }
121
+                    $file = $request->file('user');
122
+                    $file->move($newPath, date('His') . $_FILES['user']['name']);
123
+
124
+                    //修改人员上传状态
125
+                    Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->update(['is_user_upload'=>1]);
126
+                }
127
+
128
+                return Api::json($result['code'], $result['msg'], $result['data']);
129
+            } else {
130
+                return Api::json(config('code.fail'), trans('msg.method_no'));
131
+            }
132
+        } catch(\Exception $e) {
133
+            Log::info($e);
134
+            return Api::json(config('code.service_error'), '上传失败,请检测文件格式或文件是否加密!!');
135
+        }
136
+    }
137
+
138
+    /**
139
+     * 获取活动人员列表
140
+     * @param Request $request
141
+     * @return string
142
+     */
143
+    public function getUserList(Request $request){
144
+        try {
145
+            $params = $request->all();
146
+
147
+            $keys = array('activity_id', 'corp_id');
148
+            foreach ($keys as $key) {
149
+                if (empty($params[$key])) {
150
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
151
+                }
152
+            }
153
+
154
+            $pageSize = empty($params['page_size']) ? 10 : $params['page_size'];
155
+
156
+            $keyword = $request->get("keyword");
157
+
158
+            if (is_null($keyword)) {
159
+                $userInfo = Users::where('activity_id', $params['activity_id'])
160
+                                ->where('corp_id', $params['corp_id'])
161
+                                ->where('status', 1)                                    //人员状态  0 无效 1 有效
162
+                                ->orderByDesc("create_time")->paginate($pageSize);
163
+            } else {
164
+                $department_like = Departments::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('status', 1)->where("department_name", "like", "%" . $keyword . "%")->pluck('department_id');
165
+
166
+                $userInfo = Users::where('activity_id', $params['activity_id'])
167
+                                ->where('corp_id', $params['corp_id'])
168
+                                ->where('status', 1)                                    //人员状态  0 无效 1 有效
169
+                                ->where(function ($query) use ($keyword, $department_like){
170
+                                    $query->where("name", "like", "%" . $keyword . "%")->orwhereIn("department_id", $department_like);
171
+                                })
172
+                                ->orderByDesc("create_time")->paginate($pageSize);
173
+            }
174
+
175
+            $data = Api::page($userInfo);
176
+
177
+            //时间戳转换
178
+            foreach ($data['data'] as $key => $val) {
179
+                $data['data'][$key] = Api::dateFormat($val);
180
+                $department_name = Departments::where('department_id', $val['department_id'])->value('department_name');
181
+                $data['data'][$key]['department_name'] = $department_name?$department_name:'无部门';
182
+            }
183
+
184
+            //获取部门人员信息
185
+            $data['department_info'] = ActivityService::getUsersCount($params['corp_id'], $params['activity_id']);
186
+
187
+            return Api::json(config('code.success'), trans('msg.success'), $data);
188
+        }catch(\Exception $e) {
189
+            return Api::serviceError($e);
190
+        }
191
+    }
192
+
193
+    /**
194
+     * 删除人员(软删除)
195
+     * 2018-06-20 18:00:00
196
+     * @param Request $request
197
+     * @return string
198
+     */
199
+    public function postDelete(Request $request){
200
+        try{
201
+            $params = $request->all();
202
+
203
+            $keys = array('activity_id', 'corp_id', 'user_id');
204
+            foreach ($keys as $key) {
205
+                if (empty($params[$key])) {
206
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
207
+                }
208
+            }
209
+
210
+            $res = UserService::delUser($params);
211
+
212
+            return Api::json($res['code'], $res['msg'], $res['data']);
213
+        }catch(\Exception $e) {
214
+            return Api::serviceError($e);
215
+        }
216
+    }
217
+
218
+    /**
219
+     * 新增单个人员
220
+     * 部门字符串匹配
221
+     * @param Request $request
222
+     * @return string
223
+     */
224
+    public function postAdd(Request $request){
225
+        try{
226
+            $params = $request->all();
227
+
228
+            $keys = array('activity_id', 'corp_id', 'phone', 'name');
229
+            foreach ($keys as $key) {
230
+                if (empty($params[$key])) {
231
+                    return Api::json(config('code.params_error'), trans('params.'.$key) . trans('msg.params_not_null'));
232
+                }
233
+            }
234
+
235
+            $res = UserService::addUser($params);
236
+
237
+            return Api::json($res['code'], $res['msg'], $res['data']);
238
+        }catch(\Exception $e) {
239
+            return Api::serviceError($e);
240
+        }
241
+    }
242
+
243
+
244
+    /**
245
+     * 用户信息修改(姓名、部门、电话)
246
+     * @param Request $request
247
+     * @return string
248
+     */
249
+    public function postModify(Request $request){
250
+        try{
251
+            $params = $request->all();
252
+
253
+            $keys = array('activity_id', 'user_id', 'phone', 'name');
254
+            foreach ($keys as $key) {
255
+                if (empty($params[$key])) {
256
+                    return Api::json(config('code.params_error'), trans('msg.params_not_null'));
257
+                }
258
+            }
259
+
260
+            $res = UserService::ModifyUser($params);
261
+
262
+            return Api::json($res['code'], $res['msg'], $res['data']);
263
+        }catch(\Exception $e) {
264
+            return Api::serviceError($e);
265
+        }
266
+    }
267
+}
268
+?>

+ 72 - 0
app/Http/Kernel.php Целия файл

@@ -0,0 +1,72 @@
1
+<?php
2
+
3
+namespace App\Http;
4
+
5
+use Illuminate\Foundation\Http\Kernel as HttpKernel;
6
+
7
+class Kernel extends HttpKernel
8
+{
9
+    /**
10
+     * The application's global HTTP middleware stack.
11
+     *
12
+     * These middleware are run during every request to your application.
13
+     *
14
+     * @var array
15
+     */
16
+    protected $middleware = [
17
+        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
18
+        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
19
+        \App\Http\Middleware\TrimStrings::class,
20
+        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
21
+        \App\Http\Middleware\TrustProxies::class,
22
+    ];
23
+
24
+    /**
25
+     * The application's route middleware groups.
26
+     *
27
+     * @var array
28
+     */
29
+    protected $middlewareGroups = [
30
+        'web' => [
31
+            \App\Http\Middleware\EncryptCookies::class,
32
+            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
33
+            \Illuminate\Session\Middleware\StartSession::class,
34
+            // \Illuminate\Session\Middleware\AuthenticateSession::class,
35
+            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
36
+            \App\Http\Middleware\VerifyCsrfToken::class,
37
+            \Illuminate\Routing\Middleware\SubstituteBindings::class,
38
+        ],
39
+
40
+        'api' => [
41
+            'throttle:60,1',
42
+            'bindings',
43
+        ],
44
+        //活动中间键  检测登陆/日志打印
45
+        'CheckAndLog' => [
46
+            'CheckLogin' => \App\Http\Middleware\CheckLogin::class,
47
+            'ApiLog' => \App\Http\Middleware\Logs::class,
48
+        ],
49
+    ];
50
+
51
+    /**
52
+     * The application's route middleware.
53
+     *
54
+     * These middleware may be assigned to groups or used individually.
55
+     *
56
+     * @var array
57
+     */
58
+    protected $routeMiddleware = [
59
+        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
60
+        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
61
+        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
62
+        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
63
+        'can' => \Illuminate\Auth\Middleware\Authorize::class,
64
+        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
65
+        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
66
+        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
67
+        'CheckLogin' => \App\Http\Middleware\CheckLogin::class,
68
+        'Logs' => \App\Http\Middleware\Logs::class,
69
+        'CacheClear' => \App\Http\Middleware\CacheClear::class,
70
+        'superAuth' => \App\Http\Middleware\SuperAuth::class,
71
+    ];
72
+}

+ 34 - 0
app/Http/Middleware/CacheClear.php Целия файл

@@ -0,0 +1,34 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Closure;
6
+use App\Common\Api;
7
+
8
+class CacheClear
9
+{
10
+    /**
11
+     * Handle an incoming request.
12
+     *
13
+     * @param  \Illuminate\Http\Request  $request
14
+     * @param  \Closure  $next
15
+     * @return mixed
16
+     */
17
+    public function handle($request, Closure $next)
18
+    {
19
+        $response =  $next($request);
20
+
21
+        $params = $request->all();
22
+
23
+        if(isset($params['activity_id'])){
24
+
25
+            $questions_cache = env('WEB_URL').'/brainstorming/console/cache/question?activity_id='.$params['activity_id'];
26
+            $config_cache = env('WEB_URL').'/brainstorming/console/cache/config?activity_id='.$params['activity_id'];
27
+
28
+            Api::curl($config_cache);
29
+            Api::curl($questions_cache);
30
+        }
31
+
32
+        return $response;
33
+    }
34
+}

+ 37 - 0
app/Http/Middleware/CheckLogin.php Целия файл

@@ -0,0 +1,37 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Closure;
6
+use App\Common\Api;
7
+
8
+class CheckLogin
9
+{
10
+    /**
11
+     * Handle an incoming request.
12
+     *
13
+     * @param  \Illuminate\Http\Request  $request
14
+     * @param  \Closure  $next
15
+     * @return mixed
16
+     */
17
+    public function handle($request, Closure $next)
18
+    {
19
+        //登录鉴权  session内用户是否存在,存在则通过,不存在则回调到登录界面
20
+        $userInfo = $request->session()->get('userInfo');
21
+
22
+        if(empty($userInfo)){
23
+            echo Api::json(config('code.login_timeout'), trans('msg.login_timeout'));
24
+            exit;
25
+        }
26
+
27
+        //超管则按照入参传入corp_id,普通管理员则篡改为管理员所属的企业ID
28
+        $params = $request->all();
29
+        if($userInfo['is_admin'] == 1){
30
+            $request->merge(['corp_id'=>$params['corp_id']]);
31
+        } else {
32
+            $request->merge(['corp_id'=>$userInfo['corp_id']]);
33
+        }
34
+
35
+        return $next($request);
36
+    }
37
+}

+ 17 - 0
app/Http/Middleware/EncryptCookies.php Целия файл

@@ -0,0 +1,17 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
6
+
7
+class EncryptCookies extends Middleware
8
+{
9
+    /**
10
+     * The names of the cookies that should not be encrypted.
11
+     *
12
+     * @var array
13
+     */
14
+    protected $except = [
15
+        //
16
+    ];
17
+}

+ 42 - 0
app/Http/Middleware/Logs.php Целия файл

@@ -0,0 +1,42 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Closure;
6
+use App\Models\ApiLogs;
7
+
8
+class Logs
9
+{
10
+    /**
11
+     * Handle an incoming request.
12
+     *
13
+     * @param  \Illuminate\Http\Request  $request
14
+     * @param  \Closure  $next
15
+     * @return mixed
16
+     */
17
+    public function handle($request, Closure $next)
18
+    {
19
+        $response = $next($request);
20
+
21
+        //接口日志记录
22
+        $params = $request->all();
23
+
24
+        $query = [];
25
+        if(!empty($params['activity_id'])){
26
+            $query['activity_id'] = $params['activity_id'];
27
+        }
28
+
29
+        $query['api_name'] = $params['_url'];
30
+        $query['params'] = json_encode($params);
31
+        $userInfo = $request->session()->get('userInfo');
32
+        $query['admin'] = $userInfo['username'];
33
+
34
+        $codes = json_decode($response->getContent(), true);
35
+        $query['code'] = $codes['error'];
36
+        $query['create_time'] = time();
37
+
38
+        ApiLogs::insert($query);
39
+
40
+        return $response;
41
+    }
42
+}

+ 26 - 0
app/Http/Middleware/RedirectIfAuthenticated.php Целия файл

@@ -0,0 +1,26 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Closure;
6
+use Illuminate\Support\Facades\Auth;
7
+
8
+class RedirectIfAuthenticated
9
+{
10
+    /**
11
+     * Handle an incoming request.
12
+     *
13
+     * @param  \Illuminate\Http\Request  $request
14
+     * @param  \Closure  $next
15
+     * @param  string|null  $guard
16
+     * @return mixed
17
+     */
18
+    public function handle($request, Closure $next, $guard = null)
19
+    {
20
+        if (Auth::guard($guard)->check()) {
21
+            return redirect('/home');
22
+        }
23
+
24
+        return $next($request);
25
+    }
26
+}

+ 32 - 0
app/Http/Middleware/SuperAuth.php Целия файл

@@ -0,0 +1,32 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Closure;
6
+use App\Common\Api;
7
+
8
+class SuperAuth
9
+{
10
+    /**
11
+     * Handle an incoming request.
12
+     *
13
+     * @param  \Illuminate\Http\Request  $request
14
+     * @param  \Closure  $next
15
+     * @return mixed
16
+     */
17
+    public function handle($request, Closure $next)
18
+    {
19
+        //登录鉴权  session内用户是否存在,存在则通过,不存在则回调到登录界面
20
+        $userInfo = $request->session()->get('userInfo');
21
+
22
+        if(empty($userInfo)){
23
+            return redirect('manage');
24
+        }
25
+
26
+        if($userInfo['is_admin'] != 1){
27
+            return redirect('https://s1-hn.aghcdn.com/activity/common/page/crowd/errEvir.html?error='.urlencode('无权访问'));
28
+        }
29
+
30
+        return $next($request);
31
+    }
32
+}

+ 18 - 0
app/Http/Middleware/TrimStrings.php Целия файл

@@ -0,0 +1,18 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
6
+
7
+class TrimStrings extends Middleware
8
+{
9
+    /**
10
+     * The names of the attributes that should not be trimmed.
11
+     *
12
+     * @var array
13
+     */
14
+    protected $except = [
15
+        'password',
16
+        'password_confirmation',
17
+    ];
18
+}

+ 23 - 0
app/Http/Middleware/TrustProxies.php Целия файл

@@ -0,0 +1,23 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Illuminate\Http\Request;
6
+use Fideloper\Proxy\TrustProxies as Middleware;
7
+
8
+class TrustProxies extends Middleware
9
+{
10
+    /**
11
+     * The trusted proxies for this application.
12
+     *
13
+     * @var array
14
+     */
15
+    protected $proxies;
16
+
17
+    /**
18
+     * The headers that should be used to detect proxies.
19
+     *
20
+     * @var string
21
+     */
22
+    protected $headers = Request::HEADER_X_FORWARDED_ALL;
23
+}

+ 31 - 0
app/Http/Middleware/VerifyCsrfToken.php Целия файл

@@ -0,0 +1,31 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
6
+
7
+class VerifyCsrfToken extends Middleware
8
+{
9
+    /**
10
+     * The URIs that should be excluded from CSRF verification.
11
+     *
12
+     * @var array
13
+     */
14
+    protected $except = [
15
+        "/login",
16
+        "/loginOut",
17
+        "/checkLogin",
18
+        "/super/*",
19
+        "/app/*",
20
+        "/act/*",
21
+
22
+        //API路由
23
+        "/api/*",
24
+
25
+        //AghApi路由
26
+        "/agh/*",
27
+
28
+        //20180625 接口路由重写
29
+        "/*"
30
+    ];
31
+}

+ 38 - 0
app/Models/Activitys.php Целия файл

@@ -0,0 +1,38 @@
1
+<?php
2
+/**
3
+ *  agh_activitys(活动实例表)数据库连接model
4
+ *  2018-05-08 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Activitys extends Model
13
+{
14
+//    public $timestamps = false;                 //取消框架默认的created_at时间
15
+
16
+    protected $dateFormat = 'U';
17
+    const CREATED_AT="create_time";
18
+    const UPDATED_AT="update_time";
19
+
20
+    protected $table = 'agh_activitys';
21
+
22
+//    public $fillable = [
23
+//        "activity_id",
24
+//        "corp_id",
25
+//        "title",
26
+//        "logo",
27
+//        "key",
28
+//        "regulation",
29
+//        "is_complete_set",
30
+//        "status",
31
+//        "is_jobtime_limit",
32
+//        "jobtimes",
33
+//        "start_time",
34
+//        "end_time",
35
+//        "auth_type",
36
+//        "client_type"
37
+//    ];
38
+}

+ 15 - 0
app/Models/Admin.php Целия файл

@@ -0,0 +1,15 @@
1
+<?php
2
+/**
3
+ *  activity_admin(管理表)数据库连接model
4
+ *  2018-05-08 16:36
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Admin extends Model
13
+{
14
+    protected $table = 'agh_admin';
15
+}

+ 16 - 0
app/Models/AdminVip.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  agh_admin_vip(管理员VIP表)数据库连接model
4
+ *  2018-07-31 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class AdminVip extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'agh_admin_vip';
16
+}

+ 16 - 0
app/Models/ApiLogs.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_api_logs(活动实例表)数据库连接model
4
+ *  2018-05-08 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class ApiLogs extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'agh_api_logs';
16
+}

+ 15 - 0
app/Models/Apps.php Целия файл

@@ -0,0 +1,15 @@
1
+<?php
2
+/**
3
+ *  agh_apps(活动类型表)数据库连接model
4
+ *  2018-05-09 14:20
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Apps extends Model
13
+{
14
+    protected $table = 'agh_apps';
15
+}

+ 16 - 0
app/Models/BlockadeAnswer.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_blockade_user_answers(活动闯关答案)数据库连接model
4
+ *  2018-09-12 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class BlockadeAnswer extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_blockade_user_answers';
16
+}

+ 16 - 0
app/Models/Blockades.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_blockades(闯关记录表)数据库连接model
4
+ *  2018-07-17 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Blockades extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_blockades';
16
+}

+ 16 - 0
app/Models/Categorys.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  agh_activitys(活动实例表)数据库连接model
4
+ *  2018-05-08 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Categorys extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_question_categorys';
16
+}

+ 19 - 0
app/Models/Configs.php Целия файл

@@ -0,0 +1,19 @@
1
+<?php
2
+/**
3
+ *  bs_configs(活动实例表)数据库连接model
4
+ *  2018-05-08 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Configs extends Model
13
+{
14
+    protected $dateFormat = 'U';
15
+    const CREATED_AT="create_time";
16
+    const UPDATED_AT="update_time";
17
+
18
+    protected $table = 'bs_configs';
19
+}

+ 16 - 0
app/Models/CorpVip.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  agh_corp_vip(企业VIP表)数据库连接model
4
+ *  2018-11-13 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class CorpVip extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'agh_corp_vip';
16
+}

+ 21 - 0
app/Models/Corps.php Целия файл

@@ -0,0 +1,21 @@
1
+<?php
2
+/**
3
+ *  agh_corps(企业信息表)数据库连接model
4
+ *  2018-05-08 17:36
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Corps extends Model
13
+{
14
+//    public $timestamps = false;                 //取消框架默认的created_at时间
15
+
16
+    protected $dateFormat = 'U';
17
+    const CREATED_AT="create_time";
18
+    const UPDATED_AT="update_time";
19
+
20
+    protected $table = 'agh_corps';
21
+}

+ 16 - 0
app/Models/Departments.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_users(企业信息表)数据库连接model
4
+ *  2018-05-08 17:36
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Departments extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_departments';
16
+}

+ 16 - 0
app/Models/KnowledgeRecords.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_knowledge_money_records(知识币变动表)数据库连接model
4
+ *  2018-07-19 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class KnowledgeRecords extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_knowledge_money_records';
16
+}

+ 16 - 0
app/Models/LotteryBoxs.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_lottery_boxs(知识币变动表)数据库连接model
4
+ *  2018-11-6 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class LotteryBoxs extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_lottery_boxs';
16
+}

+ 16 - 0
app/Models/Lotterys.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_user_lotterys(活动实例表)数据库连接model
4
+ *  2018-05-22 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Lotterys extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_user_lotterys';
16
+}

+ 16 - 0
app/Models/Messages.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_messages(公告表)数据库连接model
4
+ *  2018-10-15 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Messages extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_messages';
16
+}

+ 16 - 0
app/Models/Orders.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  agh_orders(订单表)数据库连接model
4
+ *  2018-07-31 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Orders extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'agh_orders';
16
+}

+ 16 - 0
app/Models/PkAnswer.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_pk_user_answers(活动PK答案)数据库连接model
4
+ *  2018-09-12 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class PkAnswer extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_pk_user_answers';
16
+}

+ 16 - 0
app/Models/PkRooms.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_pk_rooms(活动PK房间表)数据库连接model
4
+ *  2018-07-17 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class PkRooms extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_pk_rooms';
16
+}

+ 20 - 0
app/Models/Prizes.php Целия файл

@@ -0,0 +1,20 @@
1
+<?php
2
+/**
3
+ *  bs_prizes(活动实例表)数据库连接model
4
+ *  2018-05-21 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Prizes extends Model
13
+{
14
+    const CREATED_AT="create_time";
15
+    const UPDATED_AT="update_time";
16
+
17
+    protected $table = 'bs_prizes';
18
+
19
+//    public $fillable=["corp_id","activity_id","user_id","question_ids","status","is_success"];
20
+}

+ 16 - 0
app/Models/Questions.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_questions(活动实例表)数据库连接model
4
+ *  2018-05-08 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Questions extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_questions';
16
+}

+ 16 - 0
app/Models/Users.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  bs_users(企业信息表)数据库连接model
4
+ *  2018-05-08 17:36
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class Users extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'bs_users';
16
+}

+ 16 - 0
app/Models/VipConfig.php Целия файл

@@ -0,0 +1,16 @@
1
+<?php
2
+/**
3
+ *  agh_vip_config(VIP设置表)数据库连接model
4
+ *  2018-08-02 17:58
5
+ *  韩
6
+ */
7
+
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class VipConfig extends Model
13
+{
14
+    public $timestamps = false;                 //取消框架默认的created_at时间
15
+    protected $table = 'agh_vip_config';
16
+}

+ 10 - 0
app/Models/Wechats.php Целия файл

@@ -0,0 +1,10 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Model;
6
+
7
+class Wechats extends Model
8
+{
9
+    protected $table = 'agh_wechats';
10
+}

+ 29 - 0
app/Providers/AppServiceProvider.php Целия файл

@@ -0,0 +1,29 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use Illuminate\Support\ServiceProvider;
6
+use Illuminate\Support\Facades\URL;
7
+
8
+class AppServiceProvider extends ServiceProvider
9
+{
10
+    /**
11
+     * Bootstrap any application services.
12
+     *
13
+     * @return void
14
+     */
15
+    public function boot()
16
+    {
17
+        URL::forceScheme('https');
18
+    }
19
+
20
+    /**
21
+     * Register any application services.
22
+     *
23
+     * @return void
24
+     */
25
+    public function register()
26
+    {
27
+        //
28
+    }
29
+}

+ 30 - 0
app/Providers/AuthServiceProvider.php Целия файл

@@ -0,0 +1,30 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use Illuminate\Support\Facades\Gate;
6
+use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
7
+
8
+class AuthServiceProvider extends ServiceProvider
9
+{
10
+    /**
11
+     * The policy mappings for the application.
12
+     *
13
+     * @var array
14
+     */
15
+    protected $policies = [
16
+        'App\Model' => 'App\Policies\ModelPolicy',
17
+    ];
18
+
19
+    /**
20
+     * Register any authentication / authorization services.
21
+     *
22
+     * @return void
23
+     */
24
+    public function boot()
25
+    {
26
+        $this->registerPolicies();
27
+
28
+        //
29
+    }
30
+}

+ 21 - 0
app/Providers/BroadcastServiceProvider.php Целия файл

@@ -0,0 +1,21 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use Illuminate\Support\ServiceProvider;
6
+use Illuminate\Support\Facades\Broadcast;
7
+
8
+class BroadcastServiceProvider extends ServiceProvider
9
+{
10
+    /**
11
+     * Bootstrap any application services.
12
+     *
13
+     * @return void
14
+     */
15
+    public function boot()
16
+    {
17
+        Broadcast::routes();
18
+
19
+        require base_path('routes/channels.php');
20
+    }
21
+}

+ 32 - 0
app/Providers/EventServiceProvider.php Целия файл

@@ -0,0 +1,32 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use Illuminate\Support\Facades\Event;
6
+use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
7
+
8
+class EventServiceProvider extends ServiceProvider
9
+{
10
+    /**
11
+     * The event listener mappings for the application.
12
+     *
13
+     * @var array
14
+     */
15
+    protected $listen = [
16
+        'App\Events\Event' => [
17
+            'App\Listeners\EventListener',
18
+        ],
19
+    ];
20
+
21
+    /**
22
+     * Register any events for your application.
23
+     *
24
+     * @return void
25
+     */
26
+    public function boot()
27
+    {
28
+        parent::boot();
29
+
30
+        //
31
+    }
32
+}

+ 73 - 0
app/Providers/RouteServiceProvider.php Целия файл

@@ -0,0 +1,73 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use Illuminate\Support\Facades\Route;
6
+use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
7
+
8
+class RouteServiceProvider extends ServiceProvider
9
+{
10
+    /**
11
+     * This namespace is applied to your controller routes.
12
+     *
13
+     * In addition, it is set as the URL generator's root namespace.
14
+     *
15
+     * @var string
16
+     */
17
+    protected $namespace = 'App\Http\Controllers';
18
+
19
+    /**
20
+     * Define your route model bindings, pattern filters, etc.
21
+     *
22
+     * @return void
23
+     */
24
+    public function boot()
25
+    {
26
+        //
27
+
28
+        parent::boot();
29
+    }
30
+
31
+    /**
32
+     * Define the routes for the application.
33
+     *
34
+     * @return void
35
+     */
36
+    public function map()
37
+    {
38
+        $this->mapApiRoutes();
39
+
40
+        $this->mapWebRoutes();
41
+
42
+        //
43
+    }
44
+
45
+    /**
46
+     * Define the "web" routes for the application.
47
+     *
48
+     * These routes all receive session state, CSRF protection, etc.
49
+     *
50
+     * @return void
51
+     */
52
+    protected function mapWebRoutes()
53
+    {
54
+        Route::middleware('web')
55
+             ->namespace($this->namespace)
56
+             ->group(base_path('routes/web.php'));
57
+    }
58
+
59
+    /**
60
+     * Define the "api" routes for the application.
61
+     *
62
+     * These routes are typically stateless.
63
+     *
64
+     * @return void
65
+     */
66
+    protected function mapApiRoutes()
67
+    {
68
+        Route::prefix('api')
69
+             ->middleware('api')
70
+             ->namespace($this->namespace)
71
+             ->group(base_path('routes/api.php'));
72
+    }
73
+}

+ 704 - 0
app/Services/ActivityService.php Целия файл

@@ -0,0 +1,704 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanl
5
+ * Date: 2018/6/5
6
+ * Time: 17:13
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Common\Api;
12
+
13
+use App\Models\Activitys;
14
+use App\Models\AdminVip;
15
+use App\Models\Apps;
16
+use App\Models\Configs;
17
+use App\Models\Corps;
18
+use App\Models\Prizes;
19
+use App\Models\Departments;
20
+use App\Models\Users;
21
+use App\Models\Questions;
22
+use App\Models\Categorys;
23
+use App\Models\LotteryBoxs;
24
+use App\Models\CorpVip;
25
+
26
+use App\Models\VipConfig;
27
+use DB;
28
+use Excel;
29
+use Illuminate\Support\Facades\Session;
30
+
31
+class ActivityService
32
+{
33
+    public function __construct($configs=[])
34
+    {
35
+
36
+    }
37
+
38
+    const ACT_STATUS_RELEASE = 1;           //活动已发布
39
+    const ACT_STATUS_NOT_RELEASE = 1;       //活动未发布
40
+    const ACT_NOT_COMPLETE = 0;             //活动设置未完成
41
+    const ACT_COMPLETE = 1;                 //活动设置完成
42
+
43
+    //宝箱设置
44
+    const LOTTERY_LEVEL = array(
45
+        'copperPrize'=>1,
46
+        'sliverPrize'=>2,
47
+        'goldPrize'  =>3,
48
+    );
49
+
50
+    /**
51
+     * 活动复制
52
+     * @param $params
53
+     * @return bool
54
+     */
55
+    public static function copyActivity($params){
56
+        //活动实例信息
57
+        $act_info = Activitys::where('activity_id', $params['activity_id'])->first()->toArray();
58
+        if(!$act_info){
59
+            return Api::json(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
60
+        }
61
+
62
+        $corp_id = empty($params['corp_id'])?$act_info['corp_id']:$params['corp_id'];
63
+
64
+        unset($act_info['activity_id']);
65
+        $act_query = $act_info;
66
+        $act_query['corp_id']     = $corp_id;
67
+        //活动参与验证方式可控
68
+        $act_query['auth_type']   = empty($params['auth_type'])?$act_info['auth_type']:$params['auth_type'];
69
+        $act_query['status']      = 1;
70
+        $act_query['is_temp_stop']= 0;                      //活动未暂停
71
+        $act_query['is_complete_set']= 0;
72
+        $act_query['update_time'] = time();
73
+        $act_query['create_time'] = time();
74
+
75
+        //插入实例
76
+        $act_res = Activitys::insertGetId($act_query);
77
+
78
+        //活动配置信息
79
+        $config_info = Configs::where('activity_id', $params['activity_id'])->first()->toArray();
80
+
81
+        $config_query = $config_info;
82
+        $config_query['activity_id'] = $act_res;
83
+        $config_query['corp_id']     = $corp_id;
84
+        $config_query['update_time'] = time();
85
+        $config_query['create_time'] = time();
86
+
87
+        //插入配置
88
+        $config_res = Configs::insert($config_query);
89
+
90
+        if(!$act_res || !$config_res){
91
+            return false;
92
+        }
93
+
94
+        //复制奖品
95
+        if(empty($params['prize'])){
96
+            $prize_res = self::copyPrize($params['activity_id'], $act_res, $corp_id);
97
+            if(!$prize_res){
98
+                return false;
99
+            }
100
+        }
101
+
102
+        //复制题库
103
+        if(empty($params['question'])){
104
+            $question_res = self::copyQuestion($params['activity_id'], $act_res, $corp_id);
105
+            if(!$question_res){
106
+                return false;
107
+            }
108
+        }
109
+
110
+        //复制用户(2018-08-08 修改为默认不复制人员)
111
+//        if(!empty($params['user'])){
112
+//            $user_res = self::copyUser($params['activity_id'], $act_res, $corp_id);
113
+//            if(!$user_res){
114
+//                return false;
115
+//            }
116
+//        }
117
+
118
+        return $act_res;
119
+    }
120
+
121
+    /**
122
+     * 复制奖品信息
123
+     * @param $old_act_id
124
+     * @param $activity_id
125
+     * @param $corp_id
126
+     * @return bool
127
+     */
128
+    public static function copyPrize($old_act_id, $activity_id, $corp_id){
129
+        //奖品信息
130
+        $prize_info = Prizes::where('activity_id', $old_act_id)->get()->toArray();
131
+        foreach ($prize_info as $k => $v) {
132
+            $prize_query = [];
133
+            unset($v['prize_id']);
134
+            $prize_query = $v;
135
+            $prize_query['activity_id'] = $activity_id;
136
+            $prize_query['corp_id'] = $corp_id;
137
+            $prize_query['prize_grant_count'] = 0;
138
+            $prize_query['create_time'] = time();
139
+            $prize_query['update_time'] = time();
140
+
141
+            $prize_res = Prizes::insert($prize_query);
142
+
143
+            if(!$prize_res){
144
+                return false;
145
+            }
146
+        }
147
+        return true;
148
+    }
149
+
150
+    /**
151
+     * 复制活动参与的人员信息和部门信息
152
+     * @param $old_act_id
153
+     * @param $activity_id
154
+     * @param $corp_id
155
+     * @return bool
156
+     */
157
+    public static function copyUser($old_act_id, $activity_id, $corp_id){
158
+        //部门信息
159
+        $department_info = Departments::where('activity_id', $old_act_id)->get()->toArray();
160
+        foreach ($department_info as $k => $v) {
161
+            //该部门的用户信息
162
+            $user_info = Users::where('activity_id', $old_act_id)->where('department_id', $v['department_id'])->get()->toArray();
163
+
164
+            $department_query = [];
165
+            unset($v['department_id']);
166
+            $department_query = $v;
167
+            $department_query['activity_id'] = $activity_id;
168
+            $department_query['corp_id'] = $corp_id;
169
+            $department_query['create_time'] = time();
170
+            $department_query['update_time'] = time();
171
+            $department_res = Departments::insertGetId($department_query);
172
+            if(!$department_res){
173
+                return false;
174
+            }
175
+
176
+            //部门用户复制
177
+            foreach($user_info as $key=>$val){
178
+                $user_query = [];
179
+                unset($val['user_id']);
180
+                $user_query['activity_id']  = $activity_id;
181
+                $user_query['corp_id']      = $corp_id;
182
+                $user_query['guid']         = $val['guid'];
183
+                $user_query['phone']        = $val['phone'];
184
+                $user_query['name']         = $val['name'];
185
+                $user_query['department_id']= $department_res;
186
+                $user_query['create_time'] = time();
187
+                $user_query['update_time'] = time();
188
+                $user_res = Users::insert($user_query);
189
+                if(!$user_res){
190
+                    return false;
191
+                }
192
+            }
193
+        }
194
+
195
+        //无部门的也需要复制
196
+        $user_not_department = Users::where('activity_id', $old_act_id)->where('department_id', 0)->get()->toArray();
197
+        if(count($user_not_department)>0){
198
+            foreach($user_not_department as $key=>$val){
199
+                $user_query = [];
200
+                unset($val['user_id']);
201
+                $user_query['activity_id']  = $activity_id;
202
+                $user_query['corp_id']      = $corp_id;
203
+                $user_query['guid']         = $val['guid'];
204
+                $user_query['phone']        = $val['phone'];
205
+                $user_query['name']         = $val['name'];
206
+                $user_query['department_id']= 0;
207
+                $user_query['create_time']  = time();
208
+                $user_query['update_time']  = time();
209
+                $user_res = Users::insert($user_query);
210
+                if(!$user_res){
211
+                    return false;
212
+                }
213
+            }
214
+        }
215
+
216
+        return true;
217
+    }
218
+
219
+    /**
220
+     * 复制题目和题库
221
+     * @param $old_act_id
222
+     * @param $activity_id
223
+     * @param $corp_id
224
+     * @return bool
225
+     */
226
+    public static function copyQuestion($old_act_id, $activity_id, $corp_id){
227
+        //题库信息
228
+        $category_info = Categorys::where('activity_id', $old_act_id)->get()->toArray();
229
+
230
+        //配置项中的题库信息匹配对应
231
+        $extend_configs = Configs::where('activity_id', $old_act_id)->value('extend_configs');
232
+        $extend_configs = json_decode($extend_configs, true);
233
+        $blockade_category_ids = explode(',', $extend_configs['blockade_category_ids']);
234
+        $must_category_ids = explode(',', $extend_configs['must_category_ids']);
235
+        $pk_category_ids = explode(',', $extend_configs['pk_category_ids']);
236
+
237
+        $must_category_ids_new = [];
238
+        $blockade_category_ids_new = [];
239
+        $pk_category_ids_new = [];
240
+        foreach ($category_info as $k => $v) {
241
+            //该题库的题目信息
242
+            $question_info = Questions::where('activity_id', $old_act_id)->where('category_id', $v['category_id'])->get()->toArray();
243
+
244
+            //题库复制
245
+            $category_query = [];
246
+            $old_category_id = $v['category_id'];
247
+            unset($v['category_id']);
248
+            $category_query = $v;
249
+            $category_query['activity_id'] = $activity_id;
250
+            $category_query['corp_id'] = $corp_id;
251
+
252
+            $category_query['create_time'] = time();
253
+            $category_query['update_time'] = time();
254
+            $category_res = Categorys::insertGetId($category_query);
255
+            if(!$category_res){
256
+                return false;
257
+            }
258
+
259
+            //题目复制
260
+            foreach($question_info as $key=>$val){
261
+                $question_query = [];
262
+                unset($val['question_id']);
263
+                $question_query = $val;
264
+                $question_query['activity_id']  = $activity_id;
265
+                $question_query['corp_id']      = $corp_id;
266
+                $question_query['category_id']  = $category_res;
267
+                $question_query['create_time']  = time();
268
+                $question_query['update_time']  = time();
269
+                $question_res = Questions::insert($question_query);
270
+                if(!$question_res){
271
+                    return false;
272
+                }
273
+            }
274
+
275
+            //对应匹配项入库
276
+            if(in_array($old_category_id, $must_category_ids)) $must_category_ids_new[] = $category_res;
277
+            if(in_array($old_category_id, $blockade_category_ids)) $blockade_category_ids_new[] = $category_res;
278
+            if(in_array($old_category_id, $pk_category_ids)) $pk_category_ids_new[] = $category_res;
279
+        }
280
+
281
+        //更新配置表的题库选择配置
282
+        $config = ActivityService::getActivityConfig($activity_id);
283
+        $extend_configs = json_decode($config['extend_configs'], true);
284
+        $extend_configs['must_category_ids']        = implode(',', $must_category_ids_new);
285
+        $extend_configs['blockade_category_ids']    = implode(',', $blockade_category_ids_new);
286
+
287
+        $extend_configs['pk_category_ids']          = implode(',', $pk_category_ids_new);
288
+        $extend_configs = json_encode($extend_configs);
289
+        $res = Configs::where('activity_id', $activity_id)->where('corp_id', $corp_id)->update(['extend_configs'=>$extend_configs]);
290
+        if(!$res){
291
+            return false;
292
+        }
293
+
294
+        return true;
295
+    }
296
+
297
+    /**
298
+     * 获取活动详情
299
+     * @param $activity_id
300
+     * @return mixed
301
+     */
302
+    public static function getActivityInfo($activity_id, $corp_id=''){
303
+        $res = Activitys::where('activity_id', $activity_id)
304
+//            ->where('corp_id', $corp_id)
305
+            ->where('status', 1)            //活动状态 0 无效 1 有效
306
+            ->first();
307
+
308
+        if($res) {
309
+            //时间格式化
310
+            $res = collect($res)->toArray();
311
+            $res = Api::dateFormat($res);
312
+        }
313
+        return $res;
314
+    }
315
+
316
+    /**
317
+     * 获取活动配置
318
+     * @param $activity_id
319
+     * @return array
320
+     */
321
+    public static function getActivityConfig($activity_id){
322
+        $res = Configs::where('activity_id', $activity_id)->first();
323
+
324
+        if(!empty($res)) {
325
+            $res = collect($res)->toArray();
326
+            $res = Api::dateFormat($res);
327
+        }
328
+        return $res;
329
+    }
330
+
331
+    /**
332
+     * 获取活动参与人员的情况
333
+     * @param $corp_id
334
+     * @param $activity_id
335
+     * @return mixed
336
+     */
337
+    public static function getUsersCount($corp_id, $activity_id){
338
+        $user_count = Users::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('status', 1)->count();
339
+        $data['total'] = $user_count;
340
+
341
+        $departments = Departments::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('status', 1)->get()->toArray();
342
+
343
+        $has_department_num = 0;
344
+        if($departments) {
345
+            foreach ($departments as $department) {
346
+                $data[$department['department_name']] = Users::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('status', 1)->where('department_id', $department['department_id'])->count();
347
+                $has_department_num += $data[$department['department_name']];
348
+            }
349
+        }
350
+
351
+        $data['其他'] = $data['total'] - $has_department_num;
352
+
353
+        return $data;
354
+    }
355
+
356
+    /**
357
+     * 获取应用信息
358
+     * @param string $app_id
359
+     * @return mixed
360
+     */
361
+    public static function getAppInfo($app_id=''){
362
+        if(empty($app_id)){
363
+            $data = Apps::get()->toArray();
364
+        } else {
365
+            $data = Apps::where('app_id', $app_id)->first()->toArray();
366
+        }
367
+
368
+        return $data;
369
+    }
370
+
371
+    /**
372
+     * 删除(下架)活动 或 恢复
373
+     * @param $params
374
+     * @return array
375
+     */
376
+    public static function changeActStatus($params){
377
+
378
+        if(isset($params['status'])){
379
+            $query['status'] = $params['status'];
380
+        } else {
381
+            $query['status'] = self::ACT_STATUS_RELEASE;
382
+        }
383
+
384
+        $res = Activitys::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->update($query);
385
+        if($res){
386
+            return Api::arr(config('code.success'), trans('msg.success'));
387
+        } else {
388
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
389
+        }
390
+    }
391
+
392
+    /**
393
+     * 暂停、开启活动
394
+     * @param $params
395
+     * @return array
396
+     */
397
+    public static function stopActivity($params){
398
+        $act_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
399
+        if(!$act_info){
400
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
401
+        }
402
+
403
+        $is_temp_stop = empty($params['is_temp_stop'])?0:$params['is_temp_stop'];
404
+
405
+        $res = Activitys::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->update(['is_temp_stop'=>$is_temp_stop]);
406
+
407
+        if($res){
408
+            return Api::arr(config('code.success'), trans('msg.success'));
409
+        } else {
410
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
411
+        }
412
+    }
413
+
414
+    /**
415
+     * 新增活动(生成默认活动,返回默认数据)
416
+     * 2018-06-19 17:00:00
417
+     * @param $corp_id
418
+     * @return array
419
+     */
420
+    public static function addAct($corp_id, $app_id){
421
+        //校验VIP权限,不符合权限则不允许创建活动
422
+        $user_info = Session::get('userInfo')->toArray();
423
+        $corpVip = CorpVip::where('corp_id', $user_info['corp_id'])->first();
424
+        if($corpVip){
425
+            if($corpVip['vip_end_time'] > time()){
426
+                $activity_num   = Activitys::where('status', 1)->where('creator', $user_info['id'])->where('end_time', '>', time())->where('is_complete_set', 1)->count();
427
+                $online_act_num = VipConfig::where('vip_level', $corpVip['vip_level'])->value('online_act_num');
428
+                if($activity_num >= $online_act_num){
429
+                    return Api::arr(config('code.fail'), trans('msg.vip_act_full'));
430
+                }
431
+            } else {
432
+                return Api::arr(config('code.fail'), trans('msg.vip_time_out'));
433
+            }
434
+        } else {
435
+            return Api::arr(config('code.fail'), trans('msg.admin_not_vip'));
436
+        }
437
+
438
+        //获取应用默认数据
439
+        $app_info = Apps::where('app_id', $app_id)->value('default_data');
440
+        $default_data = json_decode($app_info, true);
441
+
442
+        //activitys表参数拼接
443
+        $query = [];
444
+        $query['corp_id']       = $corp_id;
445
+        $query['app_id']        = $app_id;
446
+        $query['create_time']   = time();
447
+        $query['update_time']   = time();
448
+        $corpShortName          = Corps::where('corp_id', $corp_id)->value('corp_short_name');
449
+        $query['title']         = $corpShortName.env('APP_NAME');
450
+        $query['logo']          = $default_data['logo'];
451
+        $query['regulation']    = $default_data['regulation'];
452
+        $query['is_jobtime_limit'] = $default_data['is_jobtime_limit'];
453
+        $query['jobtimes']      = $default_data['jobtimes'];
454
+        $query['start_time']    = strtotime(date('Y-m-d'));
455
+        $query['end_time']      = strtotime(date('Y-m-d'))+7*3600*24-1;
456
+        $query['auth_type']     = $default_data['auth_type'];
457
+        $query['client_type']   = $default_data['client_type'];
458
+        $query['activity_type'] = $corpVip['vip_level'] == 1 ? 1 : 2;               //根据企业会员状态赋予活动收费状态
459
+        $query['creator']       = session()->get('userInfo')->id;
460
+
461
+        //管理员VIP信息
462
+//        $vip_level = AdminVip::where('admin_id', session()->get('userInfo')->id)->value('vip_level');
463
+        $query['vip_level']     = $corpVip['vip_level'];                                                                //活动vip等级,用于手机端权限控制
464
+
465
+        $activity_res = Activitys::insertGetId($query);
466
+
467
+        //configs表参数拼接
468
+        $configQuery = [];
469
+        $configQuery['activity_id']         = $activity_res;
470
+        $configQuery['corp_id']             = $corp_id;
471
+        $configQuery['top_banner']          = $default_data['top_banner'];
472
+        $configQuery['home_background']     = $default_data['home_background'];
473
+        $configQuery['mark_background']     = $default_data['mark_background'];
474
+        $configQuery['count_down_background'] = $default_data['count_down_background'];
475
+        $configQuery['sponsor_corp']        = $default_data['sponsor_corp'];
476
+        $configQuery['prize_banner']        = $default_data['prize_banner'];
477
+        $configQuery['copper_box_km']       = $default_data['copper_box_km'];
478
+        $configQuery['silver_box_km']       = $default_data['silver_box_km'];
479
+        $configQuery['gold_box_km']         = $default_data['gold_box_km'];
480
+        $configQuery['is_open_prize']       = $default_data['is_open_prize'];                                           //默认不开启抽奖
481
+        $configQuery['open_department_top'] = $default_data['open_department_top'];                                     //默认不开启单位排行
482
+        $configQuery['extend_configs']      = json_encode($default_data['extend_configs']);
483
+        $configQuery['level_star_config']   = json_encode($default_data['level_star_config']);                          //段位的默认配置
484
+        $configQuery['update_time']         = time();
485
+        $configQuery['create_time']         = time();
486
+
487
+        $config_res = Configs::insert($configQuery);
488
+
489
+        if($activity_res && $config_res){
490
+            $res = ActivityService::getConfigs($activity_res, $corp_id);
491
+            QuestionService::addDefault($activity_res);                                                                 //添加默认题库
492
+
493
+            return Api::arr(config('code.success'), trans('msg.success'), $res['data']);
494
+        } else {
495
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
496
+        }
497
+    }
498
+
499
+    /**
500
+     * 获取活动配置信息
501
+     * 2018-06-19 17:00:00
502
+     * @param $activity_id
503
+     * @param $corp_id
504
+     * @return array
505
+     */
506
+    public static function getConfigs($activity_id, $corp_id){
507
+        $activity_info = self::getActivityInfo($activity_id, $corp_id);
508
+        if (!$activity_info || empty($activity_info)) {
509
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
510
+        }
511
+        $config_info = self::getActivityConfig($activity_id);
512
+        //获取基础配置
513
+        $data['baseInfo'] = array_merge($activity_info, $config_info);
514
+        $data['baseInfo']['extend_configs'] = json_decode($data['baseInfo']['extend_configs'], true);
515
+        $corpInfo = Corps::where('corp_id', $corp_id)->value('has_wesuit');
516
+        $data['baseInfo']['has_wesuit'] = $corpInfo;                                                                    //是否开通了企业微信 0 未开通 1 已开通
517
+
518
+        //返回对应VIP的活动时间配置范围
519
+//        $admin_vip_info = AdminVip::where('admin_id', session()->get('userInfo')->id)->where('app_id', $activity_info['app_id'])->first();
520
+        $admin_vip_info = CorpVip::where('corp_id', $corp_id)->first();
521
+        $data['baseInfo']['time_range']['vip_start_time']   = date('Y-m-d H:i:s', $admin_vip_info['vip_start_time']);
522
+        $data['baseInfo']['time_range']['vip_end_time']     = date('Y-m-d H:i:s', $admin_vip_info['vip_end_time']);
523
+
524
+        //人员信息
525
+//        $data['userInfo'] = self::getUsersCount($corp_id, $activity_id);
526
+
527
+        //题库信息
528
+        $data['questionInfo'] = QuestionService::getCategoryCount($corp_id, $activity_id);
529
+
530
+        //宝箱奖品信息
531
+        $lotteryLevels = LotteryBoxs::where('activity_id', $activity_id)->where('corp_id', $corp_id)->pluck('lottery_level', 'lottery_name');
532
+        foreach($lotteryLevels as $lotteryName=>$lotteryLevel){
533
+            $prize = PrizeService::getPrizeList($corp_id, $activity_id, $lotteryLevel);
534
+            $data['prizeInfo'][$lotteryName] = $prize['data'];
535
+        }
536
+//        foreach (self::LOTTERY_LEVEL as $box_name => $lottery_level) {
537
+//            $prize = PrizeService::getPrizeList($corp_id, $activity_id, $lottery_level);
538
+//            $data['prizeInfo'][$box_name] = $prize['data'];
539
+//        }
540
+
541
+        //活动状态
542
+        if (strtotime($activity_info['start_time']) > time()) {
543
+            $data['activityStatus'] = '活动未开始';
544
+        } elseif (strtotime($activity_info['end_time']) < time()) {
545
+            $data['activityStatus'] = '活动已结束';
546
+        } else {
547
+            if ($activity_info['is_temp_stop'] == 1) {
548
+                $data['activityStatus'] = '活动已暂停';
549
+            } else {
550
+                $data['activityStatus'] = '活动进行中';
551
+            }
552
+        }
553
+
554
+        //活动参与url拼接(用于生成二维码)
555
+        $app_info = self::getAppInfo($activity_info['app_id']);
556
+        $data['QR_url'] = env('WEB_URL') . '/' . $app_info['app_code'] . '?activity_id=' . $activity_id;
557
+
558
+        $data['activity_id'] = $activity_id;
559
+
560
+        if($data){
561
+            return Api::arr(config('code.success'),  trans('msg.success'), $data);
562
+        } else {
563
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
564
+        }
565
+    }
566
+
567
+    /**
568
+     * 保存活动配置信息
569
+     * 2018-06-20 10:39:00
570
+     * @param $params
571
+     * @return array
572
+     */
573
+    public static function saveActivity($params){
574
+        //活动判断
575
+        $activityInfo = self::getActivityInfo($params['activity_id'], $params['corp_id']);
576
+        if (!$activityInfo || empty($activityInfo)) {
577
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
578
+        }
579
+
580
+        //activitys表参数
581
+        $activityQuery = [];
582
+        $activityQuery['title']             = $params['title'];
583
+        $activityQuery['logo']              = empty($params['logo']) ? '' : $params['logo'];
584
+        $activityQuery['key']               = empty($params['key']) ? 1 : $params['key'];                      //1 手机号码 2 用户ID 3 邮箱
585
+        $activityQuery['regulation']        = empty($params['regulation']) ? '' : $params['regulation'];
586
+        $activityQuery['is_complete_set']   = 1;                                                                //活动配置状态 0 未完成 1 已完成
587
+        $activityQuery['status']            = 1;                                                                //活动状态 0 无效 1 有效
588
+        $activityQuery['is_jobtime_limit']  = empty($params['is_jobtime_limit']) ? 0 : $params['is_jobtime_limit'];
589
+        $activityQuery['is_weekend_limit']  = empty($params['is_weekend_limit']) ? 0 : $params['is_weekend_limit'];
590
+        $activityQuery['jobtimes']          = isset($params['jobtimes']) ? $params['jobtimes'] : '';
591
+        $activityQuery['start_time']        = strtotime($params['start_time']);
592
+        $activityQuery['end_time']          = strtotime($params['end_time']);
593
+        //活动结束时间必须小于VIP有效期
594
+        $vipInfo = CorpVip::where('corp_id', $params['corp_id'])->first();
595
+        if($vipInfo['vip_end_time'] < $activityQuery['end_time']){
596
+            return Api::arr(config('code.fail'), trans('msg.time_out_vip'));
597
+        }
598
+        //体验版会员以外的会员不限制人数(activity_type改为2)
599
+        if($vipInfo['vip_level'] > 1 && $activityInfo['activity_type'] == 1){
600
+            $activityQuery['activity_type'] = 2;
601
+        }
602
+
603
+        //完成设置时,不允许修改游戏平台和校验方式
604
+        if($activityInfo['is_complete_set'] == 0) {
605
+            $activityQuery['client_type'] = empty($params['client_type']) ? 'wechat' : $params['client_type'];
606
+            //根据平台类型和人员参与方式,适配登录校验方式
607
+            if ($activityQuery['client_type'] == 'wesuit') {      //企业微信
608
+                $corpInfo = Corps::where('corp_id', $params['corp_id'])->first();
609
+                if ($corpInfo['has_wesuit'] == 0) {
610
+                    return Api::arr(config('code.corp_not_wesuit'), trans('msg.corp_not_wesuit'));
611
+                }
612
+                $activityQuery['auth_type'] = 'agh';            //agh:参与方式 微信+企业微信(不导入人员)
613
+            } else {                                            //微信
614
+                $activityQuery['auth_type'] = empty($params['auth_type']) ? 'wechat' : $params['auth_type'];
615
+            }
616
+        }
617
+        $activityQuery['update_time']       = time();
618
+
619
+        //configs表参数
620
+        $configQuery = [];
621
+        $configQuery['top_banner']          = empty($params['top_banner'])      ? '' : $params['top_banner'];
622
+        $configQuery['home_background']     = empty($params['home_background']) ? '' : $params['home_background'];
623
+        $configQuery['mark_background']     = empty($params['mark_background']) ? '' : $params['mark_background'];
624
+        $configQuery['count_down_background'] = $params['count_down_background'];
625
+        $configQuery['sponsor_corp']        = $params['sponsor_corp'];
626
+//        $configQuery['share_image']         = empty($params['share_image'])?null:$params['share_image'];
627
+//        $configQuery['share_home_title']    = empty($params['share_home_title'])?'':$params['share_home_title'];
628
+//        $configQuery['share_home_desc']     = empty($params['share_home_desc'])?'':$params['share_home_desc'];
629
+//        $configQuery['share_pk_title']      = empty($params['share_pk_title'])?'':$params['share_pk_title'];
630
+//        $configQuery['share_pk_desc']       = empty($params['share_pk_desc'])?'':$params['share_pk_desc'];
631
+        $configQuery['prize_banner']        = $params['prize_banner'];
632
+        $configQuery['copper_box_km']       = empty($params['copper_box_km']) ? 100 :$params['copper_box_km'];
633
+        $configQuery['silver_box_km']       = empty($params['silver_box_km']) ? 500 :$params['silver_box_km'];
634
+        $configQuery['gold_box_km']         = empty($params['gold_box_km'])   ? 1000:$params['gold_box_km'];
635
+        $configQuery['is_open_prize']       = empty($params['is_open_prize']) ? 0   :$params['is_open_prize'];              //默认不开启抽奖
636
+        $configQuery['open_department_top'] = empty($params['open_department_top'])?0:$params['open_department_top'];       //默认不开启单位排行
637
+        $configQuery['get_question_mode']   = !isset($params['get_question_mode'])?0:$params['get_question_mode'];          //出题方式 0 随机 1 优先未达 2 优先错题
638
+        $configQuery['update_time']         = time();
639
+        $configQuery['top_background_color']= empty($params['top_background_color'])?'#242f55':$params['top_background_color'];
640
+
641
+        $act_res = Activitys::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->update($activityQuery);
642
+        $config_res = Configs::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->update($configQuery);
643
+
644
+        //答题配置及参数校验
645
+        $questionConfig = QuestionService::questionConfigDetail($params);
646
+
647
+        if(!$act_res || !$config_res || $questionConfig['code'] != 0){
648
+            return Api::arr($questionConfig['code'], $questionConfig['msg']);
649
+        }
650
+
651
+        //宝箱配置
652
+        if($configQuery['is_open_prize'] == 1 && !empty($params['box_config'])){
653
+            PrizeService::defaultBox($params);
654
+        }
655
+
656
+        //返回参数组装
657
+        $data['activity_id'] = $params['activity_id'];
658
+        $actInfo = Configs::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->first()->toArray();
659
+        //全员参与时,不提示人员导入情况
660
+        if($params['auth_type'] == 'wechat_auto_add'){
661
+            $data['user_msg'] = '';
662
+        } else {
663
+            $data['user_msg']     = $actInfo['is_user_upload'] == 0 ? '未上传人员':'';
664
+        }
665
+        $data['question_msg'] = $actInfo['is_question_upload'] == 0 ? '未上传题目' : '';
666
+        $data['prize_msg']    = '';
667
+        if($actInfo['is_open_prize'] == 1){
668
+            $prizes = Prizes::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->get();
669
+            $data['prize_msg'] = count($prizes) < 1 ? '未设置奖品' : '';
670
+        }
671
+        return Api::arr(config('code.success'), trans('msg.success'), $data);
672
+    }
673
+
674
+    /**
675
+     * 修改PK段位配置
676
+     * @param $params
677
+     * @return array
678
+     */
679
+    public static function modifyLevelConfig($params){
680
+        $activityInfo = self::getActivityInfo($params['activity_id']);
681
+        if(!$activityInfo){
682
+            return Api::arr(config('code.fail'), trans('msg.activity_not_exist'));
683
+        }
684
+
685
+        $activityConfig = self::getActivityConfig($params['activity_id']);
686
+        $levelConfig = json_decode($activityConfig['level_star_config'], true);
687
+        $levelConfig[1]['name'] = Api::trimAll($params['level_one']);
688
+        $levelConfig[2]['name'] = Api::trimAll($params['level_two']);
689
+        $levelConfig[3]['name'] = Api::trimAll($params['level_three']);
690
+        $levelConfig[4]['name'] = Api::trimAll($params['level_four']);
691
+        $levelConfig[5]['name'] = Api::trimAll($params['level_five']);
692
+        $levelConfig[6]['name'] = Api::trimAll($params['level_six']);
693
+
694
+        $levelConfigNew = json_encode($levelConfig);
695
+
696
+        $res = Configs::where('activity_id', $params['activity_id'])->update(['level_star_config'=>$levelConfigNew]);
697
+        if($res){
698
+            return Api::arr(config('code.success'), trans('msg.success'));
699
+        } else {
700
+            return Api::arr(config('code.fail'), trans('msg.sql_error'));
701
+        }
702
+    }
703
+}
704
+?>

+ 162 - 0
app/Services/AghApiService.php Целия файл

@@ -0,0 +1,162 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/5/23
6
+ * Time: 18:13
7
+ */
8
+
9
+namespace App\Services;
10
+use App\Common\Curl;
11
+use App\Common\Singleton;
12
+
13
+
14
+class AghApiService
15
+{
16
+    use Singleton;
17
+
18
+    protected $configs;
19
+
20
+    public function __construct($configs=[])
21
+    {
22
+        if(empty($configs)){
23
+            $configs = config('agh');
24
+        }
25
+        $this->configs = $configs;
26
+    }
27
+
28
+    /**
29
+     * 获得签名信息
30
+     * @param $name
31
+     * @param $gets
32
+     * @param array $posts
33
+     * @return string
34
+     */
35
+
36
+    protected function getSignUri($name,$gets,$posts=[]){
37
+        $gets["partnerId"] = $this->configs["api_partner_id"];
38
+        $gets["name"] = $name;
39
+        $gets["version"] = $this->configs["api_version"];
40
+        $gets["expires"] = time()+3600;
41
+        $gets["nonce"] = uniqid();
42
+        $array=array_merge($gets,$posts);
43
+        ksort($array);
44
+        $str = "";
45
+        foreach ($array as $key=>$value){
46
+            $str = $str . $key . '=' . $value . '&';
47
+        }
48
+        $str = substr($str, 0,strlen($str)-1);
49
+
50
+        $signature = hash_hmac('SHA256',$str, $this->configs["api_key"]);
51
+
52
+        $getUri="";
53
+        foreach ($gets as $key=>$value){
54
+            $getUri = $getUri . $key . '=' . $value . '&';
55
+        }
56
+
57
+        return $getUri."signature=".$signature;
58
+    }
59
+
60
+    /**
61
+     * 获得用户信息
62
+     * @param $gCorpId
63
+     * @param $guid
64
+     * @return mixed
65
+     */
66
+    public function getUserDetail($gCorpId,$guid){
67
+        $name="b.getUserDetail";
68
+        $posts = [
69
+            "corpId" => $gCorpId,
70
+            "guid" => $guid
71
+        ];
72
+        $uri = $this->configs["api_url"]."/fe/private/?".$this->getSignUri($name,[],$posts);
73
+        $curl = new Curl($uri);
74
+        $ret = json_decode($curl->httpPost($posts),true);
75
+        return $ret;
76
+    }
77
+
78
+    /**
79
+     * 获得企业列表
80
+     * @param $page8
81
+     * @param $pageSize
82
+     * @return mixed
83
+     */
84
+    public function getCorpList($page,$pageSize){
85
+        $name="b.getCorpList";
86
+        $posts = [
87
+            "page" => $page,
88
+            "pageSize" => $pageSize
89
+        ];
90
+        $uri = $this->configs["api_url"]."/fe/private/?".$this->getSignUri($name,[],$posts);
91
+        $curl = new Curl($uri);
92
+        $ret = json_decode($curl->httpPost($posts),true);
93
+        return $ret;
94
+    }
95
+
96
+    /**
97
+     * 获得企业信息
98
+     * @param $gCorpId
99
+     * @return mixed
100
+     */
101
+    public function getCorpInfo($gCorpId){
102
+        $name="b.getCorpInfo";
103
+        $posts = [
104
+            "enterpriseId" => $gCorpId
105
+        ];
106
+        $uri = $this->configs["api_url"]."/fe/private/?".$this->getSignUri($name,[],$posts);
107
+        $curl = new Curl($uri);
108
+        $ret = json_decode($curl->httpPost($posts),true);
109
+
110
+        return $ret;
111
+    }
112
+
113
+    /**
114
+     * 获取微信access_token
115
+     * @param $appId
116
+     * @param $gCorpId
117
+     * @return mixed
118
+     */
119
+    public function getWechatToken($gCorpId,$appId){
120
+        $name="b.wechat.getToken";
121
+        $posts = [
122
+            "appId" => $appId,
123
+            "corpId" => $gCorpId
124
+        ];
125
+        $uri = $this->configs["api_url"]."/fe/private/?".$this->getSignUri($name,[],$posts);
126
+        $curl = new Curl($uri);
127
+
128
+        $ret = json_decode($curl->httpPost($posts),true);
129
+
130
+        return $ret;
131
+    }
132
+
133
+    /**
134
+     * 获取企业微信access_token
135
+     * @param $qyCorpId
136
+     * @param $suiteId
137
+     * @return mixed
138
+     */
139
+    public function getWesuitToken($qyCorpId,$suiteId){
140
+        $name="b.wesuit.getToken";
141
+        $posts = [
142
+            "qy_corpid" => $qyCorpId,
143
+            "suiteId" => $suiteId,
144
+        ];
145
+        $uri = $this->configs["api_url"]."/fe/private/?".$this->getSignUri($name,[],$posts);
146
+        $curl = new Curl($uri);
147
+
148
+        $ret = json_decode($curl->httpPost($posts),true);
149
+
150
+        return $ret;
151
+    }
152
+
153
+    /**
154
+     * 获得爱关怀的SSO URL地址
155
+     * @param $gCorpId
156
+     * @param $redirectUrl
157
+     * @return string
158
+     */
159
+    public function getSsoUrl($gCorpId,$redirectUrl){
160
+        return $this->configs["api_url"]."/".$this->configs["api_version"]."/huanan/sso/url?gcorpId={$gCorpId}&forward=1&redirectUrl=".urlencode($redirectUrl);
161
+    }
162
+}

+ 107 - 0
app/Services/DdService.php Целия файл

@@ -0,0 +1,107 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: 15051
5
+ * Date: 2018/11/22
6
+ * Time: 10:33
7
+ */
8
+namespace App\Services;
9
+
10
+use App\Models\LotteryBoxs;
11
+use App\Models\Prizes;
12
+
13
+class DdService{
14
+    public function __construct()
15
+    {
16
+    }
17
+
18
+    /**
19
+     *
20
+     * @param $activity_id
21
+     * @param $corp_id
22
+     * @return mixed
23
+     */
24
+    public static function ExampleActBox($activity_id, $corp_id){
25
+        $boxs = [1,2,3,4];
26
+        $querys = [];
27
+        foreach($boxs as $k=>$v){
28
+            $query = [];
29
+            $queryPrize = [];
30
+            $query['open_mode'] = 'km';
31
+            $query['activity_id']   = $queryPrize['activity_id']    = $activity_id;
32
+            $query['corp_id']       = $queryPrize['corp_id']        = $corp_id;
33
+            $query['lottery_level'] = $queryPrize['lottery_level']  = $v;
34
+            $query['create_time']   = $query['update_time']         = $queryPrize['update_time'] = $queryPrize['create_time'] = time();
35
+            switch($v){
36
+                case 1:
37
+                    $query['open_rule']     = 100;
38
+                    $query['status']        = 1;
39
+                    $query['lottery_name']  = '铜宝箱';
40
+                    $query['lottery_icon']  = '//s1-hn.aghcdn.com/brainstorming/prize/prize_one.png';
41
+
42
+                    //示例铜宝箱奖品
43
+                    $queryPrize['prize_name']       = '铜质奖章';
44
+                    $queryPrize['prize_day_rule']   = 10;
45
+                    $queryPrize['prize_count']      = 10;
46
+                    $queryPrize['prize_weights']    = 1000;
47
+                    $queryPrize['prize_image_url']  = '//s1-hn.aghcdn.com/management/20181025/b4b94f2a3a2c6b6b32cf8a8e6a3178f9c6b036e5.png';
48
+
49
+                    //参数组装
50
+                    $querys[] = $query;
51
+                    $queryPrizes[] = $queryPrize;
52
+                    break;
53
+                case 2:
54
+                    $query['open_rule']     = 200;
55
+                    $query['status']        = 1;
56
+                    $query['lottery_name']  = '银宝箱';
57
+                    $query['lottery_icon']  = '//s1-hn.aghcdn.com/brainstorming/prize/prize_two.png';
58
+
59
+                    //示例银宝箱奖品
60
+                    $queryPrize['prize_name']       = '银质奖章';
61
+                    $queryPrize['prize_day_rule']   = 20;
62
+                    $queryPrize['prize_count']      = 20;
63
+                    $queryPrize['prize_weights']    = 800;
64
+                    $queryPrize['prize_image_url']  = '//s1-hn.aghcdn.com/management/20181025/b0bb22a2d9f68fd484154e867fc7ac50eb7b0c49.png';
65
+
66
+                    //参数组装
67
+                    $querys[] = $query;
68
+                    $queryPrizes[] = $queryPrize;
69
+                    break;
70
+                case 3:
71
+                    $query['open_rule']     = 500;
72
+                    $query['status']        = 1;
73
+                    $query['lottery_name']  = '金宝箱';
74
+                    $query['lottery_icon']  = '//s1-hn.aghcdn.com/brainstorming/prize/prize_three.png';
75
+
76
+                    //示例金宝箱奖品
77
+                    $queryPrize['prize_name']       = '金质奖章';
78
+                    $queryPrize['prize_day_rule']   = 30;
79
+                    $queryPrize['prize_count']      = 30;
80
+                    $queryPrize['prize_weights']    = 500;
81
+                    $queryPrize['prize_image_url']  = '//s1-hn.aghcdn.com/management/20181025/85be5acc8c0dcab4d572a78d7281674ff316e86a.png';
82
+
83
+                    //参数组装
84
+                    $querys[] = $query;
85
+                    $queryPrizes[] = $queryPrize;
86
+                    break;
87
+                case 4:
88
+                    $query['lottery_level'] = 4;
89
+                    $query['open_rule']     = 0;
90
+                    $query['status']        = 0;
91
+                    $query['lottery_name']  = '幸运宝箱';
92
+                    $query['lottery_icon']  = '//s1-hn.aghcdn.com/brainstorming/prize/prize_four.png';
93
+
94
+                    //参数组装(幸运宝箱无示例奖品)
95
+                    $querys[] = $query;
96
+                    break;
97
+            }
98
+        }
99
+        $res = LotteryBoxs::insert($querys);
100
+        $res_prize = Prizes::insert($queryPrizes);
101
+        if($res && $res_prize){
102
+            return true;
103
+        } else {
104
+            return false;
105
+        }
106
+    }
107
+}

+ 148 - 0
app/Services/LogService.php Целия файл

@@ -0,0 +1,148 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanl
5
+ * Date: 2018/10/26
6
+ * Time: 10:13
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+
12
+use DB;
13
+use App\Common\Api;
14
+use App\Models\Admin;
15
+use App\Models\Corps;
16
+use App\Models\Orders;
17
+use App\Services\ActivityService;
18
+use Illuminate\Support\Facades\Redis;
19
+
20
+class LogService
21
+{
22
+    public function __construct($configs = [])
23
+    {
24
+
25
+    }
26
+
27
+    /**
28
+     * 获取日志统计数据
29
+     * @param $params
30
+     * @return array
31
+     */
32
+    public static function eventCount($params){
33
+        $keyEvent  = empty($params['event_type']) || $params['event_type'] == 'all'?'':$params['event_type'];
34
+        $keyCorp   = empty($params['keyword_corp']) ?''                 :$params['keyword_corp'];
35
+        $keyAdmin  = empty($params['keyword_admin'])?''                 :$params['keyword_admin'];
36
+        $startTime = empty($params['start_time'])   ?time()-3600*24*7   :strtotime($params['start_time']);
37
+        $endTime   = empty($params['end_time'])     ?time()-3600*24     :strtotime($params['end_time']);
38
+
39
+        $adminIds = [];
40
+        $data = [];
41
+        if(!empty($keyCorp) || !empty($keyAdmin)){
42
+            $type = 'corp';
43
+            //存在搜索条件,搜索该企业或该管理员的详细信息
44
+            $corpInfo = Corps::where('corp_short_name', $keyCorp)->where('status', 1)->first();
45
+            if(!empty($keyAdmin)){
46
+                if(!empty($keyCorp)) {
47
+                    $adminInfo = Admin::where('username', $keyAdmin)->where('corp_id', $corpInfo['corp_id'])->first();
48
+                    $adminIds[] = $adminInfo['id'];
49
+                } else {
50
+                    $adminInfo = Admin::where('username', $keyAdmin)->first();
51
+                    $adminIds[] = $adminInfo['id'];
52
+                }
53
+            } else {
54
+                $adminIds = Admin::where('corp_id', $corpInfo['corp_id'])->pluck('id');
55
+            }
56
+
57
+            //获取企业或管理员的行为日志
58
+            $curl = env('APP_LOG_URL').'/EventLog/statistics?event_type='.$keyEvent."&admin_ids=".json_encode(collect($adminIds)->toArray()).'&start_time='.$startTime.'&end_time='.$endTime;
59
+            $corpData = Api::curl($curl);
60
+
61
+            $corpData = json_decode($corpData,true);
62
+            $data = [];
63
+            foreach($corpData as $k=>$v){
64
+                $adminInfo = Admin::where('id', $v['admin_id'])->first();
65
+                $data[$k]['visit_name'] = $adminInfo['name'];
66
+                switch ($v['event']){
67
+                    case 'changeScene1':
68
+                        $data[$k]['event_type'] = '体验案例1';
69
+                        break;
70
+                    case 'changeScene2':
71
+                        $data[$k]['event_type'] = '体验案例2';
72
+                        break;
73
+                    case 'changeScene3':
74
+                        $data[$k]['event_type'] = '体验案例3';
75
+                        break;
76
+                    case 'changeScene4':
77
+                        $data[$k]['event_type'] = '体验案例4';
78
+                        break;
79
+                    case 'openClick1':
80
+                        $data[$k]['event_type'] = '点击付费购买体验版';
81
+                        break;
82
+                    case 'openClick10':
83
+                        $data[$k]['event_type'] = '点击付费购买专业版';
84
+                        break;
85
+                    case 'openClick100':
86
+                        $data[$k]['event_type'] = '点击付费购买企业版';
87
+                        break;
88
+                    case 'chatClick1':
89
+                        $data[$k]['event_type'] = '头部客服访问';
90
+                        break;
91
+                    case 'chatClick2':
92
+                        $data[$k]['event_type'] = '图标客服访问';
93
+                        break;
94
+                }
95
+                $data[$k]['visit_time'] = date('Y-m-d H:i:s', $v['create_time']);
96
+            }
97
+
98
+        } else {
99
+            $type = 'all';
100
+            //不存在搜索条件,则搜索全部企业的总计信息
101
+            $corpIds = Admin::groupBy('corp_id')->pluck('corp_id');
102
+            foreach($corpIds as $corpId){
103
+                if($corpId == 0){
104
+                    continue;
105
+                }
106
+                $corpAdminIds = Admin::where('corp_id', $corpId)->pluck('id');
107
+                $curl = env('APP_LOG_URL').'/EventLog/statistics?event_type='.$keyEvent."&admin_ids=".json_encode(collect($corpAdminIds)->toArray()).'&start_time='.$startTime.'&end_time='.$endTime;
108
+                $res = Api::curl($curl);
109
+
110
+                $corpInfo = Corps::where('corp_id', $corpId)->first();
111
+                $data[$corpId]['corp_short_name']   = $corpInfo['corp_short_name'];
112
+                $data[$corpId]['agh_corp_id']       = $corpInfo['source_id'];
113
+                $data[$corpId]['register_time']     = date('Y-m-d H:i:s', $corpInfo['register_time']);
114
+                $data[$corpId]['clickCount'] = count(json_decode($res, true));
115
+            }
116
+        }
117
+
118
+        return Api::arr(config('code.success'), trans('msg.success'), $data);
119
+    }
120
+
121
+    /**
122
+     * 获取订单信息
123
+     * @param $params
124
+     * @return mixed
125
+     */
126
+    public static function orderList($params){
127
+        $sql = Orders::where('status', 1)->whereBetween('create_time', [$params['order_start_time'], $params['order_end_time']]);
128
+
129
+        if(!empty($params['corp_name'])){
130
+            $corpIds = Corps::where('corp_name', 'like', '%'.$params['corp_name'].'%')->pluck('corp_id');
131
+            $sql = $sql->whereIn('corp_id', $corpIds);
132
+        }
133
+
134
+        $data = $sql->orderBy('create_time')->get();
135
+
136
+        foreach($data as $k=>$v){
137
+            $data[$k]['corp_name'] = Corps::where('corp_id', $v['corp_id'])->value('corp_name');
138
+            $data[$k]['admin_name'] = Admin::where('id', $v['admin_id'])->value('name');
139
+
140
+            if($params['vip_start_time'] > $v['create_time'] + 30*3600*24*$v['months'] || $params['vip_end_time'] < $v['create_time'] + 30*3600*24*$v['months']){
141
+                unset($data[$k]);
142
+            }
143
+        }
144
+
145
+        return $data;
146
+    }
147
+}
148
+?>

+ 233 - 0
app/Services/PrizeService.php Целия файл

@@ -0,0 +1,233 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanl
5
+ * Date: 2018/6/19
6
+ * Time: 10:13
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+
12
+use DB;
13
+use App\Common\Api;
14
+use App\Models\Configs;
15
+use App\Models\Prizes;
16
+use App\Models\LotteryBoxs;
17
+use App\Services\ActivityService;
18
+use Illuminate\Support\Facades\Redis;
19
+
20
+class PrizeService
21
+{
22
+    public function __construct($configs = [])
23
+    {
24
+
25
+    }
26
+
27
+    /**
28
+     * 获取奖品详情
29
+     * @param $params
30
+     * @return array
31
+     */
32
+    public static function getPrizeInfo($params){
33
+        $activity_id    = $params['activity_id'];
34
+        $corp_id        = $params['corp_id'];
35
+        $prize_id       = $params['prize_id'];
36
+
37
+        $prizeInfo = Prizes::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('prize_id', $prize_id)->first();
38
+
39
+        //数据库存储以千分位为单位,页面以百分位单位
40
+        $prizeInfo['prize_weights'] = $prizeInfo['prize_weights']/10;
41
+
42
+        return Api::arr(config('code.success'), trans('msg.success'), $prizeInfo);
43
+    }
44
+
45
+    /**
46
+     * 添加/修改奖品详情
47
+     * @param $params
48
+     * @return array|string
49
+     */
50
+    public static function prizeDetail($params){
51
+        $query = [];
52
+        $query['activity_id']       = $params['activity_id'];
53
+        $query['corp_id']           = $params['corp_id'];
54
+        $query['lottery_level']     = $params['lottery_level'];
55
+        $query['prize_name']        = $params['prize_name'];
56
+        $query['prize_day_rule']    = $params['prize_day_rule'];
57
+        $query['prize_count']       = $params['prize_count'];
58
+        $query['prize_weights']     = $params['prize_weights']*10;
59
+        $query['prize_image_url']   = $params['prize_image_url'];
60
+        $query['update_time']       = time();
61
+
62
+        if (!empty($params['prize_id'])) {
63
+            //奖品信息判断
64
+            $actPrizeInfo = self::getPrizeInfo($params);
65
+            if($actPrizeInfo['code'] != 0 || empty($actPrizeInfo['data'])){
66
+                return Api::arr(config('code.fail'), trans('msg.prize_not_exist'));
67
+            }
68
+            $res = Prizes::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('lottery_level', $params['lottery_level'])->where('prize_id', $params['prize_id'])->update($query);
69
+
70
+            //奖品每日抽取逻辑优化  设置差值同步到redis
71
+            $num = $query['prize_day_rule'] - $actPrizeInfo['data']['prize_day_rule'];
72
+            $key = 'bs_prize_count:'.$params['prize_id'].':'.date('Ymd');
73
+            if(Redis::exists($key) && $num != 0) {
74
+                Redis::incrBy($key, $num);
75
+            }
76
+
77
+        } else {
78
+            $query['create_time'] = time();
79
+            $res = Prizes::insert($query);
80
+        }
81
+
82
+        if ($res) {
83
+            return Api::arr(config('code.success'), trans('msg.success'));
84
+        } else {
85
+            return Api::arr(config('code.fail'), trans('msg.sql_error'));
86
+        }
87
+    }
88
+
89
+    /**
90
+     * 获取宝箱内的奖品列表
91
+     * @param $corp_id
92
+     * @param $activity_id
93
+     * @param $lottery_level
94
+     * @return array
95
+     */
96
+    public static function getPrizeList($corp_id, $activity_id, $lottery_level){
97
+        $actInfo = ActivityService::getActivityInfo($activity_id, $corp_id);
98
+        if(!$actInfo){
99
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
100
+        }
101
+        $data = Prizes::where('activity_id', $activity_id)
102
+                        ->where('lottery_level', $lottery_level)
103
+                        ->where('status', '!=', 0)
104
+                        ->get()->toArray();
105
+
106
+        foreach($data as $k=>$v){
107
+            $data[$k]['prize_weights'] = $v['prize_weights']/10;
108
+        }
109
+
110
+        return Api::arr(config('code.success'), trans('msg.success'), $data);
111
+    }
112
+
113
+    /**
114
+     * 奖品删除或下架
115
+     * @param $params
116
+     * @return array
117
+     */
118
+    public static function prizeSoldOut($params){
119
+        $prizeInfo = Prizes::where('activity_id', $params['activity_id'])
120
+                            ->where('corp_id', $params['corp_id'])
121
+                            ->where('lottery_level', $params['lottery_level'])
122
+                            ->where('prize_id', $params['prize_id'])
123
+                            ->first();
124
+        if(!$prizeInfo){
125
+            return Api::arr(config('code.prize_not_exist'), trans('msg.prize_not_exist'));
126
+        }
127
+
128
+        $res = Prizes::where('activity_id', $params['activity_id'])
129
+                    ->where('corp_id', $params['corp_id'])
130
+                    ->where('lottery_level', $params['lottery_level'])
131
+                    ->where('prize_id', $params['prize_id'])
132
+                    ->update([
133
+                        'status'=>$params['status'],
134
+                        'update_time'=>time()
135
+                    ]);
136
+        if ($res) {
137
+            return Api::arr(config('code.success'), trans('msg.success'));
138
+        } else {
139
+            return Api::arr(config('code.fail'), trans('msg.sql_error'));
140
+        }
141
+    }
142
+
143
+    /**
144
+     * 获取活动宝箱配置
145
+     * 2018-11-06 16:17
146
+     * @param $params
147
+     * @return array
148
+     */
149
+    public static function getLotteryBoxs($params){
150
+        $activityId = $params['activity_id'];
151
+        $corpId     = $params['corp_id'];
152
+        $boxInfo = LotteryBoxs::where('activity_id', $activityId)->where('corp_id', $corpId)->get()->toArray();
153
+        return Api::arr(config('code.success'), trans('msg.success'), $boxInfo);
154
+    }
155
+
156
+    /**
157
+     * 生成默认宝箱或保存宝箱参数
158
+     * @param $params
159
+     * @param bool $type
160
+     * @return array
161
+     */
162
+    public static function defaultBox($params, $type=false){
163
+        if($type){             //添加默认宝箱设置
164
+            $boxs = [1,2,3,4];
165
+            $querys = [];
166
+            foreach($boxs as $k=>$v){
167
+                $query = [];
168
+                $query['activity_id']   = $params['activity_id'];
169
+                $query['corp_id']       = $params['corp_id'];
170
+                $query['lottery_level'] = $v;
171
+                $query['open_mode']     = 'km';
172
+                $query['create_time']   = $query['update_time'] = time();
173
+                switch($v){
174
+                    case 1:
175
+                        $query['open_rule'] = 100;
176
+                        $query['lottery_name'] = '铜宝箱';
177
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_one.png';
178
+                        break;
179
+                    case 2:
180
+                        $query['open_rule'] = 200;
181
+                        $query['lottery_name'] = '银宝箱';
182
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_two.png';
183
+                        break;
184
+                    case 3:
185
+                        $query['open_rule'] = 500;
186
+                        $query['lottery_name'] = '金宝箱';
187
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_three.png';
188
+                        break;
189
+                    case 4:
190
+                        $query['open_rule'] = 0;
191
+                        $query['lottery_name'] = '幸运宝箱';
192
+                        $query['lottery_icon'] = '//s1-hn.aghcdn.com/brainstorming/prize/prize_four.png';
193
+                        break;
194
+                }
195
+                $querys[] = $query;
196
+            }
197
+            $res = LotteryBoxs::insert($querys);
198
+            if($res){
199
+                $data = LotteryBoxs::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->get();
200
+                return Api::arr(config('code.success'), trans('msg.success'), $data);
201
+            } else {
202
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
203
+            }
204
+        } else {                    //保存宝箱配置
205
+            $arr = collect($params['box_config'])->toArray();
206
+            foreach($arr as $k=>$v){
207
+                $query = [];
208
+                $query['lottery_name']  = $v['lottery_name'];
209
+                $query['status']        = $v['status'];
210
+                $query['open_rule']     = $v['open_rule'];
211
+                $query['update_time']   = time();
212
+                $actLevelInfo = LotteryBoxs::where('activity_id', $params['activity_id'])
213
+                                            ->where('corp_id',$params['corp_id'])
214
+                                            ->where('lottery_level', $k)
215
+                                            ->first();
216
+                if($actLevelInfo){
217
+                    LotteryBoxs::where('activity_id', $params['activity_id'])
218
+                        ->where('corp_id',$params['corp_id'])
219
+                        ->where('lottery_level', $k)
220
+                        ->update($query);
221
+                } else {
222
+                    $query['activity_id']   = $params['activity_id'];
223
+                    $query['corp_id']       = $params['corp_id'];
224
+                    $query['lottery_level'] = $params['lottery_level'];
225
+                    $query['create_time']   = time();
226
+                    LotteryBoxs::insert($query);
227
+                }
228
+            }
229
+            return true;
230
+        }
231
+    }
232
+}
233
+?>

+ 587 - 0
app/Services/QuestionService.php Целия файл

@@ -0,0 +1,587 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanl
5
+ * Date: 2018/6/8
6
+ * Time: 10:13
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use DB;
12
+use Excel;
13
+use App\Common\Api;
14
+use App\Models\Questions;
15
+use App\Models\Categorys;
16
+use App\Models\Configs;
17
+use Illuminate\Support\Facades\Log;
18
+use Illuminate\Support\Facades\Redis;
19
+
20
+class QuestionService
21
+{
22
+    public function __construct($configs = [])
23
+    {
24
+
25
+    }
26
+
27
+    const QUESTION_UPLOAD_FAIL = 'bsb_question_upload_fail:';
28
+
29
+    /**
30
+     * 获取题库详情
31
+     * @param $activity_id
32
+     * @param $corp_id
33
+     * @param $category_id
34
+     * @return array|mixed
35
+     */
36
+    public static function getCategoryInfo($activity_id, $category_id){
37
+        $res = Categorys::where('activity_id', $activity_id)->where('category_id', $category_id)->first();
38
+
39
+        if($res){
40
+            $res = collect($res)->toArray();
41
+            $res = Api::dateFormat($res);
42
+        }
43
+
44
+        return $res;
45
+    }
46
+
47
+    /**
48
+     * 添加题库
49
+     * @param $params
50
+     * @return array
51
+     */
52
+    public static function saveCategory($params){
53
+        $act_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
54
+        if(!$act_info){
55
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
56
+        }
57
+
58
+        $query = [];
59
+        $tmp = explode("-",$params["category_name"]);
60
+        Log::info("category_name:".$params["category_name"]);
61
+        Log::info(json_encode($tmp,256));
62
+        $query['category_name'] = $tmp[0];
63
+        if (!empty($tmp[1]) && $tmp[1] == "直接雇员") {
64
+            $query["direct_employees"] = 1;
65
+        } else {
66
+            $query["direct_employees"] = 0;
67
+        }
68
+        $query['update_time']   = time();
69
+        if(!empty($params['category_id']) && isset($params['category_id'])){
70
+            $res = Categorys::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('category_id', $params['category_id'])->update($query);
71
+            $category_id = $params['category_id'];
72
+        } else {
73
+            $query['corp_id']       = $params['corp_id'];
74
+            $query['activity_id']   = $params['activity_id'];
75
+            $query['create_time']   = time();
76
+            $res = Categorys::insertGetId($query);
77
+            $category_id = $res;
78
+        }
79
+
80
+        if($res){
81
+            $data['category_id'] = $category_id;
82
+            return Api::arr(config('code.success'), trans('msg.success'), $data);
83
+        } else {
84
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
85
+        }
86
+    }
87
+
88
+    /**
89
+     * 获取题库列表
90
+     * @param $params
91
+     * @return array
92
+     */
93
+    public static function getCategoryList($params){
94
+        $act_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
95
+        if(!$act_info){
96
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
97
+        }
98
+
99
+        $categorys = Categorys::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->get()->toArray();
100
+
101
+        foreach ($categorys as $k=>$v) {
102
+            $question_num = Questions::where('category_id', $v['category_id'])
103
+                ->where('corp_id', $params['corp_id'])
104
+                ->where('activity_id', $params['activity_id'])
105
+                ->where('status', 1)                            //题目状态 0 无效 1有效
106
+                ->count();
107
+            $v['questionNum'] = $question_num?$question_num:0;
108
+            //时间格式化
109
+            $categorys[$k] = Api::dateFormat($v);
110
+        }
111
+
112
+        return Api::arr(config('code.success'), trans('msg.success'), $categorys);
113
+
114
+    }
115
+
116
+    /**
117
+     *  计算多个题库内的题目总数
118
+     */
119
+    public static function getQuestionsCount($categorys, $corp_id, $activity_id){
120
+        $category = explode(',', $categorys);
121
+
122
+        $count = 0;
123
+        foreach($category as $k=>$v){
124
+            $category_count = Questions::where('corp_id', $corp_id)->where('activity_id', $activity_id)->where('category_id', $v)->count();
125
+            $count += $category_count;
126
+        }
127
+
128
+        return $count;
129
+    }
130
+
131
+    /**
132
+     * 答题设置
133
+     * @param $params
134
+     * @return array
135
+     */
136
+    public static function questionConfigDetail($params){
137
+        //闯关、必答、PK 题库不能为空  必选项
138
+        if(empty($params['must_category_ids']) || empty($params['blockade_category_ids']) || empty($params['pk_category_ids'])){
139
+            return Api::arr(config('code.params_error'), trans('msg.category_ids_null'));
140
+        }
141
+
142
+        $must_category_ids      = $params['must_category_ids'];
143
+        $blockade_category_ids  = $params['blockade_category_ids'];
144
+        $pk_category_ids        = $params['pk_category_ids'];
145
+
146
+        //计算选中的题库内题目总数
147
+        $must_count = self::getQuestionsCount($must_category_ids, $params['corp_id'], $params['activity_id']);
148
+        $blockade_count = self::getQuestionsCount($blockade_category_ids, $params['corp_id'], $params['activity_id']);
149
+        $pk_count = self::getQuestionsCount($pk_category_ids, $params['corp_id'], $params['activity_id']);
150
+
151
+        //题目数不能大于选中的题库内题目的总数
152
+        if ($must_count < $params['must_question_num'] || $blockade_count < $params['blockade_question_num'] || $pk_count < $params['pk_question_num']) {
153
+            return Api::arr(config('code.params_error'), trans('msg.num_greater_category'));
154
+        }
155
+
156
+        //允许答错的题目数不能大于总题目数
157
+        if ($params['must_answer_wrong_num'] > $params['must_question_num'] || $params['blockade_answer_wrong_num'] > $params['blockade_question_num']) {
158
+            return Api::arr(config('code.params_error'), trans('msg.wrong_greater_num'));
159
+        }
160
+
161
+        //获取配置项信息
162
+        $config_info = Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->first();
163
+        if(!$config_info){
164
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
165
+        }
166
+
167
+        //配置项入库
168
+        $config_info = collect($config_info)->toArray();
169
+        $extend_configs = json_decode($config_info['extend_configs'], true);
170
+        $extend_configs['must_question_num']             = $params['must_question_num'];
171
+        $extend_configs['must_answer_wrong_num']         = $params['must_answer_wrong_num'];
172
+        $extend_configs['must_answer_success_km']        = $params['must_answer_success_km'];
173
+        $extend_configs['blockade_question_num']         = $params['blockade_question_num'];
174
+        $extend_configs['blockade_answer_wrong_num']     = $params['blockade_answer_wrong_num'];
175
+        $extend_configs['blockade_answer_success_km']    = $params['blockade_answer_success_km'];
176
+        $extend_configs['pk_question_num']               = $params['pk_question_num'];
177
+        $extend_configs['pk_last_double']                = $params['pk_last_double'];
178
+        $extend_configs['pk_kms']                        = $params['pk_kms'];
179
+        $extend_configs['must_category_ids']             = $must_category_ids;
180
+        $extend_configs['blockade_category_ids']         = $blockade_category_ids;
181
+        $extend_configs['pk_category_ids']               = $pk_category_ids;
182
+        $extend_configs['top_prize_open']                = $params['top_prize_open'];
183
+        $extend_configs['top_prize_text']                = $params['top_prize_text'];
184
+        $extend_configs['top_prize_num']                 = $params['top_prize_num'];
185
+        $extend_configs['must_answer_count_down']        = isset($params['must_answer_count_down']) && $params['must_answer_count_down']>=5?$params['must_answer_count_down']:10;
186
+        $extend_configs['blockade_answer_count_down']    = isset($params['blockade_answer_count_down']) && $params['blockade_answer_count_down']>=5?$params['blockade_answer_count_down']:10;
187
+
188
+        $extend_configs = json_encode($extend_configs);
189
+        $res_config = Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->update(['extend_configs' => $extend_configs, 'update_time' => time()]);
190
+
191
+        return Api::arr(config('code.success'), trans('msg.success'));
192
+    }
193
+
194
+    /**
195
+     * 修改/新增题目
196
+     * @param $params
197
+     * @return array
198
+     */
199
+    public static function questionModify($params){
200
+        $query = [];
201
+        $question_options= [];
202
+        $answers = [];
203
+        if(!empty($params['option_a'])){
204
+            $question_options['A'] = Api::trimAll($params['option_a']);
205
+            $answers[] = 'A';
206
+        }
207
+        if(!empty($params['option_b'])){
208
+            $question_options['B'] = Api::trimAll($params['option_b']);
209
+            $answers[] = 'B';
210
+        }
211
+        if(!empty($params['option_c'])){
212
+            $question_options['C'] = Api::trimAll($params['option_c']);
213
+            $answers[] = 'C';
214
+        }
215
+        if(!empty($params['option_d'])){
216
+            $question_options['D'] = Api::trimAll($params['option_d']);
217
+            $answers[] = 'D';
218
+        }
219
+
220
+	$correct_answer = self::answerChange($params['correct_answer']);
221
+
222
+        //题目和答案不可为空
223
+        if(empty(Api::trimAll($params['question_title'])) || empty($correct_answer)){
224
+            return Api::arr(config('code.params_error'), trans('msg.title_answer_null'));
225
+        }
226
+
227
+        //选项最少需要两个
228
+        if(count($question_options)<2){
229
+            return Api::arr(config('code.params_error'), trans('msg.option_error'));
230
+        }
231
+
232
+	//答案必须在已有可用选项当中
233
+        foreach($correct_answer as $k=>$v){
234
+            if(!in_array($v, $answers)){
235
+                return Api::arr(config('code.params_error'), trans('msg.answer_error'));
236
+            }
237
+        }
238
+
239
+        //参数组装
240
+        $query['question_title']    = Api::trimAll($params['question_title']);
241
+        $query['question_options']  = serialize($question_options);
242
+	$query['correct_answer']    = implode('', $correct_answer);
243
+        $query['question_type']     = count($correct_answer) > 1 ? 2 : 1;       //题目类型  单选/多选
244
+        $query['category_id']       = intval($params['category_id']);
245
+        $query['update_time']       = time();
246
+
247
+        //题目ID存在则修改题目,不存在则新增题目
248
+        if(isset($params['question_id']) && $params['question_id'] != 0){
249
+            $question = Questions::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('question_id', $params['question_id'])->first();
250
+            if(!$question){
251
+                return Api::arr(config('code.question_not_exist'), trans('msg.question_not_exist'));
252
+            }
253
+
254
+            $res = Questions::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('question_id', $params['question_id'])->update($query);
255
+            if(!$res){
256
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
257
+            }
258
+
259
+        } else {
260
+            $query['corp_id']       = $params['corp_id'];
261
+            $query['activity_id']   = $params['activity_id'];
262
+            $query['create_time']   = time();
263
+
264
+            $res = Questions::insert($query);
265
+            if(!$res){
266
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
267
+            }
268
+        }
269
+
270
+        return Api::arr(config('code.success'), trans('msg.success'));
271
+    }
272
+
273
+    /**
274
+     * 获取题库内题目数量
275
+     * @param $corp_id
276
+     * @param $activity_id
277
+     * @return array
278
+     */
279
+    public static function getCategoryCount($corp_id, $activity_id){
280
+        $categorys = Categorys::where('activity_id', $activity_id)->where('corp_id', $corp_id)->get()->toArray();
281
+
282
+        $data = [];
283
+        if($categorys) {
284
+            foreach ($categorys as $category) {
285
+                $data[$category['category_name']] = Questions::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('category_id', $category['category_id'])->count();
286
+            }
287
+        }
288
+
289
+        return $data;
290
+    }
291
+
292
+    /**
293
+     * 新增题库及题目上传
294
+     * @param $data
295
+     * @param $params
296
+     * @return array|string
297
+     */
298
+    public static function questionUpload($data, $params){
299
+        if(empty($data)){
300
+            return Api::arr(config('code.fail'), trans('msg.question_not_exist'));
301
+        }
302
+
303
+        //添加题库
304
+        $categoryRes = self::saveCategory($params);
305
+
306
+        if($categoryRes['code'] != config('code.success')){
307
+            return Api::arr(config('code.fail'), trans('msg.category_add_fail'));
308
+        }
309
+
310
+        $category_id = $categoryRes['data']['category_id'];
311
+
312
+        DB::beginTransaction();
313
+        $errors = [];
314
+        $error_num = 0;
315
+        foreach ($data as $k => $v) {
316
+            $question_options = array();
317
+            $question_title = $v[0];
318
+            $answers = array();
319
+            if(!empty($v[1]) || $v[1] == '0'){
320
+                $question_options['A'] = $v[1];
321
+                $answers[] = 'A';
322
+            }
323
+            if(!empty($v[2]) || $v[2] == '0'){
324
+                $question_options['B'] = $v[2];
325
+                $answers[] = 'B';
326
+            }
327
+            if(!empty($v[3]) || $v[3] == '0'){
328
+                $question_options['C'] = $v[3];
329
+                $answers[] = 'C';
330
+            }
331
+            if(!empty($v[4]) || $v[4] == '0'){
332
+                $question_options['D'] = $v[4];
333
+                $answers[] = 'D';
334
+            }
335
+
336
+            $correct_answer = $v[5];
337
+	    $correct_answer = self::answerChange($correct_answer);
338
+
339
+            $query = array();
340
+            $query['corp_id']           = $params['corp_id'];
341
+            $query['activity_id']       = $params['activity_id'];
342
+            $query['category_id']       = $category_id;
343
+            $query['question_title']    = $question_title;
344
+
345
+            //答案单选 答案不能为空 题目不能为空 选项最少两个 答案不在选项中   都视为错误题目
346
+            if(empty($correct_answer)){
347
+                $v[6] = '答案为空';
348
+                $errors[] = $v;
349
+                $error_num += 1;
350
+                continue;
351
+            }
352
+            if(empty($query['question_title'])){
353
+                $v[6] = '题目为空';
354
+                $errors[] = $v;
355
+                $error_num += 1;
356
+                continue;
357
+            }
358
+            if(count($answers) < 2){
359
+                $v[6] = '选项少于2个';
360
+                $errors[] = $v;
361
+                $error_num += 1;
362
+                continue;
363
+            }
364
+            //支持多选
365
+            $correct_type = 0;
366
+            foreach($correct_answer as $key=>$val){
367
+                if(!in_array($val, $answers)){
368
+                    $v[6] = '答案中选项为空或不存在';
369
+                    $errors[] = $v;
370
+                    $error_num += 1;
371
+                    $correct_type = 1;
372
+                    continue;
373
+                }
374
+            }
375
+            if($correct_type == 1){
376
+                continue;
377
+            }
378
+
379
+            $query['correct_answer']   = implode('', $correct_answer);
380
+            $query['question_type']    = count($correct_answer) > 1 ? 2 : 1;
381
+            $query['question_options'] = serialize($question_options);      //序列化
382
+            $query['create_time'] = time();
383
+            $query['update_time'] = time();
384
+
385
+            $res = Questions::insert($query);
386
+            if (!$res) {
387
+                DB::rollBack();
388
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
389
+            }
390
+        }
391
+
392
+        DB::commit();
393
+
394
+        //错误记录存入redis
395
+        Redis::set(self::QUESTION_UPLOAD_FAIL.$params['activity_id'], json_encode($errors),'EX',3600);
396
+
397
+        $res = [];
398
+        $res['total']       = count($data);
399
+        $res['error_num']   = $error_num;
400
+        $res['success_num'] = $res['total'] - $error_num;
401
+        $res['category_id'] = $category_id;
402
+        return Api::arr(config('code.success'), trans('msg.success'), $res);
403
+    }
404
+
405
+    /**
406
+     * 删除题目
407
+     * 2018-06-22 10:32:00
408
+     * @param $params
409
+     * @return array
410
+     */
411
+    public static function delQuestion($params){
412
+        //题目信息
413
+        $questionInfo = Questions::where('activity_id', $params['activity_id'])
414
+                                ->where('corp_id', $params['corp_id'])
415
+                                ->where('category_id', $params['category_id'])
416
+                                ->where('question_id', $params['question_id'])
417
+                                ->where('status', 1)
418
+                                ->first();
419
+
420
+        if(!$questionInfo){
421
+            return Api::arr(config('code.question_not_exist'), trans('msg.question_not_exist'));
422
+        }
423
+
424
+        //删除题目
425
+        $res = Questions::where('activity_id', $params['activity_id'])
426
+                        ->where('corp_id', $params['corp_id'])
427
+                        ->where('category_id', $params['category_id'])
428
+                        ->where('question_id', $params['question_id'])
429
+                        ->where('status', 1)
430
+                        ->delete();
431
+
432
+        if($res){
433
+            return Api::arr(config('code.success'), trans('msg.success'));
434
+        } else {
435
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
436
+        }
437
+    }
438
+
439
+    /**
440
+     * 下载上传失败的题目数据
441
+     * @param $data
442
+     */
443
+    public static function downloadQuestionExcel($data){
444
+        $cellData = [
445
+            ['题目标题', 'A选项', 'B选项', 'C选项', 'D选项', '答案', '错误原因'],
446
+            ['填写规则'],
447
+        ];
448
+
449
+        foreach($cellData as $k=>$v){
450
+            array_unshift($data, $v);
451
+        }
452
+
453
+        Excel::create('题目导入错误数据'.date('mdHi'),function($excel) use ($data){
454
+            $excel->sheet('题目信息', function($sheet) use ($data){
455
+
456
+                $tot = count($data) ;
457
+                $sheet->setWidth(array(
458
+                    'A'     =>  50,
459
+                    'B'     =>  15,
460
+                    'C'     =>  15,
461
+                    'D'     =>  15,
462
+                    'E'     =>  15,
463
+                    'F'     =>  15,
464
+                    'G'     =>  15,
465
+                ))->rows($data)->setFontSize(12);
466
+
467
+                //设置第一行的表格格式
468
+                $sheet->setStyle([
469
+                    'font' => [
470
+                        'size' => 12,
471
+                        'bold' => false,
472
+                    ]
473
+                ])
474
+                    ->mergeCells('A1:G1')       //合并单元格
475
+                    ->setHeight(1, 100)         //设置行高
476
+                    ->setHeight(2, 30)
477
+                    ->cells('A1:G1', function($cells){          //设置单元格格式
478
+                        $cells->setValignment('center');         //文本对齐方式
479
+                        $cells->setFontWeight('bold');           //粗体
480
+                    })
481
+                    ->cells('A2:G2', function($cells){
482
+                        $cells->setValignment('center');
483
+                        $cells->setBackground('#92D050');
484
+                        $cells->setFontWeight('bold');
485
+                        $cells->setFontSize(10);
486
+                        $cells->setAlignment('center');
487
+                    })
488
+                    ->cells('B2:G'.$tot, function($cells) {
489
+                        $cells->setAlignment('center');
490
+                    })
491
+                    ->cells('G3:G'.$tot, function($cells) {
492
+                        $cells->setFontColor('#ff0000');
493
+                        $cells->setFontWeight('bold');
494
+                    });
495
+            });
496
+        })->export('xls');
497
+    }
498
+
499
+    /**
500
+     * 添加默认题库
501
+     * @param $activity_id
502
+     * @return array
503
+     */
504
+    public static function addDefault($activity_id){
505
+        $activity_info = ActivityService::getActivityInfo($activity_id);
506
+        if(!$activity_info){
507
+            return Api::arr(config('code.fail'), trans('msg.activity_not_exist'));
508
+        }
509
+
510
+        $default_questions = Questions::where('corp_id', 0)->where('activity_id', 0)->get()->toArray();
511
+        $query_category = [];
512
+        $query_category['corp_id']      = $activity_info['corp_id'];
513
+        $query_category['activity_id']  = $activity_id;
514
+        $query_category['category_name']  = '样例题库';
515
+        $query_category['create_time']  = time();
516
+        $query_category['update_time']  = time();
517
+
518
+        $res = Categorys::insertGetId($query_category);
519
+        if(!$res){
520
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
521
+        }
522
+
523
+        foreach($default_questions as $k=>$v){
524
+            $query_question = [];
525
+            $query_question['corp_id']      = $activity_info['corp_id'];
526
+            $query_question['activity_id']  = $activity_id;
527
+            $query_question['question_title'] = $v['question_title'];
528
+            $query_question['category_id']  = $res;
529
+            $query_question['question_options'] = $v['question_options'];
530
+            $query_question['correct_answer'] = $v['correct_answer'];
531
+            $query_question['create_time']  = time();
532
+            $query_question['update_time']  = time();
533
+            Questions::insert($query_question);
534
+        }
535
+
536
+        $data['category_id'] = $res;
537
+        return Api::arr(config('code.success'), trans('msg.success'), $data);
538
+    }
539
+
540
+    /**
541
+     * 删除题库(活动委发布状态才可删除)
542
+     * @param $activity_id
543
+     * @param $category_id
544
+     * @return array
545
+     */
546
+    public static function delCategory($activity_id, $category_id){
547
+        $activityInfo = ActivityService::getActivityInfo($activity_id);
548
+
549
+        if(!$activityInfo){
550
+            return Api::arr(config('code.fail'), trans('msg.activity_not_exist'));
551
+        }
552
+
553
+        if($activityInfo['is_complete_set'] == 1){
554
+            return Api::arr(config('code.fail'), '活动已发布,无法删除题库');
555
+        }
556
+
557
+        $categoryInfo = Categorys::where('category_id', $category_id)->first();
558
+        if(!$categoryInfo){
559
+            return Api::arr(config('code.fail'), trans('msg.category_not_exist'));
560
+        }
561
+
562
+        Categorys::where('category_id', $category_id)->delete();
563
+
564
+        $questions = Questions::where('category_id', $category_id)->get();
565
+        foreach($questions as $k=>$v){
566
+            Questions::where('question_id', $v['question_id'])->delete();
567
+        }
568
+
569
+        return Api::arr(config('code.success'), trans('msg.success'));
570
+    }
571
+    
572
+    /**
573
+     * 题目答案转换
574
+     * @param $correct_answer
575
+     * @return array|string
576
+     */
577
+    public static function answerChange($correct_answer){
578
+        //去除中文字并转换大写
579
+        $arr = strtoupper(preg_replace('/([\x80-\xff]*)/i','',$correct_answer));
580
+        //拆分单个选项并去除重复选项
581
+        $arr = array_unique(str_split($arr));
582
+        //排序
583
+        sort($arr);
584
+        return $arr;
585
+    }
586
+}
587
+?>

+ 551 - 0
app/Services/QuestionService.php.bak Целия файл

@@ -0,0 +1,551 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanl
5
+ * Date: 2018/6/8
6
+ * Time: 10:13
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use DB;
12
+use Excel;
13
+use App\Common\Api;
14
+use App\Models\Questions;
15
+use App\Models\Categorys;
16
+use App\Models\Configs;
17
+use Illuminate\Support\Facades\Redis;
18
+
19
+class QuestionService
20
+{
21
+    public function __construct($configs = [])
22
+    {
23
+
24
+    }
25
+
26
+    const QUESTION_UPLOAD_FAIL = 'bsb_question_upload_fail:';
27
+
28
+    /**
29
+     * 获取题库详情
30
+     * @param $activity_id
31
+     * @param $corp_id
32
+     * @param $category_id
33
+     * @return array|mixed
34
+     */
35
+    public static function getCategoryInfo($activity_id, $category_id){
36
+        $res = Categorys::where('activity_id', $activity_id)->where('category_id', $category_id)->first();
37
+
38
+        if($res){
39
+            $res = collect($res)->toArray();
40
+            $res = Api::dateFormat($res);
41
+        }
42
+
43
+        return $res;
44
+    }
45
+
46
+    /**
47
+     * 添加题库
48
+     * @param $params
49
+     * @return array
50
+     */
51
+    public static function saveCategory($params){
52
+        $act_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
53
+        if(!$act_info){
54
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
55
+        }
56
+
57
+        $query = [];
58
+        $query['category_name'] = $params['category_name'];
59
+        $query['update_time']   = time();
60
+        if(!empty($params['category_id']) && isset($params['category_id'])){
61
+            $res = Categorys::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('category_id', $params['category_id'])->update($query);
62
+            $category_id = $params['category_id'];
63
+        } else {
64
+            $query['corp_id']       = $params['corp_id'];
65
+            $query['activity_id']   = $params['activity_id'];
66
+            $query['create_time']   = time();
67
+            $res = Categorys::insertGetId($query);
68
+            $category_id = $res;
69
+        }
70
+
71
+        if($res){
72
+            $data['category_id'] = $category_id;
73
+            return Api::arr(config('code.success'), trans('msg.success'), $data);
74
+        } else {
75
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
76
+        }
77
+    }
78
+
79
+    /**
80
+     * 获取题库列表
81
+     * @param $params
82
+     * @return array
83
+     */
84
+    public static function getCategoryList($params){
85
+        $act_info = ActivityService::getActivityInfo($params['activity_id'], $params['corp_id']);
86
+        if(!$act_info){
87
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
88
+        }
89
+
90
+        $categorys = Categorys::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->get()->toArray();
91
+
92
+        foreach ($categorys as $k=>$v) {
93
+            $question_num = Questions::where('category_id', $v['category_id'])
94
+                ->where('corp_id', $params['corp_id'])
95
+                ->where('activity_id', $params['activity_id'])
96
+                ->where('status', 1)                            //题目状态 0 无效 1有效
97
+                ->count();
98
+            $v['questionNum'] = $question_num?$question_num:0;
99
+
100
+            //时间格式化
101
+            $categorys[$k] = Api::dateFormat($v);
102
+        }
103
+
104
+        return Api::arr(config('code.success'), trans('msg.success'), $categorys);
105
+
106
+    }
107
+
108
+    /**
109
+     *  计算多个题库内的题目总数
110
+     */
111
+    public static function getQuestionsCount($categorys, $corp_id, $activity_id){
112
+        $category = explode(',', $categorys);
113
+
114
+        $count = 0;
115
+        foreach($category as $k=>$v){
116
+            $category_count = Questions::where('corp_id', $corp_id)->where('activity_id', $activity_id)->where('category_id', $v)->count();
117
+            $count += $category_count;
118
+        }
119
+
120
+        return $count;
121
+    }
122
+
123
+    /**
124
+     * 答题设置
125
+     * @param $params
126
+     * @return array
127
+     */
128
+    public static function questionConfigDetail($params){
129
+        //闯关、必答、PK 题库不能为空  必选项
130
+        if(empty($params['must_category_ids']) || empty($params['blockade_category_ids']) || empty($params['pk_category_ids'])){
131
+            return Api::arr(config('code.params_error'), trans('msg.category_ids_null'));
132
+        }
133
+
134
+        $must_category_ids      = $params['must_category_ids'];
135
+        $blockade_category_ids  = $params['blockade_category_ids'];
136
+        $pk_category_ids        = $params['pk_category_ids'];
137
+
138
+        //计算选中的题库内题目总数
139
+        $must_count = self::getQuestionsCount($must_category_ids, $params['corp_id'], $params['activity_id']);
140
+        $blockade_count = self::getQuestionsCount($blockade_category_ids, $params['corp_id'], $params['activity_id']);
141
+        $pk_count = self::getQuestionsCount($pk_category_ids, $params['corp_id'], $params['activity_id']);
142
+
143
+        //题目数不能大于选中的题库内题目的总数
144
+        if ($must_count < $params['must_question_num'] || $blockade_count < $params['blockade_question_num'] || $pk_count < $params['pk_question_num']) {
145
+            return Api::arr(config('code.params_error'), trans('msg.num_greater_category'));
146
+        }
147
+
148
+        //允许答错的题目数不能大于总题目数
149
+        if ($params['must_answer_wrong_num'] > $params['must_question_num'] || $params['blockade_answer_wrong_num'] > $params['blockade_question_num']) {
150
+            return Api::arr(config('code.params_error'), trans('msg.wrong_greater_num'));
151
+        }
152
+
153
+        //获取配置项信息
154
+        $config_info = Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->first();
155
+        if(!$config_info){
156
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
157
+        }
158
+
159
+        //配置项入库
160
+        $config_info = collect($config_info)->toArray();
161
+        $extend_configs = json_decode($config_info['extend_configs'], true);
162
+        $extend_configs['must_question_num']             = $params['must_question_num'];
163
+        $extend_configs['must_answer_wrong_num']         = $params['must_answer_wrong_num'];
164
+        $extend_configs['must_answer_success_km']        = $params['must_answer_success_km'];
165
+        $extend_configs['blockade_question_num']         = $params['blockade_question_num'];
166
+        $extend_configs['blockade_answer_wrong_num']     = $params['blockade_answer_wrong_num'];
167
+        $extend_configs['blockade_answer_success_km']    = $params['blockade_answer_success_km'];
168
+        $extend_configs['pk_question_num']               = $params['pk_question_num'];
169
+        $extend_configs['pk_last_double']                = $params['pk_last_double'];
170
+        $extend_configs['pk_kms']                        = $params['pk_kms'];
171
+        $extend_configs['must_category_ids']             = $must_category_ids;
172
+        $extend_configs['blockade_category_ids']         = $blockade_category_ids;
173
+        $extend_configs['pk_category_ids']               = $pk_category_ids;
174
+        $extend_configs['top_prize_open']                = $params['top_prize_open'];
175
+        $extend_configs['top_prize_text']                = $params['top_prize_text'];
176
+        $extend_configs['top_prize_num']                 = $params['top_prize_num'];
177
+        $extend_configs['must_answer_count_down']        = isset($params['must_answer_count_down']) && $params['must_answer_count_down']>=5?$params['must_answer_count_down']:10;
178
+        $extend_configs['blockade_answer_count_down']    = isset($params['blockade_answer_count_down']) && $params['blockade_answer_count_down']>=5?$params['blockade_answer_count_down']:10;
179
+
180
+        $extend_configs = json_encode($extend_configs);
181
+        $res_config = Configs::where('corp_id', $params['corp_id'])->where('activity_id', $params['activity_id'])->update(['extend_configs' => $extend_configs, 'update_time' => time()]);
182
+
183
+        return Api::arr(config('code.success'), trans('msg.success'));
184
+    }
185
+
186
+    /**
187
+     * 修改/新增题目
188
+     * @param $params
189
+     * @return array
190
+     */
191
+    public static function questionModify($params){
192
+        $query = [];
193
+        $question_options= [];
194
+        $answers = [];
195
+        if(!empty($params['option_a'])){
196
+            $question_options['A'] = Api::trimAll($params['option_a']);
197
+            $answers[] = 'A';
198
+        }
199
+        if(!empty($params['option_b'])){
200
+            $question_options['B'] = Api::trimAll($params['option_b']);
201
+            $answers[] = 'B';
202
+        }
203
+        if(!empty($params['option_c'])){
204
+            $question_options['C'] = Api::trimAll($params['option_c']);
205
+            $answers[] = 'C';
206
+        }
207
+        if(!empty($params['option_d'])){
208
+            $question_options['D'] = Api::trimAll($params['option_d']);
209
+            $answers[] = 'D';
210
+        }
211
+
212
+        //题目和答案不可为空
213
+        if(empty(Api::trimAll($params['question_title'])) || empty($params['correct_answer'])){
214
+            return Api::arr(config('code.params_error'), trans('msg.title_answer_null'));
215
+        }
216
+
217
+        //选项最少需要两个  答案必须在已有选项当中
218
+        if(count($question_options)<2 || !in_array(strtoupper($params['correct_answer']), $answers)){
219
+            return Api::arr(config('code.params_error'), trans('msg.option_error'));
220
+        }
221
+
222
+        //参数组装
223
+        $query['question_title']    = Api::trimAll($params['question_title']);
224
+        $query['question_options']  = serialize($question_options);
225
+        $query['correct_answer']    = strtoupper($params['correct_answer']);
226
+        $query['category_id']       = intval($params['category_id']);
227
+        $query['update_time']       = time();
228
+
229
+        //题目ID存在则修改题目,不存在则新增题目
230
+        if(isset($params['question_id']) && $params['question_id'] != 0){
231
+            $question = Questions::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('question_id', $params['question_id'])->first();
232
+            if(!$question){
233
+                return Api::arr(config('code.question_not_exist'), trans('msg.question_not_exist'));
234
+            }
235
+
236
+            $res = Questions::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('question_id', $params['question_id'])->update($query);
237
+            if(!$res){
238
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
239
+            }
240
+
241
+        } else {
242
+            $query['corp_id']       = $params['corp_id'];
243
+            $query['activity_id']   = $params['activity_id'];
244
+            $query['create_time']   = time();
245
+
246
+            $res = Questions::insert($query);
247
+            if(!$res){
248
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
249
+            }
250
+        }
251
+
252
+        return Api::arr(config('code.success'), trans('msg.success'));
253
+    }
254
+
255
+    /**
256
+     * 获取题库内题目数量
257
+     * @param $corp_id
258
+     * @param $activity_id
259
+     * @return array
260
+     */
261
+    public static function getCategoryCount($corp_id, $activity_id){
262
+        $categorys = Categorys::where('activity_id', $activity_id)->where('corp_id', $corp_id)->get()->toArray();
263
+
264
+        $data = [];
265
+        if($categorys) {
266
+            foreach ($categorys as $category) {
267
+                $data[$category['category_name']] = Questions::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('category_id', $category['category_id'])->count();
268
+            }
269
+        }
270
+
271
+        return $data;
272
+    }
273
+
274
+    /**
275
+     * 新增题库及题目上传
276
+     * @param $data
277
+     * @param $params
278
+     * @return array|string
279
+     */
280
+    public static function questionUpload($data, $params){
281
+        if(empty($data)){
282
+            return Api::arr(config('code.fail'), trans('msg.question_not_exist'));
283
+        }
284
+
285
+        //添加题库
286
+        $categoryRes = self::saveCategory($params);
287
+
288
+        if($categoryRes['code'] != config('code.success')){
289
+            return Api::arr(config('code.fail'), trans('msg.category_add_fail'));
290
+        }
291
+
292
+        $category_id = $categoryRes['data']['category_id'];
293
+
294
+        DB::beginTransaction();
295
+        $errors = [];
296
+        $error_num = 0;
297
+        foreach ($data as $k => $v) {
298
+            $question_options = array();
299
+            $question_title = $v[0];
300
+            $answers = array();
301
+            if(!empty($v[1]) || $v[1] == '0'){
302
+                $question_options['A'] = $v[1];
303
+                $answers[] = 'A';
304
+            }
305
+            if(!empty($v[2]) || $v[2] == '0'){
306
+                $question_options['B'] = $v[2];
307
+                $answers[] = 'B';
308
+            }
309
+            if(!empty($v[3]) || $v[3] == '0'){
310
+                $question_options['C'] = $v[3];
311
+                $answers[] = 'C';
312
+            }
313
+            if(!empty($v[4]) || $v[4] == '0'){
314
+                $question_options['D'] = $v[4];
315
+                $answers[] = 'D';
316
+            }
317
+
318
+            $correct_answer = $v[5];
319
+
320
+            $query = array();
321
+            $query['corp_id']           = $params['corp_id'];
322
+            $query['activity_id']       = $params['activity_id'];
323
+            $query['category_id']       = $category_id;
324
+            $query['question_title']    = $question_title;
325
+            $query['correct_answer']    = strtoupper($correct_answer);
326
+
327
+            //答案单选 答案不能为空 题目不能为空 选项最少两个 答案不在选项中   都视为错误题目
328
+            if(strlen($query['correct_answer']) > 1){
329
+                $v[6] = '答案多选';
330
+                $errors[] = $v;
331
+                $error_num += 1;
332
+                continue;
333
+            }
334
+            if(empty($query['correct_answer'])){
335
+                $v[6] = '答案为空';
336
+                $errors[] = $v;
337
+                $error_num += 1;
338
+                continue;
339
+            }
340
+            if(empty($query['question_title'])){
341
+                $v[6] = '题目为空';
342
+                $errors[] = $v;
343
+                $error_num += 1;
344
+                continue;
345
+            }
346
+            if(count($answers) < 2){
347
+                $v[6] = '选项少于2个';
348
+                $errors[] = $v;
349
+                $error_num += 1;
350
+                continue;
351
+            }
352
+            if(!in_array($query['correct_answer'], $answers)){
353
+                $v[6] = '答案不在选项中';
354
+                $errors[] = $v;
355
+                $error_num += 1;
356
+                continue;
357
+            }
358
+
359
+
360
+            $query['question_options'] = serialize($question_options);      //序列化
361
+            $query['create_time'] = time();
362
+            $query['update_time'] = time();
363
+
364
+            $res = Questions::insert($query);
365
+            if (!$res) {
366
+                DB::rollBack();
367
+                return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
368
+            }
369
+        }
370
+
371
+        DB::commit();
372
+
373
+        //错误记录存入redis
374
+        Redis::set(self::QUESTION_UPLOAD_FAIL.$params['activity_id'], json_encode($errors),'EX',3600);
375
+
376
+        $res = [];
377
+        $res['total']       = count($data);
378
+        $res['error_num']   = $error_num;
379
+        $res['success_num'] = $res['total'] - $error_num;
380
+        $res['category_id'] = $category_id;
381
+        return Api::arr(config('code.success'), trans('msg.success'), $res);
382
+    }
383
+
384
+    /**
385
+     * 删除题目
386
+     * 2018-06-22 10:32:00
387
+     * @param $params
388
+     * @return array
389
+     */
390
+    public static function delQuestion($params){
391
+        //题目信息
392
+        $questionInfo = Questions::where('activity_id', $params['activity_id'])
393
+                                ->where('corp_id', $params['corp_id'])
394
+                                ->where('category_id', $params['category_id'])
395
+                                ->where('question_id', $params['question_id'])
396
+                                ->where('status', 1)
397
+                                ->first();
398
+
399
+        if(!$questionInfo){
400
+            return Api::arr(config('code.question_not_exist'), trans('msg.question_not_exist'));
401
+        }
402
+
403
+        //删除题目
404
+        $res = Questions::where('activity_id', $params['activity_id'])
405
+                        ->where('corp_id', $params['corp_id'])
406
+                        ->where('category_id', $params['category_id'])
407
+                        ->where('question_id', $params['question_id'])
408
+                        ->where('status', 1)
409
+                        ->delete();
410
+
411
+        if($res){
412
+            return Api::arr(config('code.success'), trans('msg.success'));
413
+        } else {
414
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
415
+        }
416
+    }
417
+
418
+    /**
419
+     * 下载上传失败的题目数据
420
+     * @param $data
421
+     */
422
+    public static function downloadQuestionExcel($data){
423
+        $cellData = [
424
+            ['题目标题', 'A选项', 'B选项', 'C选项', 'D选项', '答案', '错误原因'],
425
+            ['填写规则'],
426
+        ];
427
+
428
+        foreach($cellData as $k=>$v){
429
+            array_unshift($data, $v);
430
+        }
431
+
432
+        Excel::create('题目导入错误数据'.date('mdHi'),function($excel) use ($data){
433
+            $excel->sheet('题目信息', function($sheet) use ($data){
434
+
435
+                $tot = count($data) ;
436
+                $sheet->setWidth(array(
437
+                    'A'     =>  50,
438
+                    'B'     =>  15,
439
+                    'C'     =>  15,
440
+                    'D'     =>  15,
441
+                    'E'     =>  15,
442
+                    'F'     =>  15,
443
+                    'G'     =>  15,
444
+                ))->rows($data)->setFontSize(12);
445
+
446
+                //设置第一行的表格格式
447
+                $sheet->setStyle([
448
+                    'font' => [
449
+                        'size' => 12,
450
+                        'bold' => false,
451
+                    ]
452
+                ])
453
+                    ->mergeCells('A1:G1')       //合并单元格
454
+                    ->setHeight(1, 100)         //设置行高
455
+                    ->setHeight(2, 30)
456
+                    ->cells('A1:G1', function($cells){          //设置单元格格式
457
+                        $cells->setValignment('center');         //文本对齐方式
458
+                        $cells->setFontWeight('bold');           //粗体
459
+                    })
460
+                    ->cells('A2:G2', function($cells){
461
+                        $cells->setValignment('center');
462
+                        $cells->setBackground('#92D050');
463
+                        $cells->setFontWeight('bold');
464
+                        $cells->setFontSize(10);
465
+                        $cells->setAlignment('center');
466
+                    })
467
+                    ->cells('B2:G'.$tot, function($cells) {
468
+                        $cells->setAlignment('center');
469
+                    })
470
+                    ->cells('G3:G'.$tot, function($cells) {
471
+                        $cells->setFontColor('#ff0000');
472
+                        $cells->setFontWeight('bold');
473
+                    });
474
+            });
475
+        })->export('xls');
476
+    }
477
+
478
+    /**
479
+     * 添加默认题库
480
+     * @param $activity_id
481
+     * @return array
482
+     */
483
+    public static function addDefault($activity_id){
484
+        $activity_info = ActivityService::getActivityInfo($activity_id);
485
+        if(!$activity_info){
486
+            return Api::arr(config('code.fail'), trans('msg.activity_not_exist'));
487
+        }
488
+
489
+        $default_questions = Questions::where('corp_id', 0)->where('activity_id', 0)->get()->toArray();
490
+        $query_category = [];
491
+        $query_category['corp_id']      = $activity_info['corp_id'];
492
+        $query_category['activity_id']  = $activity_id;
493
+        $query_category['category_name']  = '样例题库';
494
+        $query_category['create_time']  = time();
495
+        $query_category['update_time']  = time();
496
+
497
+        $res = Categorys::insertGetId($query_category);
498
+        if(!$res){
499
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
500
+        }
501
+
502
+        foreach($default_questions as $k=>$v){
503
+            $query_question = [];
504
+            $query_question['corp_id']      = $activity_info['corp_id'];
505
+            $query_question['activity_id']  = $activity_id;
506
+            $query_question['question_title'] = $v['question_title'];
507
+            $query_question['category_id']  = $res;
508
+            $query_question['question_options'] = $v['question_options'];
509
+            $query_question['correct_answer'] = $v['correct_answer'];
510
+            $query_question['create_time']  = time();
511
+            $query_question['update_time']  = time();
512
+            Questions::insert($query_question);
513
+        }
514
+
515
+        $data['category_id'] = $res;
516
+        return Api::arr(config('code.success'), trans('msg.success'), $data);
517
+    }
518
+
519
+    /**
520
+     * 删除题库(活动委发布状态才可删除)
521
+     * @param $activity_id
522
+     * @param $category_id
523
+     * @return array
524
+     */
525
+    public static function delCategory($activity_id, $category_id){
526
+        $activityInfo = ActivityService::getActivityInfo($activity_id);
527
+
528
+        if(!$activityInfo){
529
+            return Api::arr(config('code.fail'), trans('msg.activity_not_exist'));
530
+        }
531
+
532
+        if($activityInfo['is_complete_set'] == 1){
533
+            return Api::arr(config('code.fail'), '活动已发布,无法删除题库');
534
+        }
535
+
536
+        $categoryInfo = Categorys::where('category_id', $category_id)->first();
537
+        if(!$categoryInfo){
538
+            return Api::arr(config('code.fail'), trans('msg.category_not_exist'));
539
+        }
540
+
541
+        Categorys::where('category_id', $category_id)->delete();
542
+
543
+        $questions = Questions::where('category_id', $category_id)->get();
544
+        foreach($questions as $k=>$v){
545
+            Questions::where('question_id', $v['question_id'])->delete();
546
+        }
547
+
548
+        return Api::arr(config('code.success'), trans('msg.success'));
549
+    }
550
+}
551
+?>

+ 403 - 0
app/Services/UserService.php Целия файл

@@ -0,0 +1,403 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanl
5
+ * Date: 2018/6/8
6
+ * Time: 10:13
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Models\Apps;
12
+use App\Models\Configs;
13
+use App\Models\Departments;
14
+use App\Models\Users;
15
+use App\Models\Wechats;
16
+use DB;
17
+use Excel;
18
+use App\Common\Api;
19
+use Illuminate\Database\Eloquent\Model;
20
+use Illuminate\Support\Facades\Redis;
21
+
22
+class UserService
23
+{
24
+    public function __construct($configs = [])
25
+    {
26
+
27
+    }
28
+
29
+    const USER_UPLOAD_ERROR = 'bsb_user_upload_fail:';
30
+
31
+    /**
32
+     * 人员信息上传
33
+     * @param $data
34
+     * @return array
35
+     */
36
+    public static function userUpload($users, $activity_id, $corp_id){
37
+        $data['total']      = count($users);
38
+
39
+        //获取主键(phone)重复、号码格式不对的用户的信息集合
40
+        $userError = [];
41
+        $rphones =  collect($users)->groupBy(2)->filter(function ($value, $key) use (&$userError) {
42
+            $value = collect($value)->toArray();
43
+            $preg_str = '/^(1)\d{10}$/';
44
+            if(count($value)>1){
45
+                foreach($value as $k=>$v){
46
+                    $v[3] = "号码重复";
47
+                    $userError[] = $v;
48
+                }
49
+            }else{
50
+                //!empty($value[0][2]) &&
51
+//                if(!empty($value[0][2]) && preg_match($preg_str, $value[0][2]) == 0){
52
+//                    $value[0][3] = "号码格式错误";
53
+//                    $userError[] = $value[0];
54
+//                }
55
+            }
56
+
57
+//            return count($value)>1 || preg_match($preg_str, $value[0][2]) == 0;
58
+            return count($value)>1;
59
+        });
60
+
61
+        //获取剔除掉重复数据后的正确数据
62
+        $ydata = collect($users)->filter(function ($value, $key) use($rphones, &$userError) {
63
+            if(empty($value[0])){
64
+                $value[3] = "姓名为空";
65
+                $userError[] = $value;
66
+            }
67
+            if(empty($value[2])){
68
+                $value[3] = "电话号码为空";
69
+                $userError[] = $value;
70
+            }
71
+            //剔除条件  名字不为空、电话不为空、电话不重复
72
+            return !empty($value[0])&&!empty($value[2])&&!collect($rphones)->get($value[2]);
73
+        });
74
+
75
+        //错误数据并存入redis
76
+        Redis::set(self::USER_UPLOAD_ERROR.$activity_id, json_encode($userError), 'EX', 3600);
77
+
78
+        //获取用户信息和部门信息(避免多次连接数据库)
79
+        $departments = Departments::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('status', 1)->pluck('department_id', 'department_name')->toArray();
80
+        $users = Users::where('activity_id', $activity_id)->where('corp_id', $corp_id)->pluck('department_id', 'guid')->toArray();
81
+
82
+        $update_num = 0;
83
+        $user_query = [];
84
+        //正常数据入库
85
+        foreach($ydata as $k=>$v){
86
+            $name               = Api::trimAll($v[0]);
87
+            $department_name    = Api::trimAll($v[1]);
88
+            $phone              = Api::trimAll($v[2]);
89
+
90
+            //部门信息处理
91
+            if(empty($department_name)){
92
+                $department_id = '';
93
+            } else {
94
+                $is_department = array_key_exists($department_name, $departments);
95
+                if (!$is_department) {
96
+                    $department_query['department_name']    = $department_name;
97
+                    $department_query['activity_id']        = $activity_id;
98
+                    $department_query['corp_id']            = $corp_id;
99
+                    $department_query['update_time']        = time();
100
+                    $department_query['create_time']        = time();
101
+
102
+                    $department_id = Departments::insertGetId($department_query);
103
+                    if(!$department_id){
104
+                        return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
105
+                    }
106
+                    $departments[$department_name] = $department_id;                //部门信息重新赋值
107
+                } else {
108
+                    $department_id = $departments[$department_name];
109
+                }
110
+            }
111
+
112
+            //用户信息处理
113
+            $query = [];
114
+            $is_user = array_key_exists($phone, $users);
115
+            if($is_user){           //该guid已经在库里存在
116
+                $update_num += 1;
117
+
118
+                //更新用户信息
119
+                $query['department_id'] = $department_id;
120
+                $query['name']          = $name;
121
+                $query['status']        = 1;                //保证导入的用户状态为有效,如果库内的用户以无效,也改为有效
122
+                $query['update_time']   = time();
123
+                $res = Users::where('activity_id', $activity_id)->where('corp_id', $corp_id)->where('guid', $phone)->update($query);
124
+                if(!$res){
125
+                    return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
126
+                }
127
+
128
+            } else {                                            //新的用户
129
+                $query['activity_id']   = $activity_id;
130
+                $query['corp_id']       = $corp_id;
131
+                $query['guid']          = $phone;
132
+                $query['name']          = $name;
133
+                $query['department_id'] = $department_id;
134
+                $query['phone']         = $phone;
135
+                $query['update_time']   = time();
136
+                $query['create_time']   = time();
137
+                $user_query[] = $query;
138
+            }
139
+            $users[$phone] = $department_id;                                    //人员信息重新赋值
140
+        }
141
+
142
+        //将数据分组运行到mysql,增加效率
143
+        if(!empty($user_query)) {
144
+            $chunks = collect($user_query)->chunk(1000);
145
+            $chunks->toArray();
146
+            foreach ($chunks as $chunk) {
147
+                $values = collect($chunk)->map(function ($item, $key) {
148
+                        return "('".collect($item)->implode("','")."')";
149
+                    });
150
+
151
+                DB::select("insert into bs_users(`activity_id`,`corp_id`,`guid`,`name`,`department_id`,`phone`,`update_time`,`create_time`)VALUES".collect($values)->implode(",").";");
152
+            }
153
+        }
154
+
155
+        //遍历统计部门人数,为O的部门则软删除
156
+        foreach($departments as $department_id){
157
+            $userCount = Users::where('department_id', $department_id)->where('status', 1)->count();
158
+            if($userCount <= 0 ){
159
+                Departments::where('department_id', $department_id)->update(['status'=>0]);
160
+            }
161
+        }
162
+
163
+        //统计导入情况
164
+        $data['uploadSuccess']  = count($ydata);
165
+        $data['uploadFail']     = $data['total'] - $data['uploadSuccess'];
166
+        $data['insertNum']      = count($user_query);
167
+        $data['updateNum']      = $data['uploadSuccess']-$data['insertNum'];
168
+
169
+        $userAll = collect($ydata)->groupBy(1);
170
+        foreach($userAll as $key=>$value){
171
+            if(empty($key)){
172
+                $data['departmentCount']['其他'] = count($value);
173
+            } else {
174
+                $data['departmentCount'][$key] = count($value);
175
+            }
176
+        }
177
+
178
+        //清除人员redis缓存
179
+        $redisUsersKeys = Redis::keys('bs_users:*');
180
+        $dbUserIds = Users::where('activity_id', $activity_id)->pluck('user_id');
181
+        foreach ($redisUsersKeys as $redisUsersKey) {
182
+            $keys = explode(':', $redisUsersKey);
183
+            if(in_array($keys[1], collect($dbUserIds)->toArray())){
184
+                Redis::del('bs_users:'.$keys[1]);
185
+            }
186
+        }
187
+
188
+        //排行榜缓存清理
189
+        Redis::del('bs_top:users:km:'.$activity_id);
190
+        Redis::del('bs_top:users:pk:'.$activity_id);
191
+        Redis::del('bs_top:users:'.$activity_id);
192
+
193
+        return Api::arr(config('code.success'), trans('msg.success'), $data);
194
+    }
195
+
196
+    /**
197
+     * 删除人员(软删除)
198
+     * 2018-06-20 18:00:00
199
+     * @param $params
200
+     * @return array
201
+     */
202
+    public static function delUser($params){
203
+        $userInfo = Users::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('user_id', $params['user_id'])->first();
204
+        if(!$userInfo){
205
+            return Api::arr(config('code.user_not_exist'), trans('msg.user_not_exist'));
206
+        }
207
+
208
+        if(!empty($userInfo['open_id'])) {
209
+            Wechats::where('open_id',$userInfo['open_id']) -> delete();
210
+        }
211
+
212
+        $res = Users::where('activity_id', $params['activity_id'])->where('corp_id', $params['corp_id'])->where('user_id', $params['user_id'])->update(['status'=>0]);
213
+
214
+        if($res){
215
+            $user_num = Users::where('activity_id', $params['activity_id'])->where('status', 1)->count();
216
+            if($user_num <= 0){
217
+                Configs::where('activity_id', $params['activity_id'])->update(['is_user_upload'=>0]);
218
+            }
219
+            //清除人员缓存
220
+            Redis::del('bs_users:'.$params['user_id']);
221
+            Redis::zrem('bs_top:users:km:'.$params['activity_id'], $params['user_id']);
222
+            Redis::zrem('bs_top:users:pk:'.$params['activity_id'], $params['user_id']);
223
+            Redis::hdel('bs_top:users:'.$params['activity_id'], $params['user_id']);
224
+            return Api::arr(config('code.success'), trans('msg.success'));
225
+        } else {
226
+            return Api::arr(config('code.sql_error'), trans('msg.sql_error'));
227
+        }
228
+    }
229
+
230
+    /**
231
+     * 下载上传失败的人员数据
232
+     * @param $data
233
+     */
234
+    public static function downloadUserExcel($data){
235
+        $cellData = [
236
+            ['姓名', '部门', '手机号码', '错误原因'],
237
+            ['基本信息(红色为必填)'],
238
+            ['填写规则'],
239
+        ];
240
+
241
+        foreach($cellData as $k=>$v){
242
+            array_unshift($data, $v);
243
+        }
244
+
245
+        Excel::create('人员导入错误数据'.date('mdHi'),function($excel) use ($data){
246
+            $excel->sheet('人员信息', function($sheet) use ($data){
247
+
248
+                $tot = count($data) ;
249
+                $sheet->setWidth(array(
250
+                    'A'     =>  25,
251
+                    'B'     =>  25,
252
+                    'C'     =>  25,
253
+                    'D'     =>  25,
254
+                ))->rows($data)->setFontSize(12);
255
+
256
+                //设置第一行的表格格式
257
+                $sheet->setStyle([
258
+                    'font' => [
259
+                        'size' => 12,
260
+                        'bold' => false,
261
+                    ]
262
+                ])
263
+                    ->mergeCells('A1:D1')       //合并单元格
264
+                    ->mergeCells('A2:D2')
265
+                    ->setHeight(1, 100)         //设置行高
266
+                    ->setHeight(2, 30)
267
+                    ->setHeight(3, 30)
268
+                    ->cells('A1:D1', function($cells){          //设置单元格格式
269
+                        $cells->setValignment('center');         //文本对齐方式
270
+                        $cells->setFontWeight('bold');           //粗体
271
+                    })
272
+                    ->cells('A2:D2', function($cells){
273
+                        $cells->setValignment('center');
274
+                        $cells->setFontWeight('bold');
275
+                        $cells->setFontSize(10);
276
+                        $cells->setAlignment('center');
277
+                    })
278
+                    ->cells('A3:D3', function($cells){
279
+                        $cells->setValignment('center');
280
+                        $cells->setBackground('#92D050');
281
+                        $cells->setFontWeight('bold');
282
+                        $cells->setFontColor('#DD0806');
283
+                        $cells->setAlignment('center');
284
+                    })
285
+                    ->cells('A2:D'.$tot, function($cells) {
286
+                        $cells->setAlignment('center');
287
+                    })
288
+                    ->cells('B3', function($cells) {
289
+                        $cells->setFontColor('#000000');
290
+                    })
291
+                    ->cells('D3', function($cells) {
292
+                        $cells->setFontColor('#000000');
293
+                    })
294
+                    ->cells('D4:D'.$tot, function($cells) {
295
+                        $cells->setFontColor('#ff0000');
296
+                        $cells->setFontWeight('bold');
297
+                    });
298
+            });
299
+        })->export('xls');
300
+    }
301
+
302
+    /**
303
+     * 新增单个人员
304
+     * @param $params
305
+     * @return array
306
+     */
307
+    public static function addUser($params){
308
+        $activity_info = ActivityService::getActivityInfo($params['activity_id']);
309
+        if(!$activity_info){
310
+            return Api::arr(config('code.activity_not_exist'), trans('msg.activity_not_exist'));
311
+        }
312
+
313
+        $query = [];
314
+        if(isset($params['department_name']) && !empty($params['department_name'])) {
315
+            $department_info = Departments::where('department_name', $params['department_name'])->where('activity_id', $params['activity_id'])->first();
316
+            if ($department_info) {
317
+                $query['department_id'] = $department_info['department_id'];
318
+            } else {
319
+                $department_query['department_name'] = $params['department_name'];
320
+                $department_query['activity_id'] = $params['activity_id'];
321
+                $department_query['corp_id'] = $params['corp_id'];
322
+                $department_query['create_time'] = time();
323
+                $department_query['update_time'] = time();
324
+                $query['department_id'] = Departments::insertGetId($department_query);
325
+            }
326
+        } else {
327
+            $query['department_id'] = 0;
328
+        }
329
+
330
+        $query['activity_id']   = $params['activity_id'];
331
+        $query['corp_id']       = $params['corp_id'];
332
+        $query['name']          = $params['name'];
333
+        $query['guid']          = Api::trimAll($params['phone']);
334
+        $query['phone']         = Api::trimAll($params['phone']);
335
+        $query['update_time']   = time();
336
+        $query['status']        = 1;
337
+        $query['open_id']       = null;
338
+        $query['nickname']      = null;
339
+
340
+        $user_info = Users::where('guid', Api::trimAll($params['phone']))->where('activity_id', $params['activity_id'])->orderByDesc('status')->first();
341
+        if($user_info){
342
+            $res = Users::where('user_id', $user_info['user_id'])->update($query);
343
+
344
+            //排行榜缓存清理
345
+            Redis::del('bs_top:users:km:'.$params['activity_id']);
346
+            Redis::del('bs_top:users:pk:'.$params['activity_id']);
347
+            Redis::del('bs_top:users:'.$params['activity_id']);
348
+        } else {
349
+            $query['create_time']   = time();
350
+            $res = Users::insert($query);
351
+        }
352
+        if($res){
353
+            Configs::where('activity_id', $params['activity_id'])->update(['is_user_upload'=>1]);
354
+            return Api::arr(config('code.success'), trans('msg.success'));
355
+        } else {
356
+            return Api::arr(config('code.fail'), trans('msg.sql_error'));
357
+        }
358
+    }
359
+
360
+    /**
361
+     * 修改人员信息
362
+     * @param $params
363
+     * @return array
364
+     */
365
+    public static function ModifyUser($params){
366
+        $query = [];
367
+        $query['name'] = $params['name'];
368
+        $query['guid'] = $params['phone'];
369
+        $query['phone'] = $params['phone'];
370
+        $query['update_time'] = time();
371
+        $isRepeatUser = Users::where('user_id', '!=', $params['user_id'])->where('activity_id', $params['activity_id'])->where('guid', $params['phone'])->first();
372
+        if($isRepeatUser){
373
+            return Api::arr(config('code.fail'), '号码:'.$params['phone'].'已存在,请重新修改!');
374
+        }
375
+
376
+        //部门信息处理
377
+        if(isset($params['department_name']) && !empty($params['department_name'])) {
378
+            $department_info = Departments::where('department_name', $params['department_name'])->where('activity_id', $params['activity_id'])->first();
379
+            if ($department_info) {
380
+                $query['department_id'] = $department_info['department_id'];
381
+            } else {
382
+                $department_query['department_name'] = $params['department_name'];
383
+                $department_query['activity_id'] = $params['activity_id'];
384
+                $department_query['corp_id'] = $params['corp_id'];
385
+                $department_query['create_time'] = time();
386
+                $department_query['update_time'] = time();
387
+                $query['department_id'] = Departments::insertGetId($department_query);
388
+            }
389
+        } else {
390
+            $query['department_id'] = 0;
391
+        }
392
+
393
+//        return Api::arr(config('code.success'), trans('msg.success'), $query);
394
+
395
+        $res = Users::where('user_id', $params['user_id'])->update($query);
396
+        if($res){
397
+            return Api::arr(config('code.success'), trans('msg.success'));
398
+        } else {
399
+            return Api::arr(config('code.fail'), trans('msg.sql_error'));
400
+        }
401
+    }
402
+}
403
+?>

+ 29 - 0
app/User.php Целия файл

@@ -0,0 +1,29 @@
1
+<?php
2
+
3
+namespace App;
4
+
5
+use Illuminate\Notifications\Notifiable;
6
+use Illuminate\Foundation\Auth\User as Authenticatable;
7
+
8
+class User extends Authenticatable
9
+{
10
+    use Notifiable;
11
+
12
+    /**
13
+     * The attributes that are mass assignable.
14
+     *
15
+     * @var array
16
+     */
17
+    protected $fillable = [
18
+        'name', 'email', 'password',
19
+    ];
20
+
21
+    /**
22
+     * The attributes that should be hidden for arrays.
23
+     *
24
+     * @var array
25
+     */
26
+    protected $hidden = [
27
+        'password', 'remember_token',
28
+    ];
29
+}