SysUserService.cs
17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
using Hh.Mes.Common;
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Redis;
using Hh.Mes.Common.Request;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.Repository;
using Hh.Mes.Service.SystemAuth;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Hh.Mes.Service.WebService.Base
{
/// <summary>
/// 关联服务(用户角色、角色权限、用户权限、用户部门等等)
/// </summary>
public class SysUserService : RepositorySqlSugar<SysUser>
{
private IAuth authUtil;
private SysRelevanceService sysRelevanceService;
public SysUserService(IAuth authUtil, SysRelevanceService sysRelevanceService) : base()
{
this.authUtil = authUtil;
this.sysRelevanceService = sysRelevanceService;
}
/// <summary>
/// 拼接where条件
/// </summary>
/// <param name="userIds"></param>
/// <param name="Name"></param>
/// <param name="Idcard"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public Expression<Func<SysUser, bool>> LinqWhere(List<int> userIds, string Name, string Idcard)
{
try
{
var exp = Expressionable.Create<SysUser>();
exp.And(t => userIds.Contains(t.Id) && t.Account != "System");
if (!string.IsNullOrWhiteSpace(Name)) exp.And(t => t.Name.Contains(Name));
if (!string.IsNullOrWhiteSpace(Idcard)) exp.And(t => t.Idcard.Contains(Idcard));
return exp.ToExpression();//拼接表达式
}
catch (Exception ex)
{
throw new Exception($"{ex.Message}");
}
}
/// <summary>
/// 加载当前登录用户可访问的一个部门及子部门全部用户
/// </summary>
public dynamic Load(PageReq request, int? orgId, string Name, string Idcard)
{
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var response = new Response();
var loginUser = authUtil.GetCurrentUser();
//根据部门ID获取分支ID
string cascadeId = ".0.";
if (orgId != null)
{
var org = loginUser.Orgs.SingleOrDefault(u => u.Id == orgId.Value);
cascadeId = org.CascadeId;
}
//根据分支ID找出下属的部门ID
var ids = loginUser.Orgs.Where(u => u.CascadeId.StartsWith(cascadeId)).Select(u => u.Id).ToArray();
//根据所有的部门ID,找出对应的用户ID
var userIds = Context.Queryable<SysRelevance>()
.Where(u => u.RelKey == Define.USERORG && ids.Contains(u.SecondId.Value))
.Select(u => u.FirstId.Value)
.ToList();
//用户ID去重
userIds = userIds.Distinct().ToList();
//找出用户和部门的关联
var relevances = Context.Queryable<SysRelevance>()
.Where(u => u.RelKey == Define.USERORG && userIds.Contains(u.FirstId.Value))
.ToList();
var deptIds = relevances.Select(t => t.SecondId).Distinct().ToList();
//根据用户ID,找出对应的部门ID
var depts = Context.Queryable<SysDept>().Where(u => deptIds.Contains(u.Id)).ToList();
//动态拼接表达式
var expression = LinqWhere(userIds, Name, Idcard);
var records = 0;
var users = Context.Queryable<SysUser>()
.Where(expression)
.OrderBy(u => u.Name)
.ToOffsetPage(request.page, request.limit, ref records);
var userViews = new List<SysUserView>();
foreach (var user in users)
{
//查询用户的所有组织ID
var userDeptIds = relevances.Where(t => t.FirstId == user.Id).Select(t => t.SecondId).ToList();
//根据组织ID查询所有组织信息
var orgs = depts.Where(t => userDeptIds.Contains(t.Id)).ToList();
SysUserView uv = user;
uv.Organizations = string.Join(",", orgs.Select(u => u.Name).ToList());
uv.OrganizationIds = string.Join(",", orgs.Select(u => u.Id).ToList());
uv.FaceID = user.FaceID;
uv.Idcard = user.Idcard;
uv.FacePicture = user.FacePicture;
uv.PhoneNumber = user.PhoneNumber;
uv.PassWord = null;
userViews.Add(uv);
}
response.Count = records;
response.Result = userViews;
return response;
});
}
public dynamic Ins(SysUserView view)
{
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var response = new Response();
if (string.IsNullOrEmpty(view.OrganizationIds))
{
throw new Exception("请为用户分配机构");
}
if (Context.Queryable<SysUser>().Any(u => u.Account == view.Account))
{
throw new Exception("账号已存在");
}
if (Context.Queryable<SysUser>().Any(u => u.Name == view.Name))
{
throw new Exception("用户名已存在");
}
SysUser user = view;
user.Password = Encryption.Encrypt(user.Password); //密码加密
user.CreateBy = sysWebUser?.Account;
user.CreateTime = DateTime.Now;
int[] orgIds = Array.ConvertAll(view.OrganizationIds.Split(','), int.Parse);
//用户和组织的关联
List<SysRelevance> list = new List<SysRelevance>();
foreach (var item in orgIds)
{
var sysRelevance = new SysRelevance
{
RelKey = Define.USERORG,
SecondId = item,
CreateBy = sysWebUser?.Account,
CreateTime = DateTime.Now
};
list.Add(sysRelevance);
}
var result = Context.Ado.UseTran(() =>
{
//插入用户到数据库
user.Id = Context.Insertable(user).ExecuteReturnIdentity();
//user.Id插入后才会产生,才能赋值
list.ForEach(t => t.FirstId = user.Id);
//删除用户对应的所有组织
Context.Deleteable<SysRelevance>(t => t.FirstId == user.Id && t.RelKey == Define.USERORG).ExecuteCommand();
//新增用户对应的所有组织
Context.Insertable(list).ExecuteCommand();
});
if (result.IsSuccess == false)
{
return response.ResponseError(result.ErrorMessage);
}
//要把保存后的ID存入view
view.Id = user.Id;
return response;
});
}
public dynamic Upd(SysUserView view)
{
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var response = new Response();
if (string.IsNullOrEmpty(view.OrganizationIds))
{
throw new Exception("请为用户分配机构");
}
SysUser user = view;
user.UpdateBy = sysWebUser?.Account;
user.UpdateTime = DateTime.Now;
int[] orgIds = Array.ConvertAll(view.OrganizationIds.Split(','), int.Parse);
//用户和组织的关联
List<SysRelevance> list = new List<SysRelevance>();
foreach (var item in orgIds)
{
var sysRelevance = new SysRelevance
{
RelKey = Define.USERORG,
FirstId = user.Id,
SecondId = item,
CreateBy = sysWebUser?.Account,
CreateTime = DateTime.Now
};
list.Add(sysRelevance);
}
var result = Context.Ado.UseTran(() =>
{
//更新用户信息
Context.Updateable(user).UpdateColumns(t => new { t.Account, t.Name, t.Sex, t.PhoneNumber, t.Status, t.UpdateBy, t.UpdateTime }).ExecuteCommand();
//删除用户对应的所有组织
Context.Deleteable<SysRelevance>(t => t.FirstId == user.Id && t.RelKey == Define.USERORG).ExecuteCommand();
//新增用户对应的所有组织
Context.Insertable(list).ExecuteCommand();
});
if (result.IsSuccess == false)
{
return response.ResponseError(result.ErrorMessage);
}
//清空用户的redis授权缓存,这样用的时候就会自动从数据库更新一次
var cl = new RedisBase();
if (cl.redisClient.Exists(view.Account))
{
cl.redisClient.Del(view.Account);
}
return response;
});
}
public dynamic DeleteById(int[] ids)
{
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var response = new Response();
var relkeyList = new string[] { Define.USERROLE, Define.USERORG, Define.USERELEMENT, Define.USERMODULE };
//清空被删除用户的Redis缓存
var userOnlineList = Context.Queryable<sys_user_online>().Where(t => ids.Contains(t.id)).ToList();
var cl = new RedisBase();
foreach (var item in userOnlineList)
{
if (cl.redisClient.Exists(item.account))
{
cl.redisClient.Del(item.account);
}
if (cl.redisClient.Exists(item.token))
{
cl.redisClient.Del(item.token);
}
}
Context.Deleteable<SysRelevance>().Where(t => ids.Contains(t.FirstId.Value) && relkeyList.Contains(t.RelKey)).AddQueue();
Context.Deleteable<SysUser>().In(ids).AddQueue();
if (ExecuteQueues(Context) <= 0)
{
return response.ResponseError(SystemVariable.dataActionError);
}
return response;
});
}
/// <summary>
/// 修改个人密码
/// </summary>
/// <param name="OldPassword"></param>
/// <param name="Password"></param>
/// <param name="CurrentUser"></param>
/// <exception cref="Exception"></exception>
public dynamic ChangeUserPassword(string OldPassword, string Password, SysUser CurrentUser)
{
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var response = new Response();
SysUser user = CurrentUser;
if (user.Password.Equals(Encryption.Encrypt(OldPassword)))
{
if (OldPassword == Password)
{
throw new Exception("新密码不应与旧密码相同");
}
else
{
user.Password = Encryption.Encrypt(Password);
var result = Context.Updateable(user)
.UpdateColumns(t => t.Password)
.ExecuteCommand();
if (result <= 0)
{
return response.ResponseError(SystemVariable.dataActionError);
}
}
}
else
{
throw new Exception("旧密码不正确");
}
return response;
});
}
/// <summary>
/// 重设用户密码
/// </summary>
/// <param name="currentUser"></param>
public dynamic ResetPassword(SysUser currentUser)
{
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var response = new Response();
currentUser.Password = ConfigRead.GetInstance.GetAppsetConnection().ResetPwd ;
if (string.IsNullOrEmpty(currentUser.Password)) return response.ResponseError("配置文件属性【ResetPwd】不存在或者值为空,请核实!");
var result = Context.Updateable(currentUser)
.UpdateColumns(t => t.Password)
.ExecuteCommand();
if (result <= 0)
{
return response.ResponseError(SystemVariable.dataActionError);
}
return response;
});
}
/// <summary>
///
/// </summary>
/// <param name="account"></param>
/// <returns></returns>
public SysUser GetByAccount(string account)
{
return Context.Queryable<SysUser>().First(t => t.Account == account);
}
/// <summary>
/// 创建绑定登录方式
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public string CreateBinding(string user, string userImage, string jobCard)
{
return "";
}
/// <summary>
/// //获取列表
/// </summary>
public Response LoadUserListByTeamCode(string teamCode)
{
var result = new Response();
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($@" SELECT t1.*
FROM sys_user t1
inner join base_team_user_rel t2 on t1.id=t2.userId
where t2.teamCode=@teamCode ");
var dt = base.Context.Ado.GetDataTable(stringBuilder.ToString(), new List<SugarParameter>(){
new SugarParameter("@teamCode",teamCode)
});
result.Result = dt;
result.Count = dt.Rows.Count;
return result;
}
public dynamic BindUserClient(string userAccount, bool checkeds, Guid clientKeys)
{
var response = new Response();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
if (checkeds)
{
bool isHave = Context.Queryable<sys_user_client_rel>().Any(x => x.userAccount == userAccount);
if(isHave && Context.Queryable<sys_user_client_rel>().Where(x => x.userAccount == userAccount).First().clientKeys != clientKeys)
{
response.Status = false;
response.Message = "该用户已经绑定客户,如需更改客户绑定,请先取消绑定的现有客户";
return response;
}
Context.Deleteable<sys_user_client_rel>().Where(i => i.userAccount == userAccount && i.clientKeys == clientKeys).ExecuteCommand();
var model = new sys_user_client_rel();
model.userAccount = userAccount;
model.clientKeys = clientKeys;
Context.Insertable(model).AddQueue();
response.Status = Context.SaveQueues() > 0;
if (!response.Status)
{
response.Message = "用户绑定客户失败";
}
}
else
{
Context.Deleteable<sys_user_client_rel>().Where(i => i.userAccount == userAccount && i.clientKeys == clientKeys).AddQueue();
response.Status = Context.SaveQueues() > 0;
if (!response.Status)
{
response.Message = "取消该用户绑定的客户失败!";
}
}
return response;
});
}
public dynamic GetUserBindClient(string userAccount)
{
var response = new Response();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
response.Result = Context.Queryable<sys_user_client_rel>().Where(x => x.userAccount == userAccount).ToList();
return response;
});
}
}
}