Browse Source

Merge branch 'master' of http://git.shengws.com/csx/XT_New

csx 5 years ago
parent
commit
5d69995afd

+ 31 - 1
conf/app.conf View File

@@ -34,7 +34,7 @@ sms_token = ea475ed8d3de6c54c2b3f9d78db76d1e
34 34
 sms_baseUrl = https://open.ucpaas.com/ol/sms/
35 35
 ip_max_send_count = 20
36 36
 moblie_max_send_count = 5
37
-sms_verification_code_templateid = 329532
37
+sms_verification_code_templateid = 358429
38 38
 
39 39
 
40 40
 appid = "wx43ad410d9eef426e"
@@ -86,6 +86,21 @@ writemiddleuser = syh
86 86
 writemiddlepass = xhPECP2nFObR8aUK
87 87
 writemiddlename = ky_xt_middle
88 88
 
89
+
90
+readsgjpatientmysqlhost = shengws1.mysql.rds.aliyuncs.com
91
+readsgjpatientmysqlport = 3306
92
+readsgjpatientmysqluser = syh
93
+readsgjpatientmysqlpass = xhPECP2nFObR8aUK
94
+readsgjpatientmysqlname = sgj_patient
95
+
96
+writesgjpatientmysqlhost = shengws1.mysql.rds.aliyuncs.com
97
+writesgjpatientmysqlport = 3306
98
+writesgjpatientmysqluser = syh
99
+writesgjpatientmysqlpass = xhPECP2nFObR8aUK
100
+writesgjpatientmysqlname = sgj_patient
101
+
102
+
103
+
89 104
 redishost = 349e580b2a524290.redis.rds.aliyuncs.com
90 105
 redisport = 6379
91 106
 redispasswrod = TZtBW098WId3i27clkpj3q8dnUaVFP
@@ -94,6 +109,8 @@ redisdb = 0
94 109
 
95 110
 
96 111
 
112
+
113
+
97 114
 niprocart =  63
98 115
 jms = 58
99 116
 fistula_needle_set = 65
@@ -166,6 +183,19 @@ writepatientuser = root
166 183
 writepatientpass = 1Q2W3e4r!@#$
167 184
 writepatientname = sgj_cdm
168 185
 
186
+readsgjpatientmysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
187
+readsgjpatientmysqlport = 3306
188
+readsgjpatientmysqluser = root
189
+readsgjpatientmysqlpass = 1Q2W3e4r!@#$
190
+readsgjpatientmysqlname = sgj_patient
191
+
192
+writesgjpatientmysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
193
+writesgjpatientmysqlport = 3306
194
+writesgjpatientmysqluser = root
195
+writesgjpatientmysqlpass = 1Q2W3e4r!@#$
196
+writesgjpatientmysqlname = sgj_patient
197
+
198
+
169 199
 #redishost = 120.77.235.13
170 200
 #redishost = 112.74.16.180
171 201
 redishost = localhost

+ 9 - 9
controllers/base_api_controller.go View File

@@ -95,15 +95,15 @@ func (this *BaseAuthAPIController) Prepare() {
95 95
 		//this.StopRun()
96 96
 	}
97 97
 
98
-	if this.Ctx.Request.Method != "GET" {
99
-		adminUserInfo := this.GetAdminUserInfo()
100
-
101
-		err := service.GetOrgSubscibeState(adminUserInfo.Subscibes[adminUserInfo.CurrentOrgId])
102
-		if err != nil || adminUserInfo.Subscibes[adminUserInfo.CurrentOrgId].State == 3 {
103
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
104
-			this.StopRun()
105
-		}
106
-	}
98
+	//if this.Ctx.Request.Method != "GET" {
99
+	//	adminUserInfo := this.GetAdminUserInfo()
100
+	//
101
+	//	err := service.GetOrgSubscibeState(adminUserInfo.Subscibes[adminUserInfo.CurrentOrgId])
102
+	//	if err != nil || adminUserInfo.Subscibes[adminUserInfo.CurrentOrgId].State == 3 {
103
+	//		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
104
+	//		this.StopRun()
105
+	//	}
106
+	//}
107 107
 
108 108
 	//if this.Ctx.Request.Header.Get("Permission") == "1" {
109 109
 	//

+ 7 - 8
controllers/mobile_api_controllers/mobile_api_base_controller.go View File

@@ -4,7 +4,6 @@ import (
4 4
 	"XT_New/controllers"
5 5
 	"XT_New/enums"
6 6
 	"XT_New/models"
7
-	"XT_New/service"
8 7
 	"fmt"
9 8
 )
10 9
 
@@ -54,11 +53,11 @@ func (this *MobileBaseAPIAuthController) Prepare() {
54 53
 		this.StopRun()
55 54
 	}
56 55
 
57
-	if this.Ctx.Request.Method != "GET" {
58
-		err := service.GetOrgSubscibeState(adminUserInfo.Subscibe)
59
-		if err != nil || adminUserInfo.Subscibe.State == 3 {
60
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
61
-			this.StopRun()
62
-		}
63
-	}
56
+	//if this.Ctx.Request.Method != "GET" {
57
+	//	err := service.GetOrgSubscibeState(adminUserInfo.Subscibe)
58
+	//	if err != nil || adminUserInfo.Subscibe.State == 3 {
59
+	//		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
60
+	//		this.StopRun()
61
+	//	}
62
+	//}
64 63
 }

+ 331 - 0
controllers/new_mobile_api_controllers/home_api_controller.go View File

