package new_mobile_api_controllers import ( "XT_New/controllers/mobile_api_controllers" "XT_New/enums" "XT_New/models" "XT_New/service" "XT_New/utils" "encoding/json" "github.com/astaxie/beego" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" ) type HomeController struct { NewMobileBaseAPIAuthController } func (this *HomeController) GetHomeData() { adminUserInfo := this.GetMobileAdminUserInfo() if adminUserInfo.Org != nil && adminUserInfo.Org.Id != 0 { //获取该管理员所有机构列表 var orgs []*models.Org adminUser, err := service.GetHomeData(adminUserInfo.AdminUser.Id) if err != nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError) return } for _, item := range adminUser.Org { orgs = append(orgs, item) } for _, item := range adminUser.VMApp_Role { for _, subItem := range item.Org { orgs = append(orgs, subItem) } } orgs = RemoveRepeatedOrgElement(orgs) var isSubSuperAdmin bool = false if adminUserInfo.AppRole != nil && adminUserInfo.AppRole.Id > 0 { app_role, _ := service.GetAppRoleById(adminUserInfo.AppRole.Id) if len(app_role.RoleIds) > 0 { role_ids := strings.Split(app_role.RoleIds, ",") if adminUserInfo.AdminUser.Id != adminUserInfo.Org.Creator { for _, item := range role_ids { id, _ := strconv.ParseInt(item, 10, 64) if id > 0 { role, _ := service.GetRoleByRoleID(id) if role != nil { if role.IsSystem == 1 && role.RoleName == "子管理员" { isSubSuperAdmin = true } } } } } } } apps, err := service.GetAllApp(adminUserInfo.Org.Id) if err != nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError) return } banners, err := service.GetSystemBanner() if err != nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError) return } this.ServeSuccessJSON(map[string]interface{}{ "orgs": orgs, "apps": apps, "banners": banners, "isCreateOrg": true, "isSubSuperAdmin": isSubSuperAdmin, }) } else { apps, err := service.GetAllApp(0) if err != nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError) return } banners, err := service.GetSystemBanner() if err != nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError) return } this.ServeSuccessJSON(map[string]interface{}{ "isCreateOrg": false, "apps": apps, "banners": banners, "isSubSuperAdmin": false, }) } } func RemoveRepeatedOrgElement(orgs []*models.Org) (newOrgs []*models.Org) { newOrgs = make([]*models.Org, 0) for i := 0; i < len(orgs); i++ { repeat := false for j := i + 1; j < len(orgs); j++ { if orgs[i].Id == orgs[j].Id { repeat = true break } } if !repeat { newOrgs = append(newOrgs, orgs[i]) } } return } func (this *HomeController) ChangeOrg() { org_id, _ := this.GetInt64("org_id") adminUserInfo := this.GetMobileAdminUserInfo() tempOrg, err := service.GetOrgById(org_id) if err != nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError) return } if tempOrg == nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOrgNoExist) return } mobile := adminUserInfo.AdminUser.Mobile // 只取最近被创建的 admin_role adminUser, getAdminErr := service.GetValidAdminUserByMobileReturnErr(mobile) //账号信息唯一值 if getAdminErr != nil { utils.ErrorLog("获取管理员失败:%v", getAdminErr) this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException) this.ServeJSON() return } else if adminUser == nil { utils.ErrorLog("查找不到 mobile = %v 的用户", mobile) this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong) this.ServeJSON() return } else { var appRole *models.App_Role var org *models.Org var subscibe *models.ServeSubscibe var app *models.OrgApp //根据登录信息的机构和用户id,去获取对应用户信息和机构信息 tempApp, _ := service.GetOrgApp(tempOrg.Id, 3) tempRole, _ := service.GetAppRole(tempOrg.Id, tempApp.Id, adminUser.Id) tempSubscibe, getSubscibeErr := service.GetOrgServeSubscibe(tempOrg.Id) if getSubscibeErr != nil { utils.ErrorLog("获取机构订阅信息失败:%v", getSubscibeErr) this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException) this.ServeJSON() return } subscibe = tempSubscibe org = tempOrg appRole = tempRole app = tempApp templateInfo, _ := service.GetOrgInfoTemplate(org.Id) mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{ AdminUser: adminUser, Org: org, App: app, AppRole: appRole, Subscibe: subscibe, TemplateInfo: &templateInfo, } if org != nil && appRole != nil { // 插入一条登录记录 ip := this.GetString("ip") loginLog := &models.AdminUserLoginLog{ AdminUserId: adminUser.Id, OrgId: org.Id, AppId: appRole.AppId, IP: ip, OperateType: 3, AppType: 3, CreateTime: time.Now().Unix(), } if insertErr := service.InsertLoginLog(loginLog); insertErr != nil { utils.ErrorLog("为手机号为%v的用户插入一条登录记录失败:%v", mobile, insertErr) } } //删除session和cookie this.DelSession("mobile_admin_user_info") this.Ctx.SetCookie("token_cookie", "") //设置new seesion this.SetSession("mobile_admin_user_info", mobileAdminUserInfo) //设置new cookie mobile := adminUser.Mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10) token := utils.GenerateLoginToken(mobile) expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second") this.Ctx.SetCookie("token_cookie", token, expiration, "/") var configList interface{} var FiledList []*models.FiledConfig if org.Id > 0 { configList, _ = service.GetConfigList(org.Id) FiledList, _ = service.FindFiledByOrgId(org.Id) } if len(FiledList) == 0 { var err error if org.Id > 0 { err = service.BatchInsertFiledConfig(org.Id) if err == nil { FiledList, _ = service.FindFiledByOrgId(org.Id) } else { utils.ErrorLog("字段批量插入失败:%v", err) } } else { FiledList = make([]*models.FiledConfig, 0) } } this.ServeSuccessJSON(map[string]interface{}{ "admin": adminUser, "user": appRole, "org": org, "template_info": map[string]interface{}{ "id": templateInfo.ID, "org_id": templateInfo.OrgId, "template_id": templateInfo.TemplateId, }, "config_list": configList, "filed_list": FiledList, }) } } func (this *HomeController) CreateOrg() { adminUserInfo := this.GetMobileAdminUserInfo() adminUser := adminUserInfo.AdminUser //if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil { // this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException) // this.ServeJSON() // return //} else if didCreateOrg { // this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRepeatCreateOrg) // this.ServeJSON() // return //} name := this.GetString("org_name") shortName := name provinceName := this.GetString("provinces_name") cityName := this.GetString("city_name") districtName := this.GetString("district_name") address := this.GetString("address") org_type := this.GetString("org_type") contactName := this.GetString("contact_name") openXT := true openCDM := false openSCRM := false openMall := false if len(name) == 0 || len(shortName) == 0 || len(contactName) == 0 || len(address) == 0 || len(provinceName) <= 0 || len(cityName) <= 0 || len(districtName) <= 0 || len(org_type) <= 0 { this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong) this.ServeJSON() return } orgPhone := this.GetString("telephone") provinceID := 0 cityID := 0 districtID := 0 province, getProvinceErr := service.GetProvinceWithName(provinceName) if getProvinceErr != nil { utils.ErrorLog("查询省名失败:%v", getProvinceErr) this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException) this.ServeJSON() return } else if province != nil { provinceID = int(province.ID) city, getCityErr := service.GetCityWithName(province.ID, cityName) if getCityErr != nil { utils.ErrorLog("查询城市名失败:%v", getCityErr) this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException) this.ServeJSON() return } else if city != nil { cityID = int(city.ID) district, getDistrictErr := service.GetDistrictWithName(city.ID, districtName) if getDistrictErr != nil { utils.ErrorLog("查询区县名失败:%v", getDistrictErr) this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException) this.ServeJSON() return } else if district != nil { districtID = int(district.ID) } } } var orgs []*models.Org vmAdminUser, err := service.GetHomeData(adminUser.Id) if err != nil { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError) return } for _, item := range vmAdminUser.Org { orgs = append(orgs, item) } for _, item := range vmAdminUser.VMApp_Role { for _, subItem := range item.Org { orgs = append(orgs, subItem) } } orgs = RemoveRepeatedOrgElement(orgs) orgType := service.GetOrgTypeByName(org_type) org := &models.Org{ Creator: adminUser.Id, OrgName: name, OrgShortName: shortName, Province: int64(provinceID), City: int64(cityID), District: int64(districtID), Address: address, OrgType: orgType.ID, Telephone: orgPhone, ContactName: contactName, Claim: 1, Evaluate: 5, Status: 1, CreateTime: time.Now().Unix(), ModifyTime: time.Now().Unix(), } createErr := service.CreateOrg(org, adminUser.Name, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app,如果有新类型的平台,则需要在这个方法里面把创建这一新类型的 app 的代码加上 if createErr != nil { utils.ErrorLog("mobile=%v的超级管理员创建机构失败:%v", adminUser.Mobile, createErr) this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate) this.ServeJSON() } else { //初始化病人和排班相关数据 InitPatientAndSchedule(org) //初始化透析方案 InitSystemPrescrption(org) //初始化医嘱模版 //InitAdviceTemplate(org) //初始化角色和权限 InitRoleAndPurviews(org) //初始化设备管理 InitEquitMentInformation(org) //初始化显示配置和打印模版 InitShowConfig(org) if len(orgs) == 0 { ip := utils.GetIP(this.Ctx.Request) ssoDomain := beego.AppConfig.String("sso_domain") api := ssoDomain + "/m/login/pwd" values := make(url.Values) values.Set("mobile", adminUser.Mobile) values.Set("password", adminUser.Password) values.Set("app_type", "3") values.Set("ip", ip) resp, requestErr := http.PostForm(api, values) if requestErr != nil { utils.ErrorLog("请求SSO登录接口失败: %v", requestErr) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } defer resp.Body.Close() body, ioErr := ioutil.ReadAll(resp.Body) if ioErr != nil { utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } var respJSON map[string]interface{} utils.InfoLog(string(body)) if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil { utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } if respJSON["state"].(float64) != 1 { msg := respJSON["msg"].(string) utils.ErrorLog("SSO登录接口请求失败: %v", msg) if int(respJSON["code"].(float64)) == 609 { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong) return } this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } else { utils.SuccessLog("SSO登录成功") // 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢 userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{}) userJSONBytes, _ := json.Marshal(userJSON) var adminUser models.AdminUser if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil { utils.ErrorLog("解析管理员失败:%v", err) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } var org models.Org if respJSON["data"].(map[string]interface{})["org"] != nil { orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{}) orgJSONBytes, _ := json.Marshal(orgJSON) if err := json.Unmarshal(orgJSONBytes, &org); err != nil { utils.ErrorLog("解析机构失败:%v", err) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } } var app models.OrgApp if respJSON["data"].(map[string]interface{})["app"] != nil { appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{}) appJSONBytes, _ := json.Marshal(appJSON) if err := json.Unmarshal(appJSONBytes, &app); err != nil { utils.ErrorLog("解析应用失败:%v", err) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } } var appRole models.App_Role if respJSON["data"].(map[string]interface{})["app_role"] != nil { appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{}) appRoleJSONBytes, _ := json.Marshal(appRoleJSON) if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil { utils.ErrorLog("解析AppRole失败:%v", err) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } } var subscibe models.ServeSubscibe if respJSON["data"].(map[string]interface{})["subscibe"] != nil { subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{}) subscibeJSONBytes, _ := json.Marshal(subscibeJSON) if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil { utils.ErrorLog("解析Subscibe失败:%v", err) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } } //service.GetOrgSubscibeState(&subscibe) templateInfo, _ := service.GetOrgInfoTemplate(org.Id) mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{ AdminUser: &adminUser, Org: &org, App: &app, AppRole: &appRole, Subscibe: &subscibe, TemplateInfo: &templateInfo, } this.Ctx.SetCookie("token_cookie", "") //设置seesion this.SetSession("mobile_admin_user_info", mobileAdminUserInfo) //设置cookie mobile := adminUser.Mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10) token := utils.GenerateLoginToken(mobile) expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second") this.Ctx.SetCookie("token_cookie", token, expiration, "/") var configList interface{} var FiledList []*models.FiledConfig if org.Id > 0 { configList, _ = service.GetConfigList(org.Id) FiledList, _ = service.FindFiledByOrgId(org.Id) } if len(FiledList) == 0 { var err error if org.Id > 0 { err = service.BatchInsertFiledConfig(org.Id) if err == nil { FiledList, _ = service.FindFiledByOrgId(org.Id) } else { utils.ErrorLog("字段批量插入失败:%v", err) } } else { FiledList = make([]*models.FiledConfig, 0) } } this.ServeSuccessJSON(map[string]interface{}{ "admin": adminUser, "user": appRole, "org": org, "template_info": map[string]interface{}{ "id": templateInfo.ID, "org_id": templateInfo.OrgId, "template_id": templateInfo.TemplateId, }, "config_list": configList, "filed_list": FiledList, "status": 1, }) } } else { this.ServeSuccessJSON(map[string]interface{}{ "org": org, "status": 2, }) } } } func (this *HomeController) ModifyPsw() { mobile := this.GetString("mobile") code := this.GetString("code") password := this.GetString("password") checkErr := this.checkParam(mobile, code, password) if checkErr != nil { this.ServeFailJSONWithSGJErrorCode(checkErr.Code) return } adminUser, _ := service.GetValidAdminUserByMobileReturnErr(mobile) modifyErr := service.ModifyPassword(adminUser.Id, password) if modifyErr != nil { utils.ErrorLog("修改mobile=%v的用户的密码时失败: %v", mobile, modifyErr) this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate) return } else { // 修改成功后验证码就要使其失效 redisClient := service.RedisClient() defer redisClient.Close() redisClient.Del("code_msg_" + mobile) this.ServeSuccessJSON(map[string]interface{}{ "admin": adminUser, }) return } } func (this *HomeController) checkParam(mobile string, code string, password string) *enums.SGJError { if utils.CellPhoneRegexp().MatchString(mobile) == false { return &enums.SGJError{Code: enums.ErrorCodeMobileFormat} } if len(code) == 0 { return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong} } if len(password) == 0 { return &enums.SGJError{Code: enums.ErrorCodePasswordEmpty} } if service.IsMobileRegister(mobile) == false { return &enums.SGJError{Code: enums.ErrorCodeMobileNotExit} } redisClient := service.RedisClient() defer redisClient.Close() cache_code, _ := redisClient.Get("code_msg_" + mobile).Result() if cache_code != code { return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong} } return nil } func (this *HomeController) GetFuncPermission() { adminUserInfo := this.GetMobileAdminUserInfo() user_id := adminUserInfo.AdminUser.Id app_id := adminUserInfo.App.Id org_id := adminUserInfo.Org.Id create_url := this.GetString("create_url") modify_url := this.GetString("modify_url") modify_other_url := this.GetString("modify_other_url") del_url := this.GetString("del_url") del_other_url := this.GetString("del_other_url") exce_url := this.GetString("exce_url") check_url := this.GetString("check_url") modify_exce_url := this.GetString("modify_exce_url") module, _ := this.GetInt64("module", 0) app_role, _ := service.GetAppRole(org_id, app_id, user_id) var is_has_create bool var is_has_modify bool var is_has_modify_other bool var is_has_del bool var is_has_del_other bool var is_has_exce bool var is_has_check bool var is_has_modify_exce bool if adminUserInfo.AdminUser.Id != adminUserInfo.Org.Creator { if app_role != nil { if len(app_role.RoleIds) > 0 { roles := strings.Split(app_role.RoleIds, ",") var userRolePurviews string for _, item := range roles { role_id, _ := strconv.ParseInt(item, 10, 64) purviews, _ := service.GetRoleFuncPurviewIds(role_id) if len(userRolePurviews) == 0 { userRolePurviews = purviews } else { userRolePurviews = userRolePurviews + "," + purviews } } userRolePurviewsArr := RemoveRepeatedPurviewElement2(strings.Split(userRolePurviews, ",")) funcPurviews, _ := service.FindAllFuncPurview(userRolePurviewsArr) for _, item := range funcPurviews { //for _, url := range strings.Split(item.Urlfor,","){ if strings.Split(item.Urlfor, ",")[0] == create_url { is_has_create = true } if strings.Split(item.Urlfor, ",")[0] == modify_url { is_has_modify = true } if strings.Split(item.Urlfor, ",")[0] == modify_other_url { is_has_modify_other = true } if strings.Split(item.Urlfor, ",")[0] == del_url { is_has_del = true } if strings.Split(item.Urlfor, ",")[0] == del_other_url { is_has_del_other = true } if strings.Split(item.Urlfor, ",")[0] == exce_url { is_has_exce = true } if strings.Split(item.Urlfor, ",")[0] == check_url { is_has_check = true } if strings.Split(item.Urlfor, ",")[0] == modify_exce_url { is_has_modify_exce = true } } } else { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRole) return } this.ServeSuccessJSON(map[string]interface{}{ "is_has_create": is_has_create, "is_has_modify": is_has_modify, "is_has_modify_other": is_has_modify_other, "is_has_del": is_has_del, "is_has_del_other": is_has_del_other, "is_has_exce": is_has_exce, "is_has_check": is_has_check, "is_has_modify_exce": is_has_modify_exce, "module": module, }) } else { this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAdminUserIsExit) return } } else { this.ServeSuccessJSON(map[string]interface{}{ "is_has_create": true, "is_has_modify": true, "is_has_modify_other": true, "is_has_del": true, "is_has_del_other": true, "is_has_exce": true, "is_has_check": true, "is_has_modify_exce": true, "module": true, }) } } func RemoveRepeatedPurviewElement2(arr []string) (newArr []string) { newArr = make([]string, 0) for i := 0; i < len(arr); i++ { repeat := false for j := i + 1; j < len(arr); j++ { if arr[i] == arr[j] { repeat = true break } } if !repeat { newArr = append(newArr, arr[i]) } } return }