Esempio n. 1
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task <UserDetail> GetEnterpriseWeChatUserInfo(string code)
        {
            UserDetail enterpriseWeChatUserInfo = null;
            //1.获取(access_token)缓存两小时
            var aToken = await EnterpriseWeChatApi.GetEnterpriseAccessToken(PlatformSettings.EnterpriseWeChatAppid, PlatformSettings.EnterpriseWeChatSecret);

            if (aToken == null)
            {
                return(enterpriseWeChatUserInfo);
            }
            //2.根据code查找用户信息数据
            EnterpriseWeChatApi bill = new EnterpriseWeChatApi();
            string getUserurl        = $"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={aToken.AccessToken}&code={code}";
            var    userModel         = await bill.Send <UserModel>(getUserurl);

            if (userModel == null || string.IsNullOrEmpty(userModel.UserId))
            {
                return(enterpriseWeChatUserInfo);
            }
            //3.根据用户Id查询用户信息
            string getUserDetailurl = $"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={aToken.AccessToken}&userid={userModel.UserId}";
            var    userDetail       = await bill.Send <UserDetail>(getUserDetailurl);

            if (userModel == null)
            {
                return(enterpriseWeChatUserInfo);
            }
            enterpriseWeChatUserInfo = userDetail;
            return(enterpriseWeChatUserInfo);
        }
Esempio n. 2
0
        public async Task <IActionResult> EnterpriseWeChatLogin(string code)
        {
            var aToken = await EnterpriseWeChatApi.GetEnterpriseAccessToken(PlatformSettings.EnterpriseWeChatAppid, PlatformSettings.HealthManagerMobileSecret);

            if (string.IsNullOrWhiteSpace(aToken?.AccessToken))
            {
                Logger.Error($"健康管理师端企业微信授权登录获取token失败:{aToken.Errmsg} at {nameof(HealthManagerController)}.{nameof(EnterpriseWeChatLogin)}({code})");
                return(Failed(ErrorCode.SystemException, "健康管理师端企业微信授权登录获取token失败"));
            }
            var result = await EnterpriseWeChatApi.GetEnterpriseWeChatUserInfo(code, aToken.AccessToken);

            if (result == null)
            {
                return(Failed(ErrorCode.Empty, "未找到对应用户信息"));
            }
            if (result.extattr == null || result.extattr.attrs == null || result.extattr.attrs.Length == 0)
            {
                return(Failed(ErrorCode.Empty, "未找到对应用户工号信息"));
            }
            var jobNumber = result.extattr.attrs.FirstOrDefault(a => a.name == "工号");

            if (jobNumber == null || string.IsNullOrEmpty(jobNumber.value))
            {
                return(Failed(ErrorCode.Empty, "用户工号信息为空"));
            }

            //获取指定工号对应的健康管理师资料、验证合法性
            var model = await new HealthManagerBiz().GetByJobNumberAsync(jobNumber.value);

            if (model == null)
            {
                return(Failed(ErrorCode.Unauthorized, "企业微信对应的工号的健康管理师不存在"));
            }
            if (!string.IsNullOrWhiteSpace(result.userid) && result.userid != model.EnterpriseUserId)
            {
                model.EnterpriseUserId = result.userid;
                model.LastUpdatedBy    = model.ManagerGuid;
                model.LastUpdatedDate  = DateTime.Now;
                await new HealthManagerBiz().UpdateAsync(model);
            }
            var response = new EnterPriseWeChatLoginResponseDto
            {
                UserId   = model.ManagerGuid,
                UserName = model.UserName,
                Token    = CreateToken(model.ManagerGuid, Common.EnumDefine.UserType.Unknown, 30),
            };

            return(Success(response));
        }