@@ -0,0 +1,331 @@
1
+package new_mobile_api_controllers
2
+
3
+import (
4
+	"XT_New/controllers/mobile_api_controllers"
5
+	"XT_New/enums"
6
+	"XT_New/models"
7
+	"XT_New/service"
8
+	"XT_New/utils"
9
+	"github.com/astaxie/beego"
10
+	"strconv"
11
+	"time"
12
+)
13
+
14
+type HomeController struct {
15
+	NewMobileBaseAPIAuthController
16
+}
17
+
18
+func (this *HomeController) GetHomeData() {
19
+	adminUserInfo := this.GetMobileAdminUserInfo()
20
+	if adminUserInfo.Org != nil {
21
+		//获取该管理员所有机构列表
22
+		var orgs []*models.Org
23
+		adminUser, err := service.GetHomeData(adminUserInfo.AdminUser.Id)
24
+		if err != nil {
25
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
26
+			return
27
+		}
28
+		for _, item := range adminUser.Org {
29
+			orgs = append(orgs, item)
30
+		}
31
+		for _, item := range adminUser.VMApp_Role {
32
+			for _, subItem := range item.Org {
33
+				orgs = append(orgs, subItem)
34
+			}
35
+		}
36
+		orgs = RemoveRepeatedOrgElement(orgs)
37
+
38
+		apps, err := service.GetAllApp(adminUserInfo.Org.Id)
39
+		if err != nil {
40
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
41
+			return
42
+		}
43
+
44
+		banners, err := service.GetSystemBanner()
45
+		if err != nil {
46
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
47
+			return
48
+		}
49
+
50
+		this.ServeSuccessJSON(map[string]interface{}{
51
+			"orgs":        orgs,
52
+			"apps":        apps,
53
+			"banners":     banners,
54
+			"isCreateOrg": true,
55
+		})
56
+	} else {
57
+		this.ServeSuccessJSON(map[string]interface{}{
58
+			"isCreateOrg": false,
59
+		})
60
+	}
61
+
62
+}
63
+
64
+func RemoveRepeatedOrgElement(orgs []*models.Org) (newOrgs []*models.Org) {
65
+	newOrgs = make([]*models.Org, 0)
66
+	for i := 0; i < len(orgs); i++ {
67
+		repeat := false
68
+		for j := i + 1; j < len(orgs); j++ {
69
+			if orgs[i].Id == orgs[j].Id {
70
+				repeat = true
71
+				break
72
+			}
73
+		}
74
+		if !repeat {
75
+			newOrgs = append(newOrgs, orgs[i])
76
+		}
77
+	}
78
+	return
79
+}
80
+
81
+func (this *HomeController) ChangeOrg() {
82
+	org_id, _ := this.GetInt64("org_id")
83
+	adminUserInfo := this.GetMobileAdminUserInfo()
84
+
85
+	tempOrg, err := service.GetOrgById(org_id)
86
+	if err != nil {
87
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
88
+		return
89
+	}
90
+
91
+	if tempOrg == nil {
92
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOrgNoExist)
93
+		return
94
+	}
95
+
96
+	mobile := adminUserInfo.AdminUser.Mobile
97
+	// 只取最近被创建的 admin_role
98
+	adminUser, getAdminErr := service.GetValidAdminUserByMobileReturnErr(mobile) //账号信息唯一值
99
+	if getAdminErr != nil {
100
+		utils.ErrorLog("获取管理员失败:%v", getAdminErr)
101
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
102
+		this.ServeJSON()
103
+		return
104
+	} else if adminUser == nil {
105
+		utils.ErrorLog("查找不到 mobile = %v 的用户", mobile)
106
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
107
+		this.ServeJSON()
108
+		return
109
+	} else {
110
+
111
+		var appRole *models.App_Role
112
+		var org *models.Org
113
+		var subscibe *models.ServeSubscibe
114
+		var app *models.OrgApp
115
+
116
+		//根据登录信息的机构和用户id,去获取对应用户信息和机构信息
117
+		tempApp, _ := service.GetOrgApp(tempOrg.Id, 3)
118
+		tempRole, _ := service.GetAppRole(tempOrg.Id, tempApp.Id, adminUser.Id)
119
+
120
+		tempSubscibe, getSubscibeErr := service.GetOrgServeSubscibe(tempOrg.Id)
121
+		if getSubscibeErr != nil {
122
+			utils.ErrorLog("获取机构订阅信息失败:%v", getSubscibeErr)
123
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
124
+			this.ServeJSON()
125
+			return
126
+		}
127
+
128
+		subscibe = tempSubscibe
129
+		org = tempOrg
130
+		appRole = tempRole
131
+		app = tempApp
132
+
133
+		if org != nil && appRole != nil {
134
+			// 插入一条登录记录
135
+			ip := this.GetString("ip")
136
+			loginLog := &models.AdminUserLoginLog{
137
+				AdminUserId: adminUser.Id,
138
+				OrgId:       org.Id,
139
+				AppId:       appRole.AppId,
140
+				IP:          ip,
141
+				OperateType: 3,
142
+				AppType:     int8(3),
143
+				CreateTime:  time.Now().Unix(),
144
+			}
145
+			if insertErr := service.InsertLoginLog(loginLog); insertErr != nil {
146
+				utils.ErrorLog("为手机号为%v的用户插入一条登录记录失败:%v", mobile, insertErr)
147
+			}
148
+		}
149
+
150
+		templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
151
+
152
+		mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{
153
+			AdminUser:    adminUser,
154
+			Org:          org,
155
+			App:          app,
156
+			AppRole:      appRole,
157
+			Subscibe:     subscibe,
158
+			TemplateInfo: &templateInfo,
159
+		}
160
+
161
+		//删除session和cookie
162
+		this.DelSession("mobile_admin_user_info")
163
+		this.Ctx.SetCookie("token_cookie", "")
164
+
165
+		//设置new seesion
166
+		this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
167
+		//设置new cookie
168
+		mobile := adminUser.Mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
169
+		token := utils.GenerateLoginToken(mobile)
170
+		expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
171
+		this.Ctx.SetCookie("token_cookie", token, expiration, "/")
172
+
173
+		var configList interface{}
174
+		var FiledList []*models.FiledConfig
175
+
176
+		if org.Id > 0 {
177
+			configList, _ = service.GetConfigList(org.Id)
178
+			FiledList, _ = service.FindFiledByOrgId(org.Id)
179
+		}
180
+		if len(FiledList) == 0 {
181
+			var err error
182
+			if org.Id > 0 {
183
+				err = service.BatchInsertFiledConfig(org.Id)
184
+				if err == nil {
185
+					FiledList, _ = service.FindFiledByOrgId(org.Id)
186
+				} else {
187
+					utils.ErrorLog("字段批量插入失败:%v", err)
188
+				}
189
+			} else {
190
+				FiledList = make([]*models.FiledConfig, 0)
191
+			}
192
+		}
193
+		this.ServeSuccessJSON(map[string]interface{}{
194
+			"admin": adminUser,
195
+			"user":  appRole,
196
+			"org":   org,
197
+			"template_info": map[string]interface{}{
198
+				"id":          templateInfo.ID,
199
+				"org_id":      templateInfo.OrgId,
200
+				"template_id": templateInfo.TemplateId,
201
+			},
202
+			"config_list": configList,
203
+			"filed_list":  FiledList,
204
+		})
205
+	}
206
+
207
+}
208
+
209
+func (this *HomeController) CreateOrg() {
210
+
211
+	adminUserInfo := this.GetMobileAdminUserInfo()
212
+	adminUser := adminUserInfo.AdminUser
213
+
214
+	if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil {
215
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
216
+		this.ServeJSON()
217
+		return
218
+	} else if didCreateOrg {
219
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRepeatCreateOrg)
220
+		this.ServeJSON()
221
+		return
222
+	}
223
+
224
+	name := this.GetString("org_name")
225
+	shortName := name
226
+	provinceName := this.GetString("provinces_name")
227
+	cityName := this.GetString("city_name")
228
+	districtName := this.GetString("district_name")
229
+	address := this.GetString("address")
230
+	org_type := this.GetString("org_type")
231
+	contactName := this.GetString("contact_name")
232
+
233
+	openXT := true
234
+	openCDM := false
235
+	openSCRM := false
236
+	openMall := false
237
+
238
+	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 {
239
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
240
+		this.ServeJSON()
241
+		return
242
+	}
243
+	orgPhone := this.GetString("telephone")
244
+
245
+	if len(orgPhone) > 0 {
246
+		if utils.PhoneRegexp().MatchString(orgPhone) == false {
247
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
248
+			this.ServeJSON()
249
+			return
250
+		}
251
+	}
252
+
253
+	provinceID := 0
254
+	cityID := 0
255
+	districtID := 0
256
+
257
+	province, getProvinceErr := service.GetProvinceWithName(provinceName)
258
+	if getProvinceErr != nil {
259
+		utils.ErrorLog("查询省名失败:%v", getProvinceErr)
260
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
261
+		this.ServeJSON()
262
+		return
263
+	} else if province != nil {
264
+		provinceID = int(province.ID)
265
+		city, getCityErr := service.GetCityWithName(province.ID, cityName)
266
+		if getCityErr != nil {
267
+			utils.ErrorLog("查询城市名失败:%v", getCityErr)
268
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
269
+			this.ServeJSON()
270
+			return
271
+		} else if city != nil {
272
+			cityID = int(city.ID)
273
+			district, getDistrictErr := service.GetDistrictWithName(city.ID, districtName)
274
+			if getDistrictErr != nil {
275
+				utils.ErrorLog("查询区县名失败:%v", getDistrictErr)
276
+				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
277
+				this.ServeJSON()
278
+				return
279
+			} else if district != nil {
280
+				districtID = int(district.ID)
281
+			}
282
+		}
283
+	}
284
+
285
+	orgType := service.GetOrgTypeByName(org_type)
286
+
287
+	org := &models.Org{
288
+		Creator:      adminUser.Id,
289
+		OrgName:      name,
290
+		OrgShortName: shortName,
291
+		Province:     int64(provinceID),
292
+		City:         int64(cityID),
293
+		District:     int64(districtID),
294
+		Address:      address,
295
+		OrgType:      orgType.ID,
296
+		Telephone:    orgPhone,
297
+		ContactName:  contactName,
298
+		Claim:        1,
299
+		Evaluate:     5,
300
+		Status:       1,
301
+		CreateTime:   time.Now().Unix(),
302
+		ModifyTime:   time.Now().Unix(),
303
+	}
304
+
305
+	createErr := service.CreateOrg(org, adminUser.Mobile, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app,如果有新类型的平台,则需要在这个方法里面把创建这一新类型的 app 的代码加上
306
+
307
+	if createErr != nil {
308
+		utils.ErrorLog("mobile=%v的超级管理员创建机构失败:%v", adminUser.Mobile, createErr)
309
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
310
+		this.ServeJSON()
311
+	} else {
312
+
313
+		//初始化病人和排班相关数据
314
+		InitPatientAndSchedule(org)
315
+		//初始化透析方案
316
+		InitSystemPrescrption(org)
317
+		//初始化医嘱模版
318
+		InitAdviceTemplate(org)
319
+		//初始化角色和权限
320
+
321
+		//初始化设备管理
322
+
323
+		//初始化显示配置
324
+
325
+		this.ServeSuccessJSON(map[string]interface{}{
326
+			"org": org,
327
+		})
328
+
329
+	}
330
+
331
+}

+ 548 - 54
controllers/new_mobile_api_controllers/mobile_regist_controller.go View File

@@ -8,12 +8,17 @@ import (
8 8
 	"XT_New/utils"
9 9
 	"bytes"
10 10
 	"encoding/json"
11
+	"fmt"
11 12
 	"github.com/astaxie/beego"
13
+	"io/ioutil"
12 14
 	"log"
15
+	"net/http"
16
+	"net/url"
13 17
 	"os"
14 18
 	"path"
15 19
 	"regexp"
16 20
 	"runtime"
21
+	"strconv"
17 22
 	"time"
18 23
 )
19 24
 
