username@email.com
2023-09-06 f7ff76aeadd7d92da92ee65ed658b636fa4e8036
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
437
438
439
440
441
442
443
using DocumentServiceAPI.Application.Repository;
using DocumentServiceAPI.Application.UserAndLogin.Services.Interfaces;
using DocumentServiceAPI.Application.UserAndLogin.ViewMode;
using DocumentServiceAPI.Model;
using DocumentServiceAPI.Model.cyDocumentModel;
using DocumentServiceAPI.Model.Permissions;
using DocumentServiceAPI.Model.UserInfoModel;
using DocumentServiceAPI.Services.IService;
using DocumentServiceAPI.Utility;
using Furion.Logging.Extensions;
using MapsterMapper;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
 
namespace DocumentServiceAPI.Application.UserAndLogin.Services
{
 
    /// <summary>
    /// 登录验证服务
    /// </summary>
    public class UserService : IUserService, IScoped
    {
        /// <summary>
        /// TenantPermissions在Redis中的键值
        /// </summary>
        public const string TenantPermissions_RedisKey = "TenantPermissionsKen:";
        private ISqlSugarClient _db { get; set; }
        private EmployeeRepository  _employeeRepository{ get; set; }
        private IMapper _mapper {  get; set; }
        private IRedisCacheService _cacheService { get; set; }
 
        public UserService(ISqlSugarClient db, EmployeeRepository employeeRepository, IMapper mapper , IRedisCacheService cacheService)
        {
            _db = db;
            _employeeRepository = employeeRepository;
            _mapper = mapper;
            _cacheService = cacheService;
        }
        /// <summary>
        /// 员工详情
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="TenantID"></param>
        /// <returns></returns>
        public async Task<EmployeeTenantInfo> GetEmployeeInfo(int ID, int TenantID)
        {
            var ret = await _db.Queryable<EmployeeInfo, EmployeeAtTenant, TenantInfo>((ei, eiat, ti) =>
              new JoinQueryInfos(
      JoinType.Right, ei.Id == eiat.EmployeeID, //左连接 左链接 左联 
      JoinType.Right, ti.Id == eiat.TenantID
                              )).Where((ei, eiat, ti) => ei.Id == ID && TenantID == ti.Id)
                              .Select(expression: (ei, eiat, ti) => new EmployeeTenantInfo
                              {
                                  _employeeInfo = ei,
                                  _tenantInfo = ti
 
                              }).SingleAsync();
 
            return ret;
        }
 
        /// <summary>
        /// 获取Jwt相关信息
        /// </summary>
        public JwtInfo GetJwtInfo()
        {
            JwtInfo jwtInfo = new JwtInfo();
            jwtInfo.LogInSource = (LogInFrom)(App.User?.FindFirstValue("loginfrom")?.ObjToInt() ?? 0);
            jwtInfo.EID = App.User?.FindFirstValue("eid")?.ObjToInt();
            jwtInfo.UID = App.User?.FindFirstValue("uid")?.ObjToInt();
            jwtInfo.TEID = App.User?.FindFirstValue("teid")?.ObjToInt();
            var guid = App.User?.FindFirstValue("jid");
            jwtInfo.JID = string.IsNullOrEmpty(guid) ? null: new Guid(guid);
            return jwtInfo;
        }
   
        /// <summary>
        /// 获取单位列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UnitVM>> GetUserUnitList(int  tid )
        {
 
            var list = await _db.Queryable<DocumentServiceAPI.Model.cyDocumentModel.Document_TenderUnit>()
                   .Where((tu) => tu.TenantId == tid && tu.IsEn == true && tu.IsDeled != true)
                   .Select((tu) => new UnitVM
                   {
                       UnitID = tu.UnitId,
                       UnitName = tu.UnitName,
                       Remark = tu.Remark,
                       UnitLogo = tu.UnitLogo,
                   }).WithCache(10)
                   .ToListAsync();
            return list;
        }
 
        /// <summary>
        /// 根据账号获取 Tender 列表
        /// </summary>
        /// <param name="ItCode"></param>
        /// <returns></returns>
        public async Task<List<TenderVM>> GetUserTenderList(string ItCode)
            