Esempio n. 3
0
        /// <summary>
        /// 医生离线消息通知
        /// </summary>
        /// <param name="messageModel"></param>
        /// <returns></returns>
        private void DoctorOfflineMessageNotification(MessageModel messageModel)
        {
            #region 通知医生离线消息


            if (string.IsNullOrWhiteSpace(PlatformSettings.DoctorOfflineMsgTemplate))
            {
                return;
            }
            Task.Run(() =>
            {
                string controllerName = nameof(MessageController);
                string actionName     = nameof(DoctorOfflineMessageNotification);
                try
                {
                    var topiclModel = new TopicBiz().GetModelById(messageModel.TopicGuid);
                    Logger.Debug($"{actionName}-请求参数-{JsonConvert.SerializeObject(messageModel)}{Environment.NewLine}MessageToGuid({messageModel.ToGuid})-TopicReceiverGuid({topiclModel.ReceiverGuid})");
                    if (messageModel.ToGuid == topiclModel.ReceiverGuid)
                    {
                        var doctorStatus = new UserPresenceBiz().GetPresenceStatus(messageModel.ToGuid);
                        Logger.Debug($"{actionName}-当前医生({messageModel.ToGuid})在线状态-{JsonConvert.SerializeObject(doctorStatus)}");
                        //医生为在线状态,不通知
                        if (doctorStatus.IsOnline)
                        {
                            return;
                        }
                        var doctorModel = new DoctorBiz().GetDoctor(messageModel.ToGuid);
                        if (doctorModel == null)
                        {
                            Logger.Debug($"{actionName}-当前接收者不是医生({messageModel.ToGuid})");
                            return;
                        }
                        #region 离线消息十分钟发一次逻辑去掉,改为,离线消息,全部发送给医生
                        //var timeStep = 10;//每十分钟通知一次医生
                        //var msgNotificationKey = $"CloudDoctor:MsgNotificationKey:{messageModel.ToGuid}";
                        //DateTime? latestNotificationTime = null;
                        //if (RedisHelper.Exist(msgNotificationKey))
                        //{
                        //    DateTime.TryParse(RedisHelper.Get<string>(msgNotificationKey), out DateTime result);
                        //    latestNotificationTime = result;
                        //}
                        //else
                        //{
                        //    latestNotificationTime = DateTime.Now.AddHours(-1);
                        //}
                        //Logger.Debug($"{actionName}-当前医生离线消息Redis记录时间({msgNotificationKey}-{latestNotificationTime.Value.ToString("yyyy-MM-dd HH:mm:ss")})");
                        ////通知间隔不足10分钟
                        //if ((DateTime.Now - latestNotificationTime.Value).TotalMinutes < timeStep)
                        //{
                        //    return;
                        //}
                        //RedisHelper.Set(msgNotificationKey, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        #endregion
                        //var tokenRes = WeChartApi.GetAccessToken(PlatformSettings.DoctorClientAppId, PlatformSettings.DoctorClientAppSecret).Result;

                        //用户无openId,不通知
                        if (string.IsNullOrWhiteSpace(doctorModel.WechatOpenid))
                        {
                            Logger.Debug($"{actionName}-当前医生无企业微信userid数据-{JsonConvert.SerializeObject(doctorModel)}");
                            return;
                        }
                        //if (string.IsNullOrWhiteSpace(tokenRes.AccessToken))
                        //{

                        //    Logger.Error($"GD.API.Controllers.Utility.{controllerName}.{actionName} 获取token失败  appId:[{PlatformSettings.DoctorClientAppId}] {Environment.NewLine} error:{tokenRes?.Errmsg}");
                        //    return;
                        //}
                        var userModel = new UserBiz().GetModelAsync(messageModel.FromGuid).Result;
                        var content   = messageModel.Context.Substring(0, messageModel.Context.Length > 25 ? 25 : messageModel.Context.Length);
                        //var tmplateMsg = new WeChatTemplateMsg
                        //{
                        //    Touser = doctorModel.WechatOpenid,
                        //    Template_Id = PlatformSettings.DoctorOfflineMsgTemplate,
                        //    Data = new
                        //    {
                        //        First = new { Value = "【待处理提醒】" },
                        //        //用户昵称
                        //        Keyword1 = new { Value = userModel?.NickName },
                        //        //时间
                        //        Keyword2 = new { Value = messageModel.CreationDate.ToString("MM月dd日 HH:mm") },
                        //        //咨询内容
                        //        Keyword3 = new { Value = $"{content}..." },

                        //        Remark = new { Value = "您有待办信息,请尽快处理" },
                        //    }
                        //};
                        //var response = WeChartApi.SendTemplateMsg(tmplateMsg, tokenRes.AccessToken);
                        //Logger.Debug($"{actionName}-发送模板消息结果-{JsonConvert.SerializeObject(response)}{Environment.NewLine}消息内容-{JsonConvert.SerializeObject(tmplateMsg)}");

                        var qyMsg = new QyTextCardMessageRequest
                        {
                            ToUser   = doctorModel.WechatOpenid,
                            AgentId  = PlatformSettings.EnterpriseWeChatMobileAgentid,
                            TextCard = new QyTextCardMessageRequest.Content
                            {
                                Title       = "问医离线消息通知",
                                Description = $"<div class=\"normal\">用户昵称:{userModel?.NickName}</div>" +
                                              $"<div class=\"normal\">咨询时间:{messageModel.CreationDate.ToString("MM月dd日 HH:mm")}</div>" +
                                              $"<div class=\"normal\">咨询内容:{content}...</div>" +
                                              $"<div class=\"blue\">您有待办信息,请尽快处理</div>"
                            }
                        };
                        var token = EnterpriseWeChatApi.GetEnterpriseAccessToken(PlatformSettings.EnterpriseWeChatAppid, PlatformSettings.EnterpriseWeChatMobileSecret).Result;
                        if (token.Errcode != 0)
                        {
                            Logger.Error($"发送问医离线消息通知获取企业微信token失败:{token.Errmsg}");
                            return;
                        }
                        var sendResult = EnterpriseWeChatApi.SendQyMessageAsync(qyMsg, token.AccessToken).Result;
                        Logger.Debug($"{actionName}-发送问医离线消息通知结果-{JsonConvert.SerializeObject(sendResult)}{Environment.NewLine}消息内容-{JsonConvert.SerializeObject(qyMsg)}");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error($"GD.API.Controllers.Utility.{controllerName}.{actionName}-传入参数:({JsonConvert.SerializeObject(messageModel)}) {Environment.NewLine} error:{ex.Message}");
                }
            });
            #endregion
        }
        public async Task <IActionResult> AddAHealthIndicatorAsync([FromBody] AddHealthIndicatorRequestDto requestDto)
        {
            string userId = string.Empty;

            if (string.IsNullOrWhiteSpace(requestDto.UserId))
            {
                userId = UserID;
            }
            else
            {
                userId = requestDto.UserId;
            }
            var healthIndicatorModel = await new HealthIndicatorBiz().GetAsync(requestDto.IndicatorGuid);

            if (healthIndicatorModel == null)
            {
                return(Failed(ErrorCode.DataBaseError, "未找到对应的健康指标Id"));
            }
            if (!healthIndicatorModel.IndicatorType && requestDto.HealthIndicatorOptionList.All(d => !d.IndicatorValue.HasValue))
            {
                return(Failed(ErrorCode.Empty, "单指标必须提供值,请检查!"));
            }
            if (requestDto.HealthIndicatorOptionList.Count == 0)
            {
                return(Failed(ErrorCode.DataBaseError, "健康指标选项不能为空"));
            }
            var groupOption = requestDto.HealthIndicatorOptionList.GroupBy(s => s.OptionGuid);

            foreach (var item in groupOption)
            {
                if (item.Count() > 1)
                {
                    return(Failed(ErrorCode.DataBaseError, "健康指标选项存在重复数据"));
                }
            }
            List <string> optionRequestList = requestDto.HealthIndicatorOptionList.Select(s => s.OptionGuid).ToList();
            //判断是否存在必填的选项
            var healthIndicatorOptionModelList = (await new HealthIndicatorOptionBiz().GetHealthIndicatorOptionAsync(requestDto.IndicatorGuid));

            if (healthIndicatorOptionModelList == null)
            {
                return(Failed(ErrorCode.DataBaseError, "健康指标选项不存在"));
            }
            //全局匹配差集
            var infoCheckResult = optionRequestList.Except(healthIndicatorOptionModelList.Select(s => s.OptionGuid).ToList())?.ToList();

            if (infoCheckResult != null && infoCheckResult.Count != 0)
            {
                return(Failed(ErrorCode.DataBaseError, "健康指标选项Id不存在"));
            }
            //必须有的选项值
            List <string> optionStrList = healthIndicatorOptionModelList.Where(s => s.Required).Select(s => s.OptionGuid).ToList();

            if (optionStrList != null)
            {
                //差集
                var infoResult = optionStrList.Except(optionRequestList)?.ToList();
                if (infoResult != null && infoResult.Count != 0)
                {
                    return(Failed(ErrorCode.DataBaseError, "健康指标选项必填项不能为空"));
                }
                //校验必填项值是否为空
                foreach (var item in optionStrList)
                {
                    var requestValue = requestDto.HealthIndicatorOptionList.FirstOrDefault(s => s.OptionGuid == item);
                    if (requestValue != null)
                    {
                        if (!requestValue.IndicatorValue.HasValue)
                        {
                            return(Failed(ErrorCode.DataBaseError, "健康指标选项必填项值不能为空"));
                        }
                    }
                }
            }
            ConsumerIndicatorModel consumerIndicatorModel = new ConsumerIndicatorModel()
            {
                IndicatorRecordGuid = Guid.NewGuid().ToString("N"),
                IndicatorGuid       = requestDto.IndicatorGuid,
                UserGuid            = userId,
                CreatedBy           = userId,
                CreationDate        = DateTime.Now,
                LastUpdatedDate     = DateTime.Now
            };
            List <ConsumerIndicatorDetailModel> consumerIndicatorDetailModelList = requestDto.HealthIndicatorOptionList.Select(s => new ConsumerIndicatorDetailModel
            {
                RecordDetailGuid    = Guid.NewGuid().ToString("N"),
                IndicatorRecordGuid = consumerIndicatorModel.IndicatorRecordGuid,
                IndicatorOptionGuid = s.OptionGuid,
                IndicatorValue      = s.IndicatorValue.HasValue ? s.IndicatorValue.Value : (decimal?)null,
                CreatedBy           = userId,
                CreationDate        = DateTime.Now,
                LastUpdatedDate     = DateTime.Now
            }).ToList();
            //保存健康指标数据
            var result = await new HealthIndicatorBiz().CreateHealthIndicatorAsync(consumerIndicatorModel, consumerIndicatorDetailModelList);

            //用户更新指标数据判断是否需要预警操作
            if (result && string.IsNullOrWhiteSpace(requestDto.UserId))
            {
                //查询用户指标预警是否存在
                if (consumerIndicatorDetailModelList != null)
                {
                    var consumerModel = await new ConsumerBiz().GetModelAsync(userId);
                    //该用户绑定过了健康管理师
                    if (consumerModel != null && !string.IsNullOrWhiteSpace(consumerModel.HealthManagerGuid))
                    {
                        foreach (var item in consumerIndicatorDetailModelList)
                        {
                            var consumerIndicatorWarningLimitModel = await new IndicatorWarningLimitBiz().GetModelAsyncByUserAndOption(userId, item.IndicatorOptionGuid);
                            //存在预警开启
                            if (consumerIndicatorWarningLimitModel != null)
                            {
                                if (!item.IndicatorValue.HasValue || !consumerIndicatorWarningLimitModel.MaxValue.HasValue || !consumerIndicatorWarningLimitModel.MinValue.HasValue)
                                {
                                    continue;
                                }
                                //判断更新值是否正常范围
                                if (item.IndicatorValue.Value > consumerIndicatorWarningLimitModel.MaxValue || item.IndicatorValue.Value < consumerIndicatorWarningLimitModel.MinValue)
                                {
                                    //查找指标名称
                                    var healthIndicatorOptionModel = await new HealthIndicatorOptionBiz().GetAsync(item.IndicatorOptionGuid);
                                    if (healthIndicatorOptionModel == null)
                                    {
                                        Logger.Error("发送预警失败用户Id:" + userId + "未找对应指标Id:" + item.IndicatorOptionGuid);
                                        continue;
                                    }
                                    string msgStatus = string.Empty;
                                    if (item.IndicatorValue.Value > consumerIndicatorWarningLimitModel.MaxValue)
                                    {
                                        msgStatus = "高于预警值,";
                                    }
                                    else
                                    {
                                        msgStatus = "低于预警值,";
                                    }
                                    string msg = "该用户" + healthIndicatorOptionModel.OptionName + msgStatus + "当前值为" + item.IndicatorValue.Value + healthIndicatorOptionModel.OptionUnit;
                                    //判断之前预警记录表是否存在当前用户指标预警状态是待处理就改成已失效状态
                                    var consumerIndicatorWarningModel = await new IndicatorWarningBiz().GetModelAsyncByUserAndOption(userId, item.IndicatorOptionGuid);
                                    if (consumerIndicatorWarningModel != null)
                                    {
                                        consumerIndicatorWarningModel.Status = IndicatorWarningStatusEnum.Expired.ToString();
                                        //var resultUpdateWaring = await new IndicatorWarningBiz().UpdateAsync(consumerIndicatorWarningModel);
                                    }
                                    var userModel = new UserBiz().GetUser(userId);
                                    if (userModel == null)
                                    {
                                        Logger.Error("发送预警失败用户Id:" + userId + "未找对应用户:" + userId);
                                        continue;
                                    }
                                    int age = 0;
                                    if (userModel.Birthday.HasValue)
                                    {
                                        age = DateTime.Now.Year - userModel.Birthday.Value.Year;
                                        if (DateTime.Now.Month < userModel.Birthday.Value.Month || (DateTime.Now.Month == userModel.Birthday.Value.Month && DateTime.Now.Day < userModel.Birthday.Value.Day))
                                        {
                                            age--;
                                        }
                                        if (age < 0)
                                        {
                                            age = 0;
                                        }
                                    }
                                    //新增
                                    IndicatorWarningModel indicatorWarningModel = new IndicatorWarningModel
                                    {
                                        WarningGuid         = Guid.NewGuid().ToString("N"),
                                        IndicatorOptionGuid = healthIndicatorOptionModel.OptionGuid,
                                        ConsumerGuid        = userId,
                                        HealthManagerGuid   = consumerModel.HealthManagerGuid,
                                        Name            = userModel.UserName,
                                        Status          = IndicatorWarningStatusEnum.Pending.ToString(),
                                        Age             = age,
                                        Phone           = userModel.Phone,
                                        CreatedBy       = userId,
                                        LastUpdatedBy   = userId,
                                        CreationDate    = DateTime.Now,
                                        LastUpdatedDate = DateTime.Now,
                                        Description     = msg
                                    };
                                    //数据操作方法
                                    var resultStatus = await new IndicatorWarningBiz().CreateUpdataeWarningAsync(consumerIndicatorWarningModel, indicatorWarningModel);
                                    if (!resultStatus)
                                    {
                                        Logger.Error("发送预警失败用户Id:" + userId + "数据修改或新增发生异常");
                                        continue;
                                    }
                                    var healthManagerModel = await new HealthManagerBiz().GetAsync(consumerModel.HealthManagerGuid);
                                    if (healthManagerModel == null)
                                    {
                                        Logger.Error("发送预警失败用户Id:" + userId + "未找对健康管理师Id:" + consumerModel.HealthManagerGuid);
                                    }
                                    if (string.IsNullOrWhiteSpace(healthManagerModel.EnterpriseUserId))
                                    {
                                        Logger.Error("发送预警失败用户Id:" + userId + "未找对健康管理师企业微信Id");
                                    }
                                    DateTime warningDt = DateTime.Now;
                                    var      qyMsg     = new QyTextCardMessageRequest
                                    {
                                        ToUser   = healthManagerModel.EnterpriseUserId,
                                        TextCard = new QyTextCardMessageRequest.Content
                                        {
                                            Title       = "预警通知",
                                            Description = $"<div class=\"normal\">用户姓名:{userModel.UserName}</div>" +
                                                          $"<div class=\"normal\">用户年龄:{age}</div>" +
                                                          $"<div class=\"normal\">用户手机:{userModel.Phone}</div>" +
                                                          $"<div class=\"normal\">预警时间:{warningDt.ToString("yyyy-MM-dd HH:mm:ss")}</div>" +
                                                          $"<div class=\"blue\">预警类型:{msg}</div>",
                                            Url    = PlatformSettings.WarningUrl + indicatorWarningModel.WarningGuid,
                                            BtnTxt = "详情"
                                        },
                                        AgentId = PlatformSettings.HealthManagerMobileAgentid
                                    };
                                    //WarningTextcard content = new WarningTextcard
                                    //{
                                    //    Title = "预警通知",
                                    //    Description = $"<div class=\"normal\">用户姓名:{userModel.UserName}</div>" +
                                    //    $"<div class=\"normal\">用户年龄:{age}</div>" +
                                    //    $"<div class=\"normal\">用户手机:{userModel.Phone}</div>" +
                                    //    $"<div class=\"normal\">预警时间:{warningDt.ToString("yyyy-MM-dd HH:mm:ss")}</div>" +
                                    //    $"<div class=\"blue\">预警类型:{msg}</div>",
                                    //    Url = PlatformSettings.WarningUrl + indicatorWarningModel.WarningGuid
                                    //};
                                    ////发送预警消息
                                    //QyMessageWarningRequest massage = new QyMessageWarningRequest
                                    //{
                                    //    ToUser = healthManagerModel.EnterpriseUserId,//"20200100276",//
                                    //    Textcard = content,
                                    //    ToParty = "",
                                    //    MsgType = "textcard",
                                    //    AgentId = PlatformSettings.HealthManagerMobileAgentid
                                    //};
                                    var token = await EnterpriseWeChatApi.GetEnterpriseAccessToken(PlatformSettings.EnterpriseWeChatAppid, PlatformSettings.HealthManagerMobileSecret);

                                    var sendResult = await EnterpriseWeChatApi.SendQyMessageAsync(qyMsg, token.AccessToken);

                                    if (sendResult.Errcode != 0)
                                    {
                                        Logger.Error("发送预警失败用户Id:" + userId);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(result ? Success() : Failed(ErrorCode.DataBaseError, "更新健康指标失败"));
        }