You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

983 lines
43 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
8 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
12 months ago
8 months ago
1 year ago
1 year ago
1 year ago
12 months ago
8 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
12 months ago
8 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
4 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
12 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
12 months ago
11 months ago
12 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
8 months ago
8 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. using Shentun.WebPeis.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Volo.Abp.Application.Services;
  8. using Volo.Abp.Domain.Entities;
  9. using Volo.Abp.Domain.Repositories;
  10. using Volo.Abp.Users;
  11. using Shentun.WebPeis.Wechats;
  12. using Microsoft.Extensions.Configuration;
  13. using System.Net.Http;
  14. using System.Net;
  15. using System.Text.Json;
  16. using Volo.Abp.Identity;
  17. using Volo.Abp;
  18. using Shentun.WebPeis.Enums;
  19. using System.Net.Http.Headers;
  20. using Microsoft.AspNetCore.Mvc;
  21. using OpenIddict.Abstractions;
  22. using Microsoft.AspNetCore.Identity;
  23. using Volo.Abp.ObjectMapping;
  24. using Microsoft.AspNetCore.Authorization;
  25. using Volo.Abp.Caching;
  26. using NPOI.SS.Formula.Functions;
  27. using System.Linq.Dynamic.Core.Tokenizer;
  28. using Microsoft.Extensions.Caching.Distributed;
  29. using Volo.Abp.Uow;
  30. using Scriban.Parsing;
  31. using System.IdentityModel.Tokens.Jwt;
  32. using Shentun.WebPeis.PatientRegisters;
  33. using Microsoft.AspNetCore.Http;
  34. using System.IO;
  35. using Shentun.WebPeis.CustomerOrgs;
  36. using Shentun.Utilities.Enums;
  37. using Shentun.Sms.Client;
  38. using Shentun.Utilities;
  39. using IdentityModel;
  40. using Shentun.WebPeis.SysParmValues;
  41. using Scriban.Syntax;
  42. using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.DepositMarketingMemberCardOpenCardCodesResponse.Types;
  43. namespace Shentun.WebPeis.Persons
  44. {
  45. /// <summary>
  46. /// 微信人员
  47. /// </summary>
  48. [ApiExplorerSettings(GroupName = "Work")]
  49. [Authorize]
  50. public class PersonAppService : ApplicationService
  51. {
  52. private readonly IRepository<QuestionRegister> _questionRegisterRepository;
  53. private readonly IConfiguration _configuration;
  54. private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
  55. private readonly IdentityUserManager _userManager;
  56. private readonly IRepository<Person> _repository;
  57. private readonly PersonManager _personManager;
  58. private readonly IDistributedCache<string, string> _cache;
  59. private readonly IUnitOfWorkManager _unitOfWorkManager;
  60. private readonly IRepository<PersonKinship> _personKinshipRepository;
  61. private readonly IRepository<PatientRegister> _patientRegisterRepository;
  62. private readonly IRepository<Patient> _patientRepository;
  63. private readonly CacheService _cacheService;
  64. private readonly IHttpContextAccessor _httpContextAccessor;
  65. private readonly IRepository<CustomerOrg> _customerOrgRepository;
  66. private readonly SysParmValueManager _sysParmValueManager;
  67. private readonly IRepository<RegisterCheck> _registerCheckRepository;
  68. private readonly IRepository<RegisterCheckAsbitem> _registerCheckAsbitemRepository;
  69. private readonly IRepository<Asbitem> _asbitemRepository;
  70. private readonly IRepository<CustomerOrgRegister> _customerOrgRegisterRepository;
  71. public PersonAppService(IRepository<Person> repository,
  72. IConfiguration configuration,
  73. IRepository<Volo.Abp.Identity.IdentityUser, Guid> identityUserRepository,
  74. IdentityUserManager userManager,
  75. PersonManager personManager,
  76. IUnitOfWorkManager unitOfWorkManager,
  77. IDistributedCache<string, string> cache,
  78. IRepository<PersonKinship> personKinshipRepository,
  79. IRepository<PatientRegister> patientRegisterRepository,
  80. IRepository<Patient> patientRepository,
  81. CacheService cacheService,
  82. IHttpContextAccessor httpContextAccessor,
  83. IRepository<CustomerOrg> customerOrgRepository,
  84. IRepository<QuestionRegister> questionRegisterRepository,
  85. SysParmValueManager sysParmValueManager,
  86. IRepository<RegisterCheck> registerCheckRepository,
  87. IRepository<RegisterCheckAsbitem> registerCheckAsbitemRepository,
  88. IRepository<Asbitem> asbitemRepository,
  89. IRepository<CustomerOrgRegister> customerOrgRegisterRepository)
  90. {
  91. _repository = repository;
  92. _configuration = configuration;
  93. _identityUserRepository = identityUserRepository;
  94. _userManager = userManager;
  95. _personManager = personManager;
  96. _unitOfWorkManager = unitOfWorkManager;
  97. _cache = cache;
  98. _personKinshipRepository = personKinshipRepository;
  99. _patientRegisterRepository = patientRegisterRepository;
  100. _patientRepository = patientRepository;
  101. _cacheService = cacheService;
  102. _httpContextAccessor = httpContextAccessor;
  103. _customerOrgRepository = customerOrgRepository;
  104. _questionRegisterRepository = questionRegisterRepository;
  105. _sysParmValueManager = sysParmValueManager;
  106. _registerCheckRepository = registerCheckRepository;
  107. _registerCheckAsbitemRepository = registerCheckAsbitemRepository;
  108. _asbitemRepository = asbitemRepository;
  109. _customerOrgRegisterRepository = customerOrgRegisterRepository;
  110. }
  111. public async Task<PersonDto> GetByIdAsync(PersonIdInputDto input)
  112. {
  113. var entity = await _repository.GetAsync(o => o.PersonId == input.PersonId);
  114. var entityDto = ObjectMapper.Map<Person, PersonDto>(entity);
  115. var user = await _identityUserRepository.GetAsync(input.PersonId);
  116. entityDto.MobileTelephone = user.PhoneNumber;
  117. entityDto.PersonName = user.Name;
  118. entityDto.SexName = await _cacheService.GetSexNameAsync(entityDto.SexId);
  119. entityDto.MaritalStatusName = await _cacheService.GetMaritalStatusNameAsync(entityDto.MaritalStatusId);
  120. entityDto.NationName = await _cacheService.GetNationNameAsync(entityDto.NationId);
  121. var questionRegister = await _questionRegisterRepository.FindAsync(o => o.PersonId == input.PersonId);
  122. if (questionRegister != null)
  123. {
  124. entityDto.IsHaveQuestionRegister = 'Y';
  125. }
  126. else
  127. {
  128. entityDto.IsHaveQuestionRegister = 'N';
  129. }
  130. return entityDto;
  131. }
  132. /// <summary>
  133. /// 微信用户登录
  134. /// </summary>
  135. /// <param name="input"></param>
  136. /// <returns></returns>
  137. [AllowAnonymous]
  138. [HttpPost("api/app/Person/WeChatUserLogin")]
  139. public async Task<UserTokenDto> WeChatUserLoginAsync(WechatUserJsCodeInputDto input)
  140. {
  141. var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value;
  142. var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value;
  143. var commonScopes = new List<string> {
  144. OpenIddictConstants.Permissions.Scopes.Address,
  145. OpenIddictConstants.Permissions.Scopes.Email,
  146. OpenIddictConstants.Permissions.Scopes.Phone,
  147. OpenIddictConstants.Permissions.Scopes.Profile,
  148. OpenIddictConstants.Permissions.Scopes.Roles,
  149. "WebPeis"
  150. };
  151. var dic = new Dictionary<string, object>
  152. {
  153. {"jsCode",input.JsCode},
  154. {"client_id",weChatClientId},
  155. {"client_secret",secret},
  156. {"grant_type",WeChatGrant.GrantType},
  157. {"scope","WeChat offline_access"}
  158. };
  159. var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n);
  160. var token = await GetTokenAsync(dicStr);
  161. var options = new DistributedCacheEntryOptions()
  162. .SetAbsoluteExpiration(TimeSpan.FromDays(3));
  163. var sessionKey = CacheKeys.SessionKey + Guid.NewGuid().ToString();
  164. var sessionKeyValue = Guid.NewGuid().ToString();
  165. _cache.Set(sessionKey, sessionKeyValue, options);
  166. token.SessionKey = sessionKey;
  167. token.SessionKeyValue = sessionKeyValue;
  168. var isOpenPersonalAppointmentStr = await _sysParmValueManager.GetSysParmValueAsync(Guid.Empty, "is_open_personal_appointment");
  169. if (string.IsNullOrWhiteSpace(isOpenPersonalAppointmentStr))
  170. isOpenPersonalAppointmentStr = "Y";
  171. token.IsOpenPersonalAppointment = Convert.ToChar(isOpenPersonalAppointmentStr);
  172. return token;
  173. }
  174. [AllowAnonymous]
  175. [HttpPost("api/app/Person/Create")]
  176. [UnitOfWork(IsDisabled = false)]
  177. public async Task<UserTokenDto> CreateAsync(CreatePersonDto input)
  178. {
  179. if (input == null) throw new UserFriendlyException("input参数不能为空");
  180. using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true))
  181. {
  182. var entity = ObjectMapper.Map<CreatePersonDto, Person>(input);
  183. if (string.IsNullOrWhiteSpace(input.JsCode))
  184. {
  185. throw new UserFriendlyException("jsCode不能为空");
  186. }
  187. if (string.IsNullOrWhiteSpace(input.WechatOpenId))
  188. {
  189. throw new UserFriendlyException("WechatOpenId不能为空");
  190. }
  191. if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId)
  192. {
  193. throw new UserFriendlyException("无效的WechatOpenId");
  194. }
  195. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  196. {
  197. throw new UserFriendlyException("手机号码不能为空");
  198. }
  199. if (input.MobileTelephone.Length != 11)
  200. {
  201. throw new UserFriendlyException("手机号码必须为11位");
  202. }
  203. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  204. {
  205. throw new UserFriendlyException("短信校验码键不能为空");
  206. }
  207. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  208. {
  209. throw new UserFriendlyException("无效的短信校验码或已过期");
  210. }
  211. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  212. if (person != null)
  213. {
  214. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  215. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  216. if (user == null)
  217. {
  218. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  219. }
  220. if (!string.IsNullOrWhiteSpace(person.WechatOpenId))
  221. {
  222. throw new UserFriendlyException("该身份证跟手机号已被其他微信号注册");
  223. }
  224. person.WechatOpenId = input.WechatOpenId;
  225. await _repository.UpdateAsync(person);
  226. }
  227. else
  228. {
  229. entity.WechatOpenId = input.WechatOpenId;
  230. var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName,
  231. input.Email, input.MobileTelephone);
  232. await _identityUserRepository.InsertAsync(userWithPerson.User);
  233. await _repository.InsertAsync(userWithPerson.Person);
  234. //设置密码
  235. (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors();
  236. (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities.
  237. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors();
  238. }
  239. await unitOfWork.CompleteAsync();
  240. }
  241. using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
  242. {
  243. var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value;
  244. var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value;
  245. var dic = new Dictionary<string, object>
  246. {
  247. {"jsCode",input.JsCode},
  248. {"client_id",weChatClientId},
  249. {"client_secret",secret},
  250. {"grant_type",WeChatGrant.GrantType},
  251. {"scope","WeChat offline_access"}
  252. };
  253. var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n);
  254. var token = await GetTokenAsync(dicStr);
  255. //var entityDto = ObjectMapper.Map<Person, PersonDto>(userWithPerson.Person);
  256. await unitOfWork.CompleteAsync();
  257. return token;
  258. }
  259. }
  260. /// <summary>
  261. /// 更新
  262. /// </summary>
  263. /// <param name="input"></param>
  264. /// <returns></returns>
  265. /// <exception cref="UserFriendlyException"></exception>
  266. [HttpPost("api/app/Person/Update")]
  267. public async Task<PersonDto> UpdateAsync(UpdatePersonDto input)
  268. {
  269. if (input == null) throw new UserFriendlyException("input参数不能为空");
  270. var entity = ObjectMapper.Map<UpdatePersonDto, Person>(input);
  271. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  272. {
  273. throw new UserFriendlyException("手机号码不能为空");
  274. }
  275. if (input.MobileTelephone.Length != 11)
  276. {
  277. throw new UserFriendlyException("手机号码必须为11位");
  278. }
  279. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  280. {
  281. throw new UserFriendlyException("短信校验码键不能为空");
  282. }
  283. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  284. {
  285. throw new UserFriendlyException("无效的短信校验码或已过期");
  286. }
  287. //更新人员信息
  288. var person = await _repository.GetAsync(o => o.PersonId == input.PersonId);
  289. await _personManager.UpdateAsync(entity, person);
  290. await _repository.UpdateAsync(person);
  291. //更新用户信息
  292. var user = await _identityUserRepository.GetAsync(person.PersonId);
  293. user.Name = input.PersonName;
  294. user.SetPhoneNumber(input.MobileTelephone, false);
  295. await _identityUserRepository.UpdateAsync(user);
  296. return ObjectMapper.Map<Person, PersonDto>(person);
  297. }
  298. /// <summary>
  299. /// 更新资料不带手机号码
  300. /// </summary>
  301. /// <param name="input"></param>
  302. /// <returns></returns>
  303. /// <exception cref="UserFriendlyException"></exception>
  304. [HttpPost("api/app/Person/UpdateNoMobileTelephone")]
  305. public async Task<PersonDto> UpdateNoMobileTelephoneAsync(UpdatePersonDto input)
  306. {
  307. if (input == null) throw new UserFriendlyException("input参数不能为空");
  308. var entity = ObjectMapper.Map<UpdatePersonDto, Person>(input);
  309. //更新人员信息
  310. var person = await _repository.GetAsync(o => o.PersonId == input.PersonId);
  311. await _personManager.UpdateAsync(entity, person);
  312. await _repository.UpdateAsync(person, true);
  313. //更新用户信息
  314. var user = await _identityUserRepository.GetAsync(person.PersonId);
  315. user.Name = input.PersonName;
  316. await _identityUserRepository.UpdateAsync(user, true);
  317. var personDto = await GetByIdAsync(new PersonIdInputDto() { PersonId = input.PersonId });
  318. //personDto.MobileTelephone = user.PhoneNumber;
  319. //personDto.PersonName = user.Name;
  320. return personDto;
  321. }
  322. /// <summary>
  323. /// 创建亲属
  324. /// </summary>
  325. /// <param name="input"></param>
  326. /// <returns></returns>
  327. /// <exception cref="UserFriendlyException"></exception>
  328. [HttpPost("api/app/Person/CreatePersonKinship")]
  329. public async Task CreatePersonKinshipAsync(CreatePersonKinshipDto input)
  330. {
  331. if (input == null) throw new UserFriendlyException("input参数不能为空");
  332. var entity = ObjectMapper.Map<CreatePersonKinshipDto, Person>(input);
  333. if (string.IsNullOrWhiteSpace(input.KinshipId))
  334. {
  335. throw new UserFriendlyException("亲属关系不能为空");
  336. }
  337. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  338. {
  339. throw new UserFriendlyException("短信校验码键不能为空");
  340. }
  341. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  342. {
  343. throw new UserFriendlyException("无效的短信校验码或已过期");
  344. }
  345. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  346. if (person != null)
  347. {
  348. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  349. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  350. if (user == null)
  351. {
  352. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  353. }
  354. var personKinshipExist = new PersonKinship()
  355. {
  356. PersonId = person.PersonId,
  357. ParentPersonId = (Guid)CurrentUser.Id,
  358. KinshipId = input.KinshipId,
  359. };
  360. await _personKinshipRepository.InsertAsync(personKinshipExist);
  361. return;
  362. }
  363. var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName,
  364. input.Email, input.MobileTelephone);
  365. var personKinship = new PersonKinship()
  366. {
  367. PersonId = userWithPerson.Person.PersonId,
  368. ParentPersonId = (Guid)CurrentUser.Id,
  369. KinshipId = input.KinshipId,
  370. };
  371. await _identityUserRepository.InsertAsync(userWithPerson.User);
  372. await _repository.InsertAsync(userWithPerson.Person);
  373. await _personKinshipRepository.InsertAsync(personKinship);
  374. //设置密码
  375. (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors();
  376. (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities.
  377. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors();
  378. }
  379. /// <summary>
  380. /// 取消人员绑定
  381. /// </summary>
  382. /// <param name="input"></param>
  383. /// <returns></returns>
  384. [HttpPost("api/app/Person/CancelPersonKinship")]
  385. public async Task CancelPersonKinshipAsync(PersonIdInputDto input)
  386. {
  387. var personKinship = await _personKinshipRepository.GetAsync(o => o.ParentPersonId == (Guid)CurrentUser.Id && o.PersonId == input.PersonId);
  388. await _personKinshipRepository.DeleteAsync(personKinship);
  389. }
  390. /// <summary>
  391. /// 获取体检次数列表 显示报告的列表
  392. /// </summary>
  393. /// <param name="input"></param>
  394. /// <returns></returns>
  395. [HttpPost("api/app/Person/GetMedicalTimesListByPersonId")]
  396. public async Task<List<PersonMedicalTimesDto>> GetMedicalTimesListByPersonIdAsync(PersonIdInputDto input)
  397. {
  398. var entityList = (from user in await _identityUserRepository.GetQueryableAsync()
  399. join person in await _repository.GetQueryableAsync()
  400. on user.Id equals person.PersonId
  401. join patient in await _patientRepository.GetQueryableAsync()
  402. on new { idNo = person.IdNo, phone = user.PhoneNumber } equals new { idNo = patient.IdNo, phone = patient.MobileTelephone }
  403. join patientRegister in await _patientRegisterRepository.GetQueryableAsync()
  404. on patient.PatientId equals patientRegister.PatientId
  405. where user.Id == input.PersonId &&
  406. (patientRegister.CompleteFlag == PatientRegisterCompleteFlag.SumCheck) &&
  407. !string.IsNullOrWhiteSpace(patientRegister.ReportFile)
  408. orderby patientRegister.MedicalStartDate
  409. select new PersonMedicalTimesDto()
  410. {
  411. PatientRegisterId = patientRegister.PatientRegisterId,
  412. PersonName = patient.PatientName,
  413. MedicalStartDate = patientRegister.MedicalStartDate,
  414. }).ToList();
  415. return entityList;
  416. }
  417. /// <summary>
  418. /// 获取pacs文件检查的项目列表
  419. /// </summary>
  420. /// <param name="input"></param>
  421. /// <returns></returns>
  422. [HttpPost("api/app/Person/GetIsPacsCheckList")]
  423. public async Task<List<GetIsPacsCheckListDto>> GetIsPacsCheckListAsync(PatientRegisterIdInputDto input)
  424. {
  425. var query = (from patientRegister in await _patientRegisterRepository.GetQueryableAsync()
  426. join registerCheck in await _registerCheckRepository.GetQueryableAsync() on patientRegister.PatientRegisterId equals registerCheck.PatientRegisterId
  427. join registerCheckAsbitem in await _registerCheckAsbitemRepository.GetQueryableAsync() on registerCheck.RegisterCheckId equals registerCheckAsbitem.RegisterCheckId
  428. join asbitem in await _asbitemRepository.GetQueryableAsync() on registerCheckAsbitem.AsbitemId equals asbitem.AsbitemId
  429. where patientRegister.PatientRegisterId == input.PatientRegisterId
  430. && registerCheck.IsPacsCheck == 'Y'
  431. select new
  432. {
  433. registerCheck.CheckRequestNo,
  434. asbitem.AsbitemName,
  435. registerCheck.PacsCheckDate
  436. }).ToList();
  437. var entListDto = new List<GetIsPacsCheckListDto>();
  438. if (query.Count > 0)
  439. {
  440. entListDto = query.GroupBy(g => g.CheckRequestNo).Select(s => new GetIsPacsCheckListDto
  441. {
  442. CheckRequestNo = s.Key,
  443. AsbitemName = string.Join(",", s.Select(ss => ss.AsbitemName).Distinct().ToList()),
  444. PacsCheckDate = DataHelper.ConversionDateToString(s.FirstOrDefault().PacsCheckDate)
  445. }).ToList();
  446. }
  447. return entListDto;
  448. }
  449. /// <summary>
  450. /// 获取本人和亲属列表
  451. /// </summary>
  452. /// <returns></returns>
  453. [HttpPost("api/app/Person/GetPersonKinshipList")]
  454. public async Task<List<PersonDto>> GetPersonKinshipList()
  455. {
  456. var personKinshipIds = (await _personKinshipRepository.GetQueryableAsync())
  457. .Where(o => o.ParentPersonId == CurrentUser.Id)
  458. .Select(o => o.PersonId).ToList();
  459. personKinshipIds.Add((Guid)CurrentUser.Id);
  460. var personList = (from user in await _identityUserRepository.GetQueryableAsync()
  461. join person in await _repository.GetQueryableAsync()
  462. on user.Id equals person.PersonId
  463. join questionRegister in await _questionRegisterRepository.GetQueryableAsync()
  464. on person.PersonId equals questionRegister.PersonId into emptyQuestionRegister
  465. from haveQuestionRegister in emptyQuestionRegister.DefaultIfEmpty()
  466. where personKinshipIds.Contains(user.Id)
  467. orderby user.CreationTime
  468. select new PersonDto
  469. {
  470. PersonId = user.Id,
  471. PersonNo = person.PersonNo,
  472. MedicalCenterId = person.MedicalCenterId,
  473. PersonName = user.Name,
  474. SexId = person.SexId,
  475. SexName = _cacheService.GetSexNameAsync(person.SexId).Result,
  476. MaritalStatusId = person.MaritalStatusId,
  477. MaritalStatusName = _cacheService.GetMaritalStatusNameAsync(person.MaritalStatusId).Result,
  478. BirthDate = person.BirthDate,
  479. NationId = person.NationId,
  480. NationName = _cacheService.GetNationNameAsync(person.NationId).Result,
  481. BirthPlaceId = person.BirthPlaceId,
  482. IdNo = person.IdNo,
  483. PostalCode = person.PostalCode,
  484. Email = user.Email,
  485. MobileTelephone = user.PhoneNumber,
  486. Address = person.Address,
  487. IdTypeId = person.IdTypeId,
  488. CountryCode = person.CountryCode,
  489. IsAllowBind = person.IsAllowBind,
  490. IsHaveQuestionRegister = haveQuestionRegister == null ? 'N' : 'Y',
  491. Height = person.Height,
  492. Weight = person.Weight
  493. }).Distinct().ToList();
  494. for (var i = 0; i < personList.Count; i++)
  495. {
  496. personList[i].DisplayOrder = i + 1;
  497. if (personList[i].PersonId == CurrentUser.Id)
  498. {
  499. personList[i].DisplayOrder = 0; //本人强行排第一个
  500. }
  501. }
  502. personList = personList.OrderBy(o => o.DisplayOrder).ToList();
  503. return personList;
  504. }
  505. /// <summary>
  506. /// 获取PDF体检报告
  507. /// </summary>
  508. /// <param name="input"></param>
  509. /// <returns></returns>
  510. /// <exception cref="UserFriendlyException"></exception>
  511. [HttpPost("api/app/Person/GetMedicalReportByPatientRegisterId")]
  512. public async Task<MedicalReportDto> GetMedicalReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input)
  513. {
  514. var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId);
  515. if (string.IsNullOrWhiteSpace(entity.ReportFile))
  516. {
  517. throw new UserFriendlyException("没有报告单");
  518. }
  519. #region 检查是否需要填写问卷
  520. var isQuestion =await _customerOrgRegisterRepository.FirstOrDefaultAsync(f => f.CustomerOrgRegisterId == entity.CustomerOrgRegisterId && f.IsQuestion == 'Y');
  521. if (isQuestion != null)
  522. {
  523. string baseAddress = _configuration.GetSection("MedicalHealthReport").GetSection("BaseAddress").Value;
  524. string isQuestionApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("IsQuestionApiUrl").Value;
  525. isQuestionApiUrl = isQuestionApiUrl + $"?recordNo={entity.PatientRegisterNo}"; //查询是否填写问卷
  526. var isQuestionResult = await CallAppServiceAsync<IsQuestionDto, IsQuestionDto>(baseAddress, isQuestionApiUrl, null, "get");
  527. if (isQuestionResult.code != 200
  528. || isQuestionResult.data != true
  529. )
  530. {
  531. throw new UserFriendlyException("请先填写问卷再来查看");
  532. }
  533. }
  534. #endregion
  535. var Host = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Host}:{_httpContextAccessor.HttpContext.Request.Host.Port}";
  536. var returnValue = new MedicalReportDto()
  537. {
  538. FilePath = entity.ReportFile,
  539. FileBase64 = Shentun.Utilities.FileHelper.ToBase64(Host + entity.ReportFile)
  540. };
  541. return returnValue;
  542. }
  543. /// <summary>
  544. /// 获取健康评估报告
  545. /// </summary>
  546. /// <param name="input"></param>
  547. /// <returns></returns>
  548. /// <exception cref="UserFriendlyException"></exception>
  549. [HttpPost("api/app/Person/GetMedicalHealthReportByPatientRegisterId")]
  550. public async Task<MedicalReportDto> GetMedicalHealthReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input)
  551. {
  552. var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId);
  553. string baseAddress = _configuration.GetSection("MedicalHealthReport").GetSection("BaseAddress").Value;
  554. string reportListApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportListApiUrl").Value;
  555. string reportApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportApiUrl").Value;
  556. var medicalHealthReportListInputDto = new MedicalHealthReportListInputDto
  557. {
  558. Page = 1,
  559. Size = 10,
  560. RecordNo = entity.PatientRegisterNo
  561. };
  562. var medicalHealthReportListResult = await CallAppServiceAsync<MedicalHealthReportListInputDto, MedicalHealthReportListDto>(baseAddress, reportListApiUrl, medicalHealthReportListInputDto, "post");
  563. if (medicalHealthReportListResult.Code != 200
  564. || medicalHealthReportListResult.Data.FirstOrDefault() == null
  565. || medicalHealthReportListResult.Data.FirstOrDefault().ReportStatus != "1")
  566. {
  567. throw new UserFriendlyException("没有健康评估报告");
  568. }
  569. //报告单ID
  570. var resultId = medicalHealthReportListResult.Data.FirstOrDefault().ResultId;
  571. reportApiUrl = reportApiUrl + $"?resultId={resultId}"; //获取报告apiurl
  572. var medicalHealthReportResult = await CallAppServiceAsync<MedicalHealthReportDto, MedicalHealthReportDto>(baseAddress, reportApiUrl, null, "get");
  573. if (medicalHealthReportResult.Code != 200
  574. || string.IsNullOrWhiteSpace(medicalHealthReportResult.Data)
  575. )
  576. {
  577. throw new UserFriendlyException("没有健康评估报告");
  578. }
  579. string reportUrl = medicalHealthReportResult.Data;
  580. if (reportUrl.IndexOf(baseAddress) == -1)
  581. {
  582. //替换路径为代理地址
  583. reportUrl = reportUrl.Replace("http://", "").Replace("https://", "");
  584. reportUrl = baseAddress + reportUrl.Substring(reportUrl.IndexOf('/'));
  585. }
  586. var returnValue = new MedicalReportDto()
  587. {
  588. FilePath = reportUrl,
  589. FileBase64 = Shentun.Utilities.FileHelper.ToBase64(reportUrl)
  590. };
  591. return returnValue;
  592. }
  593. /// <summary>
  594. /// 获取校验码
  595. /// </summary>
  596. /// <param name="input"></param>
  597. /// <returns></returns>
  598. /// <exception cref="UserFriendlyException"></exception>
  599. [AllowAnonymous]
  600. [HttpPost("api/app/Person/GetSmsVerifyCode")]
  601. public async Task<SmsVerifyCodeDto> GetSmsVerifyCodeAsync(SmsVerifyCodeInputDto input)
  602. {
  603. if (input == null)
  604. {
  605. throw new UserFriendlyException("input不能为空");
  606. }
  607. //if (string.IsNullOrWhiteSpace(input.WechatOpenId))
  608. //{
  609. // throw new UserFriendlyException("WechatOpenId不能为空");
  610. //}
  611. //if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId)
  612. //{
  613. // throw new UserFriendlyException("无效的WechatOpenId");
  614. //}
  615. if (string.IsNullOrWhiteSpace(input.SessionKey))
  616. {
  617. throw new UserFriendlyException("SessionKey不能为空");
  618. }
  619. if (_cache.Get(input.SessionKey) != input.SessionKeyValue)
  620. {
  621. throw new UserFriendlyException("无效的SessionKeyValue");
  622. }
  623. if (string.IsNullOrWhiteSpace(input.PersonName))
  624. {
  625. throw new UserFriendlyException("姓名不能为空");
  626. }
  627. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  628. {
  629. throw new UserFriendlyException("手机号码不能为空");
  630. }
  631. if (input.MobileTelephone.Length != 11)
  632. {
  633. throw new UserFriendlyException("手机号码必须为11位");
  634. }
  635. if (string.IsNullOrWhiteSpace(input.IdNo))
  636. {
  637. throw new UserFriendlyException("身份证号码不能为空");
  638. }
  639. input.IdNo = input.IdNo.Trim();
  640. if (input.IdNo.Length != 18)
  641. {
  642. throw new UserFriendlyException("身份证长度必须为18位");
  643. }
  644. //var sexByIdNo = ConvertExtr.ToSexByIdNo(idNo).ToCharArray();
  645. if (input.PersonId == null || input.PersonId == default(Guid))
  646. {
  647. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  648. if (person != null)
  649. {
  650. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  651. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  652. if (user == null)
  653. {
  654. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  655. }
  656. //if (!string.IsNullOrWhiteSpace(person.WechatOpenId))
  657. //{
  658. // throw new UserFriendlyException("该微信号已注册");
  659. //}
  660. }
  661. }
  662. var createSmsTaskDto = new CreateSmsTaskDto()
  663. {
  664. PersonId = "0001",
  665. PersonName = input.PersonName,
  666. MobileTelephone = input.MobileTelephone,
  667. CountryCode = "86",
  668. };
  669. var smsVerifyCodeKey = await SendVerifySms(createSmsTaskDto);
  670. var SmsVerifyCodeDto = new SmsVerifyCodeDto()
  671. {
  672. SmsVerifyCodeKey = smsVerifyCodeKey
  673. };
  674. return SmsVerifyCodeDto;
  675. }
  676. private async Task<UserTokenDto> GetTokenAsync(string request)
  677. {
  678. using var client = new HttpClient();
  679. HttpContent httpContent = new StringContent(request);
  680. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  681. var url = _configuration.GetSection("AuthServer").
  682. GetSection("Authority").Value + "/connect/token";
  683. var tokenResult = await client.PostAsync(url
  684. , httpContent);
  685. var tokenResultStr = await tokenResult.Content.ReadAsStringAsync();
  686. if (tokenResult.IsSuccessStatusCode)
  687. {
  688. if (!string.IsNullOrEmpty(tokenResultStr))
  689. {
  690. if (tokenResultStr.ToLower().Contains("openid"))
  691. {
  692. var wechatUserDto = JsonSerializer.Deserialize<WechatUserDto>(tokenResultStr,
  693. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  694. var userTokenDto = new UserTokenDto
  695. {
  696. IsNewUser = "Y",
  697. OpenId = wechatUserDto.OpenId
  698. };
  699. var options = new DistributedCacheEntryOptions()
  700. .SetAbsoluteExpiration(TimeSpan.FromDays(3));
  701. _cache.Set(CacheKeys.OpenIdKey + wechatUserDto.OpenId,
  702. wechatUserDto.OpenId, options);
  703. return userTokenDto;
  704. }
  705. else
  706. {
  707. var signResult = JsonSerializer.Deserialize<SignInResultDto>(tokenResultStr,
  708. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  709. var userTokenDto = new UserTokenDto
  710. {
  711. IsNewUser = "N",
  712. AccessToken = signResult.access_token,
  713. RefreshToken = signResult.refresh_token
  714. };
  715. return userTokenDto;
  716. }
  717. }
  718. else
  719. {
  720. throw new UserFriendlyException("token值为空");
  721. }
  722. }
  723. else
  724. {
  725. //tokenResultStr = tokenResultStr.Replace("<", "").Replace(">", "");
  726. //var grantErrorDto = JsonSerializer.Deserialize<GrantErrorDto>(tokenResultStr,
  727. // new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  728. throw new UserFriendlyException("获取token失败:" + tokenResultStr);
  729. }
  730. }
  731. public async Task<string> SendVerifySms(CreateSmsTaskDto createSmsTaskDto)
  732. {
  733. if (createSmsTaskDto == null)
  734. {
  735. throw new UserFriendlyException("createSmsTaskDto参数不能为空");
  736. }
  737. var message = Shentun.Utilities.Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.Num, 6);
  738. var verifySmsValidTimeStr = _configuration.GetSection("Sms")
  739. .GetSection("VerifySmsValidTime").Value;
  740. var isTemplateTimeStr = _configuration.GetSection("Sms")
  741. .GetSection("IsTemplateTime").Value;
  742. if (!int.TryParse(verifySmsValidTimeStr, out var verifySmsValidTime))
  743. {
  744. throw new Exception("解析校验短信有效时间错误");
  745. }
  746. if (isTemplateTimeStr == "N")
  747. {
  748. createSmsTaskDto.Content = message;
  749. }
  750. else
  751. {
  752. createSmsTaskDto.Content = message + "|" + verifySmsValidTime.ToString();
  753. }
  754. //发送短信
  755. createSmsTaskDto.TaskCycleType = '0';
  756. await SmsClientHelper.CreateVerifySmsTask(createSmsTaskDto);
  757. //存储短信校验码
  758. var options = new DistributedCacheEntryOptions()
  759. .SetAbsoluteExpiration(TimeSpan.FromMinutes(verifySmsValidTime));
  760. var smsVerifyCodeKey = CacheKeys.SmsKey + createSmsTaskDto.MobileTelephone + Guid.NewGuid().ToString();
  761. _cache.Set(smsVerifyCodeKey, message, options);
  762. return smsVerifyCodeKey;
  763. }
  764. private async static Task<TOut> CallAppServiceAsync<TInput, TOut>(string baseAddress, string url, TInput? data, string method = "post")
  765. {
  766. using (var httpClientHandler = new HttpClientHandler())
  767. {
  768. using (var httpClient = new HttpClient(httpClientHandler))
  769. {
  770. httpClient.BaseAddress = new Uri(baseAddress);
  771. httpClient.DefaultRequestHeaders.Accept.Add(
  772. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  773. var jsonOptions = new JsonSerializerOptions
  774. {
  775. WriteIndented = true, // 设置为true以便于可读性更好的JSON输出
  776. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  777. // 如果你想要对日期进行格式化,可以使用JsonConverter
  778. Converters = { new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss") }
  779. };
  780. var sendData = System.Text.Json.JsonSerializer.Serialize(data, jsonOptions);
  781. using (HttpContent httpContent = new StringContent(sendData))
  782. {
  783. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  784. HttpResponseMessage response = null;
  785. if (method == "post")
  786. {
  787. response = await httpClient.PostAsync(url, httpContent);
  788. }
  789. else
  790. {
  791. response = await httpClient.GetAsync(url);
  792. }
  793. string result;
  794. if (!response.IsSuccessStatusCode)
  795. {
  796. result = response.Content.ReadAsStringAsync().Result;
  797. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  798. }
  799. result = await response.Content.ReadAsStringAsync();
  800. var resultDto = System.Text.Json.JsonSerializer.Deserialize<TOut>(result, jsonOptions);
  801. return resultDto;
  802. }
  803. }
  804. }
  805. }
  806. #region 注册信息列表
  807. /// <summary>
  808. /// 查询注册信息
  809. /// </summary>
  810. /// <param name="input"></param>
  811. /// <returns></returns>
  812. [HttpPost("api/app/Person/GetPersonList")]
  813. public async Task<List<PersonListDto>> GetPersonListAsync(GetPersonListInputDto input)
  814. {
  815. var query = from user in await _identityUserRepository.GetQueryableAsync()
  816. join person in await _repository.GetQueryableAsync() on user.Id equals person.PersonId
  817. select new
  818. {
  819. user,
  820. person
  821. };
  822. if (!string.IsNullOrWhiteSpace(input.PatientName))
  823. {
  824. query = query.Where(m => m.user.Name == input.PatientName);
  825. }
  826. if (input.SexId != null)
  827. {
  828. query = query.Where(m => m.person.SexId == input.SexId);
  829. }
  830. if (!string.IsNullOrWhiteSpace(input.IdNo))
  831. {
  832. query = query.Where(m => m.person.IdNo == input.IdNo);
  833. }
  834. if (!string.IsNullOrWhiteSpace(input.MobileTelephone))
  835. {
  836. query = query.Where(m => m.user.PhoneNumber == input.MobileTelephone);
  837. }
  838. var entListDto = query.Select(s => new PersonListDto
  839. {
  840. CreationTime = DataHelper.ConversionDateShortToString(s.person.CreationTime),
  841. IdNo = s.person.IdNo,
  842. MobileTelephone = s.user.PhoneNumber,
  843. PatientName = s.user.Name,
  844. SexName = _cacheService.GetSexNameAsync(s.person.SexId).GetAwaiter().GetResult()
  845. }).ToList();
  846. return entListDto;
  847. }
  848. #endregion
  849. }
  850. }