        {
          
            var tentlist= await _db.Queryable<TenantInfo, EmployeeAtTenant, Document_EmployeeInfo>((ti, et, ei) =>
 
              new JoinQueryInfos
              (
                 JoinType.Right, ti.Id == et.TenantID, //左连接 左链接 左联 
             JoinType.Right, ei.EmployeeId == et.EmployeeID
                  )
             )
                .Where((ti, et, ei) =>
              ( ei.UserName == ItCode) && (ti.IsEn == true) && (ti.IsDel != true) && (ei.IsWork == null || ei.IsWork == 1))
 
             .Select((ti, et, ei) => new TenderVM
             {
                 EmployeeID = ei.EmployeeId,
                 Description = ti.Description,
                 ItCode = ItCode,
                 Name = ti.Name,
                 TenderId = ti.Id
                 
             }
              ).WithCache( 10).ToListAsync();
            //不再选择租户
            //var ten = await _db.Queryable<TenantInfo>().Where(x => x.IsEn == true && x.IsDel != true && x.ItCode == ItCode)
            //       .Select(x => new TenderVM
            //       {
 
            //           Description = x.Description,
            //           ItCode = ItCode,
            //           Name = x.Name,
            //           TenderId = x.Id,
            //           IsTender = true
 
            //       }
            //  ).WithCache(10).ToListAsync()  ;
            //ten.AddRange(tentlist);
            return tentlist;
 
        }
 
        /// <summary>
        /// 检查密码是否登录
        /// </summary>
        /// <param name="TenantID"> 租户ID</param>
        /// <param name="employeeID">员工ID</param>
        /// <param name="PsW">密码</param>
        /// <returns></returns>
        public async Task<bool> CheckPsw(int TenantID, int? employeeID, string PsW)
        {
            if (employeeID == null)
            {
                var psw = await _db.Queryable<TenantInfo>().Where(x => x.Id == TenantID).Select(x => x.PsW).SingleAsync();
                if (PsW == psw)
                    return true;
            }
            else
            {
                var psw = await _db.Queryable<Document_EmployeeInfo, EmployeeAtTenant, TenantInfo>((ei, et, ti) =>
 
             new JoinQueryInfos
             (
                JoinType.Left, ei.EmployeeId == et.EmployeeID, //左连接 左链接 左联 
            JoinType.Left, ti.Id == et.TenantID
                 )
            ).Where((ei, et, ti) =>
 
                ei.EmployeeId == employeeID && ti.Id == TenantID
            )
            .Select((ei, et, ti) => ei.UserPassWord)
            .SingleAsync();
                if (PsW == psw)
                    return true;
            }
            return false;
 
        }
 
 
        /// <summary>
        /// 获取用户详情,包括员工信息,租户信息,单位信息
        /// </summary>
        /// <param name="TenantID"> 租户ID</param>
        /// <param name="EmployeeID">员工ID </param>
        /// <param name="UnitID">单位ID</param>
        /// <returns></returns>
        public async Task<RetUserInfo> GetUserInfo(int? TenantID,int? EmployeeID,int?  UnitID)
        {
            TenderInfoVM Tenant = null;
            EmployeeInfoVM Employee = null;
            if (TenantID != null)
             Tenant = await _db.Queryable<TenantInfo>().Where(x => x.Id == TenantID)
                 .Select(x => new TenderInfoVM
                 {
                     Description = x.Description,
                     Id = x.Id,
                     ItCode = x.ItCode,
                     Name = x.Name,
                     ReMark = x.ReMark,
                 }).WithCache(20).FirstAsync();
            if (EmployeeID != null)
                Employee = await _db.Queryable<Document_EmployeeInfo>().Where(x => x.EmployeeId == EmployeeID)
                .Select(x => new EmployeeInfoVM
                { AdviseFlag = x.AdviseFlag,
                 CardPositive = x.CardPositive,
                  CardPositiveSize = x.CardPositiveSize,
                   CardPositiveVersionNo = x.CardPositiveVersionNo,
                    EmployeeId = x.EmployeeId,
                     EmployeeName = x.EmployeeName,                     
                     Job = x.Job,
                      LastUpdateName = x.LastUpdateName,
                       UserName = x.UserName,
                        IsLogin = x.IsLogin,
                      
                   
                }).WithCache(20).FirstAsync();
            UnitInfoVM Unit = null;
            if (UnitID != null)
                 Unit = await _db.Queryable<Model.cyDocumentModel.Document_TenderUnit>().Where(x => x.UnitId == UnitID)
              .Select(x => new UnitInfoVM
              {
                   FirmQualificationLevel = x.FirmQualificationLevel,
                    Fax = x.Fax,
                       CorporaterTechnicalPost= x.CorporaterTechnicalPost,
                        LastUpdateName= x.LastUpdateName,
                         Address = x.Address,
                          AdviseFlag = x.AdviseFlag, BankNum = x.BankNum,
                           BusinessContent = x.BusinessContent,
                            BusinessLicense = x.BusinessLicense,
                             CardPositive= x.CardPositive,
                              CardPositiveSize= x.CardPositiveSize,
                               CardPositiveVersionNo= x.CardPositiveVersionNo,
                                ContactPerson= x.ContactPerson,
                                 ContactPhone= x.ContactPhone,
                                  CorporatePhone= x.CorporatePhone,
                                   Corporater= x.Corporater,
                                    CorporaterPost= x.CorporaterPost,
                                     CreatTime= x.CreatTime,
                                      Mechanicer= x.Mechanicer,
                                       MiddleStaff= x.MiddleStaff,
                                        OpenBank= x.OpenBank,
                                         OrgStructure= x.OrgStructure,
                                          PrimaryStaff= x.PrimaryStaff,
                                           ProjectManager= x.ProjectManager,
                                            RegMoney= x.RegMoney,
                                             Remark= x.Remark,
                                              UnitId= x.UnitId,
                                               TechnicalLeader= x.TechnicalLeader,
                                                 SeniorStaff= x.SeniorStaff,
                                                  StaffCount= x.StaffCount,
                                                   TechnicalPhone= x.TechnicalPhone,
                                                    TechnicalPost= x.TechnicalPost,
                                                     UnitLogo= x.UnitLogo,
                                                      UnitLogoSize= x.UnitLogoSize, 
                                                       UnitLogoVersionNo= x.UnitLogoVersionNo,
                                                        UnitName= x.UnitName,
                                                         UnitType= x.UnitType,
                                                          WebUrl= x.WebUrl,
                                                           ZipCode= x.ZipCode,
                                                            
 
 
 
              }).WithCache(20).FirstAsync();
 
 
            return new RetUserInfo
            {
                EmployeeInfo = Employee,
                TenderInfo = Tenant,
                UnitInfo = Unit
            };
        }
 
