AuthController.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. using Microsoft.AspNetCore.SignalR;
  2. using OASystem.API.OAMethodLib;
  3. using OASystem.API.OAMethodLib.Hotmail;
  4. using OASystem.API.OAMethodLib.Hub.HubClients;
  5. using OASystem.API.OAMethodLib.Hub.Hubs;
  6. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  7. using OASystem.Domain.AesEncryption;
  8. using OASystem.Domain.Attributes;
  9. using OASystem.Domain.Dtos.UserDto;
  10. using OASystem.Domain.Entities.Customer;
  11. using OASystem.Domain.Entities.Groups;
  12. using OASystem.Infrastructure.Repositories.Login;
  13. using System.IdentityModel.Tokens.Jwt;
  14. using System.Text.Json;
  15. using static OASystem.API.OAMethodLib.Hotmail.HotmailService;
  16. using static OASystem.API.OAMethodLib.JWTHelper;
  17. namespace OASystem.API.Controllers
  18. {
  19. /// <summary>
  20. /// 鉴权相关
  21. /// </summary>
  22. [Route("api/")]
  23. public class AuthController : ControllerBase
  24. {
  25. private readonly IMapper _mapper;
  26. private readonly IConfiguration _config;
  27. private readonly LoginRepository _loginRep;
  28. private readonly MessageRepository _message;
  29. private readonly SystemMenuPermissionRepository _sysMenuPermRep;
  30. private readonly MessageRepository _messageRep;
  31. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  32. private readonly IHubContext<ChatHub, IChatClient> _hubContext;
  33. private readonly DeviceTokenRepository _deviceTokenRep;
  34. private readonly HotmailService _hotmailService;
  35. private readonly System.Net.Http.IHttpClientFactory _httpClientFactory;
  36. /// <summary>
  37. ///
  38. /// </summary>
  39. /// <param name="config"></param>
  40. /// <param name="loginRep"></param>
  41. /// <param name="mapper"></param>
  42. /// <param name="message"></param>
  43. /// <param name="sysMenuPermRep"></param>
  44. /// <param name="qiYeWeChatApiService"></param>
  45. /// <param name="messageRep"></param>
  46. /// <param name="deviceRep"></param>
  47. /// <param name="hubContext"></param>
  48. /// <param name="hotmailService"></param>
  49. /// <param name="httpClientFactory"></param>
  50. public AuthController(
  51. IConfiguration config,
  52. LoginRepository loginRep,
  53. IMapper mapper,
  54. MessageRepository message,
  55. SystemMenuPermissionRepository sysMenuPermRep,
  56. IQiYeWeChatApiService qiYeWeChatApiService,
  57. MessageRepository messageRep,
  58. DeviceTokenRepository deviceRep,
  59. IHubContext<ChatHub, IChatClient> hubContext,
  60. HotmailService hotmailService,
  61. System.Net.Http.IHttpClientFactory httpClientFactory)
  62. {
  63. _config = config;
  64. _loginRep = loginRep;
  65. _mapper = mapper;
  66. _message = message;
  67. _sysMenuPermRep = sysMenuPermRep;
  68. _qiYeWeChatApiService = qiYeWeChatApiService;
  69. _messageRep = messageRep;
  70. _deviceTokenRep = deviceRep;
  71. _hubContext = hubContext;
  72. _hotmailService = hotmailService;
  73. _httpClientFactory = httpClientFactory;
  74. }
  75. /// <summary>
  76. /// 用户登录
  77. /// </summary>
  78. /// <param name="dto"></param>
  79. /// <returns></returns>
  80. [Route("login")]
  81. [HttpPost]
  82. [ApiLog("Login", OperationEnum.Login)]
  83. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  84. public async Task<IActionResult> LoginAsync(LoginDto dto)
  85. {
  86. if (string.IsNullOrWhiteSpace(dto.Number) || string.IsNullOrWhiteSpace(dto.Password))
  87. {
  88. return Ok(JsonView(false, "账号或密码不能为空!!"));
  89. }
  90. #region 校验用户信息
  91. var userData = _loginRep.Login(dto).Result;
  92. if (userData.Code != 0) return Ok(JsonView(false, userData.Msg));
  93. #endregion
  94. #region 限制销售部门 除gyy外可登录
  95. var userInfo = userData.Data as UserLoginInfoView;
  96. if (userInfo == null) return Ok(JsonView(false, userData.Msg));
  97. if (userInfo.DepName.Contains("市场部"))
  98. {
  99. var noLoginAuth = _config.GetSection("NoLoginAuth").Get<List<string>>();
  100. if (noLoginAuth.Any())
  101. {
  102. if (noLoginAuth.Contains(userInfo.CnName)) return Ok(JsonView(false, "NO ACCESS!!"));
  103. }
  104. //其他市场部人员 限制登录时间段
  105. var currentDateTime = DateTime.Now;
  106. var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  107. var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  108. if (currentDateTime < startTime && currentDateTime > endTime) return Ok(JsonView(false, "NO ACCESS!!"));
  109. }
  110. #endregion
  111. Result authData = null;
  112. string uName = string.Empty,
  113. role = string.Empty,
  114. depName = string.Empty;
  115. int uId = 0;
  116. int unReadCount = 0;
  117. int announcementUnReadCount = 0;
  118. if (userData.Data != null)
  119. {
  120. uId = (userData.Data as UserLoginInfoView).UserId;
  121. uName = (userData.Data as UserLoginInfoView).CnName;
  122. depName = (userData.Data as UserLoginInfoView).DepName;
  123. role = (userData.Data as UserLoginInfoView).JobName;
  124. authData = _sysMenuPermRep.QueryMenuLoad(uId, dto.PortType);
  125. unReadCount = await _messageRep.GetUnReadCount(uId);
  126. announcementUnReadCount = await _messageRep.GetAnnouncementUnReadCount(uId);
  127. }
  128. //_hubContext.Login(uId, uName);
  129. var view = new LoginView
  130. {
  131. UserInfo = userData?.Data,
  132. AuthData = authData?.Data,
  133. UnReadCount = unReadCount,
  134. AnnouncementUnReadCount = announcementUnReadCount
  135. };
  136. DateTime createZebraTime = DateTime.Now;
  137. string authorId = dto.Number + "Token";
  138. string authorToken = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>(authorId);//string 取
  139. if (authorToken != null)
  140. {
  141. #region 解析出过期时间
  142. var jwtHandler = new JwtSecurityTokenHandler();
  143. JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(authorToken);
  144. DateTime expDt = (securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
  145. #endregion
  146. if (expDt >= createZebraTime) //超时重新获取token
  147. {
  148. authorToken = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Department = depName, Role = role }); //
  149. }
  150. view.Expires = expDt;
  151. view.Token = authorToken;
  152. }
  153. else
  154. {
  155. view.Expires = createZebraTime.AddMinutes(30);
  156. //view.Token = await GeneralMethod.GetToken(_config, dto.Number, uId, uName, createZebraTime); //JwtHelper
  157. view.Token = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Department = depName, Role = role }); //
  158. TimeSpan ts = view.Expires.AddMinutes(-1) - createZebraTime; //设置redis 过期时间 比 jwt 时间 快一分钟
  159. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(authorId, view.Token, ts);//string 存
  160. }
  161. //#region 添加登录用户上线信息
  162. //_hubContext.SignalRLogin(uId);
  163. //#endregion
  164. #region 测试添加系统消息
  165. //await _message.AddMsg(new MessageDto()
  166. //{
  167. // Type = 1,
  168. // IssuerId = 208,
  169. // Title = "测试添加消息标题",
  170. // Content = "消息体测试",
  171. // ReleaseTime = DateTime.Now,
  172. // UIdList = new List<int> {
  173. // 5,
  174. // 208,
  175. // 219
  176. // }
  177. //});
  178. #endregion
  179. return Ok(JsonView(view));
  180. }
  181. /// <summary>
  182. /// 移动端用户登录
  183. /// </summary>
  184. /// <param name="dto"></param>
  185. /// <returns></returns>
  186. [Route("MobileLogin")]
  187. [HttpPost]
  188. [ApiLog("Login", OperationEnum.Login)]
  189. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  190. public async Task<IActionResult> MobileLoginAsync(LoginDto dto)
  191. {
  192. if (string.IsNullOrWhiteSpace(dto.Number) || string.IsNullOrWhiteSpace(dto.Password))
  193. {
  194. return Ok(JsonView(false, "账号或密码不能为空!!"));
  195. }
  196. #region 校验用户信息
  197. var userData = _loginRep.Login(dto).Result;
  198. if (userData.Code != 0) return Ok(JsonView(false, userData.Msg));
  199. #endregion
  200. Result authData = null;
  201. string uName = string.Empty;
  202. string role = string.Empty;
  203. int uId = 0;
  204. int unReadCount = 0;
  205. int announcementUnReadCount = 0;
  206. if (userData.Data != null)
  207. {
  208. uId = (userData.Data as UserLoginInfoView).UserId;
  209. uName = (userData.Data as UserLoginInfoView).CnName;
  210. role = (userData.Data as UserLoginInfoView).JobName;
  211. authData = _sysMenuPermRep.MobileMenuLoad(uId, dto.PortType);
  212. unReadCount = await _messageRep.GetUnReadCount(uId);
  213. announcementUnReadCount = await _messageRep.GetAnnouncementUnReadCount(uId);
  214. }
  215. //_hubContext.Login(uId, uName);
  216. var view = new LoginView
  217. {
  218. UserInfo = userData?.Data,
  219. AuthData = authData?.Data,
  220. UnReadCount = unReadCount,
  221. AnnouncementUnReadCount = announcementUnReadCount
  222. };
  223. DateTime createZebraTime = DateTime.Now;
  224. string authorId = dto.Number + "Token";
  225. string authorToken = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>(authorId);//string 取
  226. if (authorToken != null)
  227. {
  228. #region 解析出过期时间
  229. var jwtHandler = new JwtSecurityTokenHandler();
  230. JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(authorToken);
  231. DateTime expDt = (securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
  232. #endregion
  233. if (expDt >= createZebraTime) //超时重新获取token
  234. {
  235. authorToken = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Role = role }); //
  236. }
  237. view.Expires = expDt;
  238. view.Token = authorToken;
  239. }
  240. else
  241. {
  242. view.Expires = createZebraTime.AddMinutes(30);
  243. //view.Token = await GeneralMethod.GetToken(_config, dto.Number, uId, uName, createZebraTime); //JwtHelper
  244. view.Token = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Role = role }); //
  245. TimeSpan ts = view.Expires.AddMinutes(-1) - createZebraTime; //设置redis 过期时间 比 jwt 时间 快一分钟
  246. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(authorId, view.Token, ts);//string 存
  247. }
  248. //#region 添加登录用户上线信息
  249. //_hubContext.SignalRLogin(uId);
  250. //#endregion
  251. #region 测试添加系统消息
  252. //await _message.AddMsg(new MessageDto()
  253. //{
  254. // Type = 1,
  255. // IssuerId = 208,
  256. // Title = "测试添加消息标题",
  257. // Content = "消息体测试",
  258. // ReleaseTime = DateTime.Now,
  259. // UIdList = new List<int> {
  260. // 5,
  261. // 208,
  262. // 219
  263. // }
  264. //});
  265. #endregion
  266. return Ok(JsonView(view));
  267. }
  268. /// <summary>
  269. /// 申请注册 数据Data
  270. /// </summary>
  271. /// <returns></returns>
  272. //[Authorize]
  273. [HttpPost]
  274. [Route("register/daraSource")]
  275. public async Task<IActionResult> RegisterDataSource()
  276. {
  277. string sql = string.Format(@"Select sc.Id CompanyId,sc.CompanyName,sd.Id DepId,sd.DepName,sjp.Id JobId,sjp.JobName From Sys_Company sc
  278. Left Join Sys_Department sd On sd.IsDel = 0 And sc.Id = sd.CompanyId
  279. Left Join Sys_JobPost sjp On sjp.IsDel = 0 And sjp.DepId = sd.Id
  280. Where sc.IsDel = 0");
  281. var companyDetails = _loginRep._sqlSugar.SqlQueryable<CompanyDetailsView>(sql).ToList();
  282. var detailsView1 = new List<CompanyDetailsView1>();
  283. if (companyDetails.Count > 0)
  284. {
  285. var companyDetails1 = companyDetails.GroupBy(it => it.CompanyId).Select(it => it.First()).ToList();
  286. detailsView1 = companyDetails1.Select(it =>
  287. {
  288. var itemCompany = new CompanyDetailsView1();
  289. var depDetailsView = new List<DepDetailsView>();
  290. var companyDetails2 = companyDetails.GroupBy(it => it.DepId).Select(it => it.First()).ToList();
  291. //部门
  292. depDetailsView = companyDetails2.Where(depIt => depIt.CompanyId == it.CompanyId).Select(depIt =>
  293. {
  294. var depDetails = new DepDetailsView();
  295. var jobDetails = new List<JobDetailsView>();
  296. //岗位
  297. jobDetails = companyDetails.Where(jobIt => jobIt.DepId == depIt.DepId).Select(jobIt =>
  298. {
  299. var jobDetail = new JobDetailsView()
  300. {
  301. JobId = jobIt.JobId,
  302. JobName = jobIt.JobName,
  303. };
  304. return jobDetail;
  305. }).ToList();
  306. depDetails.DepId = depIt.DepId;
  307. depDetails.DepName = depIt.DepName;
  308. depDetails.SubJob = jobDetails;
  309. return depDetails;
  310. }).ToList();
  311. itemCompany.CompanyId = it.CompanyId;
  312. itemCompany.CompanyName = it.CompanyName;
  313. itemCompany.SubDep = depDetailsView;
  314. return itemCompany;
  315. }).ToList();
  316. }
  317. return Ok(new { Code = 200, Msg = "查询成功!", Data = detailsView1 });
  318. }
  319. /// <summary>
  320. /// 申请注册
  321. /// </summary>
  322. /// <param name="dto"></param>
  323. /// <returns></returns>
  324. //[Authorize]
  325. [HttpPost]
  326. [Route("register")]
  327. public async Task<IActionResult> Register(RegisterDto dto)
  328. {
  329. #region 企业微信添加员工
  330. //string lastName = dto.CnName.Substring(0, 1);
  331. //string lastNamePy = string.Empty;
  332. //if (PinyinHelper.IsChinese(Convert.ToChar(lastName)))
  333. //{
  334. // lastNamePy = PinyinHelper.GetPinyin(lastName);
  335. //}
  336. //string userId = string.Format("{0}.{1}", dto.EnName, lastNamePy.ToLower());
  337. //Create_Request request = new Create_Request()
  338. //{
  339. // userid = userId,
  340. // name = dto.CnName,
  341. // mobile = dto.Phone,
  342. // department = new List<long>() { dto.DepId },
  343. // position = dto.JobPostId.ToString(),
  344. // gender = dto.Sex == 0 ? 1 : dto.Sex == 1 ? 2 : 1,
  345. // biz_mail = dto.Email
  346. //};
  347. //var qiYeWeChatCreateData = await _qiYeWeChatApiServic.CreateAsync(request);
  348. #endregion
  349. var userData = _loginRep.Register(dto);
  350. if (userData.Result.Code != 0)
  351. {
  352. return Ok(JsonView(false, userData.Result.Msg));
  353. }
  354. return Ok(JsonView(true, userData.Result.Msg));
  355. }
  356. /// <summary>
  357. /// 修改密码
  358. /// </summary>
  359. /// <param name="dto"></param>
  360. /// <returns></returns>
  361. [Authorize]
  362. [HttpPost]
  363. [Route("UpdPassword")]
  364. public async Task<IActionResult> UpdateUserPassword(UpdateDto dto)
  365. {
  366. //Result result = new Result();
  367. //var httpContext = HttpContext.User.Claims.FirstOrDefault(it => it.Type == ClaimTypes.Name)?.Value;
  368. //Sys_Users sys_Users = _mapper.Map<Sys_Users>(dto);
  369. var _view = await _loginRep.ChangePassword(dto.UserId, dto.Password);
  370. if (_view.Code == 0) return Ok(JsonView(true, "操作成功!"));
  371. return Ok(JsonView(false, _view.Msg));
  372. }
  373. /// <summary>
  374. /// 保存deviceToken
  375. /// </summary>
  376. /// <param name="dto"></param>
  377. /// <returns></returns>
  378. [HttpPost("SaveDeviceToken")]
  379. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  380. public async Task<IActionResult> SaveDeviceToken(SaveDeviceToken dto)
  381. {
  382. var view = await _deviceTokenRep.SaveToken(dto);
  383. if (view.Code == 0) return Ok(JsonView(true, "操作成功!"));
  384. return Ok(JsonView(false, view.Msg));
  385. }
  386. /// <summary>
  387. /// 获取deviceToken
  388. /// </summary>
  389. /// <param name="dto"></param>
  390. /// <returns></returns>
  391. [HttpPost("GetDeviceToken")]
  392. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  393. public async Task<IActionResult> GetDeviceToken(GetDeviceToken dto)
  394. {
  395. var view = await _deviceTokenRep.GetToken(dto.account);
  396. if (view.Code == 0) return Ok(JsonView(true, "操作成功!", view.Data));
  397. return Ok(JsonView(false, view.Msg));
  398. }
  399. #region microsoft 鉴权验证
  400. /// <summary>
  401. /// microsoft - hotmail 鉴权验证
  402. /// </summary>
  403. /// <returns></returns>
  404. [HttpGet("microsoft/auth/verify/{currUserId}")]
  405. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  406. public async Task<IActionResult> MicrosoftHotmailPrepareAuth(int currUserId)
  407. {
  408. var (code, message) = await _hotmailService.PrepareAuth(currUserId);
  409. return code switch
  410. {
  411. // 无需授权
  412. 0 => Ok(JsonView(true, "已通过验证", new { isAuth = false })),
  413. // 需要跳转授权 (1)
  414. 1 => Ok(JsonView(true, "请点击链接进行 Auth 验证!", new { isAuth = true, url = message })),
  415. //1 => Redirect(message),
  416. // 配置错误或异常 (-1)
  417. _ => Ok(JsonView(false, message))
  418. };
  419. }
  420. /// <summary>
  421. /// microsoft - hotmail 刷新客户端token
  422. /// </summary>
  423. /// <returns></returns>
  424. [HttpGet("microsoft/auth/refresh/{currUserId}")]
  425. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  426. public async Task<IActionResult> MicrosoftHotmailRefreshToken()
  427. {
  428. var hotmailConfigs = await _hotmailService.GetUserMailConfigListAsync(_loginRep._sqlSugar);
  429. if (hotmailConfigs == null)
  430. {
  431. return Ok(JsonView(false, "未找到 Hotmail 配置"));
  432. }
  433. var sb = new StringBuilder();
  434. foreach (var hotmailConfig in hotmailConfigs)
  435. {
  436. var result = await _hotmailService.ForceRefreshTokenAsync(hotmailConfig.UserName);
  437. sb.AppendLine($"User: {hotmailConfig.UserName} -> {result};");
  438. }
  439. return Ok(JsonView(true, sb.ToString()));
  440. }
  441. /// <summary>
  442. /// microsoft auth 回调
  443. /// </summary>
  444. /// <param name="code"></param>
  445. /// <param name="state"></param>
  446. /// <returns></returns>
  447. [HttpGet("microsoft/auth/callback")]
  448. public async Task<IActionResult> HandleCallback([FromQuery] string code, [FromQuery] string state)
  449. {
  450. if (string.IsNullOrEmpty(code)) return BadRequest("授权码无效");
  451. // 1. 状态与配置校验
  452. if (!int.TryParse(state, out int userId)) return BadRequest("非法的 state 标识");
  453. var config = await _hotmailService.GetUserMailConfig(userId);
  454. if (config == null) return BadRequest("对应配置信息不存在");
  455. try
  456. {
  457. // 2. 换取令牌 (使用严格的参数清洗)
  458. var httpClient = _httpClientFactory.CreateClient();
  459. var tokenRequest = new Dictionary<string, string>
  460. {
  461. { "client_id", config.ClientId.Trim() },
  462. { "client_secret", config.ClientSecret.Trim() },
  463. { "code", code },
  464. { "redirect_uri", config.RedirectUri.Trim() }, // 确保与 PrepareAuth 阶段完全一致
  465. { "grant_type", "authorization_code" },
  466. // 换取时再次明确 scope
  467. { "scope", "openid offline_access Mail.ReadWrite Mail.Send User.Read" }
  468. };
  469. var response = await httpClient.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", new FormUrlEncodedContent(tokenRequest));
  470. var responseContent = await response.Content.ReadAsStringAsync();
  471. if (!response.IsSuccessStatusCode) return BadRequest($"令牌交换失败: {responseContent}");
  472. var root = JsonDocument.Parse(responseContent).RootElement;
  473. // 3. 提取令牌 (准则:确保 refresh_token 存在)
  474. var accessToken = root.GetProperty("access_token").GetString()!;
  475. var refreshToken = root.TryGetProperty("refresh_token", out var rt) ? rt.GetString()! : null;
  476. var expiresIn = root.GetProperty("expires_in").GetInt32();
  477. if (string.IsNullOrEmpty(refreshToken))
  478. return BadRequest("未能获取长效刷新令牌,请检查 offline_access 权限。");
  479. // 4. 获取用户信息
  480. string userEmail = await GetEmailFromGraphApiAsync(accessToken);
  481. // 5. 缓存 (准则 2 & 3)
  482. var userToken = new UserToken
  483. {
  484. Email = userEmail,
  485. AccessToken = accessToken,
  486. RefreshToken = refreshToken,
  487. ExpiresAt = DateTime.UtcNow.AddSeconds(expiresIn),
  488. Source = "Microsoft_Graph" // 准则 3: 增加标识
  489. };
  490. // Redis 缓存 (用于 API 快速调用)
  491. var redisKey = HotmailService.GetRedisKey(userEmail);
  492. await RedisRepository.RedisFactory.CreateRedisRepository()
  493. .StringSetAsync(redisKey, System.Text.Json.JsonSerializer.Serialize(userToken), TimeSpan.FromDays(90));
  494. // 6. 返回结果
  495. return Ok(new
  496. {
  497. status = "Success",
  498. account = userEmail,
  499. expiresInSeconds = expiresIn,
  500. source = userToken.Source
  501. });
  502. }
  503. catch (Exception ex)
  504. {
  505. // _logger.LogError(ex, "Callback processing failed");
  506. return StatusCode(500, "回调失败,请检查控制台日志");
  507. }
  508. }
  509. private async Task<string> GetEmailFromGraphApiAsync(string accessToken)
  510. {
  511. // 1. 使用 HttpClientFactory 获取预设或独立的 Client
  512. var httpClient = _httpClientFactory.CreateClient("MicrosoftGraph");
  513. // 2. 构造请求头
  514. var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
  515. request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
  516. // 3. 发送请求并确保成功
  517. var response = await httpClient.SendAsync(request);
  518. if (!response.IsSuccessStatusCode)
  519. {
  520. var errorContent = await response.Content.ReadAsStringAsync();
  521. throw new Exception($"Graph API 身份验证失败: {response.StatusCode}, {errorContent}");
  522. }
  523. // 4. 安全解析 JSON
  524. using var doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
  525. var root = doc.RootElement;
  526. // 优先序:mail (邮箱) > userPrincipalName (登录名)
  527. string? email = null;
  528. if (root.TryGetProperty("mail", out var mailProp))
  529. email = mailProp.GetString();
  530. if (string.IsNullOrEmpty(email) && root.TryGetProperty("userPrincipalName", out var upnProp))
  531. email = upnProp.GetString();
  532. if (string.IsNullOrWhiteSpace(email))
  533. throw new Exception("Graph API 返回结果中缺失有效的身份标识 (mail/upn)");
  534. return email.Trim().ToLower(); // 准则:归一化存储,避免大小写导致的缓存失效
  535. }
  536. #endregion
  537. /// <summary>
  538. /// 测试auth
  539. /// </summary>
  540. /// <param name="dto"></param>
  541. /// <returns></returns>
  542. [OASystemAuthentication]
  543. [HttpPost("TestToken")]
  544. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  545. public async Task<IActionResult> TestToken(LoginDto dto)
  546. {
  547. string authorId = dto.Number + "Token";
  548. // 从Redis里面取数据
  549. //string userToken = _redis.StringGet(authorId);
  550. string userToken = "";
  551. var view = new LoginView
  552. {
  553. Token = authorId + ":" + userToken
  554. };
  555. return Ok(JsonView(view));
  556. }
  557. /// <summary>
  558. /// 限流测试
  559. /// </summary>
  560. /// <returns></returns>
  561. [HttpGet("rate-test")]
  562. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  563. public IActionResult RateTest()
  564. {
  565. return Ok(JsonView(true, $"限流测试 - IP:{HttpContext.Connection.RemoteIpAddress?.ToString()}", "", GetRequestCount()));
  566. }
  567. private static int _requestCount = 0;
  568. private int GetRequestCount()
  569. {
  570. return ++_requestCount;
  571. }
  572. ///// <summary>
  573. ///// 员工信息 迁移
  574. ///// Old OA To New OA
  575. ///// </summary>
  576. ///// <returns></returns>
  577. //[HttpPost("UpdateUserDataOldOAToNewOA")]
  578. //[ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  579. //public async Task<IActionResult> UpdateUserDataOldOAToNewOA()
  580. //{
  581. // dynamic view = null;
  582. // try
  583. // {
  584. // var _sqlSuar = _loginRep._sqlSugar;
  585. // var oldOaUsersData = await _sqlSuar.Queryable<OA2014UsersView>().AS("OA2014.dbo.Users").ToListAsync();
  586. // var newOaCompanyData = await _sqlSuar.Queryable<Sys_Company>().ToListAsync();
  587. // var newOaDepartmentData = await _sqlSuar.Queryable<Sys_Department>().ToListAsync();
  588. // var newOaJobPostData = await _sqlSuar.Queryable<Sys_JobPost>().ToListAsync();
  589. // List<Sys_Users> newOaUserDatas = new List<Sys_Users>();
  590. // foreach (var oldUser in oldOaUsersData)
  591. // {
  592. // int depId = 0, postId = 0;
  593. // #region 处理部门岗位
  594. // int did = oldUser.Did;
  595. // string post = oldUser.Post;
  596. // switch (did)
  597. // {
  598. // case 1 : //信息部
  599. // depId = 2;
  600. // if (post.Equals("信息部经理")) postId = 4;
  601. // else if (post.Equals("美工")) { depId = 5; postId = 18; }
  602. // else if(post.Equals("网络推广")) postId = 46;
  603. // else if (post.Equals("软件开发")) postId = 5;
  604. // else if (post.Equals("平面设计师")) { depId = 5; postId = 18; }
  605. // else if (post.Equals("平面设计")) { depId = 5; postId = 18; }
  606. // else if (post.Equals("平面设计师")) { depId = 5; postId = 18; }
  607. // else if (post.Equals("软件工程师")) postId = 5;
  608. // else if (post.Equals("OP操作")) { depId = 7; postId = 28; }
  609. // else if (post.Equals("软件工程师.")) postId = 5;
  610. // else if (post.Equals(".net工程师")) postId = 5;
  611. // else if (post.Equals("安卓开发工程师")) postId = 7;
  612. // else if (post.Equals("web前端")) postId = 6;
  613. // else if (post.Equals("Web后端开发")) postId = 5;
  614. // break;
  615. // case 2 : //财务部
  616. // depId=3;
  617. // if (post.Equals("主管")) postId = 47;
  618. // else if (post.Equals("财务总监")) { postId = 9; }
  619. // else if (post.Equals("会计")) { postId = 10; }
  620. // else if (post.Equals("财务经理")) { postId = 47; }
  621. // else if (post.Equals("财务助理")) { postId = 50; }
  622. // else if (post.Equals("出纳")) { postId = 48; }
  623. // else { postId = 10; }
  624. // break;
  625. // case 3: //人事部
  626. // depId = 4;
  627. // if (post.Equals("主管")) postId = 51;
  628. // else if (post.Equals("人事部主管")) { postId = 51; }
  629. // else if (post.Equals("人事行政主管")) { postId = 51; }
  630. // else if (post.Equals("行政人事助理")) { postId = 52; }
  631. // else if (post.Equals("人事助理")) { postId = 52; }
  632. // else if (post.Equals("人事主管")) { postId = 51; }
  633. // else if (post.Equals("行政人事专员")) { postId = 12; }
  634. // else if (post.Equals("行政司机")) { postId = 14; }
  635. // else if (post.Equals("司机")) { postId = 14; }
  636. // else if (post.Equals("统筹执行")) { postId = 12; }
  637. // else if (post.Equals("培训专员")) { postId = 13; }
  638. // else if (post.Equals("人事经理")) { postId = 11; }
  639. // else if (post.Equals("前台")) { postId = 33; }
  640. // else if (post.Equals("人事行政经理")) { postId = 11; }
  641. // else if (post.Equals("人事部经理")) { postId = 11; }
  642. // else if (post.Equals("人事专员")) { postId = 12; }
  643. // else if (post.Equals("人事经理")) { postId = 11; }
  644. // else postId = 12;
  645. // break;
  646. // case 4: //国交部
  647. // //22 7 主管
  648. // //23 7 计调
  649. // //24 7 机票
  650. // //25 7 酒店
  651. // //26 7 签证
  652. // //27 7 商邀
  653. // //28 7 OP
  654. // //32 7 经理
  655. // depId = 7;
  656. // if (post.Equals("酒店")) postId = 25;
  657. // else if (post.Equals("经理")) { postId = 32; }
  658. // else if (post.Equals("OP专员")) { postId = 28; }
  659. // else if (post.Equals("酒店预订")) { postId = 25; }
  660. // else if (post.Equals("商务邀请")) { postId = 27; }
  661. // else if (post.Equals("-")) { postId = 0; }
  662. // else if (post.Equals("签证专员")) { postId = 26; }
  663. // else if (post.Equals("OP操作")) { postId = 28; }
  664. // else if (post.Equals("司机")) { postId = 14; }
  665. // else if (post.Equals("国际交流部经理")) { postId = 32; }
  666. // else if (post.Equals("机票酒店")) { postId = 24; }
  667. // else if (post.Equals("签证")) { postId = 26; }
  668. // else if (post.Equals("票房")) { postId = 24; }
  669. // else if (post.Equals("票务专员")) { postId = 24; }
  670. // else if (post.Equals("酒店/机票")) { postId = 24; }
  671. // else if (post.Equals("OP")) { postId = 28; }
  672. // else if (post.Equals("主管")) { postId = 22; }
  673. // else if (post.Equals("订票专员")) { postId = 24; }
  674. // else if (post.Equals("机票")) { postId = 24; }
  675. // else if (post.Equals("国交部经理")) { postId = 32; }
  676. // else if (post.Equals("计调")) { postId = 23; }
  677. // else if (post.Equals("票务")) { postId = 24; }
  678. // else if (post.Equals("国交部主管")) { postId = 22; }
  679. // else if (post.Equals("暂无")) { postId = 22; }
  680. // else if (post.Equals("初级OP")) { postId = 28; }
  681. // else if (post.Equals("计调")) { postId = 23; }
  682. // else { postId = 0; }
  683. // break;
  684. // case 5: //会展部
  685. // //15 5 经理
  686. // //16 5 文案策划
  687. // //17 5 活动执行
  688. // //18 5 平面设计师
  689. // //19 5 3D设计师
  690. // depId = 5;
  691. // if (post.Equals("-")) postId = 16;
  692. // break;
  693. // case 6: //市场销售部
  694. // //20 6 经理
  695. // //21 6 市场专员
  696. // //53 6 主管
  697. // depId = 6;
  698. // if (post.Equals("主管")) postId = 53;
  699. // else if (post.Equals("-")) postId = 21;
  700. // else if (post.Equals("销售总监")) postId = 53;
  701. // else if (post.Equals("市场专员")) postId = 21;
  702. // else if (post.Equals("销售专员")) postId = 54;
  703. // else if (post.Equals("市场助理")) postId = 55;
  704. // else if (post.Equals("销售")) postId = 54;
  705. // break;
  706. // case 99: //总经办
  707. // //1 1 总经理
  708. // //2 1 副总经理
  709. // //3 1 总经理助理
  710. // depId = 1;
  711. // if (post.Equals("总经理")) postId = 1;
  712. // else if (post.Equals("副总")) postId = 2;
  713. // break;
  714. // case 107: //会议会展策划部
  715. // //15 5 经理
  716. // //16 5 文案策划
  717. // //17 5 活动执行
  718. // //18 5 平面设计师
  719. // //19 5 3D设计师
  720. // //56 5 销售
  721. // //46 5 网络推广
  722. // //57 5 市场推广
  723. // depId = 5;
  724. // if (post.Equals("销售")) postId = 56;
  725. // else if (post.Equals("策划执行")) postId = 16;
  726. // else if (post.Equals("策活动划")) postId = 16;
  727. // else if (post.Equals("活动执行")) postId = 17;
  728. // else if (post.Equals("网络媒介推广")) postId = 46;
  729. // else if (post.Equals("媒介主任")) postId = 46;
  730. // else if (post.Equals("公关部经理")) postId = 15;
  731. // else if (post.Equals("项目执行")) postId = 17;
  732. // else if (post.Equals("市场推广")) postId = 57;
  733. // else if (post.Equals("策划")) postId = 16;
  734. // else if (post.Equals("3D设计师")) postId = 19;
  735. // else if (post.Equals("平面设计")) postId = 18;
  736. // else if (post.Equals("设计")) postId = 18;
  737. // else if (post.Equals("活动策划")) postId = 16;
  738. // else if (post.Equals("活动策划执行")) postId = 17;
  739. // else if (post.Equals("高级活动策划")) postId = 16;
  740. // else postId = 0;
  741. // break;
  742. // case 115:
  743. // if (post.Equals("系统管理员")) { depId = 9; postId = 31; }
  744. // else if (post.Equals("后勤专员")) { depId = 5; postId = 58; }
  745. // break;
  746. // case 287: //会展部
  747. // //59 2 17 经理
  748. // //60 2 17 主管
  749. // //61 2 17 会展专员
  750. // //62 2 17 会展销售
  751. // //63 2 17 会展策划
  752. // //64 2 17 招商专员
  753. // //65 2 17 媒介专员
  754. // depId = 17;
  755. // if (post.Equals("会展部经理")) postId = 59;
  756. // else if (post.Equals("会展专员")) postId = 61;
  757. // else if (post.Equals("会展销售")) postId = 62;
  758. // else if (post.Equals("招商招展")) postId = 63;
  759. // else if (post.Equals("会展部主管")) postId = 60;
  760. // else if (post.Equals("媒介专员")) postId = 65;
  761. // else if (post.Equals("会展策划")) postId = 63;
  762. // else if (post.Equals("招商专员")) postId = 64;
  763. // else postId = 61;
  764. // break;
  765. // case 304: //总经理助理
  766. // //1 1 总经理
  767. // //2 1 副总经理
  768. // //3 1 总经理助理
  769. // depId = 1;
  770. // postId = 3;
  771. // break;
  772. // case 323: //海外游学部
  773. // //66 3 19 游学顾问
  774. // depId = 19;
  775. // postId = 66;
  776. // break;
  777. // case 335: //会议会展策划部
  778. // //15 5 经理
  779. // //16 5 文案策划
  780. // //17 5 活动执行
  781. // //18 5 平面设计师
  782. // //19 5 3D设计师
  783. // //56 5 销售
  784. // //46 5 网络推广
  785. // //57 5 市场推广
  786. // //67 5 策划主管
  787. // depId = 5;
  788. // if (post.Equals("会展专员")) { depId = 17; postId = 61; }
  789. // else if (post.Equals("策划执行")) postId = 16;
  790. // else if (post.Equals("策划主管")) postId = 67;
  791. // else if (post.Equals("策划")) postId = 16;
  792. // else if (post.Equals("文案")) postId = 16;
  793. // else if (post.Equals("策划执行")) postId = 17;
  794. // else if (post.Equals("执行专员 ")) postId = 17;
  795. // break;
  796. // case 761://项目部
  797. // //20 6 经理
  798. // //21 6 市场专员
  799. // //53 6 主管
  800. // if (post.Equals("销售主管")) { depId = 6; postId = 20; }
  801. // else if (post.Equals("场站经理")) { depId = 6; postId = 53; }
  802. // else if (post.Equals("暂无")) { depId = 5; postId = 58; }
  803. // else
  804. // {
  805. // if (oldUser.CnName.Equals("许婷"))
  806. // {
  807. // depId = 5; postId = 16;
  808. // }
  809. // else if (oldUser.CnName.Equals("陈雪"))
  810. // {
  811. // depId = 5; postId = 17;
  812. // }
  813. // }
  814. // break;
  815. // default:
  816. // break;
  817. // }
  818. // #endregion
  819. // string idCrad = string.Empty;
  820. // string idCradNumber = string.Empty;
  821. // DateTime? birthday = null;
  822. // if (!string.IsNullOrEmpty(oldUser.IDCard))
  823. // {
  824. // idCrad = oldUser.IDCard.Trim();
  825. // #region 处理身份证Number 出生日期
  826. // if (idCrad.ValidateIdNumber())
  827. // {
  828. // idCradNumber = idCrad.ToString();
  829. // string birthDate = idCrad.Substring(6, 8); // 提取从第6位开始的8个字符,即出生日期部分
  830. // birthday = new DateTime(int.Parse(birthDate.Substring(0, 4)), int.Parse(birthDate.Substring(4, 2)), int.Parse(birthDate.Substring(6, 2)));
  831. // }
  832. // #endregion
  833. // }
  834. // DateTime? startWorkDate = null;
  835. // #region 判断是否是日期格式的字符串
  836. // string format = "yyyy-MM-dd"; // 日期格式
  837. // DateTime date;
  838. // bool isParsed = DateTime.TryParseExact(oldUser.StartWorkDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
  839. // if (isParsed)
  840. // {
  841. // startWorkDate = date;
  842. // }
  843. // #endregion
  844. // int education = 0;
  845. // #region 处理学历
  846. // if (!string.IsNullOrEmpty(oldUser.Education))
  847. // {
  848. // //0 未设置 1 小学、2 初中、3 高中、4 专科、5 本科、6 研究生
  849. // if (oldUser.Education.Equals("本科")) education = 5;
  850. // else if (oldUser.Education.Equals("大学专科")) education = 4;
  851. // else if (oldUser.Education.Equals("大专")) education = 4;
  852. // else if (oldUser.Education.Equals("全日制本科")) education = 5;
  853. // else if (oldUser.Education.Equals("硕士")) education = 6;
  854. // else if (oldUser.Education.Equals("硕士研究生")) education = 6;
  855. // else if (oldUser.Education.Equals("学士")) education = 6;
  856. // else if (oldUser.Education.Equals("研究生")) education = 6;
  857. // else if (oldUser.Education.Equals("专科")) education = 4;
  858. // }
  859. // #endregion
  860. // int theOrAdultEducation = 0;
  861. // #region 处理统招/成人
  862. // if (!string.IsNullOrEmpty(oldUser.TheOrAdultEducation))
  863. // {
  864. // //0 未设置 1 成教 2 统招 3 留学
  865. // if (oldUser.TheOrAdultEducation.Equals("成教")) theOrAdultEducation = 1;
  866. // if (oldUser.TheOrAdultEducation.Equals("自考")) theOrAdultEducation = 1;
  867. // else if (oldUser.TheOrAdultEducation.Equals("统招")) theOrAdultEducation = 2;
  868. // else if (oldUser.TheOrAdultEducation.Equals("留学")) theOrAdultEducation = 3;
  869. // }
  870. // #endregion
  871. // Sys_Users user = new Sys_Users()
  872. // {
  873. // Id = oldUser.Id,
  874. // CnName = oldUser.CnName,
  875. // EnName = oldUser.EnName,
  876. // Number = oldUser.Number,
  877. // CompanyId = 2,
  878. // DepId = depId,
  879. // JobPostId = postId,
  880. // Password = oldUser.Password,
  881. // Sex = oldUser.Sex,
  882. // Ext = oldUser.Ext,
  883. // Phone = oldUser.Phone,
  884. // UrgentPhone = oldUser.UrgentPhone,
  885. // Email = oldUser.Email,
  886. // Address = oldUser.Address,
  887. // Edate = oldUser.Edate,
  888. // Rdate = oldUser.Rdate,
  889. // Seniority = oldUser.Seniority,
  890. // Birthday = birthday,
  891. // IDCard = idCradNumber,
  892. // StartWorkDate = startWorkDate,
  893. // GraduateInstitutions = oldUser.GraduateInstitutions,
  894. // Professional = oldUser.Professional,
  895. // Education = education,
  896. // TheOrAdultEducation = theOrAdultEducation,
  897. // MaritalStatus = oldUser.MaritalStatus,
  898. // HomeAddress = oldUser.HomeAddress,
  899. // UsePeriod = oldUser.UsePeriod,
  900. // WorkExperience = oldUser.WorkExperience,
  901. // Certificate = oldUser.Certificate,
  902. // HrAudit = 1,
  903. // CreateUserId = 208,
  904. // CreateTime = DateTime.Now,
  905. // DeleteUserId = null,
  906. // DeleteTime = string.Empty,
  907. // Remark = oldUser.Remark,
  908. // IsDel = oldUser.IsDel,
  909. // };
  910. // newOaUserDatas.Add(user);
  911. // }
  912. // if (newOaUserDatas.Count > 0)
  913. // {
  914. // //执行删除
  915. // bool resetStatus = _sqlSuar.DbMaintenance.TruncateTable<Sys_Users>();
  916. // //执行批量添加
  917. // int addTotal = await _sqlSuar.Insertable(newOaUserDatas).IgnoreColumns(it => it.Id).ExecuteCommandAsync();
  918. // }
  919. // view = new
  920. // {
  921. // Code = 200,
  922. // Msg = "操作成功!",
  923. // Data = newOaUserDatas
  924. // };
  925. // }
  926. // catch (Exception ex)
  927. // {
  928. // view = new
  929. // {
  930. // Code = 400,
  931. // Msg = ex.Message
  932. // };
  933. // }
  934. // return Ok(JsonView(view));
  935. //}
  936. /// <summary>
  937. /// 测试
  938. /// 创建员工号
  939. /// </summary>
  940. /// <param name="depId">部门Id</param>
  941. /// <returns></returns>
  942. [HttpPost("TestCreateUserNumber")]
  943. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  944. public async Task<IActionResult> TestCreateUserNumber(int depId)
  945. {
  946. try
  947. {
  948. var number = await _loginRep.CreateNumber(depId);
  949. return Ok(JsonView(true, "操作成功!", number));
  950. }
  951. catch (Exception ex)
  952. {
  953. return Ok(JsonView(false, "操作失败!", ex.Message));
  954. }
  955. }
  956. /// <summary>
  957. /// ClientTest
  958. /// </summary>
  959. /// <returns></returns>
  960. [HttpPost("ClientTest")]
  961. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  962. public async Task<IActionResult> ClientTest()
  963. {
  964. var _sqlsugar = _loginRep._sqlSugar;
  965. var groups = await _sqlsugar.Queryable<Grp_DelegationInfo>()
  966. .Where(x => x.IsDel == 0 && x.VisitDate >= Convert.ToDateTime("2024-01-01") && x.VisitDate <= Convert.ToDateTime("2024-12-31"))
  967. .Select(x => new { x.Id, x.TeamName, x.ClientUnit, x.ClientName, x.VisitDate })
  968. .ToListAsync();
  969. var newClients = await _sqlsugar.Queryable<Crm_NewClientData>()
  970. .Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Contact))
  971. .Select(x => new Crm_NewClientData() { Contact = x.Contact, Telephone = x.Telephone, Phone = x.Phone })
  972. .ToListAsync();
  973. foreach (var item in newClients) EncryptionProcessor.DecryptProperties(item);
  974. var datas = new List<NewClientInfo>();
  975. foreach (var group in groups)
  976. {
  977. var clientName = group.ClientName;
  978. var clientInfo = newClients.Find(x => !string.IsNullOrEmpty(clientName) && !string.IsNullOrEmpty(x.Contact) && clientName.Contains(x.Contact));
  979. if (clientInfo != null)
  980. {
  981. datas.Add(new NewClientInfo()
  982. {
  983. TeamName = group.TeamName,
  984. ClientUnit = group.ClientUnit,
  985. ClientName = group.ClientName,
  986. VisitDate = group.VisitDate,
  987. NewClientContact = clientInfo?.Contact ?? "",
  988. Telephone = clientInfo?.Telephone ?? "",
  989. Phone = clientInfo?.Phone ?? "",
  990. });
  991. }
  992. }
  993. datas = datas.OrderBy(x => x.VisitDate).ToList();
  994. return Ok(JsonView(datas));
  995. }
  996. public class NewClientInfo
  997. {
  998. public string TeamName { get; set; }
  999. public string ClientUnit { get; set; }
  1000. public string ClientName { get; set; }
  1001. public DateTime VisitDate { get; set; }
  1002. public string NewClientContact { get; set; }
  1003. public string Telephone { get; set; }
  1004. public string Phone { get; set; }
  1005. }
  1006. }
  1007. }