UserService.php 16KB

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