        /// <summary>
        /// 获取员工列表
        /// </summary>
        /// <param name="_businessService"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task<PageResult<EmployeeInfoVM>> postEmployeeList( EmployeePageSearch page)
        {
            var a = GetJwtInfo();
            if(a.EID!=null)
                throw Oops.Oh($"没有权限");
            SqlSugar.PageModel pg = new SqlSugar.PageModel();
            pg.PageSize = page.PageSize;
            pg.PageIndex = page.PageIndex;
            RefAsync<int> total = 0;
            PageResult<EmployeeInfoVM> result = new PageResult<EmployeeInfoVM>();
            result.Items = await _db.Queryable<EmployeeAtTenant, Document_EmployeeInfo>((et, ei) =>
             new JoinQueryInfos(JoinType.Left, et.EmployeeID==ei.EmployeeId
                 )).Where((ei,et)=>ei.TenantID==a.TEID)
                 .Select((ei,et)=>new EmployeeInfoVM
                 {
                      EmployeeId = et.EmployeeId,
                       AdviseFlag=et.AdviseFlag,
                        CardPositive=et.CardPositive,
                         CardPositiveSize=et.CardPositiveSize,
                          CardPositiveVersionNo=et.CardPositiveVersionNo,
                           EmployeeName=et.EmployeeName,
                            IsWork=et.IsWork,
                             Job=et.Job,
                              LeaveTime=et.LeaveTime,
                               Phone=et.Phone,                            
                                  UserId=et.UserId,
                                   UserName=et.UserName,
                                    
 
 
 
 
                 }).MergeTable().OrderBy(x=>x.EmployeeId).ToPageListAsync(page.PageIndex,page.PageSize, total);
 
            result.TotalCount = pg.TotalCount;
            return result;
        }
 
 
 
 
        public async Task<bool > UpEmployee(EmployeeInfoVM vm)
        {
      
            var jwtinfo = GetJwtInfo();
 
            if (jwtinfo.EID != null)
                throw Oops.Oh($"没有权限");
            var info = await GetUserInfo(jwtinfo.TEID, null, null);
            Document_EmployeeInfo a =  _mapper.Map<Document_EmployeeInfo>(vm);
           
            a.LastUpdateName = info.EmployeeInfo.UserName;
            a.LastUpdateTime = DateTime.Now;
 
             return await   _employeeRepository.UpdateAsync(a);  
 
        }
 
