using Microsoft.AspNetCore.SignalR; using Microsoft.International.Converters.PinYinConverter; using OASystem.API.OAMethodLib.Hub.HubClients; using OASystem.API.OAMethodLib.Hub.Hubs; using OASystem.API.OAMethodLib.JuHeAPI; using OASystem.API.OAMethodLib.SignalR.Hubs; using OASystem.Domain.Entities.Customer; using OASystem.Domain.Entities.District; using OASystem.Domain.Entities.Financial; using OASystem.Domain.Entities.Groups; using OASystem.Domain.ViewModels.Financial; using OASystem.Domain.ViewModels.JuHeExchangeRate; using OASystem.Infrastructure.Repositories.CRM; using OASystem.Infrastructure.Repositories.Groups; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; namespace OASystem.API.OAMethodLib { public static class GeneralMethod { //团组信息 private readonly static DelegationInfoRepository _dirRep = AutofacIocManager.Instance.GetService(); private readonly static TeamRateRepository _teamRateRep = AutofacIocManager.Instance.GetService(); private readonly static IJuHeApiService _juHeApi = AutofacIocManager.Instance.GetService(); private readonly static SetDataRepository _setDataRep = AutofacIocManager.Instance.GetService(); private readonly static TableOperationRecordRepository _tableOperationRecordRep = AutofacIocManager.Instance.GetService(); private readonly static MessageRepository _messageRep = AutofacIocManager.Instance.GetService(); private readonly static IHubContext _hubContext = AutofacIocManager.Instance.GetService>(); #region 消息 /// /// 消息 发布And 通知 /// /// /// 消息类型 /// 1 公告通知 /// 2 团组流程管控通知 /// 3 团组业务操作通知 /// 4 团组费用审核消息 /// 5 团组签证进度通知 /// 6 团组任务进度通知 /// /// 消息标题 /// 消息内容 /// /// 团组id /// 团组id /// public static async Task MessageIssueAndNotification(MessageTypeEnum msgTypeEnum, string title, string content, List userIds, int diId = 0, string param = "") { MessageDto messageDto = new() { Type = msgTypeEnum, IssuerId = 4,//管理员 DiId = diId, Title = title, Content = content, ReleaseTime = DateTime.Now, UIdList = userIds, Param = param }; var status = await _messageRep.AddMsg(messageDto);//添加消息 if (status) { //给在线在用户发送消息 List connIds = UserStore.OnlineUser.Where(it => userIds.Contains(it.UserId)).Select(it => it.ConnectionId).ToList(); string notificationTypeStr1 = GetMsgNotificationType(msgTypeEnum); string notificationTypeStr = JsonConvert.SerializeObject( new { UserIds = userIds, Msg = $"您有一条{notificationTypeStr1}相关的消息!" } ); await _hubContext.Clients.Clients(connIds).ReceiveMessage($"您有一条{notificationTypeStr1}相关的消息!"); return true; } return false; } /// /// 根据消息类型 获取 消息通知类型 /// /// public static string GetMsgNotificationType(MessageTypeEnum msgTypeEnum) { int notificationType = 0; string notificationStr = ""; List notificationTypeViews = AppSettingsHelper.Get("MessageNotificationType"); notificationType = notificationTypeViews.Where(it => it.MsgTypeIds.Contains((int)msgTypeEnum)).Select(it => it.TypeId).FirstOrDefault(); if (notificationType == 1021) notificationStr = "操作"; else if (notificationType == 1020) notificationStr = "任务"; return notificationStr; } #endregion #region md5 加密 /// /// MD5加密,和动网上的16/32位MD5加密结果相同, /// 使用的UTF8编码 /// /// 待加密字串 /// 16或32值之一,其它则采用.net默认MD5加密算法 /// 加密后的字串 public static string Encrypt(string source, int length = 32) { if (string.IsNullOrWhiteSpace(source)) return string.Empty; HashAlgorithm hashAlgorithm = CryptoConfig.CreateFromName("MD5") as HashAlgorithm; byte[] bytes = Encoding.UTF8.GetBytes(source); byte[] hashValue = hashAlgorithm.ComputeHash(bytes); StringBuilder sb = new StringBuilder(); switch (length) { case 16://16位密文是32位密文的9到24位字符 for (int i = 4; i < 12; i++) { sb.Append(hashValue[i].ToString("x2")); } break; case 32: for (int i = 0; i < 16; i++) { sb.Append(hashValue[i].ToString("x2")); } break; default: for (int i = 0; i < hashValue.Length; i++) { sb.Append(hashValue[i].ToString("x2")); } break; } return sb.ToString(); } #endregion #region jwt /// /// 获取token /// /// /// /// /// public static async Task GetToken(IConfiguration _config, string Number, int uId, string uName, DateTime exp) { string userId = Guid.NewGuid().ToString().Replace("-", ""); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, uName), new Claim(ClaimTypes.NameIdentifier, uId.ToString()), new Claim(ClaimTypes.NameIdentifier, userId), new Claim("Number",Number) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "OASystem.com", audience: "OASystem.com", claims: claims, expires: exp, signingCredentials: creds); var indentity = new ClaimsIdentity(claims, "formlogin"); var principal = new ClaimsPrincipal(indentity); // await _httpContext.SignInAsync (CookieAuthenticationDefaults.AuthenticationScheme, principal); return new JwtSecurityTokenHandler().WriteToken(token); } #endregion #region 数据类型转换 /// /// object 转 Int /// /// /// public static int GetInt(this object obj) { if (obj == null) return 0; int _number = 0; bool reslut = Int32.TryParse(obj.ToString(), out _number); return _number; } private static DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0); private static long longTime = 621355968000000000; private static int samllTime = 10000000; /// /// 时间戳 转 datetime /// /// /// public static DateTime GetTimeSpmpToDate(this object timeStamp) { if (timeStamp == null) return dateStart; DateTime dateTime = new DateTime(longTime + Convert.ToInt64(timeStamp) * samllTime, DateTimeKind.Utc).ToLocalTime(); return dateTime; } #endregion #region 用户页面操作功能 权限 /// /// 用户页面操作功能(可使用) /// /// 用户Id /// 页面Id /// public static async Task PostUserPageFuncDatas(int userId, int PageId) { PageFunAuthViewBase pageFunAuth = new PageFunAuthViewBase(); List userPageFuncDatas = new List(); string sql = string.Format(@"Select ua.UId As UserId, u.CnName As UserName, pa.ModuleId,pa.ModuleName,pa.PageId,pa.PageName,pa.PageIsEnable, pa.PagePhoneIsEnable,pa.FuncId,pa.FuncName,pa.FuncIsEnable From Sys_UserAuthority ua Left Join Sys_Users u On ua.UId = u.Id Left Join ( Select sd.Id As ModuleId,sd.Name As ModuleName, smp.Id As PageId,smp.Name As PageName,smp.IsEnable As PageIsEnable, smp.phoneIsEnable As PagePhoneIsEnable,pfp.Id As FuncId,pfp.FunctionName As FuncName,pfp.IsEnable As FuncIsEnable From Sys_SystemMenuAndFunction smaf Left Join Sys_SystemMenuPermission smp On smaf.SmId = smp.Id Left Join Sys_SetData sd On sd.STid = 5 And smp.Mid = sd.Id Left Join Sys_PageFunctionPermission pfp On smaf.FId = pfp.Id Where smaf.IsDel = 0 And smp.IsDel = 0 And pfp.IsDel = 0 And sd.IsDel = 0 And smp.IsEnable = 1 ) As pa On ua.SmId = pa.PageId And ua.FId = pa.FuncId Where ua.IsDel = 0 And ua.UId = {0} And pa.PageId = {1} Order By ModuleId,PageId,FuncId Asc", userId, PageId); userPageFuncDatas = await _dirRep._sqlSugar.SqlQueryable(sql).ToListAsync(); if (userPageFuncDatas.Count <= 0) { return pageFunAuth; } UserPageFuncView userPageFunc = new UserPageFuncView(); //查询 1 userPageFunc = userPageFuncDatas.Where(it => it.FuncId == 1).FirstOrDefault(); if (userPageFunc != null) pageFunAuth.CheckAuth = 1; //删除 2 userPageFunc = userPageFuncDatas.Where(it => it.FuncId == 2).FirstOrDefault(); if (userPageFunc != null) pageFunAuth.DeleteAuth = 1; //编辑 3 userPageFunc = userPageFuncDatas.Where(it => it.FuncId == 3).FirstOrDefault(); if (userPageFunc != null) pageFunAuth.EditAuth = 1; //下载 4 userPageFunc = userPageFuncDatas.Where(it => it.FuncId == 4).FirstOrDefault(); if (userPageFunc != null) pageFunAuth.FilesDownloadAuth = 1; //上传 5 userPageFunc = userPageFuncDatas.Where(it => it.FuncId == 5).FirstOrDefault(); if (userPageFunc != null) pageFunAuth.FilesUploadAuth = 1; //添加 11 userPageFunc = userPageFuncDatas.Where(it => it.FuncId == 11).FirstOrDefault(); if (userPageFunc != null) pageFunAuth.AddAuth = 1; //审核 12 userPageFunc = userPageFuncDatas.Where(it => it.FuncId == 12).FirstOrDefault(); if (userPageFunc != null) pageFunAuth.AuditAuth = 1; return pageFunAuth; } #endregion #region 业务模块 团组权限 /// /// 业务模块 团组操作权限 /// 验证 /// /// 团组Id /// 用户Id /// 业务模块Id /// public static async Task PostGroupOperationAuth(int diId, int userId, int CTable) { Result _result = new Result { Code = -1, Msg = "No Operation Authorty!" }; if (CTable < 1) { _result.Msg = "请填写正确的用户Id!"; return _result; } var data = await _dirRep._sqlSugar.Queryable().Where(it => it.DIId == diId && it.UId == userId && it.CTId == CTable && it.IsDel == 0).FirstAsync(); if (data == null) { _result.Msg = "你没有本团下的该业务模块操作,请联系主管分配操作权限!"; } else { _result.Code = 0; } return _result; } #endregion #region 团组相关 #region 建团按国家默认添加汇率 / 默认权限分配 /// /// 团组汇率 /// 建团时 添加基础汇率 CNY /// 按国家 添加 默认币种 /// /// /// /// public static async Task PostGroupRateAddInit(int userId, int diId) { Result result = new() { Code = -2 }; if (userId < 1) { result.Msg = string.Format(@"请传入正确的userId"); return result; } if (diId < 1) { result.Msg = string.Format(@"请传入正确的DiId"); return result; } //美元(USD):1.0000|欧元(EUR):1.0000|墨西哥比索(MXN):1.0000 string rateInit = string.Format(@"人名币(CNY):1.0000"); //var gropInfo = _dirRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.Id == diId).First(); //if (gropInfo == null) //{ // result.Msg = $@"未查询到团组信息!"; // return result; //} var juheRateData = await _juHeApi.GetExchangeRateAsync(); if (juheRateData.Error_code != 0) { result.Msg = juheRateData.Reason; return result; } List exchangeRateModels = (List)juheRateData.Result; if (exchangeRateModels.Count <= 0) { result.Msg = $@"未查询到聚合接口汇率信息!"; return result; } if (exchangeRateModels.Count > 0) { var codes = _dirRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.STid == 66).ToList(); for (int i = 0; i < exchangeRateModels.Count; i++) { string currencyName = exchangeRateModels[i].Name; string code = ""; var currencyData = codes.Where(it => it.Remark == currencyName).FirstOrDefault(); if (currencyData != null) { code = currencyData.Name; decimal currRate = 0.00M; string MSellPri = exchangeRateModels[i].MSellPri; if (!string.IsNullOrEmpty(MSellPri)) { currRate = Convert.ToDecimal(MSellPri) / 100M; } rateInit += $@"|{currencyName}({code}):{currRate.ToString("#0.0000")}"; } } } var cTableIds = _dirRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.STid == 16).ToList(); if (cTableIds.Count < 1) { result.Msg = $@"未查询到操作模块信息!"; return result; } List grp_TeamRates = new List(); foreach (var item in cTableIds) { grp_TeamRates.Add( new Grp_TeamRate() { DiId = diId, CTable = item.Id, Remark = rateInit, CreateUserId = userId } ); } if (grp_TeamRates.Count > 0) { var addId = _teamRateRep._sqlSugar.Fastest().PageSize(100000).BulkCopy(grp_TeamRates); if (addId < 1) { result.Msg = string.Format(@"添加失败!"); return result; } } result.Code = 0; result.Msg = string.Format(@"操作成功!"); return result; } /// /// 团组汇率 /// 建团时 默认按照岗位分配权限 /// /// /// /// /// public static async Task PostGroupAuthAddInit(int userId, int diId, int companyId = 2) { Result result = new() { Code = -2 }; if (userId < 0) { result.Msg = string.Format(@"请传入正确的userId"); return result; } if (companyId < 0) { result.Msg = string.Format(@"请传入正确的companyId"); return result; } if (diId < 0) { result.Msg = string.Format(@"请传入正确的DiId"); return result; } var userDatas = await _teamRateRep._sqlSugar .Queryable() .LeftJoin((su,sd) => su.DepId == sd.Id && sd.IsDel == 0) .LeftJoin((su,sd,sjp) => su.JobPostId == sjp.Id && sjp.IsDel == 0) .Where(su => su.IsDel == 0) .Select((su,sd,sjp) => new { su.DepId, sd.DepName, su.JobPostId, sjp.JobName, su.Id, su.CnName }) .ToListAsync(); /* * 76 酒店预订 --> 国交部门 酒店 岗位 * 77 行程 --> 国交部门 经理,主管 岗位 * 79 车/导游地接 --> 国交部门 OP 岗位 * 80 签证 --> 国交部门 签证 岗位 * 81 邀请/公务活动 --> 国交部门 商邀 岗位 * 82 团组客户保险 --> 国交部 经理,主管 岗位 * 85 机票预订 --> 国交部门 机票 岗位 * 98 其他款项 --> 总经办部门 总经理 岗位/国交部门(ALL) 岗位/财务部门(ALL) 岗位/策划部门(ALL) 岗位/人事部门 采购 岗位 * 1015 超支费用 --> 财务部门(ALL)岗位 */ List _GroupsTaskAssignments = new List(); // 76 酒店预订 --> 国交部门(7) 酒店(25) 岗位 _GroupsTaskAssignments.AddRange( userDatas .Where(it => it.DepId == 7 && it.JobPostId == 25) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 76, UId = it.Id, CreateUserId = userId }).ToList() ); // 77 行程 --> 国交部门(7) 经理(32),主管(22) 岗位 _GroupsTaskAssignments.AddRange( userDatas .Where(it => it.DepId == 7 && (it.JobPostId == 22 || it.JobPostId == 32)) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 77, UId = it.Id, CreateUserId = userId }).ToList() ); //79 车/导游地接 --> 国交部门(7) OP(28) 岗位 _GroupsTaskAssignments.AddRange( userDatas.Where(it => it.DepId == 7 && it.JobPostId == 28) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 79, UId = it.Id, CreateUserId = userId }).ToList() ); //81 邀请/公务活动 --> 国交部门(7) 商邀(27) 岗位 _GroupsTaskAssignments.AddRange( userDatas .Where(it => it.DepId == 7 && it.JobPostId == 27) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 81, UId = it.Id, CreateUserId = userId }).ToList() ); //80 签证 --> 国交部门(7) 签证(26) 岗位 _GroupsTaskAssignments.AddRange( userDatas .Where(it => it.DepId == 7 && it.JobPostId == 26) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 80, UId = it.Id, CreateUserId = userId }).ToList() ); //82 团组客户保险 --> 国交部(7) 经理(32),主管(22) 岗位 _GroupsTaskAssignments.AddRange( userDatas .Where(it => it.DepId == 7 && (it.JobPostId == 22 || it.JobPostId == 32)) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 82, UId = it.Id, CreateUserId = userId }).ToList() ); //85 机票预订 --> 国交部门(7) 机票(24) 岗位 _GroupsTaskAssignments.AddRange( userDatas .Where(it => it.DepId == 7 && it.JobPostId == 24) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 85, UId = it.Id, CreateUserId = userId }).ToList() ); //98 其他款项 --> 总经办部门(1) 总经理(1) 岗位/国交部门(7)(ALL) 岗位/财务部门(3)(ALL) 岗位/策划部门(5)(ALL) 岗位/人事部门(4) 采购(74) 岗位 List depIds = new List() { 7,3,5 }; List jobIds = new List() { 1,74}; _GroupsTaskAssignments.AddRange( userDatas .Where(it => depIds.Contains(it.DepId) || jobIds.Contains(it.JobPostId)) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 98, UId = it.Id, CreateUserId = userId }).ToList() ); //1015 超支费用 --> 财务部门(3)(ALL)岗位 _GroupsTaskAssignments.AddRange( userDatas .Where(it => it.DepId == 3) .Select(it => new Grp_GroupsTaskAssignment() { DIId = diId, CTId = 1015, UId = it.Id, CreateUserId = userId }).ToList() ); if (_GroupsTaskAssignments.Count > 0) { var addId =_teamRateRep._sqlSugar.Fastest().PageSize(100000).BulkCopy(_GroupsTaskAssignments); } result.Code = 0; result.Msg = string.Format(@"操作成功!"); return result; } #endregion #endregion #region 团组汇率 /// /// 团组汇率 /// 获取板块 币种 及 汇率 /// 76 酒店预订 77 行程 79 车/导游地接 /// 80 签证 82 团组客户保险 85 机票预订 /// 98 其他款项 285 收款退还 /// /// /// /// /// /// string /// eg: CNY 1.0000 /// public static async Task PostGroupRateByCTableAndCurrency(List teamRateModels, int cTable, List currencyCodes) { string str = ""; List currencyRates = new List(); TeamRateModelView hotelRateData = teamRateModels.Where(it => it.CTableId == cTable).FirstOrDefault(); if (hotelRateData != null) { var hotelRates = hotelRateData.TeamRates; foreach (var item in currencyCodes) { if (!string.IsNullOrEmpty(item)) { var hotelRateInfo = hotelRates.Where(it => it.CurrencyCode.Equals(item)).FirstOrDefault(); if (hotelRateInfo != null) { string str1 = string.Format("{0} {1}\r\n", hotelRateInfo.CurrencyCode, hotelRateInfo.Rate); currencyRates.Add(str1); } } } if (currencyRates != null || currencyRates.Count > 0) { currencyRates = currencyRates.Distinct().ToList(); foreach (var item in currencyRates) { str += item; } } } return str; } /// /// 团组汇率 币种 Item (来源:团组汇率) /// 根据 团组Id And 业务类型(CTable)Id /// api处理CTable = 285,默认返回CNY /// /// /// /// /// public static async Task PostGroupTeamRateByDiIdAndCTableId(int portType, int diId, int cTable) { TeamRateModelGeneralView _view = new TeamRateModelGeneralView(); _view = await _teamRateRep.PostGroupTeamRateByDiIdAndCTableId(portType, diId, cTable); return _view; } #endregion #region 汉字转换拼音 private static Dictionary> GetTotalPingYinDictionary(string text) { var chs = text.ToCharArray(); //记录每个汉字的全拼 Dictionary> totalPingYinList = new Dictionary>(); for (int i = 0; i < chs.Length; i++) { var pinyinList = new List(); //是否是有效的汉字 if (ChineseChar.IsValidChar(chs[i])) { ChineseChar cc = new ChineseChar(chs[i]); pinyinList = cc.Pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); } else { pinyinList.Add(chs[i].ToString()); } //去除声调,转小写 pinyinList = pinyinList.ConvertAll(p => Regex.Replace(p, @"\d", "").ToLower()); //去重 pinyinList = pinyinList.Where(p => !string.IsNullOrWhiteSpace(p)).Distinct().ToList(); if (pinyinList.Any()) { totalPingYinList[i] = pinyinList; } } return totalPingYinList; } /// /// 获取汉语拼音全拼 /// /// The string. /// public static List GetTotalPingYin(this string text) { var result = new List(); foreach (var pys in GetTotalPingYinDictionary(text)) { var items = pys.Value; if (result.Count <= 0) { result = items; } else { //全拼循环匹配 var newTotalPingYinList = new List(); foreach (var totalPingYin in result) { newTotalPingYinList.AddRange(items.Select(item => totalPingYin + item)); } newTotalPingYinList = newTotalPingYinList.Distinct().ToList(); result = newTotalPingYinList; } } return result; } /// /// 获取汉语拼音首字母 /// /// /// public static List GetFirstPingYin(this string text) { var result = new List(); foreach (var pys in GetTotalPingYinDictionary(text)) { var items = pys.Value; if (result.Count <= 0) { result = items.ConvertAll(p => p.Substring(0, 1)).Distinct().ToList(); } else { //首字母循环匹配 var newFirstPingYinList = new List(); foreach (var firstPingYin in result) { newFirstPingYinList.AddRange(items.Select(item => firstPingYin + item.Substring(0, 1))); } newFirstPingYinList = newFirstPingYinList.Distinct().ToList(); result = newFirstPingYinList; } } return result; } #endregion #region 新客户资料表 操作记录 /// /// 新客户资料表 /// 操作记录添加 /// /// /// /// /// /// /// public static async Task NewClientOperationRecord(int portType, OperationEnum operationEnum, int userId, int dataId, string remark) { Crm_TableOperationRecord _TableOperationRecord = new Crm_TableOperationRecord() { TableName = "Crm_NewClientData", PortType = portType, OperationItem = operationEnum, DataId = dataId, CreateUserId = userId, CreateTime = DateTime.Now, Remark = remark }; bool add = await _tableOperationRecordRep._Add(_TableOperationRecord); if (add) return false; return false; } #endregion } }