AuthController.cs 51 KB

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