public ActionResult GetDepartmentList() { var accessToken = Senparc.Weixin.QY.Containers.AccessTokenContainer.TryGetToken(CorpId, CorpSecrets); GetDepartmentListResult result = MailListApi.GetDepartmentList(accessToken); return(Json(result.department, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 同步通讯录 /// </summary> /// <param name="context"></param> /// <param name="msg"></param> /// <param name="P1">初始化密码</param> /// <param name="P2"></param> /// <param name="UserInfo"></param> #region 企业号相关 /// <summary> /// 将系统的组织架构同步到微信中去 /// </summary> /// <param name="context"></param> /// <param name="msg"></param> /// <param name="P1"></param> /// <param name="P2"></param> /// <param name="UserInfo"></param> public void TBBRANCHUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo) { //判断是否启用微信后,启用部门需要同步添加微信部门 if (UserInfo.QYinfo.IsUseWX == "Y") { #region 步部门 //系统部门 List <JH_Auth_Branch> branchList = new JH_Auth_BranchB().GetEntities(d => d.ComId == UserInfo.User.ComId && d.WXBMCode == null).ToList(); WXHelp wx = new WXHelp(UserInfo.QYinfo); //微信部门 GetDepartmentListResult bmlist = wx.WX_GetBranchList(""); foreach (JH_Auth_Branch branch in branchList) { List <DepartmentList> departList = bmlist.department.Where(d => d.name == branch.DeptName).ToList(); WorkJsonResult result = null; if (departList.Count() > 0) { branch.WXBMCode = int.Parse(departList[0].id.ToString()); result = wx.WX_UpdateBranch(branch); } else { int branchWxCode = int.Parse(wx.WX_CreateBranchTB(branch).ToString()); branch.WXBMCode = branchWxCode; } new JH_Auth_BranchB().Update(branch); } #endregion #region 步人员 JH_Auth_Branch branchModel = new JH_Auth_BranchB().GetEntity(d => d.DeptRoot == -1 && d.ComId == UserInfo.User.ComId); GetDepartmentMemberInfoResult yg = wx.WX_GetDepartmentMemberInfo(branchModel.WXBMCode.Value); List <JH_Auth_User> userList = new JH_Auth_UserB().GetEntities(d => d.ComId == UserInfo.User.ComId && d.UserName != "administrator").ToList(); foreach (JH_Auth_User user in userList) { if (yg.userlist.Where(d => d.name == user.UserName || d.mobile == user.mobphone).Count() > 0) { wx.WX_UpdateUser(user); } else { wx.WX_CreateUser(user); } } #endregion } }
public GetDepartmentListResult WX_GetBranchList(string strDeptCode) { GetDepartmentListResult Ret = new GetDepartmentListResult(); int?id = null; if (!string.IsNullOrEmpty(strDeptCode)) { id = Int32.Parse(strDeptCode); } if (Qyinfo.IsUseWX == "Y") { Ret = MailListApi.GetDepartmentList(GetToken(), id); } return(Ret); }
/// <summary> /// 当前用户是否在指定部门 /// </summary> /// <param name="deptName">部门名称,可以是子部门</param> /// <returns>true|false</returns> public bool IsInDept(string deptName, WorkOption option) { if(string.IsNullOrEmpty(option.AccessToken)) option.AccessToken = AccessTokenContainer.TryGetToken(option.CorpId, option.Secret); GetDepartmentMemberInfoResult membersinfo = MailListApi.GetDepartmentMemberInfo(option.AccessToken, 1, 1); GetMemberResult user = membersinfo.userlist.FirstOrDefault(m => m.name == CurrentUser); GetDepartmentListResult depts = MailListApi.GetDepartmentList(option.AccessToken); long landDeptId = depts.department.First(d => d.name == deptName).id; foreach (var deptId in user.department) { if (deptId == landDeptId) return true; } return false; }
public ActionResult GetDepartmentList(QyOrgModel model) { #region 校验 var account = GetAccount(model.corpid); if (account == null) { LogWriter.Info(string.Format("corpid为“{0}”的GetDepartmentList获取失败,原因:企业号不存在", model.corpid)); return(Json(new { errorcode = "500", errormsg = "企业号不存在", })); } if (!ValidateAccessToken(account, model.accesstoken)) { LogWriter.Info(string.Format("corpid为“{0}”的GetDepartmentList获取失败,原因:accesstoken错误", model.corpid)); return(Json(new { errorcode = "500", errormsg = "非法访问", })); } #endregion #region 获取用户信息 var wxFO = Formula.FormulaHelper.CreateFO <WxFO>(); GetDepartmentListResult userinfo = null; try { userinfo = wxFO.GetDepartmentList(model.corpid, model.id); } catch (Exception ex) { return(Json(new { errorcode = "500", errormsg = ex.Message, })); } #endregion return(Json(userinfo)); }
public static List <DepartmentResult> ToDepartmentResult(this GetDepartmentListResult result) { if (result == null) { throw new ArgumentNullException(nameof(result)); } var list = result.department?.Select(department => new DepartmentResult { ErrorCode = result.ErrorCodeValue, ErrorMessage = result.errmsg, Name = department.name, Order = department.order, Id = department.id, ParentId = department.parentid })?.ToList(); return(list); }
/// <summary> /// 获取组织 /// </summary> /// <param name="QyID">企业ID</param> /// <param name="id">部门ID。获取指定部门ID下的子部门</param> /// <returns>指定部门及其下的子部门</returns> public GetDepartmentListResult GetDepartmentList(string QyID, int?id = null) { GetDepartmentListResult result = null; try { result = MailListApi.GetDepartmentList(GetAccessToken(QyID), id); } catch (Exception ex) { LogWriter.Error(ex, string.Format("获取QyID为{0}的部门失败", QyID)); result = MailListApi.GetDepartmentList(GetAccessToken(QyID, true), id); } if (result.errcode != ReturnCode_QY.请求成功) { LogWriter.Info(string.Format("获取QyID为{0}的部门失败,原因:{1}", QyID, result.errmsg)); } return(result); }
/// <summary> /// 更新部门 /// </summary> /// <param name="QyID"></param> private void ReFreshDepart(string QyID) { GetDepartmentListResult result = null; try { result = MailListApi.GetDepartmentList(GetAccessToken(QyID)); } catch (Exception ex) { LogWriter.Error(ex, string.Format("获取QyID为{0}的部门失败", QyID)); result = MailListApi.GetDepartmentList(GetAccessToken(QyID, true)); } if (result.errcode != ReturnCode_QY.请求成功) { LogWriter.Info(string.Format("获取QyID为{0}的部门失败,原因:{1}", QyID, result.errmsg)); throw new Exception(string.Format("获取QyID为{0}的部门失败,原因:{1}", QyID, result.errmsg)); } var olddepts = entities.Set <QyDepart>().Where(c => c.QyID == QyID).ToList(); List <QyDepart> addlist = new List <QyDepart>(), alllist = new List <QyDepart>(); //新增 foreach (var add in result.department.Where(c => !olddepts.Select(d => d.DepartID).Contains(c.id))) { QyDepart qd = new QyDepart(); qd.ID = FormulaHelper.CreateGuid(); qd.QyID = QyID; qd.DepartName = add.name; qd.ParentDepartID = add.parentid; qd.DepartID = add.id; qd.DepartOrder = add.order; addlist.Add(qd); alllist.Add(qd); } //修改 foreach (var update in olddepts.Where(c => result.department.Select(d => d.id).Contains(c.DepartID.Value))) { var item = result.department.Where(c => c.id == update.DepartID).FirstOrDefault(); update.DepartName = item.name; update.ParentDepartID = item.parentid; update.DepartOrder = item.order; alllist.Add(update); } //删除 foreach (var delete in olddepts.Where(c => !result.department.Select(d => d.id).Contains(c.DepartID.Value))) { var relateusers = entities.Set <QyUser>().Where(c => c.DepartIDs.Contains(delete.ID)).ToList(); for (int i = 0; i < relateusers.Count(); i++) { var olddeparts = relateusers[i].DepartIDs.Split(',').ToList(); olddeparts.Remove(delete.ID); relateusers[i].DepartIDs = string.Join(",", olddeparts); } entities.Set <QyDepart>().Remove(delete); } //更新树形字段 var root = alllist.Where(c => !alllist.Select(d => d.DepartID).Contains(c.ParentDepartID)).FirstOrDefault(); if (root != null) { root.ParentID = ""; root.Length = 1; root.FullPath = root.ID; root.ChildCount = alllist.Where(c => c.ParentDepartID == root.DepartID).Count(); var ids = new int?[] { root.DepartID }; var parentlength = 1; while (ids.Count() > 0) { var children = alllist.Where(c => ids.Contains(c.ParentDepartID)).ToList(); for (int i = 0; i < children.Count(); i++) { var child = children[i]; var parent = alllist.Where(c => c.DepartID == child.ParentDepartID).FirstOrDefault(); if (parent == null) { continue; } child.ParentID = parent.ID; child.Length = parentlength + 1; child.FullPath = parent.FullPath + "." + child.ID; child.ChildCount = alllist.Where(c => c.ParentDepartID == child.DepartID).Count(); } ids = children.Select(c => c.DepartID).ToArray(); parentlength++; } } foreach (var item in addlist) { entities.Set <QyDepart>().Add(item); } entities.SaveChanges(); }
/// <summary> /// 从企业微信同步到系统里 /// </summary> /// <param name="context"></param> /// <param name="msg"></param> /// <param name="P1"></param> /// <param name="P2"></param> /// <param name="UserInfo"></param> public void TBTXL(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo) { try { int bmcount = 0; int rycount = 0; if (P1 == "") { msg.ErrorMsg = "请输入初始密码"; return; } WXHelp wx = new WXHelp(UserInfo.QYinfo); #region 更新部门 GetDepartmentListResult bmlist = wx.WX_GetBranchList(""); foreach (var wxbm in bmlist.department.OrderBy(d => d.parentid)) { var bm = new JH_Auth_BranchB().GetEntity(p => p.ComId == UserInfo.User.ComId && p.WXBMCode == wxbm.id); if (bm == null) { #region 新增部门 JH_Auth_Branch jab = new JH_Auth_Branch(); jab.WXBMCode = int.Parse(wxbm.id.ToString()); jab.ComId = UserInfo.User.ComId; jab.DeptName = wxbm.name; jab.DeptDesc = wxbm.name; jab.DeptShort = int.Parse(wxbm.order.ToString()); if (wxbm.parentid == 0)//如果是跟部门,设置其跟部门为-1 { jab.DeptRoot = -1; } else { var bm1 = new JH_Auth_BranchB().GetEntity(p => p.ComId == UserInfo.User.ComId && p.WXBMCode == wxbm.parentid); jab.DeptRoot = bm1.DeptCode; jab.Remark1 = new JH_Auth_BranchB().GetBranchNo(UserInfo.User.ComId.Value, jab.DeptRoot); } new JH_Auth_BranchB().Insert(jab); jab.Remark1 = new JH_Auth_BranchB().GetBranchNo(UserInfo.User.ComId.Value, jab.DeptRoot) + jab.DeptCode; new JH_Auth_BranchB().Update(jab); bmcount = bmcount + 1; #endregion } else { //同步部门时放弃更新现有部门 } } #endregion #region 更新人员 JH_Auth_Branch branchModel = new JH_Auth_BranchB().GetEntity(d => d.DeptRoot == -1 && d.ComId == UserInfo.User.ComId); GetDepartmentMemberInfoResult yg = wx.WX_GetDepartmentMemberInfo(branchModel.WXBMCode.Value); foreach (var u in yg.userlist) { var user = new JH_Auth_UserB().GetUserByUserName(UserInfo.QYinfo.ComId, u.userid); if (user == null) { #region 新增人员 JH_Auth_User jau = new JH_Auth_User(); jau.ComId = UserInfo.User.ComId; jau.UserName = u.userid; jau.UserPass = CommonHelp.GetMD5(P1); jau.UserRealName = u.name; jau.Sex = u.gender == 1 ? "男" : "女"; if (u.department.Length > 0) { int id = int.Parse(u.department[0].ToString()); var bm1 = new JH_Auth_BranchB().GetEntity(p => p.ComId == UserInfo.User.ComId && p.WXBMCode == id); jau.BranchCode = bm1.DeptCode; jau.remark = bm1.Remark1.Split('-')[0];//用户得部门路径 } jau.mailbox = u.email; jau.mobphone = u.mobile; jau.zhiwu = string.IsNullOrEmpty(u.position) ? "员工" : u.position; jau.IsUse = "Y"; if (u.status == 1 || u.status == 4) { jau.isgz = u.status.ToString(); } jau.txurl = u.avatar; new JH_Auth_UserB().Insert(jau); rycount = rycount + 1; #endregion //为所有人增加普通员工的权限 JH_Auth_Role rdefault = new JH_Auth_RoleB().GetEntity(p => p.ComId == UserInfo.User.ComId && p.isSysRole == "Y" && p.RoleName == "员工");//找到默认角色 if (rdefault != null) { JH_Auth_UserRole jaurdefault = new JH_Auth_UserRole(); jaurdefault.ComId = UserInfo.User.ComId; jaurdefault.RoleCode = rdefault.RoleCode; jaurdefault.UserName = jau.UserName; new JH_Auth_UserRoleB().Insert(jaurdefault); } } else { //同步人员时放弃更新现有人员 #region 更新人员 user.UserRealName = u.name; if (u.department.Length > 0) { int id = int.Parse(u.department[0].ToString()); var bm1 = new JH_Auth_BranchB().GetEntity(p => p.ComId == UserInfo.User.ComId && p.WXBMCode == id); user.BranchCode = bm1.DeptCode; } user.mailbox = u.email; user.mobphone = u.mobile; user.zhiwu = string.IsNullOrEmpty(u.position) ? "员工" : u.position; user.Sex = u.gender == 1 ? "男" : "女"; if (u.status == 1 || u.status == 4) { user.IsUse = "Y"; user.isgz = u.status.ToString(); } else if (u.status == 2) { user.IsUse = "N"; } user.txurl = u.avatar; new JH_Auth_UserB().Update(user); #endregion } #region 更新角色(职务) if (!string.IsNullOrEmpty(u.position)) { var r = new JH_Auth_RoleB().GetEntity(p => p.ComId == UserInfo.User.ComId && p.RoleName == u.position); if (r == null) { JH_Auth_Role jar = new JH_Auth_Role(); jar.ComId = UserInfo.User.ComId; jar.RoleName = u.position; jar.RoleDec = u.position; jar.PRoleCode = 0; jar.isSysRole = "N"; jar.IsUse = "Y"; jar.leve = 0; jar.DisplayOrder = 0; new JH_Auth_RoleB().Insert(jar); JH_Auth_UserRole jaur = new JH_Auth_UserRole(); jaur.ComId = UserInfo.User.ComId; jaur.RoleCode = jar.RoleCode; jaur.UserName = u.userid; new JH_Auth_UserRoleB().Insert(jaur); } else { } } #endregion } #endregion msg.Result1 = bmcount; msg.Result2 = rycount; } catch (Exception ex) { msg.ErrorMsg = ex.ToString(); } }
public ActionResult UploadUser() { try { //同步部门 GetDepartmentListResult result = MailListApi.GetDepartmentList(WeixinWorkService.GetToken()); var departments = dbContext.SysDepartment.OrderByDescending(c => c.DepartmentName).ToList(); foreach (var item in departments) { if (item.DepartmentId == Guid.Parse("2379788E-45F0-417B-A103-0B6440A9D55D")) { continue; } var parentId = Convert.ToInt64(departments.Where(c => c.DepartmentId == item.ParentId).FirstOrDefault().WeixinWorkId); DepartmentList qyDep = result.department.Where(c => c.id == item.WeixinWorkId).FirstOrDefault(); if (qyDep == null) { var createResult = MailListApi.CreateDepartment(WeixinWorkService.GetToken(), item.DepartmentName, parentId == 0 ? 1 : parentId, 1000 - (item.OrderNo.HasValue ? item.OrderNo.Value : 0)); item.WeixinWorkId = createResult.id; } else { MailListApi.UpdateDepartment(WeixinWorkService.GetToken(), qyDep.id, item.DepartmentName, parentId == 0 ? 1 : parentId, 1000 - (item.OrderNo.HasValue ? item.OrderNo.Value : 0)); } dbContext.SaveChanges(); } //同步用户 var users = dbContext.SysUser.Where(c => c.UserCode != "admin").ToList(); foreach (var userItem in users) { long[] longArr = new long[1]; longArr[0] = Convert.ToInt64(dbContext.SysDepartment.Where(c => c.DepartmentId == userItem.DepartmentId).FirstOrDefault().WeixinWorkId); try { var memberResult = MailListApi.GetMember(WeixinWorkService.GetToken(), userItem.UserCode); if (memberResult.errcode == Senparc.Weixin.ReturnCode_Work.UserID不存在) { MemberCreateRequest request = new MemberCreateRequest(); request.email = userItem.Email; request.department = longArr; request.enable = 1; request.mobile = userItem.Mobile; request.name = userItem.UserName; request.userid = userItem.UserCode; MailListApi.CreateMember(WeixinWorkService.GetToken(), request); } else { MemberUpdateRequest updateRequest = new MemberUpdateRequest(); updateRequest.department = longArr; updateRequest.email = userItem.Email; updateRequest.enable = 1; updateRequest.mobile = userItem.Mobile; updateRequest.name = userItem.UserName; updateRequest.userid = userItem.UserCode; MailListApi.UpdateMember(WeixinWorkService.GetToken(), updateRequest); } } catch { } } return(Json(new { Code = 0, Msg = "同步成功!" })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
/// <summary> /// Get the wechat users and save to database. /// </summary> /// <returns></returns> public static bool GetWechatUserToDB() { string token = AccessTokenContainer.TryGetToken(corpID, corpSecret); WechatContext context = new WechatContext(); //todo: 清空现有用户数据 //获取微信企业号内的用户架构信息 Dictionary <string, List <Tag> > _userTags = new Dictionary <string, List <Tag> >(); Dictionary <int, List <Tag> > _partyTags = new Dictionary <int, List <Tag> >(); Dictionary <string, User> Users = new Dictionary <string, User>(); //查找所有Tag并插入数据库 GetTagListResult tagList = MailListApi.GetTagList(token); if (tagList != null && tagList.taglist != null && tagList.taglist.Count > 0) { foreach (var tag in tagList.taglist) { int tagId = -1; if (Int32.TryParse(tag.tagid, out tagId)) { Tag tempTag = new Tag() { TagId = tagId, TagName = tag.tagname }; GetTagMemberResult tagMemberResult = MailListApi.GetTagMember(token, tagId); if (tagMemberResult != null && tagMemberResult.partylist != null && tagMemberResult.partylist.Length > 0) { foreach (int party in tagMemberResult.partylist) { if (!_partyTags.ContainsKey(party)) { _partyTags[party] = new List <Tag>(); } _partyTags[party].Add(tempTag); } } if (tagMemberResult != null && tagMemberResult.userlist != null && tagMemberResult.userlist.Count > 0) { foreach (var tagUser in tagMemberResult.userlist) { if (!_userTags.ContainsKey(tagUser.userid)) { _userTags[tagUser.userid] = new List <Tag>(); } _userTags[tagUser.userid].Add(tempTag); } } context.Tags.Add(tempTag); } } context.SaveChanges(); } //查找所有部门并插入数据库 GetDepartmentListResult departmentList = MailListApi.GetDepartmentList(token); if (departmentList != null && departmentList.department != null) { foreach (var party in departmentList.department) { var tempParty = new Party() { PartyId = party.id, Name = party.name, Order = party.order, ParentPartyId = party.parentid }; //此处需要查询所有的Tag保存到库中 if (_partyTags.ContainsKey(party.id)) { tempParty.PartyTags = _partyTags[party.id].Select(f => new PartyTag() { PartyId = tempParty.PartyId, TagId = f.TagId }).ToList(); } //根据部门查找所有用户并存入缓存 GetDepartmentMemberInfoResult memberInfos = MailListApi.GetDepartmentMemberInfo(token, party.id, 1, 0); if (memberInfos != null && memberInfos.userlist != null && memberInfos.userlist.Count > 0) { foreach (var member in memberInfos.userlist) { if (!Users.ContainsKey(member.userid)) { Users[member.userid] = new User() { Avatar = member.avatar, Email = member.email, Gender = member.gender, Mobile = member.mobile, Name = member.name, Position = member.position, Status = member.status, UserId = member.userid, Weixinid = member.weixinid, UserTags = (_userTags.ContainsKey(member.userid) && _userTags[member.userid].Count > 0) ? _userTags[member.userid].Select(f => new UserTag() { UserId = member.userid, TagId = f.TagId }).ToList() : null }; } Users[member.userid].UserPartys.Add(new UserParty() { PartyId = tempParty.PartyId, UserId = member.userid }); } } context.Partys.Add(tempParty); } context.SaveChanges(); } if (Users != null && Users.Count > 0) { foreach (var user in Users.Values) { context.Users.Add(user); } context.SaveChanges(); } return(true); }