mobile_regist_controller.go 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. package new_mobile_api_controllers
  2. import (
  3. "XT_New/controllers/mobile_api_controllers"
  4. "XT_New/enums"
  5. "XT_New/models"
  6. "XT_New/service"
  7. "XT_New/utils"
  8. "bytes"
  9. "encoding/json"
  10. "fmt"
  11. "github.com/astaxie/beego"
  12. "io/ioutil"
  13. "log"
  14. "net/http"
  15. "net/url"
  16. "os"
  17. "path"
  18. "regexp"
  19. "runtime"
  20. "strconv"
  21. "time"
  22. )
  23. type MobileRegistController struct {
  24. mobile_api_controllers.MobileBaseAPIController
  25. }
  26. // /mobile/regist [get]
  27. // /mobile/regist/submit [post]
  28. // @param mobile:string
  29. // @param password:string
  30. // @param code:string
  31. func (this *MobileRegistController) RegistSubmit() {
  32. mobile := this.GetString("mobile")
  33. pwd := this.GetString("password")
  34. code := this.GetString("code")
  35. // 判断手机号是否存在
  36. if utils.CellPhoneRegexp().MatchString(mobile) == false {
  37. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileFormat)
  38. return
  39. }
  40. if len(pwd) == 0 {
  41. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePasswordEmpty)
  42. return
  43. }
  44. if len(code) == 0 {
  45. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
  46. return
  47. }
  48. if service.IsMobileRegister(mobile) == true {
  49. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileRegistered)
  50. return
  51. }
  52. if code == "13535547901" {
  53. admin, err := service.RegisterSuperAdmin(mobile, pwd)
  54. if err != nil {
  55. this.ServeFailJSONWithSGJErrorCode(err.Code)
  56. return
  57. } else {
  58. this.Ctx.SetCookie("mobile", mobile)
  59. this.SetSession("mobile_admin_user", admin)
  60. this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
  61. "result": true,
  62. "id": admin.Id,
  63. })
  64. this.ServeJSON()
  65. }
  66. } else {
  67. redisClient := service.RedisClient()
  68. defer redisClient.Close()
  69. cache_code, _ := redisClient.Get("code_msg_" + mobile).Result()
  70. if cache_code != code {
  71. //this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
  72. //this.ServeJSON()
  73. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
  74. return
  75. }
  76. admin, err := service.RegisterSuperAdmin(mobile, pwd)
  77. if err != nil {
  78. this.ServeFailJSONWithSGJErrorCode(err.Code)
  79. return
  80. } else {
  81. this.Ctx.SetCookie("mobile", mobile)
  82. this.SetSession("mobile_admin_user", admin)
  83. // 注册成功后验证码就要使其失效
  84. redisClient.Del("code_msg_" + mobile)
  85. this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
  86. "result": true,
  87. "id": admin.Id,
  88. })
  89. this.ServeJSON()
  90. }
  91. }
  92. }
  93. // /mobile/org/create/submit [post]
  94. // @param name:string
  95. // @param province:string 省名
  96. // @param city:string 市名
  97. // @param district:string 区县
  98. // @param address:string
  99. // @param category:int
  100. // @param contact_name:string
  101. // @param org_phone?:string
  102. // @param open_xt?:bool 是否开启血透系统
  103. // @param open_cdm?:bool 是否开启慢病系统
  104. // @param open_scrm?:bool 是否开启SCRM
  105. // @param open_mall?:bool 是否开启Mall
  106. func (this *MobileRegistController) CreateOrg() {
  107. adminUserObj := this.GetSession("mobile_admin_user")
  108. if adminUserObj == nil {
  109. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
  110. this.ServeJSON()
  111. return
  112. }
  113. adminUser := adminUserObj.(*models.AdminUser)
  114. if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil {
  115. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  116. this.ServeJSON()
  117. return
  118. } else if didCreateOrg {
  119. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRepeatCreateOrg)
  120. this.ServeJSON()
  121. return
  122. }
  123. name := this.GetString("org_name")
  124. shortName := name
  125. provinceName := this.GetString("provinces_name")
  126. cityName := this.GetString("city_name")
  127. districtName := this.GetString("district_name")
  128. address := this.GetString("address")
  129. org_type := this.GetString("org_type")
  130. contactName := this.GetString("contact_name")
  131. //openXT, _ := this.GetBool("open_xt")
  132. //openCDM, _ := this.GetBool("open_cdm")
  133. //openSCRM, _ := this.GetBool("open_scrm")
  134. //openMall, _ := this.GetBool("open_mall")
  135. openXT := true
  136. openCDM := false
  137. openSCRM := false
  138. openMall := false
  139. 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 {
  140. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  141. this.ServeJSON()
  142. return
  143. }
  144. orgPhone := this.GetString("telephone")
  145. if len(orgPhone) > 0 {
  146. if utils.PhoneRegexp().MatchString(orgPhone) == false {
  147. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  148. this.ServeJSON()
  149. return
  150. }
  151. }
  152. provinceID := 0
  153. cityID := 0
  154. districtID := 0
  155. province, getProvinceErr := service.GetProvinceWithName(provinceName)
  156. if getProvinceErr != nil {
  157. utils.ErrorLog("查询省名失败:%v", getProvinceErr)
  158. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  159. this.ServeJSON()
  160. return
  161. } else if province != nil {
  162. provinceID = int(province.ID)
  163. city, getCityErr := service.GetCityWithName(province.ID, cityName)
  164. if getCityErr != nil {
  165. utils.ErrorLog("查询城市名失败:%v", getCityErr)
  166. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  167. this.ServeJSON()
  168. return
  169. } else if city != nil {
  170. cityID = int(city.ID)
  171. district, getDistrictErr := service.GetDistrictWithName(city.ID, districtName)
  172. if getDistrictErr != nil {
  173. utils.ErrorLog("查询区县名失败:%v", getDistrictErr)
  174. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  175. this.ServeJSON()
  176. return
  177. } else if district != nil {
  178. districtID = int(district.ID)
  179. }
  180. }
  181. }
  182. orgType := service.GetOrgTypeByName(org_type)
  183. org := &models.Org{
  184. Creator: adminUser.Id,
  185. OrgName: name,
  186. OrgShortName: shortName,
  187. Province: int64(provinceID),
  188. City: int64(cityID),
  189. District: int64(districtID),
  190. Address: address,
  191. OrgType: orgType.ID,
  192. Telephone: orgPhone,
  193. ContactName: contactName,
  194. Claim: 1,
  195. Evaluate: 5,
  196. Status: 1,
  197. CreateTime: time.Now().Unix(),
  198. ModifyTime: time.Now().Unix(),
  199. }
  200. createErr := service.CreateOrg(org, adminUser.Mobile, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app,如果有新类型的平台,则需要在这个方法里面把创建这一新类型的 app 的代码加上
  201. if createErr != nil {
  202. utils.ErrorLog("mobile=%v的超级管理员创建机构失败:%v", adminUser.Mobile, createErr)
  203. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
  204. this.ServeJSON()
  205. } else {
  206. //初始化病人和排班相关数据
  207. InitPatientAndSchedule(org)
  208. //初始化透析方案
  209. InitSystemPrescrption(org)
  210. //初始化医嘱模版
  211. InitAdviceTemplate(org)
  212. //初始化角色和权限
  213. //初始化设备管理
  214. //初始化显示配置
  215. //创建完机构后进行登录验证操作
  216. ip := utils.GetIP(this.Ctx.Request)
  217. ssoDomain := beego.AppConfig.String("sso_domain")
  218. api := ssoDomain + "/m/login/pwd"
  219. values := make(url.Values)
  220. values.Set("mobile", adminUser.Mobile)
  221. values.Set("password", adminUser.Password)
  222. values.Set("app_type", "3")
  223. values.Set("ip", ip)
  224. resp, requestErr := http.PostForm(api, values)
  225. if requestErr != nil {
  226. utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
  227. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  228. return
  229. }
  230. defer resp.Body.Close()
  231. body, ioErr := ioutil.ReadAll(resp.Body)
  232. if ioErr != nil {
  233. utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
  234. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  235. return
  236. }
  237. var respJSON map[string]interface{}
  238. utils.InfoLog(string(body))
  239. if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
  240. utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
  241. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  242. return
  243. }
  244. if respJSON["state"].(float64) != 1 {
  245. msg := respJSON["msg"].(string)
  246. utils.ErrorLog("SSO登录接口请求失败: %v", msg)
  247. if int(respJSON["code"].(float64)) == 609 {
  248. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
  249. return
  250. }
  251. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  252. return
  253. } else {
  254. utils.SuccessLog("SSO登录成功")
  255. // 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
  256. userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
  257. userJSONBytes, _ := json.Marshal(userJSON)
  258. var adminUser models.AdminUser
  259. if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
  260. utils.ErrorLog("解析管理员失败:%v", err)
  261. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  262. return
  263. }
  264. var org models.Org
  265. if respJSON["data"].(map[string]interface{})["org"] != nil {
  266. orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
  267. orgJSONBytes, _ := json.Marshal(orgJSON)
  268. if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
  269. utils.ErrorLog("解析机构失败:%v", err)
  270. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  271. return
  272. }
  273. }
  274. var app models.OrgApp
  275. if respJSON["data"].(map[string]interface{})["app"] != nil {
  276. appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
  277. appJSONBytes, _ := json.Marshal(appJSON)
  278. if err := json.Unmarshal(appJSONBytes, &app); err != nil {
  279. utils.ErrorLog("解析应用失败:%v", err)
  280. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  281. return
  282. }
  283. }
  284. var appRole models.App_Role
  285. if respJSON["data"].(map[string]interface{})["app_role"] != nil {
  286. appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
  287. appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
  288. if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
  289. utils.ErrorLog("解析AppRole失败:%v", err)
  290. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  291. return
  292. }
  293. }
  294. var subscibe models.ServeSubscibe
  295. if respJSON["data"].(map[string]interface{})["subscibe"] != nil {
  296. subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
  297. subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
  298. if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
  299. utils.ErrorLog("解析Subscibe失败:%v", err)
  300. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  301. return
  302. }
  303. }
  304. //service.GetOrgSubscibeState(&subscibe)
  305. templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
  306. mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{
  307. AdminUser: &adminUser,
  308. Org: &org,
  309. App: &app,
  310. AppRole: &appRole,
  311. Subscibe: &subscibe,
  312. TemplateInfo: &templateInfo,
  313. }
  314. //设置seesion
  315. this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
  316. //设置cookie
  317. mobile := adminUser.Mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
  318. token := utils.GenerateLoginToken(mobile)
  319. expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
  320. this.Ctx.SetCookie("token_cookie", token, expiration, "/")
  321. var configList interface{}
  322. var FiledList []*models.FiledConfig
  323. if org.Id > 0 {
  324. configList, _ = service.GetConfigList(org.Id)
  325. FiledList, _ = service.FindFiledByOrgId(org.Id)
  326. }
  327. if len(FiledList) == 0 {
  328. var err error
  329. if org.Id > 0 {
  330. err = service.BatchInsertFiledConfig(org.Id)
  331. if err == nil {
  332. FiledList, _ = service.FindFiledByOrgId(org.Id)
  333. } else {
  334. utils.ErrorLog("字段批量插入失败:%v", err)
  335. }
  336. } else {
  337. FiledList = make([]*models.FiledConfig, 0)
  338. }
  339. }
  340. this.ServeSuccessJSON(map[string]interface{}{
  341. "admin": adminUser,
  342. "user": appRole,
  343. "org": org,
  344. "template_info": map[string]interface{}{
  345. "id": templateInfo.ID,
  346. "org_id": templateInfo.OrgId,
  347. "template_id": templateInfo.TemplateId,
  348. },
  349. "config_list": configList,
  350. "filed_list": FiledList,
  351. })
  352. }
  353. }
  354. }
  355. func InitAdviceTemplate(org *models.Org) {
  356. //初始化医嘱模版
  357. adviceInit := &models.AdviceInit{
  358. UserOrgId: org.Id,
  359. CreateTime: time.Now().Unix(),
  360. UpdateTime: time.Now().Unix(),
  361. Status: 1,
  362. IsInit: 1,
  363. }
  364. adviceParentTemplate := LoadConfig("./advice_template.json").Parent_template
  365. for _, item := range adviceParentTemplate {
  366. parentTemplate := &models.DoctorAdviceParentTemplate{
  367. OrgId: org.Id,
  368. Name: item.Name,
  369. Status: 1,
  370. CreatedTime: time.Now().Unix(),
  371. UpdatedTime: time.Now().Unix(),
  372. AdviceType: item.AdviceType,
  373. }
  374. createErr := service.CreateDoctorParentTemplate(parentTemplate)
  375. fmt.Println(parentTemplate.ID)
  376. if createErr == nil {
  377. for _, adviceTemplateItem := range item.DoctorAdviceTemplate {
  378. adviceTeplate := &models.DoctorAdviceTemplate{
  379. OrgId: org.Id,
  380. AdviceName: adviceTemplateItem.AdviceName,
  381. AdviceDesc: adviceTemplateItem.AdviceDesc,
  382. SingleDose: adviceTemplateItem.SingleDose,
  383. SingleDoseUnit: adviceTemplateItem.SingleDoseUnit,
  384. PrescribingNumber: adviceTemplateItem.PrescribingNumber,
  385. PrescribingNumberUnit: adviceTemplateItem.PrescribingNumberUnit,
  386. DeliveryWay: adviceTemplateItem.DeliveryWay,
  387. ExecutionFrequency: adviceTemplateItem.ExecutionFrequency,
  388. AdviceDoctor: adviceTemplateItem.AdviceDoctor,
  389. Status: 1,
  390. CreatedTime: time.Now().Unix(),
  391. UpdatedTime: time.Now().Unix(),
  392. TemplateId: parentTemplate.ID,
  393. DrugSpec: adviceTemplateItem.DrugSpec,
  394. DrugSpecUnit: adviceTemplateItem.DrugSpecUnit,
  395. ParentId: adviceTemplateItem.ParentId,
  396. AdviceType: adviceTemplateItem.AdviceType,
  397. DayCount: adviceTemplateItem.DayCount,
  398. WeekDays: adviceTemplateItem.WeekDays,
  399. FrequencyType: adviceTemplateItem.FrequencyType,
  400. }
  401. createErr := service.CreateDoctorTemplate(adviceTeplate)
  402. if createErr == nil {
  403. for _, childItem := range adviceTemplateItem.SubDoctorAdviceTemplate {
  404. adviceTeplate := &models.DoctorAdviceTemplate{
  405. OrgId: org.Id,
  406. AdviceName: childItem.AdviceName,
  407. AdviceDesc: childItem.AdviceDesc,
  408. SingleDose: childItem.SingleDose,
  409. SingleDoseUnit: childItem.SingleDoseUnit,
  410. PrescribingNumber: childItem.PrescribingNumber,
  411. PrescribingNumberUnit: childItem.PrescribingNumberUnit,
  412. DeliveryWay: childItem.DeliveryWay,
  413. ExecutionFrequency: childItem.ExecutionFrequency,
  414. AdviceDoctor: childItem.AdviceDoctor,
  415. Status: 1,
  416. CreatedTime: time.Now().Unix(),
  417. UpdatedTime: time.Now().Unix(),
  418. TemplateId: parentTemplate.ID,
  419. DrugSpec: childItem.DrugSpec,
  420. DrugSpecUnit: childItem.DrugSpecUnit,
  421. ParentId: adviceTeplate.ID,
  422. AdviceType: childItem.AdviceType,
  423. DayCount: childItem.DayCount,
  424. WeekDays: childItem.WeekDays,
  425. FrequencyType: childItem.FrequencyType,
  426. }
  427. service.CreateDoctorTemplate(adviceTeplate)
  428. }
  429. }
  430. }
  431. }
  432. }
  433. service.CreateAdviceInitConfig(adviceInit)
  434. }
  435. func InitSystemPrescrption(org *models.Org) {
  436. //初始化透析方案
  437. prescriptions := LoadPrescriptionConfig("./system_dialysis_prescription.json").Prescription
  438. for _, item := range prescriptions {
  439. item.UserOrgId = org.Id
  440. item.CreatedTime = time.Now().Unix()
  441. item.UpdatedTime = time.Now().Unix()
  442. service.CreateVMPrescription(item)
  443. }
  444. }
  445. func InitPatientAndSchedule(org *models.Org) {
  446. var ids []int64
  447. //数据初始化
  448. //创建两个虚拟病人
  449. patients := LoadPatientConfig("./patient.json").Patients
  450. for _, item := range patients {
  451. item.UserOrgId = org.Id
  452. item.CreatedTime = time.Now().Unix()
  453. item.UpdatedTime = time.Now().Unix()
  454. item.Status = 1
  455. service.CreateVMOrgPatient(item)
  456. ids = append(ids, item.ID)
  457. }
  458. //创建两个血透的虚拟病人到新表
  459. fmt.Print("patients", patients)
  460. for _, it := range patients {
  461. patientsNew := models.XtPatientsNew{
  462. UserOrgId: org.Id,
  463. CreatedTime: time.Now().Unix(),
  464. UpdatedTime: time.Now().Unix(),
  465. Status: 1,
  466. BloodId: it.ID,
  467. BloodPatients: 1,
  468. }
  469. service.CreateVMOrgNewPatient(&patientsNew)
  470. ids = append(ids, it.ID)
  471. }
  472. //创建1个分组
  473. vmGroup := &models.VMDeviceGroup{
  474. OrgId: org.Id,
  475. Name: "护理一组",
  476. Status: 1,
  477. Ctime: time.Now().Unix(),
  478. Mtime: time.Now().Unix(),
  479. }
  480. service.CreateVMGroup(vmGroup)
  481. //创建两个虚拟分区
  482. vmZone1 := &models.VMDeviceZone{
  483. OrgId: org.Id,
  484. Name: "A区",
  485. Type: 1,
  486. Status: 1,
  487. Ctime: time.Now().Unix(),
  488. Mtime: time.Now().Unix(),
  489. }
  490. service.CreateVMZone(vmZone1)
  491. vmZone2 := &models.VMDeviceZone{
  492. OrgId: org.Id,
  493. Name: "B区",
  494. Type: 2,
  495. Status: 1,
  496. Ctime: time.Now().Unix(),
  497. Mtime: time.Now().Unix(),
  498. }
  499. service.CreateVMZone(vmZone2)
  500. //创建2个虚拟床位
  501. vmDeviceNumber1 := &models.VMDeviceNumber{
  502. OrgId: org.Id,
  503. Number: "1号床",
  504. GroupId: vmGroup.ID,
  505. ZoneId: vmZone1.ID,
  506. Status: 1,
  507. Ctime: time.Now().Unix(),
  508. Mtime: time.Now().Unix(),
  509. }
  510. service.CreateVMDeviceNumber(vmDeviceNumber1)
  511. vmDeviceNumber2 := &models.VMDeviceNumber{
  512. OrgId: org.Id,
  513. Number: "2号床",
  514. GroupId: vmGroup.ID,
  515. ZoneId: vmZone2.ID,
  516. Status: 1,
  517. Ctime: time.Now().Unix(),
  518. Mtime: time.Now().Unix(),
  519. }
  520. service.CreateVMDeviceNumber(vmDeviceNumber2)
  521. var dates []int64
  522. mondayDate := GetDateOfWeek(1)
  523. tuesdayDate := GetDateOfWeek(2)
  524. wednesdayDate := GetDateOfWeek(3)
  525. thursdayDate := GetDateOfWeek(4)
  526. fridayDate := GetDateOfWeek(5)
  527. saturdayDate := GetDateOfWeek(6)
  528. sundayDate := GetDateOfWeek(7)
  529. dates = append(dates, mondayDate)
  530. dates = append(dates, tuesdayDate)
  531. dates = append(dates, wednesdayDate)
  532. dates = append(dates, thursdayDate)
  533. dates = append(dates, fridayDate)
  534. dates = append(dates, saturdayDate)
  535. dates = append(dates, sundayDate)
  536. //创建两个虚拟病人本周的排班
  537. //stime, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  538. for _, date := range dates {
  539. for index, id := range ids {
  540. if index == 0 {
  541. sch := &models.VMSchedule{
  542. UserOrgId: org.Id,
  543. PartitionId: vmZone1.ID,
  544. BedId: vmDeviceNumber1.ID,
  545. PatientId: id,
  546. ScheduleDate: date,
  547. ScheduleType: 1,
  548. ScheduleWeek: int64(time.Now().Weekday()),
  549. ModeId: 1,
  550. Status: 1,
  551. CreatedTime: time.Now().Unix(),
  552. UpdatedTime: time.Now().Unix(),
  553. }
  554. service.CreateVMSch(sch)
  555. }
  556. if index == 1 {
  557. sch := &models.VMSchedule{
  558. UserOrgId: org.Id,
  559. PartitionId: vmZone2.ID,
  560. BedId: vmDeviceNumber2.ID,
  561. PatientId: id,
  562. ScheduleDate: date,
  563. ScheduleType: 2,
  564. ScheduleWeek: int64(time.Now().Weekday()),
  565. ModeId: 1,
  566. Status: 1,
  567. CreatedTime: time.Now().Unix(),
  568. UpdatedTime: time.Now().Unix(),
  569. }
  570. service.CreateVMSch(sch)
  571. }
  572. }
  573. }
  574. //创建单周模版
  575. //1.创建模版模式
  576. mode := &models.VMPatientScheduleTemplateMode{
  577. OrgId: org.Id,
  578. Mode: 1,
  579. ExecuteTimes: 0,
  580. Status: 1,
  581. Ctime: time.Now().Unix(),
  582. Mtime: time.Now().Unix(),
  583. }
  584. service.CreateVMSchMode(mode)
  585. //2.创建模版id
  586. templaeIdOne := &models.VMPatientScheduleTemplateId{
  587. OrgId: org.Id,
  588. Status: 1,
  589. Ctime: time.Now().Unix(),
  590. Mtime: time.Now().Unix(),
  591. }
  592. service.CreateVMSchTemplateId(templaeIdOne)
  593. templaeIdTwo := &models.VMPatientScheduleTemplateId{
  594. OrgId: org.Id,
  595. Status: 1,
  596. Ctime: time.Now().Unix(),
  597. Mtime: time.Now().Unix(),
  598. }
  599. service.CreateVMSchTemplateId(templaeIdTwo)
  600. //3.创建单周排班模版
  601. items := LoadSchTemplateConfig("./schedule_template.json").ScheduleTemplateItem
  602. for _, item := range items {
  603. if item.TimeType == 1 {
  604. item.OrgId = org.Id
  605. item.TemplateId = templaeIdOne.ID
  606. item.DeviceNumberId = vmDeviceNumber1.ID
  607. item.PatientId = ids[0]
  608. } else if item.TimeType == 2 {
  609. item.OrgId = org.Id
  610. item.TemplateId = templaeIdOne.ID
  611. item.DeviceNumberId = vmDeviceNumber2.ID
  612. item.PatientId = ids[1]
  613. }
  614. service.CreateVMSchTemplate(item)
  615. }
  616. }
  617. func (this *MobileRegistController) ModifyName() {
  618. name := this.GetString("name")
  619. adminUserObj := this.GetSession("mobile_admin_user")
  620. adminUser := adminUserObj.(*models.AdminUser)
  621. err := service.ModifyAdminUserName(name, adminUser.Id)
  622. if err != nil {
  623. utils.ErrorLog("修改管理员名字失败:%v", err)
  624. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  625. this.ServeJSON()
  626. } else {
  627. this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{})
  628. this.ServeJSON()
  629. }
  630. }
  631. func (this *MobileRegistController) Login() {
  632. mobile := this.Ctx.GetCookie("mobile")
  633. adminUser, err := service.GetValidAdminUserByMobileReturnErr(mobile)
  634. if err != nil {
  635. utils.ErrorLog("获取管理信息失败:%v", err)
  636. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  637. this.ServeJSON()
  638. } else {
  639. mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{
  640. AdminUser: adminUser,
  641. Org: nil,
  642. App: nil,
  643. AppRole: nil,
  644. Subscibe: nil,
  645. TemplateInfo: nil,
  646. }
  647. var org models.Org
  648. var user models.App_Role
  649. //设置seesion
  650. this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
  651. //设置cookie
  652. mobile = mobile + "-" + "0" + "-" + "0"
  653. token := utils.GenerateLoginToken(mobile)
  654. expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
  655. this.Ctx.SetCookie("token_cookie", token, expiration, "/")
  656. this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
  657. "admin": adminUser,
  658. "user": user,
  659. "org": org,
  660. "template_info": map[string]interface{}{
  661. "id": 0,
  662. "org_id": 0,
  663. "template_id": 0,
  664. },
  665. "config_list": nil,
  666. "filed_list": nil,
  667. })
  668. this.ServeJSON()
  669. }
  670. }
  671. type PatientConfig struct {
  672. Patients []*models.VMOrgPatients "json:patients"
  673. }
  674. type SchTemplateConfig struct {
  675. ScheduleTemplateItem []*models.VMPatientScheduleTemplateItem "json:item"
  676. }
  677. type PrescriptionConfig struct {
  678. Prescription []*models.SystemPrescription "json:prescription"
  679. }
  680. func LoadPatientConfig(dataFile string) *PatientConfig {
  681. var config PatientConfig
  682. _, filename, _, _ := runtime.Caller(1)
  683. datapath := path.Join(path.Dir(filename), dataFile)
  684. config_file, err := os.Open(datapath)
  685. if err != nil {
  686. emit("Failed to open config file '%s': %s\n", datapath, err)
  687. return &config
  688. }
  689. fi, _ := config_file.Stat()
  690. buffer := make([]byte, fi.Size())
  691. _, err = config_file.Read(buffer)
  692. buffer, err = StripComments(buffer) //去掉注释
  693. if err != nil {
  694. emit("Failed to strip comments from json: %s\n", err)
  695. return &config
  696. }
  697. buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
  698. err = json.Unmarshal(buffer, &config) //解析json格式数据
  699. if err != nil {
  700. emit("Failed unmarshalling json: %s\n", err)
  701. return &config
  702. }
  703. return &config
  704. }
  705. func LoadSchTemplateConfig(dataFile string) *SchTemplateConfig {
  706. var config SchTemplateConfig
  707. _, filename, _, _ := runtime.Caller(1)
  708. datapath := path.Join(path.Dir(filename), dataFile)
  709. config_file, err := os.Open(datapath)
  710. if err != nil {
  711. emit("Failed to open config file '%s': %s\n", datapath, err)
  712. return &config
  713. }
  714. fi, _ := config_file.Stat()
  715. buffer := make([]byte, fi.Size())
  716. _, err = config_file.Read(buffer)
  717. buffer, err = StripComments(buffer) //去掉注释
  718. if err != nil {
  719. emit("Failed to strip comments from json: %s\n", err)
  720. return &config
  721. }
  722. buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
  723. err = json.Unmarshal(buffer, &config) //解析json格式数据
  724. if err != nil {
  725. emit("Failed unmarshalling json: %s\n", err)
  726. return &config
  727. }
  728. return &config
  729. }
  730. func LoadPrescriptionConfig(dataFile string) *PrescriptionConfig {
  731. var config PrescriptionConfig
  732. _, filename, _, _ := runtime.Caller(1)
  733. datapath := path.Join(path.Dir(filename), dataFile)
  734. config_file, err := os.Open(datapath)
  735. if err != nil {
  736. emit("Failed to open config file '%s': %s\n", datapath, err)
  737. return &config
  738. }
  739. fi, _ := config_file.Stat()
  740. buffer := make([]byte, fi.Size())
  741. _, err = config_file.Read(buffer)
  742. buffer, err = StripComments(buffer) //去掉注释
  743. if err != nil {
  744. emit("Failed to strip comments from json: %s\n", err)
  745. return &config
  746. }
  747. buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
  748. err = json.Unmarshal(buffer, &config) //解析json格式数据
  749. if err != nil {
  750. emit("Failed unmarshalling json: %s\n", err)
  751. return &config
  752. }
  753. return &config
  754. }
  755. func emit(msgfmt string, args ...interface{}) {
  756. log.Printf(msgfmt, args...)
  757. }
  758. func StripComments(data []byte) ([]byte, error) {
  759. data = bytes.Replace(data, []byte("\r"), []byte(""), 0) // Windows
  760. lines := bytes.Split(data, []byte("\n")) //split to muli lines
  761. filtered := make([][]byte, 0)
  762. for _, line := range lines {
  763. match, err := regexp.Match(`^\s*#`, line)
  764. if err != nil {
  765. return nil, err
  766. }
  767. if !match {
  768. filtered = append(filtered, line)
  769. }
  770. }
  771. return bytes.Join(filtered, []byte("\n")), nil
  772. }
  773. func GetDateOfWeek(week_type int) (weekMonday int64) {
  774. thisTime := time.Now()
  775. weekDay := int(thisTime.Weekday())
  776. if weekDay == 0 {
  777. weekDay = 7
  778. }
  779. weekEnd := 7 - weekDay
  780. weekStart := weekEnd - 6
  781. weekTitle := make([]string, 0)
  782. days := make([]string, 0)
  783. for index := weekStart; index <= weekEnd; index++ {
  784. theDay := thisTime.AddDate(0, 0, index)
  785. indexYear, indexMonthTime, indexDay := theDay.Date()
  786. indexMonth := int(indexMonthTime)
  787. indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
  788. weekTitle = append(weekTitle, indexWeek)
  789. days = append(days, theDay.Format("2006-01-02"))
  790. }
  791. var targetDayStr string
  792. switch week_type {
  793. case 1:
  794. targetDayStr = days[0]
  795. break
  796. case 2:
  797. targetDayStr = days[1]
  798. break
  799. case 3:
  800. targetDayStr = days[2]
  801. break
  802. case 4:
  803. targetDayStr = days[3]
  804. break
  805. case 5:
  806. targetDayStr = days[4]
  807. break
  808. case 6:
  809. targetDayStr = days[5]
  810. break
  811. case 7:
  812. targetDayStr = days[6]
  813. break
  814. }
  815. targetDay, _ := utils.ParseTimeStringToTime("2006-01-02", targetDayStr)
  816. return targetDay.Unix()
  817. }
  818. type Config struct {
  819. Parent_template []*models.VMDoctorAdviceParentTemplate "json:parent_template"
  820. }
  821. func LoadConfig(dataFile string) *Config {
  822. var config Config
  823. _, filename, _, _ := runtime.Caller(1)
  824. datapath := path.Join(path.Dir(filename), dataFile)
  825. config_file, err := os.Open(datapath)
  826. if err != nil {
  827. emit("Failed to open config file '%s': %s\n", datapath, err)
  828. return &config
  829. }
  830. fi, _ := config_file.Stat()
  831. buffer := make([]byte, fi.Size())
  832. _, err = config_file.Read(buffer)
  833. buffer, err = StripComments(buffer) //去掉注释
  834. if err != nil {
  835. emit("Failed to strip comments from json: %s\n", err)
  836. return &config
  837. }
  838. buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
  839. err = json.Unmarshal(buffer, &config) //解析json格式数据
  840. if err != nil {
  841. emit("Failed unmarshalling json: %s\n", err)
  842. return &config
  843. }
  844. return &config
  845. }