        public async Task<bool> InEmployee(EmployeeInfoVM vm)
        {
            var jwtinfo = GetJwtInfo();
            if (jwtinfo.EID != null)
                throw Oops.Oh($"没有权限");
            Document_EmployeeInfo a = _mapper.Map<Document_EmployeeInfo>(vm);
 
            var info = await GetUserInfo(jwtinfo.TEID, null, null);
            EmployeeAtTenant elt = new EmployeeAtTenant
            {
                CreatBy = info.TenderInfo.ItCode,
                CreatTime = DateTime.Now,
                TenantID = info.TenderInfo.Id,
 
 
 
            };
            try
            {
             await   _employeeRepository.AsTenant().BeginTranAsync();
              var jwtId=   await _employeeRepository.InsertReturnIdentityAsync(a);
                elt.EmployeeID = jwtId;
                await _db.Insertable(elt).ExecuteCommandAsync();
 
              await  _employeeRepository.AsTenant().CommitTranAsync();
 
            }
            catch (Exception e)
            {
 
                await _employeeRepository.AsTenant().RollbackTranAsync();
                //写日志
               $"   插入新员工失败, 错误消息:{e.Message} \r\n 堆栈错误:{e.StackTrace}" .LogInformation();
                throw Oops.Oh("新增失败");
            }
           
             return await  _employeeRepository.InsertAsync(a);
 
 
 
 
 
        }
 
        /// <summary>
        /// 租户是否已经超时过期
        /// </summary>
        /// <param name="TenderID">租户ID</param>
        /// <returns> true 代表没有超时有权限使用,false 代表没有权限使用了</returns>
        public async Task<bool> TenderHasPermissions( int TenderID)
        {
            var Key = TenantPermissions_RedisKey + TenderID.ToString();
          var tp=  _cacheService.Get<TenantPermissions>(TenantPermissions_RedisKey+ TenderID.ToString());
            if(tp == null )
            {
               tp= await  _db.Queryable<TenantPermissions>().Where(x=>x.TenantId == TenderID).FirstAsync();
                if (tp != null)
                    _cacheService.Add<TenantPermissions>(Key, tp, 300);
                else
                    return false;
            }
            if (tp.OverTime > DateTime.Now)
                return true;
            return false;
 
        }
        /// <summary>
        /// 租户是否已经超时过期 根据token中包含的TID 识别是否有权限
        /// </summary>       
        /// <returns> true 代表没有超时有权限使用,false 代表没有权限使用了</returns>
        public async Task<bool> TenderHasPermissions()
        {
            var jwtinfo= GetJwtInfo();
            if(jwtinfo != null&&jwtinfo.TEID!=null )
            {
                var Key = TenantPermissions_RedisKey + jwtinfo.TEID.ToString();
                var tp = _cacheService.Get<TenantPermissions>(TenantPermissions_RedisKey + jwtinfo.TEID.ToString());
                if (tp == null)
                {
                    tp = await _db.Queryable<TenantPermissions>().Where(x => x.TenantId == jwtinfo.TEID).FirstAsync();
                    if (tp == null)
                        _cacheService.Add<TenantPermissions>(Key, tp, 300);
                    else
                        return false;
                }
                
                if (tp.OverTime > DateTime.Now)
                    return true;
                return false;
            }
            return false;
        }
 
    }
 
 
}