@@ -198,7 +203,7 @@ func (this *MobileRegistController) CreateOrg() {
198 203
 
199 204
 	orgType := service.GetOrgTypeByName(org_type)
200 205
 
201
-	org := models.Org{
206
+	org := &models.Org{
202 207
 		Creator:      adminUser.Id,
203 208
 		OrgName:      name,
204 209
 		OrgShortName: shortName,
@@ -216,17 +221,294 @@ func (this *MobileRegistController) CreateOrg() {
216 221
 		ModifyTime:   time.Now().Unix(),
217 222
 	}
218 223
 
219
-	createErr := service.CreateOrg(&org, adminUser.Mobile, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app,如果有新类型的平台,则需要在这个方法里面把创建这一新类型的 app 的代码加上
220
-	var ids []int64
224
+	createErr := service.CreateOrg(org, adminUser.Mobile, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app,如果有新类型的平台,则需要在这个方法里面把创建这一新类型的 app 的代码加上
225
+
226
+	if createErr != nil {
227
+		utils.ErrorLog("mobile=%v的超级管理员创建机构失败:%v", adminUser.Mobile, createErr)
228
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
229
+		this.ServeJSON()
230
+	} else {
221 231
 
232
+		//初始化病人和排班相关数据
233
+		InitPatientAndSchedule(org)
234
+		//初始化透析方案
235
+		InitSystemPrescrption(org)
236
+		//初始化医嘱模版
237
+		InitAdviceTemplate(org)
238
+		//初始化角色和权限
239
+
240
+		//初始化设备管理
241
+
242
+		//初始化显示配置
243
+
244
+		//创建完机构后进行登录验证操作
245
+		ip := utils.GetIP(this.Ctx.Request)
246
+		ssoDomain := beego.AppConfig.String("sso_domain")
247
+		api := ssoDomain + "/m/login/pwd"
248
+		values := make(url.Values)
249
+		values.Set("mobile", adminUser.Mobile)
250
+		values.Set("password", adminUser.Password)
251
+		values.Set("app_type", "3")
252
+		values.Set("ip", ip)
253
+		resp, requestErr := http.PostForm(api, values)
254
+
255
+		if requestErr != nil {
256
+			utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
257
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
258
+			return
259
+		}
260
+		defer resp.Body.Close()
261
+		body, ioErr := ioutil.ReadAll(resp.Body)
262
+		if ioErr != nil {
263
+			utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
264
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
265
+			return
266
+		}
267
+		var respJSON map[string]interface{}
268
+		utils.InfoLog(string(body))
269
+		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
270
+			utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
271
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
272
+			return
273
+		}
274
+
275
+		if respJSON["state"].(float64) != 1 {
276
+			msg := respJSON["msg"].(string)
277
+			utils.ErrorLog("SSO登录接口请求失败: %v", msg)
278
+			if int(respJSON["code"].(float64)) == 609 {
279
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
280
+				return
281
+			}
282
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
283
+			return
284
+		} else {
285
+			utils.SuccessLog("SSO登录成功")
286
+			// 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
287
+			userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
288
+			userJSONBytes, _ := json.Marshal(userJSON)
289
+			var adminUser models.AdminUser
290
+			if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
291
+				utils.ErrorLog("解析管理员失败:%v", err)
292
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
293
+				return
294
+			}
295
+
296
+			var org models.Org
297
+			if respJSON["data"].(map[string]interface{})["org"] != nil {
298
+				orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
299
+				orgJSONBytes, _ := json.Marshal(orgJSON)
300
+				if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
301
+					utils.ErrorLog("解析机构失败:%v", err)
302
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
303
+					return
304
+				}
305
+			}
306
+
307
+			var app models.OrgApp
308
+
309
+			if respJSON["data"].(map[string]interface{})["app"] != nil {
310
+				appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
311
+				appJSONBytes, _ := json.Marshal(appJSON)
312
+				if err := json.Unmarshal(appJSONBytes, &app); err != nil {
313
+					utils.ErrorLog("解析应用失败:%v", err)
314
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
315
+					return
316
+				}
317
+			}
318
+
319
+			var appRole models.App_Role
320
+
321
+			if respJSON["data"].(map[string]interface{})["app_role"] != nil {
322
+				appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
323
+				appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
324
+				if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
325
+					utils.ErrorLog("解析AppRole失败:%v", err)
326
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
327
+					return
328
+				}
329
+			}
330
+
331
+			var subscibe models.ServeSubscibe
332
+			if respJSON["data"].(map[string]interface{})["subscibe"] != nil {
333
+				subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
334
+				subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
335
+				if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
336
+					utils.ErrorLog("解析Subscibe失败:%v", err)
337
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
338
+					return
339
+				}
340
+
341
+			}
342
+
343
+			//service.GetOrgSubscibeState(&subscibe)
344
+			templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
345
+
346
+			mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{
347
+				AdminUser:    &adminUser,
348
+				Org:          &org,
349
+				App:          &app,
350
+				AppRole:      &appRole,
351
+				Subscibe:     &subscibe,
352
+				TemplateInfo: &templateInfo,
353
+			}
354
+			//设置seesion
355
+			this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
356
+
357
+			//设置cookie
358
+			mobile := adminUser.Mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
359
+			token := utils.GenerateLoginToken(mobile)
360
+			expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
361
+			this.Ctx.SetCookie("token_cookie", token, expiration, "/")
362
+
363
+			var configList interface{}
364
+			var FiledList []*models.FiledConfig
365
+
366
+			if org.Id > 0 {
367
+				configList, _ = service.GetConfigList(org.Id)
368
+				FiledList, _ = service.FindFiledByOrgId(org.Id)
369
+			}
370
+			if len(FiledList) == 0 {
371
+				var err error
372
+				if org.Id > 0 {
373
+					err = service.BatchInsertFiledConfig(org.Id)
374
+					if err == nil {
375
+						FiledList, _ = service.FindFiledByOrgId(org.Id)
376
+					} else {
377
+						utils.ErrorLog("字段批量插入失败:%v", err)
378
+					}
379
+				} else {
380
+					FiledList = make([]*models.FiledConfig, 0)
381
+				}
382
+			}
383
+
384
+			this.ServeSuccessJSON(map[string]interface{}{
385
+				"admin": adminUser,
386
+				"user":  appRole,
387
+				"org":   org,
388
+				"template_info": map[string]interface{}{
389
+					"id":          templateInfo.ID,
390
+					"org_id":      templateInfo.OrgId,
391
+					"template_id": templateInfo.TemplateId,
392
+				},
393
+				"config_list": configList,
394
+				"filed_list":  FiledList,
395
+			})
396
+		}
397
+
398
+	}
399
+
400
+}
401
+
402
+func InitAdviceTemplate(org *models.Org) {
403
+
404
+	//初始化医嘱模版
405
+	adviceInit := &models.AdviceInit{
406
+		UserOrgId:  org.Id,
407
+		CreateTime: time.Now().Unix(),
408
+		UpdateTime: time.Now().Unix(),
409
+		Status:     1,
410
+		IsInit:     1,
411
+	}
412
+
413
+	adviceParentTemplate := LoadConfig("./advice_template.json").Parent_template
414
+	for _, item := range adviceParentTemplate {
415
+		parentTemplate := &models.DoctorAdviceParentTemplate{
416
+			OrgId:       org.Id,
417
+			Name:        item.Name,
418
+			Status:      1,
419
+			CreatedTime: time.Now().Unix(),
420
+			UpdatedTime: time.Now().Unix(),
421
+			AdviceType:  item.AdviceType,
422
+		}
423
+
424
+		createErr := service.CreateDoctorParentTemplate(parentTemplate)
425
+		fmt.Println(parentTemplate.ID)
426
+		if createErr == nil {
427
+			for _, adviceTemplateItem := range item.DoctorAdviceTemplate {
428
+				adviceTeplate := &models.DoctorAdviceTemplate{
429
+					OrgId:                 org.Id,
430
+					AdviceName:            adviceTemplateItem.AdviceName,
431
+					AdviceDesc:            adviceTemplateItem.AdviceDesc,
432
+					SingleDose:            adviceTemplateItem.SingleDose,
433
+					SingleDoseUnit:        adviceTemplateItem.SingleDoseUnit,
434
+					PrescribingNumber:     adviceTemplateItem.PrescribingNumber,
435
+					PrescribingNumberUnit: adviceTemplateItem.PrescribingNumberUnit,
436
+					DeliveryWay:           adviceTemplateItem.DeliveryWay,
437
+					ExecutionFrequency:    adviceTemplateItem.ExecutionFrequency,
438
+					AdviceDoctor:          adviceTemplateItem.AdviceDoctor,
439
+					Status:                1,
440
+					CreatedTime:           time.Now().Unix(),
441
+					UpdatedTime:           time.Now().Unix(),
442
+					TemplateId:            parentTemplate.ID,
443
+					DrugSpec:              adviceTemplateItem.DrugSpec,
444
+					DrugSpecUnit:          adviceTemplateItem.DrugSpecUnit,
445
+					ParentId:              adviceTemplateItem.ParentId,
446
+					AdviceType:            adviceTemplateItem.AdviceType,
447
+					DayCount:              adviceTemplateItem.DayCount,
448
+					WeekDays:              adviceTemplateItem.WeekDays,
449
+					FrequencyType:         adviceTemplateItem.FrequencyType,
450
+				}
451
+				createErr := service.CreateDoctorTemplate(adviceTeplate)
452
+
453
+				if createErr == nil {
454
+					for _, childItem := range adviceTemplateItem.SubDoctorAdviceTemplate {
455
+						adviceTeplate := &models.DoctorAdviceTemplate{
456
+							OrgId:                 org.Id,
457
+							AdviceName:            childItem.AdviceName,
458
+							AdviceDesc:            childItem.AdviceDesc,
459
+							SingleDose:            childItem.SingleDose,
460
+							SingleDoseUnit:        childItem.SingleDoseUnit,
461
+							PrescribingNumber:     childItem.PrescribingNumber,
462
+							PrescribingNumberUnit: childItem.PrescribingNumberUnit,
463
+							DeliveryWay:           childItem.DeliveryWay,
464
+							ExecutionFrequency:    childItem.ExecutionFrequency,
465
+							AdviceDoctor:          childItem.AdviceDoctor,
466
+							Status:                1,
467
+							CreatedTime:           time.Now().Unix(),
468
+							UpdatedTime:           time.Now().Unix(),
469
+							TemplateId:            parentTemplate.ID,
470
+							DrugSpec:              childItem.DrugSpec,
471
+							DrugSpecUnit:          childItem.DrugSpecUnit,
472
+							ParentId:              adviceTeplate.ID,
473
+							AdviceType:            childItem.AdviceType,
474
+							DayCount:              childItem.DayCount,
475
+							WeekDays:              childItem.WeekDays,
476
+							FrequencyType:         childItem.FrequencyType,
477
+						}
478
+						service.CreateDoctorTemplate(adviceTeplate)
479
+					}
480
+				}
481
+			}
482
+		}
483
+	}
484
+	service.CreateAdviceInitConfig(adviceInit)
485
+
486
+}
487
+
488
+func InitSystemPrescrption(org *models.Org) {
489
+	//初始化透析方案
490
+	prescriptions := LoadPrescriptionConfig("./system_dialysis_prescription.json").Prescription
491
+	for _, item := range prescriptions {
492
+		item.UserOrgId = org.Id
493
+		item.CreatedTime = time.Now().Unix()
494
+		item.UpdatedTime = time.Now().Unix()
495
+		service.CreateVMPrescription(item)
496
+	}
497
+
498
+}
499
+
500
+func InitPatientAndSchedule(org *models.Org) {
501
+	var ids []int64
222 502
 	//数据初始化
503
+
223 504
 	//创建两个虚拟病人
224
-	patients := LoadConfig("./patient.json").patients
505
+	patients := LoadPatientConfig("./patient.json").Patients
225 506
 	for _, item := range patients {
226 507
 		item.UserOrgId = org.Id
227 508
 		item.CreatedTime = time.Now().Unix()
228 509
 		item.UpdatedTime = time.Now().Unix()
229 510
 		item.Status = 1
511
+
230 512
 		service.CreateVMOrgPatient(item)
231 513
 		ids = append(ids, item.ID)
232 514
 	}
@@ -234,7 +516,7 @@ func (this *MobileRegistController) CreateOrg() {
234 516
 	//创建1个分组
235 517
 	vmGroup := &models.VMDeviceGroup{
236 518
 		OrgId:  org.Id,
237
-		Name:   "测试分组1",
519
+		Name:   "护理一组",
238 520
 		Status: 1,
239 521
 		Ctime:  time.Now().Unix(),
240 522
 		Mtime:  time.Now().Unix(),
@@ -245,7 +527,7 @@ func (this *MobileRegistController) CreateOrg() {
245 527
 	//创建两个虚拟分区
246 528
 	vmZone1 := &models.VMDeviceZone{
247 529
 		OrgId:  org.Id,
248
-		Name:   "分区1",
530
+		Name:   "A区",
249 531
 		Type:   1,
250 532
 		Status: 1,
251 533
 		Ctime:  time.Now().Unix(),
@@ -255,7 +537,7 @@ func (this *MobileRegistController) CreateOrg() {
255 537
 
256 538
 	vmZone2 := &models.VMDeviceZone{
257 539
 		OrgId:  org.Id,
258
-		Name:   "分区2",
540
+		Name:   "B区",
259 541
 		Type:   2,
260 542
 		Status: 1,
261 543
 		Ctime:  time.Now().Unix(),
@@ -263,10 +545,10 @@ func (this *MobileRegistController) CreateOrg() {
263 545
 	}
264 546
 	service.CreateVMZone(vmZone2)
265 547
 
266
-	//创建4个虚拟床位
548
+	//创建2个虚拟床位
267 549
 	vmDeviceNumber1 := &models.VMDeviceNumber{
268 550
 		OrgId:   org.Id,
269
-		Number:  "1",
551
+		Number:  "1号床",
270 552
 		GroupId: vmGroup.ID,
271 553
 		ZoneId:  vmZone1.ID,
272 554
 		Status:  1,
@@ -277,7 +559,7 @@ func (this *MobileRegistController) CreateOrg() {
277 559
 
278 560
 	vmDeviceNumber2 := &models.VMDeviceNumber{
279 561
 		OrgId:   org.Id,
280
-		Number:  "2",
562
+		Number:  "2号床",
281 563
 		GroupId: vmGroup.ID,
282 564
 		ZoneId:  vmZone2.ID,
283 565
 		Status:  1,
@@ -286,53 +568,111 @@ func (this *MobileRegistController) CreateOrg() {
286 568
 	}
287 569
 	service.CreateVMDeviceNumber(vmDeviceNumber2)
288 570
 
289
-	//创建两个虚拟病人排班
290
-	stime, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
291
-	for index, id := range ids {
292
-		if index == 0 {
293
-			sch := &models.VMSchedule{
294
-				UserOrgId:    org.Id,
295
-				PartitionId:  vmZone1.ID,
296
-				BedId:        vmDeviceNumber1.ID,
297
-				PatientId:    id,
298
-				ScheduleDate: stime.Unix(),
299
-				ScheduleType: 1,
300
-				ScheduleWeek: int64(time.Now().Weekday()),
301
-				ModeId:       1,
302
-				Status:       1,
303
-				CreatedTime:  time.Now().Unix(),
304
-				UpdatedTime:  time.Now().Unix(),
571
+	var dates []int64
572
+
573
+	mondayDate := GetDateOfWeek(1)
574
+	tuesdayDate := GetDateOfWeek(2)
575
+	wednesdayDate := GetDateOfWeek(3)
576
+	thursdayDate := GetDateOfWeek(4)
577
+	fridayDate := GetDateOfWeek(5)
578
+	saturdayDate := GetDateOfWeek(6)
579
+	sundayDate := GetDateOfWeek(7)
580
+
581
+	dates = append(dates, mondayDate)
582
+	dates = append(dates, tuesdayDate)
583
+	dates = append(dates, wednesdayDate)
584
+	dates = append(dates, thursdayDate)
585
+	dates = append(dates, fridayDate)
586
+	dates = append(dates, saturdayDate)
587
+	dates = append(dates, sundayDate)
588
+
589
+	//创建两个虚拟病人本周的排班
590
+	//stime, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
591
+	for _, date := range dates {
592
+		for index, id := range ids {
593
+			if index == 0 {
594
+				sch := &models.VMSchedule{
595
+					UserOrgId:    org.Id,
596
+					PartitionId:  vmZone1.ID,
597
+					BedId:        vmDeviceNumber1.ID,
598
+					PatientId:    id,
599
+					ScheduleDate: date,
600
+					ScheduleType: 1,
601
+					ScheduleWeek: int64(time.Now().Weekday()),
602
+					ModeId:       1,
603
+					Status:       1,
604
+					CreatedTime:  time.Now().Unix(),
605
+					UpdatedTime:  time.Now().Unix(),
606
+				}
607
+				service.CreateVMSch(sch)
305 608
 			}
306
-			service.CreateVMSch(sch)
307
-		}
308 609
 
309
-		if index == 1 {
310
-
311
-			sch := &models.VMSchedule{
312
-				UserOrgId:    org.Id,
313
-				PartitionId:  vmZone2.ID,
314
-				BedId:        vmDeviceNumber2.ID,
315
-				PatientId:    id,
316
-				ScheduleDate: stime.Unix(),
317
-				ScheduleType: 1,
318
-				ScheduleWeek: int64(time.Now().Weekday()),
319
-				ModeId:       1,
320
-				Status:       1,
321
-				CreatedTime:  time.Now().Unix(),
322
-				UpdatedTime:  time.Now().Unix(),
610
+			if index == 1 {
611
+
612
+				sch := &models.VMSchedule{
613
+					UserOrgId:    org.Id,
614
+					PartitionId:  vmZone2.ID,
615
+					BedId:        vmDeviceNumber2.ID,
616
+					PatientId:    id,
617
+					ScheduleDate: date,
618
+					ScheduleType: 2,
619
+					ScheduleWeek: int64(time.Now().Weekday()),
620
+					ModeId:       1,
621
+					Status:       1,
622
+					CreatedTime:  time.Now().Unix(),
623
+					UpdatedTime:  time.Now().Unix(),
624
+				}
625
+				service.CreateVMSch(sch)
323 626
 			}
324
-			service.CreateVMSch(sch)
325 627
 		}
628
+
326 629
 	}
327 630
 
328
-	if createErr != nil {
329
-		utils.ErrorLog("mobile=%v的超级管理员创建机构失败:%v", adminUser.Mobile, createErr)
330
-		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
331
-		this.ServeJSON()
332
-	} else {
333
-		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{})
334
-		this.ServeJSON()
631
+	//创建单周模版
632
+	//1.创建模版模式
633
+	mode := &models.VMPatientScheduleTemplateMode{
634
+		OrgId:        org.Id,
635
+		Mode:         1,
636
+		ExecuteTimes: 0,
637
+		Status:       1,
638
+		Ctime:        time.Now().Unix(),
639
+		Mtime:        time.Now().Unix(),
640
+	}
641
+	service.CreateVMSchMode(mode)
642
+	//2.创建模版id
643
+	templaeIdOne := &models.VMPatientScheduleTemplateId{
644
+		OrgId:  org.Id,
645
+		Status: 1,
646
+		Ctime:  time.Now().Unix(),
647
+		Mtime:  time.Now().Unix(),
648
+	}
649
+	service.CreateVMSchTemplateId(templaeIdOne)
650
+	templaeIdTwo := &models.VMPatientScheduleTemplateId{
651
+		OrgId:  org.Id,
652
+		Status: 1,
653
+		Ctime:  time.Now().Unix(),
654
+		Mtime:  time.Now().Unix(),
655
+	}
656
+	service.CreateVMSchTemplateId(templaeIdTwo)
657
+	//3.创建单周排班模版
658
+	items := LoadSchTemplateConfig("./schedule_template.json").ScheduleTemplateItem
659
+	for _, item := range items {
660
+		if item.TimeType == 1 {
661
+			item.OrgId = org.Id
662
+			item.TemplateId = templaeIdOne.ID
663
+			item.DeviceNumberId = vmDeviceNumber1.ID
664
+			item.PatientId = ids[0]
665
+
666
+		} else if item.TimeType == 2 {
667
+			item.OrgId = org.Id
668
+			item.TemplateId = templaeIdOne.ID
669
+			item.DeviceNumberId = vmDeviceNumber2.ID
670
+			item.PatientId = ids[1]
671
+		}
672
+
673
+		service.CreateVMSchTemplate(item)
335 674
 	}
675
+
336 676
 }
337 677
 
338 678
 func (this *MobileRegistController) ModifyName() {
@@ -394,12 +734,80 @@ func (this *MobileRegistController) Login() {
394 734
 
395 735
 }
396 736
 
397
-type Config struct {
398
-	patients []*models.VMOrgPatients "json:patients"
737
+type PatientConfig struct {
738
+	Patients []*models.VMOrgPatients "json:patients"
399 739
 }
400 740
 
401
-func LoadConfig(dataFile string) *Config {
402
-	var config Config
741
+type SchTemplateConfig struct {
742
+	ScheduleTemplateItem []*models.VMPatientScheduleTemplateItem "json:item"
743
+}
744
+
745
+type PrescriptionConfig struct {
746
+	Prescription []*models.SystemPrescription "json:prescription"
747
+}
748
+
749
+func LoadPatientConfig(dataFile string) *PatientConfig {
750
+	var config PatientConfig
751
+	_, filename, _, _ := runtime.Caller(1)
752
+	datapath := path.Join(path.Dir(filename), dataFile)
753
+	config_file, err := os.Open(datapath)
754
+	if err != nil {
755
+		emit("Failed to open config file '%s': %s\n", datapath, err)
756
+		return &config
757
+	}
758
+
759
+	fi, _ := config_file.Stat()
760
+
761
+	buffer := make([]byte, fi.Size())
762
+	_, err = config_file.Read(buffer)
763
+
764
+	buffer, err = StripComments(buffer) //去掉注释
765
+	if err != nil {
766
+		emit("Failed to strip comments from json: %s\n", err)
767
+		return &config
768
+	}
769
+
770
+	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
771
+	err = json.Unmarshal(buffer, &config)         //解析json格式数据
772
+	if err != nil {
773
+		emit("Failed unmarshalling json: %s\n", err)
774
+		return &config
775
+	}
776
+	return &config
777
+}
778
+
779
+func LoadSchTemplateConfig(dataFile string) *SchTemplateConfig {
780
+	var config SchTemplateConfig
781
+	_, filename, _, _ := runtime.Caller(1)
782
+	datapath := path.Join(path.Dir(filename), dataFile)
783
+	config_file, err := os.Open(datapath)
784
+	if err != nil {
785
+		emit("Failed to open config file '%s': %s\n", datapath, err)
786
+		return &config
787
+	}
788
+
789
+	fi, _ := config_file.Stat()
790
+
791
+	buffer := make([]byte, fi.Size())
792
+	_, err = config_file.Read(buffer)
793
+
794
+	buffer, err = StripComments(buffer) //去掉注释
795
+	if err != nil {
796
+		emit("Failed to strip comments from json: %s\n", err)
797
+		return &config
798
+	}
799
+
800
+	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
801
+	err = json.Unmarshal(buffer, &config)         //解析json格式数据
802
+	if err != nil {
803
+		emit("Failed unmarshalling json: %s\n", err)
804
+		return &config
805
+	}
806
+	return &config
807
+}
808
+
809
+func LoadPrescriptionConfig(dataFile string) *PrescriptionConfig {
810
+	var config PrescriptionConfig
403 811
 	_, filename, _, _ := runtime.Caller(1)
404 812
 	datapath := path.Join(path.Dir(filename), dataFile)
405 813
 	config_file, err := os.Open(datapath)
@@ -449,3 +857,89 @@ func StripComments(data []byte) ([]byte, error) {
449 857
 
450 858
 	return bytes.Join(filtered, []byte("\n")), nil
451 859
 }
860
+
861
+func GetDateOfWeek(week_type int) (weekMonday int64) {
862
+	thisTime := time.Now()
863
+	weekDay := int(thisTime.Weekday())
864
+	if weekDay == 0 {
865
+		weekDay = 7
866
+	}
867
+	weekEnd := 7 - weekDay
868
+	weekStart := weekEnd - 6
869
+	weekTitle := make([]string, 0)
870
+	days := make([]string, 0)
871
+	for index := weekStart; index <= weekEnd; index++ {
872
+		theDay := thisTime.AddDate(0, 0, index)
873
+		indexYear, indexMonthTime, indexDay := theDay.Date()
874
+		indexMonth := int(indexMonthTime)
875
+		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
876
+		weekTitle = append(weekTitle, indexWeek)
877
+		days = append(days, theDay.Format("2006-01-02"))
878
+	}
879
+	var targetDayStr string
880
+	switch week_type {
881
+	case 1:
882
+		targetDayStr = days[0]
883
+		break
884
+	case 2:
885
+		targetDayStr = days[1]
886
+
887
+		break
888
+	case 3:
889
+		targetDayStr = days[2]
890
+
891
+		break
892
+	case 4:
893
+		targetDayStr = days[3]
894
+
895
+		break
896
+	case 5:
897
+		targetDayStr = days[4]
898
+
899
+		break
900
+	case 6:
901
+		targetDayStr = days[5]
902
+
903
+		break
904
+	case 7:
905
+		targetDayStr = days[6]
906
+
907
+		break
908
+	}
909
+	targetDay, _ := utils.ParseTimeStringToTime("2006-01-02", targetDayStr)
910
+	return targetDay.Unix()
911
+}
912
+
913
+type Config struct {
914
+	Parent_template []*models.VMDoctorAdviceParentTemplate "json:parent_template"
915
+}
916
+
917
+func LoadConfig(dataFile string) *Config {
918
+	var config Config
919
+	_, filename, _, _ := runtime.Caller(1)
920
+	datapath := path.Join(path.Dir(filename), dataFile)
921
+	config_file, err := os.Open(datapath)
922
+	if err != nil {
923
+		emit("Failed to open config file '%s': %s\n", datapath, err)
924
+		return &config
925
+	}
926
+
927
+	fi, _ := config_file.Stat()
928
+
929
+	buffer := make([]byte, fi.Size())
930
+	_, err = config_file.Read(buffer)
931
+
932
+	buffer, err = StripComments(buffer) //去掉注释
933
+	if err != nil {
934
+		emit("Failed to strip comments from json: %s\n", err)
935
+		return &config
936
+	}
937
+
938
+	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
939
+	err = json.Unmarshal(buffer, &config)         //解析json格式数据
940
+	if err != nil {
941
+		emit("Failed unmarshalling json: %s\n", err)
942
+		return &config
943
+	}
944
+	return &config
945
+}

+ 7 - 0
controllers/new_mobile_api_controllers/new_login_api_controller.go View File

@@ -22,6 +22,7 @@ type NewLoginApiController struct {
22 22
 }
23 23
 
24 24
 func (this *NewLoginApiController) GetLogin() {
25
+
25 26
 	token_cookie := this.Ctx.GetCookie("token_cookie")
26 27
 	if len(token_cookie) == 0 {
27 28
 		this.ServeSuccessJSON(map[string]interface{}{
@@ -517,6 +518,12 @@ func (this *NewLoginApiController) GetCode() {
517 518
 		return
518 519
 	}
519 520
 
521
+	adminUser, _ := service.GetValidAdminUserByMobileReturnErr(mobile)
522
+	if adminUser != nil {
523
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRegisterExist)
524
+		this.ServeJSON()
525
+		return
526
+	}
520 527
 	//this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
521 528
 	//	"msg": "短信发送成功,有效期为10分钟",
522 529
 	//})

+ 8 - 1
controllers/new_mobile_api_controllers/new_mobile_api_router_register.go View File

@@ -1,6 +1,8 @@
1 1
 package new_mobile_api_controllers
2 2
 
3
-import "github.com/astaxie/beego"
3
+import (
4
+	"github.com/astaxie/beego"
5
+)
4 6
 
5 7
 // 平板端路由,以 /m/api 为前缀
6 8
 func NewMobileAPIControllersRegisterRouters() {
@@ -29,6 +31,10 @@ func NewMobileAPIControllersRegisterRouters() {
29 31
 
30 32
 	beego.Router("/m/api/org/create", &MobileRegistController{}, "post:CreateOrg")
31 33
 
34
+	beego.Router("/m/api/home", &HomeController{}, "get:GetHomeData")
35
+	beego.Router("/m/api/changeorg", &HomeController{}, "post:ChangeOrg")
36
+	beego.Router("/m/api/createOrg", &HomeController{}, "post:CreateOrg")
37
+
32 38
 	beego.Router("/m/api/patient/getbloodpatientinfo", &NewDialysisApiController{}, "Get:GetBloodPatientInfo")
33 39
 	beego.Router("/m/api/patient/getslowpatientinfo", &NewDialysisApiController{}, "Get:GetSlowPatientInfo")
34 40
 	beego.Router("/m/api/patient/getmemberpatientinfo", &NewDialysisApiController{}, "Get:GetMemberpatientInfo")
@@ -50,4 +56,5 @@ func NewMobileAPIControllersRegisterRouters() {
50 56
 	beego.Router("/m/api/patient/getrescuerecord", &NewDialysisApiController{}, "Get:GetRescuerecord")
51 57
 	beego.Router("/m/api/patient/getscheduling", &NewDialysisApiController{}, "Get:GetScheduling")
52 58
 	beego.Router("/m/api/patient/geteducation", &NewDialysisApiController{}, "Get:GetEducation")
59
+
53 60
 }

+ 30 - 0
controllers/new_mobile_api_controllers/new_role_api_controller.go View File

@@ -0,0 +1,30 @@
1
+package new_mobile_api_controllers
2
+
3
+import (
4
+	"XT_New/service"
5
+)
6
+
7
+type NewRoleApiController struct {
8
+	NewMobileBaseAPIAuthController
9
+}
10
+
11
+func (this *NewRoleApiController) GetAllOrgUser() {
12
+	adminUserInfo := this.GetMobileAdminUserInfo()
13
+	viewModels, _, _ := service.GetAdminUsersAndLoginInfo(adminUserInfo.Org.Id, adminUserInfo.App.Id, 1, 10)
14
+	this.ServeSuccessJSON(map[string]interface{}{
15
+		"admins": viewModels,
16
+	})
17
+
18
+}
19
+func (this *NewRoleApiController) CreateOrgUser() {
20
+
21
+}
22
+func (this *NewRoleApiController) ModifyOrgUser() {
23
+
24
+}
25
+func (this *NewRoleApiController) GetOrgRole() {
26
+
27
+}
28
+func (this *NewRoleApiController) CreateOrgRole() {
29
+
30
+}

+ 14 - 14
controllers/new_mobile_api_controllers/patient.json View File

@@ -3,19 +3,19 @@
3 3
     {
4 4
       "avatar": "https://images.shengws.com/201809182128111.png",
5 5
       "patient_type": 1,
6
-      "dialysis_no": "01",
6
+      "dialysis_no": "001",
7 7
       "admission_number": "",
8 8
       "source": 1,
9 9
       "lapseto": 2,
10 10
       "partition_id": 0,
11 11
       "bed_id": 0,
12
-      "name": "测试病人",
12
+      "name": "演示患者一",
13 13
       "alias": "",
14
-      "gender": 2,
14
+      "gender": 1,
15 15
       "nation": "汉",
16 16
       "native_place": "广东深圳",
17 17
       "marital_status": 1,
18
-      "id_card_no": "430503196002063010",
18
+      "id_card_no": "431230199808081111",
19 19
       "birthday": -312537600,
20 20
       "reimbursement_way_id": 7,
21 21
       "health_care_type": 0,
@@ -27,10 +27,10 @@
27 27
       "health_care_due_alert_date": 0,
28 28
       "education_level": 5,
29 29
       "profession": 10,
30
-      "phone": "13535547901",
31
-      "home_telephone": "12221903097",
32
-      "relative_phone": "18123074302",
33
-      "relative_relations": "哥哥",
30
+      "phone": "13800000001",
31
+      "home_telephone": "",
32
+      "relative_phone": "",
33
+      "relative_relations": "",
34 34
       "home_address": "深圳市罗湖区鸿翔花园",
35 35
       "work_unit": "无",
36 36
       "unit_address": "无",
@@ -82,19 +82,19 @@
82 82
     {
83 83
       "avatar": "https://images.shengws.com/201809182128111.png",
84 84
       "patient_type": 1,
85
-      "dialysis_no": "01",
85
+      "dialysis_no": "002",
86 86
       "admission_number": "",
87 87
       "source": 1,
88 88
       "lapseto": 2,
89 89
       "partition_id": 0,
90 90
       "bed_id": 0,
91
-      "name": "测试病人2",
91
+      "name": "演示患者二",
92 92
       "alias": "",
93 93
       "gender": 2,
94 94
       "nation": "汉",
95 95
       "native_place": "广东深圳",
96 96
       "marital_status": 1,
97
-      "id_card_no": "430503196002063010",
97
+      "id_card_no": "4312301999090952222",
98 98
       "birthday": -312537600,
99 99
       "reimbursement_way_id": 7,
100 100
       "health_care_type": 0,
@@ -106,9 +106,9 @@
106 106
       "health_care_due_alert_date": 0,
107 107
       "education_level": 5,
108 108
       "profession": 10,
109
-      "phone": "13535547901",
110
-      "home_telephone": "12221903097",
111
-      "relative_phone": "18123074302",
109
+      "phone": "13800000001",
110
+      "home_telephone": "",
111
+      "relative_phone": "",
112 112
       "relative_relations": "哥哥",
113 113
       "home_address": "深圳市罗湖区鸿翔花园",
114 114
       "work_unit": "无",

+ 86 - 0
controllers/new_mobile_api_controllers/schedule_template.json View File

@@ -0,0 +1,86 @@
1
+{
2
+  "item": [
3
+    {
4
+      "treat_mode": 1,
5
+      "weekday": 1,
6
+      "time_type": 1
7
+    },
8
+    {
9
+      "treat_mode": 1,
10
+      "weekday": 1,
11
+      "time_type": 2
12
+    },
13
+    {
14
+
15
+      "treat_mode": 1,
16
+      "weekday": 2,
17
+      "time_type": 1
18
+    },
19
+
20
+    {
21
+
22
+      "treat_mode": 1,
23
+      "weekday": 2,
24
+      "time_type": 2
25
+    },
26
+    {
27
+
28
+      "treat_mode": 1,
29
+      "weekday": 3,
30
+      "time_type": 1
31
+    },
32
+    {
33
+
34
+      "treat_mode": 1,
35
+      "weekday": 3,
36
+      "time_type": 2
37
+    },
38
+    {
39
+
40
+      "treat_mode": 1,
41
+      "weekday": 4,
42
+      "time_type": 1
43
+    },
44
+    {
45
+
46
+      "treat_mode": 1,
47
+      "weekday": 4,
48
+      "time_type": 2
49
+    },
50
+    {
51
+
52
+      "treat_mode": 1,
53
+      "weekday": 5,
54
+      "time_type": 1
55
+    },
56
+    {
57
+
58
+      "treat_mode": 1,
59
+      "weekday": 5,
60
+      "time_type": 2
61
+    },
62
+    {
63
+
64
+      "treat_mode": 1,
65
+      "weekday": 6,
66
+      "time_type": 1
67
+    },
68
+    {
69
+
70
+      "treat_mode": 1,
71
+      "weekday": 6,
72
+      "time_type": 2
73
+    },
74
+    {
75
+
76
+      "treat_mode": 1,
77
+      "weekday": 7,
78
+      "time_type": 1
79
+    },
80
+    {
81
+      "treat_mode": 1,
82
+      "weekday": 7,
83
+      "time_type": 2
84
+    }
85
+  ]
86
+}

+ 44 - 0
controllers/new_mobile_api_controllers/system_dialysis_prescription.json View File

@@ -0,0 +1,44 @@
1
+{
2
+  "prescription": [
3
+    {
4
+      "anticoagulant": 3,
5
+      "anticoagulant_shouji": 4000,
6
+      "anticoagulant_weichi": 0,
7
+      "anticoagulant_zongliang": 4000,
8
+      "mode_id": 1,
9
+      "blood_flow_volume": 250,
10
+      "kalium": 2,
11
+      "sodium": 135,
12
+      "calcium": 1.5,
13
+      "status": 1,
14
+      "dialysis_duration_hour": 4,
15
+      "dialysis_duration_minute": 0
16
+    },{
17
+      "anticoagulant": 3,
18
+      "anticoagulant_shouji": 4000,
19
+      "anticoagulant_weichi": 0,
20
+      "anticoagulant_zongliang": 4000,
21
+      "mode_id": 2,
22
+      "blood_flow_volume": 250,
23
+      "kalium": 2,
24
+      "sodium": 135,
25
+      "calcium": 1.5,
26
+      "status": 1,
27
+      "dialysis_duration_hour": 4,
28
+      "dialysis_duration_minute": 0
29
+    },{
30
+      "anticoagulant": 3,
31
+      "anticoagulant_shouji": 4000,
32
+      "anticoagulant_weichi": 0,
33
+      "anticoagulant_zongliang": 4000,
34
+      "mode_id": 3,
35
+      "blood_flow_volume": 200,
36
+      "kalium": 2,
37
+      "sodium": 135,
38
+      "calcium": 1.5,
39
+      "status": 1,
40
+      "dialysis_duration_hour": 4,
41
+      "dialysis_duration_minute": 0
42
+    }
43
+  ]
44
+}

+ 8 - 1
enums/error_code.go View File

@@ -178,7 +178,10 @@ const ( // ErrorCode
178 178
 
179 179
 	ErrorCodeHisIdExist = 20030
180 180
 
181
-	ErrorCodePreExist = 20031
181
+	ErrorCodePreExist   = 20031
182
+	ErrorCodeOrgNoExist = 20032
183
+
184
+	ErrorCodeRegisterExist = 20033
182 185
 )
183 186
 
184 187
 var ErrCodeMsgs = map[int]string{
@@ -356,6 +359,10 @@ var ErrCodeMsgs = map[int]string{
356 359
 	ErrorCodePreExist: "没有该权限",
357 360
 
358 361
 	ErrorCodeRepeatCreateOrg: "该账号已创建过机构了",
362
+
363
+	ErrorCodeOrgNoExist: "该机构不存在",
364
+
365
+	ErrorCodeRegisterExist: "该账号已经注册,请登录",
359 366
 }
360 367
 
361 368
 type SGJError struct {

+ 12 - 8
models/org_models.go View File

@@ -49,14 +49,18 @@ func (OrgGallery) TableName() string {
49 49
 }
50 50
 
51 51
 type OrgApp struct {
52
-	Id         int64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // ID
53
-	AppType    int   `gorm:"column:app_type" json:"app_type"`      // 应用类型 1.病友经营;2.科普号;3.血透经营;4.慢病管理
54
-	Creator    int   `json:"creator"`                              // 创建者,即管理员用户的 id
55
-	OrgId      int   `gorm:"column:org_id" json:"org_id"`
56
-	OpenStatus int   `gorm:"column:open_status" json:"open_status"`
57
-	Status     int8  `json:"status"`                    // 状态 0.无效 1.有效 2.禁用
58
-	CreateTime int64 `gorm:"column:ctime" json:"ctime"` // 创建时间
59
-	ModifyTime int64 `gorm:"column:mtime" json:"mtime"` // 修改时间
52
+	Id         int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // ID
53
+	AppType    int    `gorm:"column:app_type" json:"app_type"`      // 应用类型 1.病友经营;2.科普号;3.血透经营;4.慢病管理
54
+	Creator    int    `json:"creator"`                              // 创建者,即管理员用户的 id
55
+	OrgId      int    `gorm:"column:org_id" json:"org_id"`
56
+	OpenStatus int    `gorm:"column:open_status" json:"open_status"`
57
+	Status     int8   `json:"status"`                    // 状态 0.无效 1.有效 2.禁用
58
+	CreateTime int64  `gorm:"column:ctime" json:"ctime"` // 创建时间
59
+	ModifyTime int64  `gorm:"column:mtime" json:"mtime"` // 修改时间
60
+	Name       string `gorm:"column:name" json:"name" form:"name"`
61
+	Url        string `gorm:"column:url" json:"url" form:"url"`
62
+	Pid        int64  `gorm:"column:pid" json:"pid" form:"pid"`
63
+	Number     int64  `gorm:"column:number" json:"number" form:"number"`
60 64
 }
61 65
 
62 66
 func (OrgApp) TableName() string {

+ 80 - 0
models/vm_models.go View File

@@ -151,3 +151,83 @@ type VMSchedule struct {
151 151
 func (VMSchedule) TableName() string {
152 152
 	return "xt_schedule"
153 153
 }
154
+
155
+type VMApp_Role struct {
156
+	Id          int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`
157
+	AdminUserId int64  `gorm:"column:admin_user_id" json:"admin_user_id"`
158
+	OrgId       int64  `gorm:"column:org_id" json:"org_id"`
159
+	Org         []*Org `gorm:"ForeignKey:ID;AssociationForeignKey:OrgId" json:"orgs"`
160
+}
161
+
162
+func (VMApp_Role) TableName() string {
163
+	return "sgj_user_admin_role"
164
+}
165
+
166
+type VMAdminUser struct {
167
+	ID         int64         `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // 管理员用户 ID
168
+	Org        []*Org        `gorm:"ForeignKey:Creator;AssociationForeignKey:ID" json:"orgs"`
169
+	VMApp_Role []*VMApp_Role `gorm:"ForeignKey:AdminUserId;AssociationForeignKey:ID" json:"roles"`
170
+}
171
+
172
+func (VMAdminUser) TableName() string {
173
+	return "sgj_user_admin"
174
+}
175
+
176
+type VMAdminBanner struct {
177
+	ID     int64  `gorm:"column:id" json:"id" form:"id"`
178
+	Thumb  string `gorm:"column:thumb" json:"thumb" form:"thumb"`
179
+	Url    string `gorm:"column:url" json:"url" form:"url"`
180
+	Status int64  `gorm:"column:status" json:"status" form:"status"`
181
+	Ctime  int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
182
+	Mtime  int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
183
+	Title  string `gorm:"column:title" json:"title" form:"title"`
184
+	Desc   string `gorm:"column:desc" json:"desc" form:"desc"`
185
+}
186
+
187
+func (VMAdminBanner) TableName() string {
188
+	return "sgj_admin_banner"
189
+}
190
+
191
+type VMPatientScheduleTemplateId struct {
192
+	ID     int64 `gorm:"column:id" json:"id" form:"id"`
193
+	OrgId  int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
194
+	Status int64 `gorm:"column:status" json:"status" form:"status"`
195
+	Ctime  int64 `gorm:"column:ctime" json:"ctime" form:"ctime"`
196
+	Mtime  int64 `gorm:"column:mtime" json:"mtime" form:"mtime"`
197
+}
198
+
199
+func (VMPatientScheduleTemplateId) TableName() string {
200
+	return "xt_patient_schedule_template_id"
201
+}
202
+
203
+type VMPatientScheduleTemplateItem struct {
204
+	ID             int64 `gorm:"column:id" json:"id" form:"id"`
205
+	OrgId          int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
206
+	TemplateId     int64 `gorm:"column:template_id" json:"template_id" form:"template_id"`
207
+	DeviceNumberId int64 `gorm:"column:device_number_id" json:"device_number_id" form:"device_number_id"`
208
+	PatientId      int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
209
+	TreatMode      int64 `gorm:"column:treat_mode" json:"treat_mode" form:"treat_mode"`
210
+	Weekday        int64 `gorm:"column:weekday" json:"weekday" form:"weekday"`
211
+	TimeType       int64 `gorm:"column:time_type" json:"time_type" form:"time_type"`
212
+	Status         int64 `gorm:"column:status" json:"status" form:"status"`
213
+	Ctime          int64 `gorm:"column:ctime" json:"ctime" form:"ctime"`
214
+	Mtime          int64 `gorm:"column:mtime" json:"mtime" form:"mtime"`
215
+}
216
+
217
+func (VMPatientScheduleTemplateItem) TableName() string {
218
+	return "xt_patient_schedule_template_id"
219
+}
220
+
221
+type VMPatientScheduleTemplateMode struct {
222
+	ID           int64 `gorm:"column:id" json:"id" form:"id"`
223
+	OrgId        int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
224
+	Mode         int64 `gorm:"column:mode" json:"mode" form:"mode"`
225
+	ExecuteTimes int64 `gorm:"column:execute_times" json:"execute_times" form:"execute_times"`
226
+	Status       int64 `gorm:"column:status" json:"status" form:"status"`
227
+	Ctime        int64 `gorm:"column:ctime" json:"ctime" form:"ctime"`
228
+	Mtime        int64 `gorm:"column:mtime" json:"mtime" form:"mtime"`
229
+}
230
+
231
+func (VMPatientScheduleTemplateMode) TableName() string {
232
+	return "xt_patient_schedule_template_id"
233
+}

+ 42 - 0
service/db.go View File

@@ -34,6 +34,9 @@ var writeMiddleDb *gorm.DB
34 34
 
35 35
 var readPatientDb *gorm.DB
36 36
 var writePatientDb *gorm.DB
37
+
38
+var readSgjPatientDb *gorm.DB
39
+var writeSgjPatientDb *gorm.DB
37 40
 var err error
38 41
 
39 42
 func ConnectDB() {
@@ -85,6 +88,18 @@ func ConnectDB() {
85 88
 	writePatientPass := beego.AppConfig.String("writepatientpass")
86 89
 	writePatientName := beego.AppConfig.String("writepatientname")
87 90
 
91
+	readSgjPatientHost := beego.AppConfig.String("readsgjpatientmysqlhost")
92
+	readSgjPatientPort := beego.AppConfig.String("readsgjpatientmysqlport")
93
+	readSgjPatientUser := beego.AppConfig.String("readsgjpatientmysqluser")
94
+	readSgjPatientPass := beego.AppConfig.String("readsgjpatientmysqlpass")
95
+	readSgjPatientName := beego.AppConfig.String("readsgjpatientmysqlname")
96
+
97
+	writeSgjPatientHost := beego.AppConfig.String("writesgjpatientmysqlhost")
98
+	writeSgjPatientPort := beego.AppConfig.String("writesgjpatientmysqlport")
99
+	writeSgjPatientUser := beego.AppConfig.String("writesgjpatientmysqluser")
100
+	writeSgjPatientPass := beego.AppConfig.String("writesgjpatientmysqlpass")
101
+	writeSgjPatientName := beego.AppConfig.String("writesgjpatientmysqlname")
102
+
88 103
 	rdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUser, readPass, readHost, readPort, readName)
89 104
 	wdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUser, writePass, writeHost, writePort, writeName)
90 105
 
@@ -97,6 +112,9 @@ func ConnectDB() {
97 112
 	rpdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readPatientUser, readPatientPass, readPatientHost, readPatientPort, readPatientName)
98 113
 	wpdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writePatientUser, writePatientPass, writePatientHost, writePatientPort, writePatientName)
99 114
 
115
+	rspdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readSgjPatientUser, readSgjPatientPass, readSgjPatientHost, readSgjPatientPort, readSgjPatientName)
116
+	wspdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeSgjPatientUser, writeSgjPatientPass, writeSgjPatientHost, writeSgjPatientPort, writeSgjPatientName)
117
+
100 118
 	readDb, err = gorm.Open("mysql", rdsn)
101 119
 	if err != nil {
102 120
 		//beego.Error(err)
@@ -160,6 +178,22 @@ func ConnectDB() {
160 178
 	writePatientDb.DB().SetMaxIdleConns(10)
161 179
 	writePatientDb.DB().SetMaxOpenConns(100)
162 180
 	writePatientDb.LogMode(true)
181
+
182
+	readSgjPatientDb, err = gorm.Open("mysql", rspdsn)
183
+	if err != nil {
184
+		beego.Error(err)
185
+	}
186
+	readSgjPatientDb.DB().SetMaxIdleConns(10)
187
+	readSgjPatientDb.DB().SetMaxOpenConns(100)
188
+	readSgjPatientDb.LogMode(true)
189
+
190
+	writeSgjPatientDb, err = gorm.Open("mysql", wspdsn)
191
+	if err != nil {
192
+		beego.Error(err)
193
+	}
194
+	writeSgjPatientDb.DB().SetMaxIdleConns(10)
195
+	writeSgjPatientDb.DB().SetMaxOpenConns(100)
196
+	writeSgjPatientDb.LogMode(true)
163 197
 }
164 198
 
165 199
 //func DisconnectDB() {
@@ -195,3 +229,11 @@ func PatientReadDB() *gorm.DB {
195 229
 func PatientWriteDB() *gorm.DB {
196 230
 	return writePatientDb
197 231
 }
232
+
233
+func SgjPatientReadDB() *gorm.DB {
234
+	return readSgjPatientDb
235
+}
236
+
237
+func SgjPatientWriteDB() *gorm.DB {
238
+	return writeSgjPatientDb
239
+}

+ 25 - 0
service/home_service.go View File

@@ -0,0 +1,25 @@
1
+package service
2
+
3
+import (
4
+	"XT_New/models"
5
+	"github.com/jinzhu/gorm"
6
+)
7
+
8
+func GetHomeData(adminUserId int64) (adminUser models.VMAdminUser, err error) {
9
+	err = readUserDb.Model(&models.VMAdminUser{}).Where("status = 1 AND id = ?", adminUserId).
10
+		Preload("Org", "status = 1").
11
+		Preload("VMApp_Role", func(db *gorm.DB) *gorm.DB {
12
+			return db.Preload("Org", "status = 1").Where("status = 1")
13
+		}).Find(&adminUser).Error
14
+	return
15
+}
16
+
17
+func GetAllApp(org_id int64) (apps []*models.OrgApp, err error) {
18
+	err = readUserDb.Model(&models.OrgApp{}).Where("status = 1 AND pid > 0 AND org_id = ?", org_id).Order("number asc").Find(&apps).Error
19
+	return
20
+}
21
+
22
+func GetSystemBanner() (banners []*models.VMAdminBanner, err error) {
23
+	err = readUserDb.Model(&models.VMAdminBanner{}).Where("status = 1 ").Find(&banners).Error
24
+	return
25
+}

+ 72 - 17
service/orginfo_service.go View File

@@ -75,7 +75,7 @@ func CreateOrg(org *models.Org, mobile string, openXT bool, openCDM bool, openSC
75 75
 		return err
76 76
 	}
77 77
 
78
-	tx_patient := writeDb.Begin()
78
+	tx_patient := writeSgjPatientDb.Begin()
79 79
 	if err := tx_patient.Exec("INSERT INTO sgj_patient_articles_menu (name, status, type, user_org_id, ctime, mtime) VALUES(?, ?, ?, ?, ?, ?);", "科普教育", 1, 1, org.Id, now.Unix(), now.Unix()).Error; err != nil {
80 80
 		tx_patient.Rollback()
81 81
 		tx_admin.Rollback()
@@ -99,27 +99,53 @@ func CreateOrg(org *models.Org, mobile string, openXT bool, openCDM bool, openSC
99 99
 }
100 100
 
101 101
 func createOrgApp(tx *gorm.DB, superAdminRole *models.Role, userName string, appType int, open bool) error {
102
-	openStatus := 0
103
-	if open {
104
-		openStatus = 1
105
-	}
102
+
103
+	//创建应用
106 104
 	now := time.Now().Unix()
107
-	app := models.OrgApp{
108
-		Creator:    int(superAdminRole.Creator),
109
-		OrgId:      int(superAdminRole.OrgId),
110
-		AppType:    appType,
111
-		OpenStatus: openStatus,
112
-		Status:     1,
113
-		CreateTime: now,
114
-		ModifyTime: now,
115
-	}
116
-	if createAppErr := tx.Create(&app).Error; createAppErr != nil {
117
-		return createAppErr
105
+	var app_id int64
106
+	apps, _ := FindSystemOrgApp()
107
+	for _, item := range apps {
108
+		app := &VMOrgApp{
109
+			AppType:    item.AppType,
110
+			Creator:    int(superAdminRole.Creator),
111
+			OrgId:      int(superAdminRole.OrgId),
112
+			OpenStatus: item.OpenStatus,
113
+			Status:     1,
114
+			CreateTime: now,
115
+			ModifyTime: now,
116
+			Name:       item.Name,
117
+			Url:        item.Url,
118
+			Order:      item.Order,
119
+			Pid:        0,
120
+		}
121
+		writeUserDb.Create(&app)
122
+		if app.AppType == 3 {
123
+			app_id = app.ID
124
+
125
+		}
126
+
127
+		for _, subItem := range item.VMOrgApp {
128
+			app := &VMOrgApp{
129
+				AppType:    subItem.AppType,
130
+				Creator:    int(superAdminRole.Creator),
131
+				OrgId:      int(superAdminRole.OrgId),
132
+				OpenStatus: subItem.OpenStatus,
133
+				Status:     1,
134
+				CreateTime: now,
135
+				ModifyTime: now,
136
+				Name:       subItem.Name,
137
+				Url:        subItem.Url,
138
+				Order:      subItem.Order,
139
+				Pid:        app.ID,
140
+			}
141
+			writeUserDb.Create(&app)
142
+		}
118 143
 	}
144
+
119 145
 	app_role := models.App_Role{
120 146
 		AdminUserId: superAdminRole.Creator,
121 147
 		OrgId:       superAdminRole.OrgId,
122
-		AppId:       app.Id,
148
+		AppId:       app_id,
123 149
 		RoleId:      superAdminRole.Id,
124 150
 		Avatar:      "",
125 151
 		UserName:    userName,
@@ -140,3 +166,32 @@ func GetOrgTypeByName(org_type_name string) (org_type models.OrgType) {
140 166
 	readUserDb.Model(&models.OrgType{}).Where("status = 1 AND name = ?", org_type_name).First(&org_type)
141 167
 	return
142 168
 }
169
+
170
+type VMOrgApp struct {
171
+	ID         int64       `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // ID
172
+	AppType    int         `gorm:"column:app_type" json:"app_type"`
173
+	Creator    int         `json:"creator"` // 创建者,即管理员用户的 id
174
+	OrgId      int         `gorm:"column:org_id" json:"org_id"`
175
+	OpenStatus int         `gorm:"column:open_status" json:"open_status"`
176
+	Status     int8        `json:"status"`                    // 状态 0.无效 1.有效 2.禁用
177
+	CreateTime int64       `gorm:"column:ctime" json:"ctime"` // 创建时间
178
+	ModifyTime int64       `gorm:"column:mtime" json:"mtime"` // 修改时间
179
+	Name       string      `gorm:"column:name" json:"name" form:"name"`
180
+	Url        string      `gorm:"column:url" json:"url" form:"url"`
181
+	Pid        int64       `gorm:"column:pid" json:"pid" form:"pid"`
182
+	Order      int64       `gorm:"column:order" json:"order" form:"order"`
183
+	VMOrgApp   []*VMOrgApp `gorm:"ForeignKey:Pid;AssociationForeignKey:Id" `
184
+}
185
+
186
+func (VMOrgApp) TableName() string {
187
+	return "sgj_user_org_app"
188
+}
189
+
190
+func FindSystemOrgApp() (app []*VMOrgApp, err error) {
191
+	err = readUserDb.Model(&VMOrgApp{}).Preload("VMOrgApp", "org_id = 0 AND status =1 AND pid > 0").Where("status = 1 AND org_id = 0 AND pid = 0").Find(&app).Error
192
+	return
193
+}
194
+
195
+func GetAllOrgByAdminUserId() {
196
+
197
+}

+ 11 - 1
service/role_service.go View File

@@ -106,6 +106,7 @@ type AdminUserManageViewModel struct {
106 106
 	Ip          string `gorm:"ip" json:"ip"`
107 107
 	Ctime       int64  `gorm:"ctime" json:"last_login_time"`
108 108
 	Status      int    `gorm:"status" json:"status"`
109
+	Avatar      string `gorm:"avatar" json:"avatar"`
109 110
 
110 111
 	// LastLoginTimeStr string `gorm:"-" json:"last_login_time_formatted"`
111 112
 	TitleName string `gorm:"-" json:"title_name"`
@@ -119,7 +120,7 @@ func GetAdminUsersAndLoginInfo(orgID int64, appID int64, page int, count int) ([
119 120
 		page = 1
120 121
 	}
121 122
 	var viewModels []*AdminUserManageViewModel = make([]*AdminUserManageViewModel, 0)
122
-	rows, err := readUserDb.Raw("SELECT u_a_r.admin_user_id, u_a_r.user_name, u_r.role_name, u_a_r.user_title, u_l.ip, u_l.ctime, u_a_r.status FROM sgj_user_admin_role AS u_a_r INNER JOIN sgj_user_role AS u_r ON u_a_r.org_id = u_r.org_id AND u_a_r.app_id = u_r.app_id AND u_r.id = u_a_r.role_id LEFT JOIN (SELECT * FROM (SELECT admin_user_id, org_id, app_id, ip, ctime FROM sgj_user_admin_login_log WHERE org_id = ? AND app_id = ? ORDER BY ctime DESC) AS t GROUP BY admin_user_id) AS u_l ON u_a_r.org_id = u_l.org_id AND u_a_r.app_id = u_l.app_id AND u_a_r.admin_user_id = u_l.admin_user_id WHERE u_a_r.org_id = ? AND u_a_r.app_id = ? GROUP BY u_a_r.admin_user_id LIMIT ? OFFSET ?;", orgID, appID, orgID, appID, count, (page-1)*count).Rows()
123
+	rows, err := readUserDb.Raw("SELECT u_a_r.admin_user_id, u_a_r.user_name, u_r.role_name, u_a_r.user_title, u_l.ip, u_l.ctime, u_a_r.status,u_a_r.avatar FROM sgj_user_admin_role AS u_a_r INNER JOIN sgj_user_role AS u_r ON u_a_r.org_id = u_r.org_id AND u_a_r.app_id = u_r.app_id AND u_r.id = u_a_r.role_id LEFT JOIN (SELECT * FROM (SELECT admin_user_id, org_id, app_id, ip, ctime FROM sgj_user_admin_login_log WHERE org_id = ? AND app_id = ? ORDER BY ctime DESC) AS t GROUP BY admin_user_id) AS u_l ON u_a_r.org_id = u_l.org_id AND u_a_r.app_id = u_l.app_id AND u_a_r.admin_user_id = u_l.admin_user_id WHERE u_a_r.org_id = ? AND u_a_r.app_id = ? GROUP BY u_a_r.admin_user_id LIMIT ? OFFSET ?;", orgID, appID, orgID, appID, count, (page-1)*count).Rows()
123 124
 	defer rows.Close()
124 125
 	if err != nil {
125 126
 		if err == gorm.ErrRecordNotFound {
@@ -403,3 +404,12 @@ func ModifyAdminUserInfo(adminUserID int64, orgID int64, appID int64, name strin
403 404
 	tx.Commit()
404 405
 	return nil
405 406
 }
407
+
408
+func GetOrgApp(orgID int64, app_type int) (*models.OrgApp, error) {
409
+	var apps models.OrgApp
410
+	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
411
+	if err != nil {
412
+		return nil, err
413
+	}
414
+	return &apps, nil
415
+}

+ 19 - 1
service/vm_service.go View File

@@ -1,6 +1,8 @@
1 1
 package service
2 2
 
3
-import "XT_New/models"
3
+import (
4
+	"XT_New/models"
5
+)
4 6
 
5 7
 func CreateVMOrgPatient(patients *models.VMOrgPatients) {
6 8
 	writeDb.Model(&models.VMOrgPatients{}).Create(&patients)
@@ -21,3 +23,19 @@ func CreateVMDeviceNumber(number *models.VMDeviceNumber) {
21 23
 func CreateVMSch(sch *models.VMSchedule) {
22 24
 	writeDb.Model(&models.VMSchedule{}).Create(&sch)
23 25
 }
26
+
27
+func CreateVMSchMode(schMode *models.VMPatientScheduleTemplateMode) {
28
+	writeDb.Model(&models.VMPatientScheduleTemplateMode{}).Create(&schMode)
29
+}
30
+
31
+func CreateVMSchTemplateId(schTemplateId *models.VMPatientScheduleTemplateId) {
32
+	writeDb.Model(&models.VMPatientScheduleTemplateId{}).Create(&schTemplateId)
33
+}
34
+
35
+func CreateVMSchTemplate(schTemplate *models.VMPatientScheduleTemplateItem) {
36
+	writeDb.Model(&models.VMPatientScheduleTemplateItem{}).Create(&schTemplate)
37
+}
38
+
39
+func CreateVMPrescription(sys *models.SystemPrescription) {
40
+	writeDb.Model(&models.SystemPrescription{}).Create(&sys)
41
+}