Browse Source

Merge branch 'dev' of http://192.168.1.220:10080/Amoy/patient-co-management into dev

DESKTOP-G6NQ3SI\dante 7 năm trước cách đây
mục cha
commit
4c77907625
100 tập tin đã thay đổi với 4085 bổ sung82 xóa
  1. 9 0
      common/common-entity/src/main/java/com/yihu/es/entity/HealthEduArticlePatient.java
  2. 96 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/health/DoctorHealthStandard.java
  3. 11 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/scheme/DoctorSchemeBloodPressure.java
  4. 11 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/scheme/DoctorSchemeBloodSugger.java
  5. 10 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/team/admin/AdminTeam.java
  6. 1 1
      common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/PatientSchemeList.java
  7. 0 37
      common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prescription/PrescriptionPay.java
  8. 29 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/vo/PatientCodeDeviceType.java
  9. 26 9
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/common/account/CustomerController.java
  10. 11 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/Doctor.java
  11. 51 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/account/CustomerService.java
  12. 2 0
      patient-co-manage/wlyy-manage/src/main/resources/application.yml
  13. 3 1
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/dao/PatientHealthIndexDao.java
  14. 8 0
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/model/Patient.java
  15. 71 1
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java
  16. 68 8
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/ArchivesController.java
  17. 17 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/PrescriptionController.java
  18. 48 5
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/SignController.java
  19. 3 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/dao/DoctorMappingDao.java
  20. 3 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/dao/prescription/PrescriptionExpressageDao.java
  21. 44 1
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ArchivesService.java
  22. 24 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/SignZYService.java
  23. 163 9
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java
  24. 68 8
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/prescription/PrescriptionService.java
  25. 19 2
      patient-co-service/wlyy_service/src/main/resources/application.yml
  26. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/1.png
  27. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/2.png
  28. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/3.png
  29. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/4.png
  30. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/5.png
  31. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/6.png
  32. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/7.png
  33. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/8.png
  34. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot项目启动的2种方式.docx
  35. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/1.png
  36. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/10.png
  37. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/11.png
  38. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/12.png
  39. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/13.png
  40. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/2.png
  41. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/3.png
  42. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/4.png
  43. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/5.png
  44. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/6.png
  45. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/7.png
  46. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/8.png
  47. BIN
      patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/9.png
  48. 112 0
      patient-co/patient-co-doctor-assistant/doc/技术文档/es/统计新增索引.txt
  49. BIN
      patient-co/patient-co-doctor-assistant/doc/接口文档/厦门i健康API文档.docx
  50. BIN
      patient-co/patient-co-doctor-assistant/doc/接口文档/对外接口文档/集美健康教育/集美健康教育对外接口文档.docx
  51. 10 0
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/00.readme.txt
  52. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/HBuilder使用该证书打包的例子.png
  53. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/aps推送证书.p12
  54. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/xmijkPro.mobileprovision
  55. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/证书.p12
  56. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/医生端通过HBuilder打包说明(草稿,完整版V0.2).docx
  57. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/发布修改参数.docx
  58. 10 0
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/00.readme.txt
  59. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/20160721170424_该证书的生成命令.png
  60. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/HBuilder使用该证书打包的例子.png
  61. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/ssgg_doctor.keystore
  62. 5 0
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/文档.txt
  63. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/im/im.docx
  64. BIN
      patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/微信端/微信端发布.docx
  65. 500 0
      patient-co/patient-co-doctor-assistant/pom.xml
  66. 29 0
      patient-co/patient-co-doctor-assistant/readme.MD
  67. 20 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/Application.java
  68. 323 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/adapter/PresModeAdapter.java
  69. 14 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/aop/ObserverRequired.java
  70. 90 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/aop/ObserverRequiredAOP.java
  71. 59 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  72. 27 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/FastDFSConfig.java
  73. 80 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/MvcConfig.java
  74. 199 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/SwaggerConfig.java
  75. 54 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/async/AsyncConfig.java
  76. 93 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java
  77. 49 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java
  78. 61 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/jpa/HealthJpa.java
  79. 27 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/jpa/HibernateProperties.java
  80. 67 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/jpa/WlyyJpa.java
  81. 48 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/security/WebSecurityConfig.java
  82. 20 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/war/ServletInitializer.java
  83. 30 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java
  84. 101 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java
  85. 58 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/BaseInterceptor.java
  86. 221 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/DoctorInterceptor.java
  87. 53 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/EncodingFilter.java
  88. 74 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/GateWayAOP.java
  89. 165 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/GateWayInterceptor.java
  90. 62 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/MutableHttpServletRequest.java
  91. 85 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/ObserverRequiredInterceptor.java
  92. 157 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/PatientInterceptor.java
  93. 59 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/UserAgentFilter.java
  94. 103 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/logs/BusinessLogs.java
  95. 42 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/logs/InterfaceCallLogs.java
  96. 101 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/redis/RedisMsgPubSubListener.java
  97. 44 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/redis/RedisThread.java
  98. 17 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/VersionsDao.java
  99. 20 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/address/CityDao.java
  100. 0 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/address/CountryDao.java

+ 9 - 0
common/common-entity/src/main/java/com/yihu/es/entity/HealthEduArticlePatient.java

@ -44,6 +44,7 @@ public class HealthEduArticlePatient {
    private String level;//等级
    private Integer allCount;//所有的推送数目
    private String type;//推送类型 1:文章 2:健康课程
    private String articleUrl;//集美宣教,文章的url
    public String getId() {
        return id;
@ -268,4 +269,12 @@ public class HealthEduArticlePatient {
    public void setType(String type) {
        this.type = type;
    }
    public String getArticleUrl() {
        return articleUrl;
    }
    public void setArticleUrl(String articleUrl) {
        this.articleUrl = articleUrl;
    }
}

+ 96 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/health/DoctorHealthStandard.java

@ -0,0 +1,96 @@
package com.yihu.wlyy.entity.doctor.health;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 医生预警值方案
 * @author huangwenjie
 * @date 2017/9/14 21:08
 */
@Entity
@Table(name = "wlyy_doctor_health_standard")
public class DoctorHealthStandard extends IdEntity {
    private static final long serialVersionUID = -8343925049051333359L;
    // 患者标识
    private String doctor;
    // 健康指标类型:1血糖,2血压,3体重,4腰围
    private Integer type;
    // 最低安全值(血糖餐前\收缩压\BMI\腰围)
    private Double minValue1;
    // 最高安全值(血糖餐前\收缩压\BMI\腰围)
    private Double maxValue1;
    // 最低安全值(血糖餐后\舒张压\步数)
    private Double minValue2;
    // 最高安全值(血糖餐后\舒张压\步数)
    private Double maxValue2;
    // 设置时间
    private Date czrq;
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    @Column(name = "min_value_1")
    public Double getMinValue1() {
        return minValue1;
    }
    public void setMinValue1(Double minValue) {
        this.minValue1 = minValue;
    }
    @Column(name = "max_value_1")
    public Double getMaxValue1() {
        return maxValue1;
    }
    public void setMaxValue1(Double maxValue) {
        this.maxValue1 = maxValue;
    }
    @Column(name = "min_value_2")
    public Double getMinValue2() {
        return minValue2;
    }
    public void setMinValue2(Double minValue) {
        this.minValue2 = minValue;
    }
    @Column(name = "max_value_2")
    public Double getMaxValue2() {
        return maxValue2;
    }
    public void setMaxValue2(Double maxValue) {
        this.maxValue2 = maxValue;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 11 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/scheme/DoctorSchemeBloodPressure.java

@ -32,6 +32,7 @@ public class DoctorSchemeBloodPressure extends IdEntity {
    private Timestamp createTime;      //创建时间
    private Short alertTag;            //是否提醒用户
    private String content;            //方案说明
    private Short del;          //0为正常,1为删除
    @Basic
    @Column(name = "name")
@ -209,4 +210,14 @@ public class DoctorSchemeBloodPressure extends IdEntity {
        this.content = content;
    }
    @Basic
    @Column(name = "del")
    public Short getDel() {
        return del;
    }
    public void setDel(Short del) {
        this.del = del;
    }
}

+ 11 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/scheme/DoctorSchemeBloodSugger.java

@ -36,6 +36,7 @@ public class DoctorSchemeBloodSugger extends IdEntity {
    private Timestamp createTime;
    private Short alertTag;                 //是否提醒用户
    private String content;                 //方案说明
    private Short del;          //0为正常,1为删除
    @Basic
    @Column(name = "name")
@ -241,6 +242,16 @@ public class DoctorSchemeBloodSugger extends IdEntity {
        return alertTag;
    }
    @Basic
    @Column(name = "del")
    public Short getDel() {
        return del;
    }
    public void setDel(Short del) {
        this.del = del;
    }
    public void setAlertTag(Short alertTag) {
        this.alertTag = alertTag;
    }

+ 10 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/doctor/team/admin/AdminTeam.java

@ -26,6 +26,7 @@ public class AdminTeam extends IdEntity {
    private String orgName;
    private String townCode;
    private String townName;
    private String mappingCode;
    public String getName() {
        return name;
@ -78,6 +79,15 @@ public class AdminTeam extends IdEntity {
        this.available = available;
    }
    @Column(name = "mapping_code")
    public String getMappingCode() {
        return mappingCode;
    }
    public void setMappingCode(String mappingCode) {
        this.mappingCode = mappingCode;
    }
    @Transient
    public String getOrgName() {
        return orgName;

+ 1 - 1
common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/PatientSchemeList.java

@ -16,7 +16,7 @@ public class PatientSchemeList extends IdEntity {
    private String code;
    private String patientcode;
    private String schemecode;
    private Short type;//方案类型:0为血压,1为血糖
    private Short type;//方案类型:1为血糖,2为血压
    private String doctorcode;
    private Timestamp createTime;

+ 0 - 37
common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prescription/PrescriptionPay.java

@ -58,43 +58,6 @@ public class PrescriptionPay extends IdEntity {
    private String mxlist;//处方明细
    private Date createTime;//续方确认支付时间
    private Date czrq;//续方记录最后操作时间
    //    易联众新增查询返回字段v1.3.7
    private String medOrgNo;//医疗机构编号
    private String medOrgName;//医疗机构名称
    private Date traceTime;//交易成功时间
    private String traceNo;//支付平台跟踪号
    public Date getTraceTime() {
        return traceTime;
    }
    public void setTraceTime(Date traceTime) {
        this.traceTime = traceTime;
    }
    public String getTraceNo() {
        return traceNo;
    }
    public void setTraceNo(String traceNo) {
        this.traceNo = traceNo;
    }
    public String getMedOrgNo() {
        return medOrgNo;
    }
    public void setMedOrgNo(String medOrgNo) {
        this.medOrgNo = medOrgNo;
    }
    public String getMedOrgName() {
        return medOrgName;
    }
    public void setMedOrgName(String medOrgName) {
        this.medOrgName = medOrgName;
    }
    public Integer getAccountBalance() {
        return accountBalance;

+ 29 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/vo/PatientCodeDeviceType.java

@ -0,0 +1,29 @@
package com.yihu.wlyy.entity.patient.vo;
/**
 * 患者CODE,设备类型VO类
 * @author huangwenjie
 * @date 2017/9/14 22:44
 */
public class PatientCodeDeviceType {
    private String user;            //患者CODE
    private Integer deviceType;     //患者设备类型
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public Integer getDeviceType() {
        return deviceType;
    }
    public void setDeviceType(Integer deviceType) {
        this.deviceType = deviceType;
    }
}

+ 26 - 9
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/common/account/CustomerController.java

@ -1,15 +1,14 @@
package com.yihu.wlyy.controller.common.account;
import com.yihu.wlyy.controller.BaseController;
import com.yihu.wlyy.entity.Doctor;
import com.yihu.wlyy.entity.Patient;
import com.yihu.wlyy.entity.User;
import com.yihu.wlyy.entity.WlyyCustomerLog;
import com.yihu.wlyy.repository.ManageDictDao;
import com.yihu.wlyy.repository.PatientDao;
import com.yihu.wlyy.service.manager.account.CustomerService;
import com.yihu.wlyy.service.manager.family.FamilyMemberService;
import com.yihu.wlyy.service.manager.hos.HosDoctorService;
import com.yihu.wlyy.service.manager.patient.AdminPatientService;
import com.yihu.wlyy.service.manager.sign.SignFamilyService;
import com.yihu.wlyy.service.manager.user.UserService;
import com.yihu.wlyy.service.manager.user.WlyyCustomerLogService;
import io.swagger.annotations.ApiParam;
@ -37,15 +36,9 @@ public class CustomerController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private ManageDictDao manageDictDao;
    @Autowired
    private AdminPatientService patientService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private FamilyMemberService familyMemberService;
    @Autowired
    private SignFamilyService signFamilyService;
    @Autowired
    private WlyyCustomerLogService wlyyCustomerLogService;
@ -53,6 +46,8 @@ public class CustomerController extends BaseController {
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private HosDoctorService doctorService;
    @RequestMapping(value = "/login",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ResponseBody
@ -174,4 +169,26 @@ public class CustomerController extends BaseController {
        return write(200,"查询成功","data",respon);
    }
    /**
     * 客服给医生发送短信,微信提醒
     * (医生助手功能)
     * @param msg
     * @param doctorCode
     * @return
     */
    @RequestMapping(value = "/sendMsg",produces="application/json;charset=UTF-8")
    @ResponseBody
    public String sendMsg(@ApiParam(name="msg",value="消息内容")@RequestParam(name="msg")String msg,
                          @ApiParam(name="doctorCode",value="发送给某个医生code")@RequestParam(name="doctorCode")String doctorCode,
                          @ApiParam(name="type",value="发送类型  1发送短信   2发送微信   3短信微信都发送")@RequestParam(name="doctorCode",required = false)String type) throws Exception {
        //用于返回的resp
        Doctor doctor = doctorService.getDoctorByCode(doctorCode);
        if(StringUtils.isBlank(type)){
            type="3";
        }
        Map<String, Object> resp = customerService.sendMsg(doctor,msg,type);
        return write(200,"","data",resp);
    }
}

+ 11 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/Doctor.java

@ -99,6 +99,8 @@ public class Doctor extends IdEntity {
    private String adminTeamId;
    private String adminTeamName;
	private String openid; //医生微信openID
    @Column(name = "idcard")
    public String getIdCard() {
        return idCard;
@ -417,4 +419,13 @@ public class Doctor extends IdEntity {
    public void setAdminTeamName(String adminTeamName) {
        this.adminTeamName = adminTeamName;
    }
	@Column(name="openid")
	public String getOpenid() {
		return openid;
	}
	public void setOpenid(String openid) {
		this.openid = openid;
	}
}

+ 51 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/account/CustomerService.java

@ -6,8 +6,13 @@ import com.yihu.wlyy.entity.SignFamily;
import com.yihu.wlyy.service.manager.family.FamilyMemberService;
import com.yihu.wlyy.service.manager.hos.HosDoctorService;
import com.yihu.wlyy.service.manager.sign.FamilyContractService;
import com.yihu.wlyy.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@ -25,6 +30,10 @@ public class CustomerService{
	@Autowired
	private HosDoctorService hosDoctorService;
	@Value(("${doctorAssistant.api}")+"/wlyygc/doctor/message")
	private String messageApi;
	public Map<String,Object> findServerInfo(Patient patient) throws Exception {
		Map<String, Object> resp = new HashMap<>();
@ -93,4 +102,46 @@ public class CustomerService{
		return resp;
	}
	/**
	 *
	 * @param doctor
	 * @param msg
	 * @param type  1发送短信   2发送微信   3短信微信都发送
	 * @return
	 */
	public Map<String, Object> sendMsg(Doctor doctor,String msg,String type) {
		Map<String, Object> resp = new HashMap<String, Object>();
		//发送短信消息啦
		String mobile = doctor.getMobile();
		//
		if(!StringUtils.isBlank(mobile)&&!"2".equals(type)){
			List<NameValuePair> par = new ArrayList<NameValuePair>();
			par.add(new BasicNameValuePair("mobiles", mobile));
			par.add(new BasicNameValuePair("content", msg));
			String result = HttpClientUtil.post(messageApi+"/sendMobileMessage",par,"UTF-8");
			JSONObject resultJson = new JSONObject(result);
			if(1!=resultJson.getInt("successNum")){
				resp.put("mobile","-1");//-1代表发送失败
			}
		}
		//发送微信消息啦
		String openId = doctor.getOpenid();
		if(!StringUtils.isBlank(openId)&&!"1".equals(type)){
			List<NameValuePair> par = new ArrayList<NameValuePair>();
			par.add(new BasicNameValuePair("openIds", openId));
			par.add(new BasicNameValuePair("content", msg));
			JSONObject params = new JSONObject();
			String result = HttpClientUtil.post(messageApi+"/sendWechatMessage", par,"UTF-8");
			JSONObject resultJson = new JSONObject(result);
			if(1!=resultJson.getInt("successNum")){
				resp.put("wechat","-1");//-1代表发送失败
			}
		}
		return resp;
	}
}

+ 2 - 0
patient-co-manage/wlyy-manage/src/main/resources/application.yml

@ -73,6 +73,8 @@ im-service:
  im_service_url: http://172.19.103.88:3000/api/v2
yueren:
  api: http://120.77.209.211:8080
doctorAssistant:
  api: http://127.0.0.1:8080
---
spring:

+ 3 - 1
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/dao/PatientHealthIndexDao.java

@ -51,5 +51,7 @@ public interface PatientHealthIndexDao
	@Query("select a from PatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.type = ?4 and a.recordDate = ?5 and a.del = '1' ")
	List<PatientHealthIndex> findByType(String patient, String deviceSn, String value1, Integer type, Date recordDate);
	
	@Query("select a from PatientHealthIndex a where a.user = ?1 and a.type =?2  order by recordDate desc ")
    List<PatientHealthIndex> findByPatientAndType(String patientCode, String diseaseType, Pageable pageable);
}

+ 8 - 0
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/model/Patient.java

@ -325,4 +325,12 @@ public class Patient extends IdEntity implements Serializable {
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}
	public Integer getStandardStatus() {
		return standardStatus;
	}
	public void setStandardStatus(Integer standardStatus) {
		this.standardStatus = standardStatus;
	}
}

+ 71 - 1
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java

@ -19,6 +19,10 @@ import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@ -390,6 +394,59 @@ public class DeviceService {
                uploadHealthIndex(result);
                System.out.println(result);
                //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----START
                String patientCode = result.getUser();
                //患者信息
                Patient patient = patientDao.findByCode(patientCode);
                int bloodPressureBbnormalCount = 0;//血压异常次数
                int bloodSuggurBbnormalCount = 0;//血糖异常次数
                // 排序
                Sort sort = new Sort(Sort.Direction.DESC, "recordDate");
                // 分页信息
                Pageable pageRequest = new PageRequest(0, 5, sort);
                Pageable pageable = new PageRequest(1, 5);
                List<PatientHealthIndex> bloodPressurepatientHealthIndices = new ArrayList<>();
                List<PatientHealthIndex> bloodSuggurpatientHealthIndices = new ArrayList<>();
                if( 1 == patient.getDisease()){
                    bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"2",pageable);
                } else if( 2 == patient.getDisease()){
                    bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"1",pageable);
                } else {
                    bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"2",pageable);
                    bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"1",pageable);
                }
                for (PatientHealthIndex patientHealthIndex : bloodPressurepatientHealthIndices) {
                    if(1 == patientHealthIndex.getStatus()){
                        bloodPressureBbnormalCount++;
                    }
                }
                for (PatientHealthIndex patientHealthIndex : bloodSuggurpatientHealthIndices) {
                    if(1 == patientHealthIndex.getStatus()){
                        bloodSuggurBbnormalCount++;
                    }
                }
                //连续5次异常,修改用户为预警状态
                if( (5 == bloodPressureBbnormalCount || 5 == bloodSuggurBbnormalCount) && 0 == patient.getStandardStatus()){
                    patient.setStandardStatus(1);
                }
                //连续5次正常,修改用户为非预警状态
                if((0 == bloodPressureBbnormalCount && 0 == bloodSuggurBbnormalCount) && 1 == patient.getStandardStatus()){
                    patient.setStandardStatus(0);
                }
                //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----END
            }
        } catch (Exception e) {
            e.printStackTrace();
@ -451,6 +508,7 @@ public class DeviceService {
            obj.setUser(user);
            obj.setIdcard(device.getUserIdcard());
            obj.setStatus(0);
            //  1血糖 2血压 3体重 4腰围
            switch (type) {
                case "1":
@ -485,7 +543,7 @@ public class DeviceService {
                default:
                    throw new Exception("Can not support the metric!");
            }
            patientHealthIndexDao.save(obj);
            obj = patientHealthIndexDao.save(obj);
            return obj;
        } else {
            DeviceInfo deviceInfo = new DeviceInfo();
@ -592,10 +650,18 @@ public class DeviceService {
            if (index % 2 == 0) {
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueBefore, minValueBefore)) {
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L),请处理";
                    //体征异常,更新体征数据状态
                    data.setStatus(1);
                    patientHealthIndexDao.save(data);
                }
            } else { //餐前
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueAfter, minValueAfter)) {
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L),请处理";
                    //体征异常,更新体征数据状态
                    data.setStatus(1);
                    patientHealthIndexDao.save(data);
                }
            }
        }
@ -626,6 +692,10 @@ public class DeviceService {
            // 收缩压/舒张压校验
            if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY) || !checkHealthIndex(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)) {
                msgContent = patient.getName() + "血压异常(舒张压 " + value2 + "mmHg、收缩压 " + value1 + "mmHg),请处理";
                //体征异常,更新体征数据状态
                data.setStatus(1);
                patientHealthIndexDao.save(data);
            }
        }

+ 68 - 8
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/ArchivesController.java

@ -8,16 +8,14 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;
/**
 * 智业服务接口
 * */
@Controller
@RestController
@RequestMapping(value = "/third/archives/")
@Api(description = "智业档案服务接口")
public class ArchivesController {
@ -28,7 +26,6 @@ public class ArchivesController {
	/********************************* 居民档案相关接口 ****************************************************************/
	@RequestMapping(value = "getEhrSickMedicalList",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("查询居民健康体检列表信息接口")
	public Result getEhrSickMedicalList(
			@ApiParam(name="idcard",value="患者身份证",defaultValue = "350821201112240026")
@ -49,7 +46,6 @@ public class ArchivesController {
	}
	@RequestMapping(value = "getEhrSickMedicalRecord",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("查询居民健康体检详情接口")
	public Result getEhrSickMedicalRecord(
			@ApiParam(name="medicalNo",value="体检ID",defaultValue = "")
@ -70,7 +66,6 @@ public class ArchivesController {
	}
	@RequestMapping(value = "uploadFollowup",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("上传随访记录接口")
	public Result uploadFollowup(@ApiParam(name="id",value="随访记录id",defaultValue = "4")
								  @RequestParam(value="id",required = true) Long id){
@ -90,7 +85,6 @@ public class ArchivesController {
	}
	@RequestMapping(value = "uploadHealthIndex",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("上传体征指标接口")
	public Result uploadHealthIndex(@ApiParam(name="id",value="体征记录id",defaultValue = "5226")
									 @RequestParam(value="id",required = true) Long id){
@ -108,4 +102,70 @@ public class ArchivesController {
			}
		}
	}
	/*****************************************自助建档***************************************************/
	@RequestMapping(value = "getSickArchiveFlag",method = RequestMethod.POST)
	@ApiOperation("查询居民是否有建立健康档案接口")
	public Result getSickArchiveFlag(
			@ApiParam(name="idcard",value="身份证号",defaultValue = "")
			@RequestParam(value="idcard",required = true) String idcard){
		try {
			String response = archivesService.getSickArchiveFlag(idcard);
			return Result.success("查询居民是否有建立健康档案接口成功!",response);
		} catch (Exception ex) {
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
	@RequestMapping(value = "getSickArchiveRecord",method = RequestMethod.POST)
	@ApiOperation("查询居民健康档案信息接口")
	public Result getSickArchiveRecord(
			@ApiParam(name="idcard",value="身份证号",defaultValue = "")
			@RequestParam(value="idcard",required = true) String idcard){
		try {
			String response = archivesService.getSickArchiveRecord(idcard);
			return Result.success("查询居民健康档案信息接口!",response);
		} catch (Exception ex) {
			ex.printStackTrace();
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
	@RequestMapping(value = "saveSickArchiveRecord",method = RequestMethod.POST)
	@ApiOperation("上传居民档案建档信息接口")
	public Result saveSickArchiveRecord(@ApiParam(name="json",value="居民建档信息",defaultValue = "")
										@RequestParam(value="json",required = true) String json,
										@ApiParam(name="doctor",value="医生code",defaultValue = "")
										@RequestParam(value="doctor",required = true) String doctor){
		try {
			String response = archivesService.saveSickArchiveRecord(json,doctor);
			return Result.success("上传居民档案建档信息接口!",response);
		} catch (Exception ex) {
			ex.printStackTrace();
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
}

+ 17 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/PrescriptionController.java

@ -195,6 +195,23 @@ public class PrescriptionController extends BaseController{
		}
	}
	@RequestMapping(value = "getRecipeMasterList",method = RequestMethod.POST)
	@ApiOperation("获取历史处方列表")
	public Result getRecipeMasterList(@ApiParam(name="patientCode",value="居民code",defaultValue = "")
							@RequestParam(value = "patientCode",required = true) String patientCode,
							@ApiParam(name="applyTimeFrom",value="开始时间",defaultValue = "")
							@RequestParam(value = "applyTimeFrom",required = false) String applyTimeFrom,
							@ApiParam(name="applyTimeEnd",value="结束时间",defaultValue = "")
							@RequestParam(value = "applyTimeEnd",required = false) String applyTimeEnd){
		try {
			String re = prescriptionService.getRecipeMasterList(patientCode,applyTimeFrom,applyTimeEnd);
			return Result.success("获取历史处方列表!",re);
		} catch (Exception ex) {
			ex.printStackTrace();
			return Result.error(ex.getMessage());
		}
	}
	@RequestMapping(value = "saveRecipe",method = RequestMethod.POST)
	@ApiOperation("挂号开处方接口,调整处方接口")

+ 48 - 5
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/SignController.java

@ -9,10 +9,7 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@ -20,6 +17,7 @@ import java.util.Map;
 * 智业服务接口
 * */
@Controller
@RestController
@RequestMapping(value = "/third/sign/")
@Api(description = "基卫签约服务接口")
public class SignController {
@ -33,7 +31,6 @@ public class SignController {
	/******************************* 签约接口 ********************************************************/
	@RequestMapping(value = "CheckSignFamily",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("查询是否已签约")
	public Result checkSignFamily(
			@ApiParam(name="idcard",value="患者身份证",defaultValue = "350821201112240026")
@ -53,4 +50,50 @@ public class SignController {
		}
	}
	@RequestMapping(value = "getSickFamilyDoctorSignLimit",method = RequestMethod.POST)
	@ApiOperation("查询家庭医生签约人数上限接口")
	public Result getSickFamilyDoctorSignLimit(
			@ApiParam(name="jwTeamCode",value="智业行政团队code",defaultValue = "44")
			@RequestParam(value="jwTeamCode",required = true) String jwTeamCode){
		try {
			String response = signZYService.getSickFamilyDoctorSignLimit(jwTeamCode);
			return Result.success("查询签约成功!",response);
		} catch (Exception ex) {
			ex.printStackTrace();
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
	@RequestMapping(value = "getSickFamilyDoctorSpecialistControl",method = RequestMethod.POST)
	@ApiOperation("查询家签慢病患者定标情况接口")
	public Result getSickFamilyDoctorSpecialistControl(
			@ApiParam(name="TIME_START",value="修改的开始时间",defaultValue = "2016-9-1 00:00:00")
			@RequestParam(value="TIME_START",required = true) String TIME_START,
			@ApiParam(name="TIME_END",value="修改的开始时间",defaultValue = "2016-9-1 12:00:00")
			@RequestParam(value="TIME_END",required = true) String TIME_END){
		try {
			String response = signZYService.getSickFamilyDoctorSpecialistControl(TIME_START,TIME_END);
			return Result.success("查询签约成功!","");
		} catch (Exception ex) {
			ex.printStackTrace();
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
}

+ 3 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/dao/DoctorMappingDao.java

@ -27,4 +27,7 @@ public interface DoctorMappingDao extends PagingAndSortingRepository<DoctorMappi
    @Query("select a from Doctor a,DoctorMapping b where a.code = b.doctorCode and a.code = ?1 and b.jwDoctorHospital = ?2")
    Doctor getDoctor(String docotrCode,String jwDoctorHospital);
    @Query(value = "select a.* from wlyy_doctor_mapping a where a.jw_doctor_hospital = ?1 and a.doctor_code=?2 order by a.id DESC limit 1",nativeQuery = true)
    DoctorMapping findByJwDoctorHospitalAndDoctorCode(String jwDoctorHospital,String doctorCode);
}

+ 3 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/dao/prescription/PrescriptionExpressageDao.java

@ -11,4 +11,7 @@ public interface PrescriptionExpressageDao extends PagingAndSortingRepository<Pr
    @Query("from PrescriptionExpressage p where p.mailno=?1")
    PrescriptionExpressage findByPrescriptionExpressMailno(String mailno);
    @Query(" from PrescriptionExpressage p where p.prescriptionCode=?1 and p.del=1")
    PrescriptionExpressage findByPrescriptionCode(String prescriptionCode);
}

+ 44 - 1
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ArchivesService.java

@ -24,7 +24,8 @@ public class ArchivesService {
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
@ -330,4 +331,46 @@ public class ArchivesService {
        }
    }
    /*****************************************自助建档***************************************************/
    /**
     * 7.1查询居民是否有建立健康档案接口
     * @param idcard
     * @return
     */
    public String getSickArchiveFlag(String idcard) throws Exception{
        String[] hm = getHospitalMapping(null);
        return zysoftService.getSickArchiveFlag(idcard,hm[0],hm[1]);
    }
    /**
     * 7.2查询居民健康档案信息接口
     * @param idcard
     * @return
     */
    public String getSickArchiveRecord(String idcard) throws Exception{
        String[] hm = getHospitalMapping(null);
        return zysoftService.getSickArchiveRecord(idcard,hm[0],hm[1]);
    }
    /**
     * 上传居民档案建档信息接口
     * @param json
     * @param doctor
     * @return
     * @throws Exception
     */
    public String saveSickArchiveRecord(String json,String doctor) throws Exception{
        Doctor d = doctorDao.findByCode(doctor);
        String[] hm = getHospitalMapping(d.getHospital());
        DoctorMapping doctorMapping = doctorMappingDao.findByJwDoctorHospitalAndDoctorCode(hm[0],doctor);
        return zysoftService.saveSickArchiveRecord(json,hm[0],hm[1],doctorMapping);
    }
}

+ 24 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/SignZYService.java

@ -124,5 +124,29 @@ public class SignZYService {
    }
    /**
     * 7.51查询家庭医生签约人数上限接口
     * @param jwTeamCode
     * @return
     * @throws Exception
     */
    public String getSickFamilyDoctorSignLimit(String jwTeamCode) throws Exception{
        String[] hospitalMapping = getHospitalMapping(null); //获取机构映射
        String response = zysoftService.getSickFamilyDoctorSignLimit(jwTeamCode,hospitalMapping[0],hospitalMapping[1]);
        return response;
    }
    /**
     * 查询家签慢病患者定标情况接口
     * @param time_start
     * @param time_end
     * @return
     */
    public String getSickFamilyDoctorSpecialistControl(String time_start, String time_end)throws Exception {
        String[] hospitalMapping = getHospitalMapping(null); //获取机构映射
        String response = zysoftService.getSickFamilyDoctorSpecialistControl(time_start,time_end,hospitalMapping[0],hospitalMapping[1]);
        return response;
    }
}

+ 163 - 9
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java

@ -1,8 +1,11 @@
package com.yihu.wlyy.service.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.service.common.http.HttpApiException;
import com.yihu.wlyy.service.common.util.StringUtil;
import com.yihu.wlyy.service.entity.DoctorMapping;
import com.zoe.phip.ssp.sdk.ApiException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@ -10,7 +13,9 @@ import org.springframework.stereotype.Service;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by hzp on 2016/9/9.
@ -172,6 +177,66 @@ public class ZysoftService {
        return re;
    }
    /**
     * 基卫二次封装Post接口
     */
    private String postSecond(String api, String content, com.alibaba.fastjson.JSONObject jsonParams, Map<String,String> headers) throws Exception
    {
        String re = "";
        headers.put("INTERFACE",api);
        Map<String,String> paramsList = new HashMap<>();
        String msgBody = com.alibaba.fastjson.JSONObject.toJSONString(jsonParams, SerializerFeature.WriteMapNullValue);
        String msgHeader = JSONObject.fromObject(headers).toString();
        paramsList.put("msgHeader",msgHeader);
        paramsList.put("msgBody",msgBody);
        //System.out.print("msgHeader:"+msgHeader+"\r\n");
        //System.out.print("msgBody:"+msgBody+"\r\n");
        //新增日志
        String method = "POST";
        Boolean isSuccess = true;
        String error = "";
        try {
            re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,true);
            Map<String,String> map = objectMapper.readValue(re,Map.class);
            String code = map.get("CODE");
            if(!code.equals("1"))
            {
                throw new HttpApiException(Integer.valueOf(code),map.get("MESSAGE"));
            }
            //保存http日志
            logService.saveHttpLog(isSuccess,api,content,method,msgHeader,msgBody,re,error);
        }
        catch (Exception ex)
        {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            error = sw.toString();
            isSuccess = false;
            //保存http日志
            logService.saveHttpLog(isSuccess,api,content,method,msgHeader,msgBody,re,error);
            if(ex instanceof ApiException)
            {
                ApiException apiEx = (ApiException) ex;
                throw new HttpApiException(apiEx.errorCode(),ex.getMessage());
            }
            else{
                throw new HttpApiException(-1,ex.getMessage());
            }
        }
        return re;
    }
    /*************************** 格式转换 *******************************************************/
    /**
@ -224,9 +289,9 @@ public class ZysoftService {
    }
    /**
     * 查询居民健康档案信息接口
     * 查询是否已签约
     */
    public String getSickArchiveRecord(String idcard,String hospital,String licence)  throws Exception
    public String getSickFamilySignFlag(String idcard,String hospital,String licence)  throws Exception
    {
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
@ -235,24 +300,28 @@ public class ZysoftService {
        Map<String,String> params = new HashMap<>();
        params.put("IDENTITY_CARD_NO",idcard);
        String response = postSecond("getSickArchiveRecord","查询居民健康档案信息",params,header,false);
        String response = postSecond("getSickFamilySignFlag","查询是否已签约",params,header,false);
        return response;
    }
    /**
     * 查询是否已签约
     * 7.51查询家庭医生签约人数上限接口
     * @param jwTeamCode 智业行政团队code
     * @param hospital
     * @param licence
     * @return
     * @throws Exception
     */
    public String getSickFamilySignFlag(String idcard,String hospital,String licence)  throws Exception
    {
    public String getSickFamilyDoctorSignLimit(String jwTeamCode,String hospital,String licence) throws Exception{
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        Map<String,String> params = new HashMap<>();
        params.put("IDENTITY_CARD_NO",idcard);
        params.put("TEAM_CODE",jwTeamCode);
        String response = postSecond("getSickFamilySignFlag","查询是否已签约",params,header,false);
        String response = postSecond("getSickFamilyDoctorSignLimit","查询家庭医生签约人数上限接口",params,header,false);
        return response;
    }
@ -603,6 +672,67 @@ public class ZysoftService {
        }
    }
    /**************************** 建档相关接口 add by ysj at 2017-09-11 *************************************************/
    /**
     * 7.1查询居民是否有建立健康档案接口
     * @param idcard
     * @param hospital
     * @param licence
     * @return
     * @throws Exception
     */
    public String getSickArchiveFlag(String idcard,String hospital,String licence)  throws Exception
    {
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        Map<String,String> params = new HashMap<>();
        params.put("IDENTITY_CARD_NO",idcard);
        String response = postSecond("getSickArchiveFlag","查询居民是否有建立健康档案接口",params,header,false);
        return response;
    }
    /**
     * 查询居民健康档案信息接口
     */
    public String getSickArchiveRecord(String idcard,String hospital,String licence)  throws Exception
    {
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        Map<String,String> params = new HashMap<>();
        params.put("IDENTITY_CARD_NO",idcard);
        String response = postSecond("getSickArchiveRecord","查询居民健康档案信息",params,header,false);
        return response;
    }
    /**
     * 上传居民档案建档信息接口
     * @param json
     * @param hospital
     * @param licence
     * @param doctor
     * @return
     */
    public String saveSickArchiveRecord(String json, String hospital, String licence, DoctorMapping doctor) throws Exception{
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        header.put("OPERATOR",doctor.getJwDoctor());
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(json);
        jsonObject.put("ARCHIVE_OPERATOR_NAME",doctor.getJwDoctorName());
        String response = postSecond("saveSickArchiveRecord","上传居民档案建档信息接口",jsonObject,header);
        return response;
    }
    /**************************** 妇幼相关接口 add by hzp at 2017-07-12 *********************************************************/
@ -624,4 +754,28 @@ public class ZysoftService {
        return response;
    }
    /**
     * 查询家签慢病患者定标情况接口
     * @param time_start
     * @param time_end
     * @param hospital
     * @param licence
     * @return
     * @throws Exception
     */
    public String getSickFamilyDoctorSpecialistControl(String time_start, String time_end,String hospital,String licence) throws Exception{
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        Map<String,String> params = new HashMap<>();
        params.put("TEAM_CODE",time_start);
        params.put("TEAM_CODE",time_end);
        String response = postSecond("getSickFamilyDoctorSpecialistControl","查询家签慢病患者定标情况接口",params,header,false);
        return response;
    }
}

+ 68 - 8
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/prescription/PrescriptionService.java

@ -356,18 +356,41 @@ public class PrescriptionService extends ZysoftBaseService{
                    log.setUserCode(prescription.getDoctor());
                    log.setStatus(PrescriptionLog.PrescriptionLogStatus.wait_expressage.getValue());
                    prescriptionLogDao.save(log);
                }
                //判断健管师配送要添加续方消息,提示健管师有续方代配送
                JSONObject message = new JSONObject();
                message.put("title","dispensingComplete");
                message.put("state",1);
                message.put("prescription",prescription.getCode());
                message.put("mes","success");
                    //健管师配送
                    PrescriptionExpressage expressage = prescriptionExpressageDao.findByPrescriptionCode(prescription.getCode());
                    if(StringUtils.isNotBlank(expressage.getExpressageCode())){
                        Message message = new Message();
                        message.setCzrq(new Date());
                        message.setCreateTime(new Date());
                        message.setRead(1);//设置未读
                        message.setOver("1");
                        message.setReceiver(expressage.getExpressageCode());
                        message.setSender("system");
                        message.setCode(getCode());
                        message.setSenderName("系统");
                        message.setTitle("居民"+prescription.getPatientName()+"的续方订单待取药");
                        message.setContent("您有一条新的续方订单待取药!");
                        message.setType(7);//续方订单待取药
                        message.setReadonly(1);//是否只读消息
                        message.setDel("1");
                        message.setRelationCode(prescription.getCode());
                        message.setPrescriptionStatus("0");//待取药
                        message.setData(prescription.getAdminTeamId()+"");
                        messageDao.save(message);
                    }
                    //判断提示健管师有续方代配送,居民待取药
                    JSONObject message = new JSONObject();
                    message.put("title","dispensingComplete");
                    message.put("state",1);
                    message.put("prescription",prescription.getCode());
                    message.put("mes","success");
//                redisTemplate.convertAndSend(channelTopic,message.toString());
//                redisTemplate.watch(channelTopic);
                redisTemplate.opsForList().leftPush(channelTopic,message.toString());
                    redisTemplate.opsForList().leftPush(channelTopic,message.toString());
//                redisTemplate.unwatch();
                }
            }
        }catch (JSONException ex){
@ -687,6 +710,43 @@ public class PrescriptionService extends ZysoftBaseService{
        return response;
    }
    /**
     * 获取历史处方列表
     * @param patientCode
     * @param applyTimeFrom
     * @param applyTimeEnd
     * @return
     * @throws Exception
     */
    public String getRecipeMasterList(String patientCode,String applyTimeFrom,String applyTimeEnd)  throws Exception
    {
        Patient patient = patientDao.findByCode(patientCode);
        SignFamily signFamily = signFamilyDao.findByPatient(patientCode);
        String[] hospitalMapping = getHospitalMapping(signFamily.getHospital()); //获取机构映射
        String hospital = hospitalMapping[0];
        String licence = hospitalMapping[1];
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        if(StringUtils.isEmpty(applyTimeFrom)){
            applyTimeEnd = DateUtil.getStringDateShort();
            applyTimeFrom = DateUtil.getNextDay(new Date(),-60);
        }
        Map<String,String> params = new HashMap<>();
        params.put("cardNo",patient.getSsc());
        params.put("applyTimeFrom",applyTimeFrom);
        params.put("applyTimeEnd",applyTimeEnd);
        String response = postSecond("getRecipeMasterList","获取历史处方列表",params,null,header,false,2);
        return response;
    }
    /**
     * 7.4 挂号开处方接口,调整处方接口
     * 开方和调整处方接口的区别-开方会传ca认证

+ 19 - 2
patient-co-service/wlyy_service/src/main/resources/application.yml

@ -53,7 +53,7 @@ zysoftApi:
  base: base/CallEhrInterface
redisChannel:
    prescription: redisPrescription
    prescription: redisMessage
---
spring:
@ -75,10 +75,27 @@ im:
  data_base_name: im_new
---
spring:
  profiles: test
  profiles: devtest
  datasource:
#    url: jdbc:mysql://172.17.110.160:3306/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    url: jdbc:mysql://172.19.103.85:3306/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: linzhou
    password: linzhou
    driverClassName: com.mysql.jdbc.Driver
    maxTotal: 500
    maxIdle: 30
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
#    password: jkzl_ehr
im:
  data_base_name: im_new
---
spring:
  profiles: test
  datasource:
    url: jdbc:mysql://172.17.110.160:3306/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: ssgg
    password: ssgg
    driverClassName: com.mysql.jdbc.Driver

BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/1.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/2.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/3.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/4.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/5.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/6.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/7.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot启动/8.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/boot项目启动的2种方式.docx


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/1.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/10.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/11.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/12.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/13.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/2.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/3.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/4.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/5.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/6.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/7.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/8.png


BIN
patient-co/patient-co-doctor-assistant/doc/技术文档/IDEA操作/tomcat启动/9.png


+ 112 - 0
patient-co/patient-co-doctor-assistant/doc/技术文档/es/统计新增索引.txt

@ -0,0 +1,112 @@
创建索引
POST  http://172.19.103.68:9200/health_edu_article_patient_test
查询索引
GET http://172.19.103.68:9200/health_edu_article_patient_test/
给索引加mapping
POST http://172.19.103.68:9200/health_edu_article_patient_test/health_edu_article_patient_test/_mapping
{
    "health_edu_article_patient_test": {
            "properties": {
                "patient": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "patientName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "sendCode": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "sendName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "sendPic": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "sendSex": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "sendLevel": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "adminTeamCode": {
                    "type": "integer",
                    "index": "not_analyzed"
                },
                "adminTeamName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "hospital": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "hospitalName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "town": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "townName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "batchNo": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "articleId": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "attachedTitle": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "attachedPic": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "attachedContent": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "attachedMessage": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "articleType": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "level1Type": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "level2Type": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "level": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "type": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "createTime": {
                    "type": "date",
                    "index": "not_analyzed"
                }
            }
        }
  }

BIN
patient-co/patient-co-doctor-assistant/doc/接口文档/厦门i健康API文档.docx


BIN
patient-co/patient-co-doctor-assistant/doc/接口文档/对外接口文档/集美健康教育/集美健康教育对外接口文档.docx


+ 10 - 0
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/00.readme.txt

@ -0,0 +1,10 @@
----------------------------------
包名:
com.yihu.xmijk
证书密码:
111111
----------------------------------
develope.apple.com 账号:
chunyudang.yihu@gmail.com 
Jkzldangchunyu060201

BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/HBuilder使用该证书打包的例子.png


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/aps推送证书.p12


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/xmijkPro.mobileprovision


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/ios/证书.p12


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/医生端通过HBuilder打包说明(草稿,完整版V0.2).docx


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/发布修改参数.docx


+ 10 - 0
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/00.readme.txt

@ -0,0 +1,10 @@
----------------------------------
包名:
com.wjw.ssgg.doctor
证书别名:
ssgg_doctor.keystore
证书密码:
ssgg_doctor
----------------------------------

BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/20160721170424_该证书的生成命令.png


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/HBuilder使用该证书打包的例子.png


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/ssgg_doctor.keystore


+ 5 - 0
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/app/安卓/文档.txt

@ -0,0 +1,5 @@
upload_preview.js
common_http.js
im_new.js

BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/im/im.docx


BIN
patient-co/patient-co-doctor-assistant/doc/部署文档/正式库/微信端/微信端发布.docx


+ 500 - 0
patient-co/patient-co-doctor-assistant/pom.xml

@ -0,0 +1,500 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>patient-co-lib</artifactId>
        <groupId>com.yihu</groupId>
        <version>1.0.0</version>
        <relativePath>../../patient-co-lib/pom.xml</relativePath>
    </parent>
    <artifactId>patient-co-doctor-assistant</artifactId>
    <name>patient-co-doctor-assistant</name>
    <version>1.0.0</version>
    <packaging>war</packaging>
    <!-- 设定插件仓库, 如有Nexus私服, 取消注释并指向正确的服务器地址. -->
    <pluginRepositories>
        <pluginRepository>
            <id>nexus</id>
            <name>Team Nexus Repository</name>
            <url>http://172.19.103.47:8081/nexus/content/groups/public</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    <dependencies>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <!--Spring boot family-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-docs</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-devtools</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!-- end -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <!-- spring start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-keyvalue</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
        </dependency>
        <!-- spring end -->
        <!--activemq start-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-spring</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-broker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-jaas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-camel</artifactId>
        </dependency>
        <!--activemq end-->
        <!--Swagger start -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <!--activemq start-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
        <!--Swagger end -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>jave-ffmpegjave</artifactId>
        </dependency>
        <!-- poi start-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
        </dependency>
        <!-- poi end-->
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis</artifactId>
        </dependency>
        <dependency>
            <groupId>axis</groupId>
            <artifactId>axis-jaxrpc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>sehrCrypto</groupId>
            <artifactId>sehrCrypto</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom</artifactId>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
        </dependency>
        <!-- Apache Commons fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <!-- SPRINGSIDE -->
        <dependency>
            <groupId>org.springside</groupId>
            <artifactId>springside-core</artifactId>
        </dependency>
        <!-- PERSISTENCE begin -->
        <dependency>
            <groupId>com.google.code.kaptcha</groupId>
            <artifactId>kaptcha</artifactId>
        </dependency>
        <!-- spring data access -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>
        <!-- aspectjrt start -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <!-- aspectjrt end -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- jdbc driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- PERSISTENCE end -->
        <!-- WEB begin -->
        <dependency>
            <groupId>opensymphony</groupId>
            <artifactId>sitemesh</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <!-- WEB end -->
        <!-- JSON begin -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-jaxb-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <!-- JSON end -->
        <dependency>
            <groupId>org.htmlparser</groupId>
            <artifactId>htmlparser</artifactId>
        </dependency>
        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
        </dependency>
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
        </dependency>
        <!-- LOGGING begin -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <!-- 代码直接调用log4j会被桥接到slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
        </dependency>
        <!-- 代码直接调用common-logging会被桥接到slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
        </dependency>
        <!-- 代码直接调用java.util.logging会被桥接到slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
        </dependency>
        <!-- LOGGING end -->
        <!-- GENERAL UTILS begin -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <!-- GENERAL UTILS end -->
        <!-- selenium 2.0 -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.seleniumhq.selenium</groupId>
                    <artifactId>selenium-htmlunit-driver</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.seleniumhq.selenium</groupId>
                    <artifactId>selenium-android-driver</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.seleniumhq.selenium</groupId>
                    <artifactId>selenium-iphone-driver</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.seleniumhq.selenium</groupId>
                    <artifactId>selenium-safari-driver</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-remote-driver</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>cglib</groupId>
                    <artifactId>cglib-nodep</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--二维码生成 start-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
        </dependency>
        <!--二维码生成 end-->
        <!-- redis start  -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <!-- redis end  -->
        <!--fastdfs start-->
        <dependency>
            <groupId>org.csource</groupId>
            <artifactId>fastdfs_lib</artifactId>
        </dependency>
        <!--fastdfs end-->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <!--易联众支付-->
        <dependency>
            <groupId>com.ylz</groupId>
            <artifactId>onpay-java-sdk-all</artifactId>
        </dependency>
        <dependency>
            <groupId>org.nlpcn</groupId>
            <artifactId>elasticsearch-sql</artifactId>
            <version>2.4.1.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>wlyy</finalName>
        <plugins>
            <!--打成war包需要的配置-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArguments>
                        <verbose/>
                        <bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>
                    </compilerArguments>
                </configuration>
                <version>3.1</version>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <!--打包的时候把webapp下的资源移到根目录下-->
                <directory>${basedir}/src/main/webapp</directory>
                <targetPath>${basedir}/</targetPath>
                <includes>
                    <include>**/**</include>
                </includes>
                <!--防止以下两个文件编译的时候出现在项目根目录中,打包的时候还是会打包进去这2个文件-->
                <excludes>
                    <exclude>downloadPage.html</exclude>
                    <exclude>ssgg_doctor.plist</exclude>
                    <exclude>images/**</exclude>
                </excludes>
            </resource>
            <resource>
                <!--打包的时候把resources下的资源移到classpath下-->
                <directory>${basedir}/src/main/resources</directory>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

+ 29 - 0
patient-co/patient-co-doctor-assistant/readme.MD

@ -0,0 +1,29 @@
项目中涉及到的框架
spring,springMVC,springJPA,springSecurity,springBoot
quartz,swagger-ui,hibernate,redis,fastDfs
项目包结构
doc 项目相关文档
src 代码
    main
        java
            com.yihu.wlyy
                aop 切面相关代码
                config 配置相关代码
                entity jpa 实体类相关代码
                event 事件相关代码
                exception 异常相关代码
                health 体征设备相关代码
                interceptors 拦截器相关代码
                job 任务相关代码
                logs 日志相关代码
                repository dao相关代码
                rest 
                service 服务类相关代码
                task 线程相关代码
                util 工具类相关代码
                web controller相关代码
                wechat 微信相关代码
        resource 资源和配置文件
        webapp  web相关代码

+ 20 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/Application.java

@ -0,0 +1,20 @@
package com.yihu.wlyy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
/**
 * Created by chenweida on 2017/7/28.
 */
@SpringBootApplication
public class Application {
    public static ApplicationContext ctx = null;
    public static void main(String[] args) {
        ctx = SpringApplication.run(Application.class, args);
    }
}

+ 323 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/adapter/PresModeAdapter.java

@ -0,0 +1,323 @@
package com.yihu.wlyy.adapter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.prescription.PrescriptionDiagnosis;
import com.yihu.wlyy.entity.patient.prescription.PrescriptionInfo;
import com.yihu.wlyy.service.system.Icd10DictServcie;
import com.yihu.wlyy.service.third.jw.ZyDictService;
import com.yihu.wlyy.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * Created by Trick on 2017/8/10.
 */
@Component
public class PresModeAdapter {
    private static Logger logger = LoggerFactory.getLogger(PresModeAdapter.class);
    @Autowired
    private Icd10DictServcie icd10DictServcie;
    @Autowired
    private ZyDictService zyDictService;
    /**
     * 处方模板适配器
     * @param json
     * @return
     * @throws Exception
     */
    public JSONArray modeTopresInfo(String json){
        try{
            JSONObject oldJson = JSONObject.parseObject(json);
            if(oldJson.getInteger("status")!=200){
                throw new RuntimeException("智业接口失败:"+oldJson.getString("msg"));
            }
            String dataStr = oldJson.getString("data");
            JSONObject data = JSONObject.parseObject(dataStr);
            JSONArray returnData = data.getJSONArray("returnData");
            String code = data.getString("CODE");
            if(StringUtils.isNotBlank(code)&&"1".equals(code)&&returnData.size()>0){
                JSONArray rs = new JSONArray();
                Iterator iterator = returnData.iterator();
                while (iterator.hasNext()){
                    JSONArray modeArray = (JSONArray) iterator.next();
                    for(int i=0;i<modeArray.size();i++){
                        JSONObject mode = (JSONObject) modeArray.get(i);
                        JSONObject m = new JSONObject();
                        m.put("templateNo",mode.getInteger("TEMPLATE_NO"));
                        m.put("templateName",mode.getString("TEMPLATE_NAME"));
                        //m.put("templateExplain",mode.getInt("TEMPLATE_EXPLAIN"));
                        JSONArray infos = mode.getJSONArray("TEMPLATE_DETAIL");
                        Iterator infoIt = infos.iterator();
                        JSONArray is = new JSONArray();
                        while (infoIt.hasNext()){
                            JSONObject info = (JSONObject) infoIt.next();
                            PrescriptionInfo prescriptionInfo = new PrescriptionInfo();
                            prescriptionInfo.setRemark(info.getString("REMARK"));
                            prescriptionInfo.setBindFlag(info.getString("BIND_FLAG"));
                            prescriptionInfo.setDirection(info.getString("USAGE_NAME"));//药品用法
                            prescriptionInfo.setDrugCode(info.getString("ITEM_CODE"));//药品code
                            prescriptionInfo.setDrugName(info.getString("ITEM_NAME"));//药品名称
                            prescriptionInfo.setDrugRate(info.getString("FREQUENCY"));//吃药频率 FREQUENCY
                            prescriptionInfo.setDrugRateName(info.getString("FREQUENCY_NAME"));
                            prescriptionInfo.setDrugFormat(info.getString("ITEM_SPEC"));//药品规格
                            prescriptionInfo.setPrice(info.getInteger("ITEM_PRICE"));//药品单价
                            prescriptionInfo.setNum(info.getInteger("ITEM_QUANTITY"));//药品数目
                            prescriptionInfo.setJwSubCode("");//智业子处方号
                            prescriptionInfo.setSubjectClass(info.getString("SUBJECT_CLASS"));//"科目类别编码",
                            prescriptionInfo.setDrugNumUnit(info.getString("ITEM_UNIT"));//数量单位编码
                            prescriptionInfo.setDrugNumUnitName(info.getString("ITEM_UNIT_NAME"));//数量单位名称
//                            prescriptionInfo.setCost(1);//金额
//                            prescriptionInfo.setCharge(0);//自付
                            prescriptionInfo.setBindFlag(info.getString("BIND_FLAG"));//成组标志, 0.非成组,1.成组
                            prescriptionInfo.setDayCount(info.getInteger("DAY_COUNT"));//用药天数
                            prescriptionInfo.setDrugUsage(info.getString("USAGE"));//用药方法编码
                            prescriptionInfo.setUsageName(info.getString("USAGE_NAME"));//用药方法名称
                            prescriptionInfo.setPhysicDose(info.getString("PHYSIC_DOSE"));//用药剂量
                            prescriptionInfo.setPhysicDoseUnit(info.getString("PHYSIC_DOSE_UNIT"));//剂量单位编码
                            prescriptionInfo.setPhysicDoseUnitName(info.getString("PHYSIC_DOSE_UNIT_NAME"));//剂量单位名称
                            prescriptionInfo.setPhysicAmount(info.getString("PHYSIC_AMOUNT"));//用药总量
                            prescriptionInfo.setPhysicAmountUnit(info.getString("PHYSIC_AMOUNT_UNIT"));//总量单位编码
                            prescriptionInfo.setPhysicAmountUnitName(info.getString("PHYSIC_AMOUNT_UNIT_NAME"));//总量单位名称
                            prescriptionInfo.setPhysicInjectPlace("");//注射地点编码
                            prescriptionInfo.setPhysicInjectPlaceName("");//注射地点名称
                            prescriptionInfo.setPhysicSkinTest(info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                            prescriptionInfo.setPhysicSkinTestName(info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                            is.add(prescriptionInfo);
                        }
                        m.put("prescriptionInfo",is);
                        rs.add(m);
                    }
                }
                return rs;
            }
        }catch (Exception e){
            logger.info("PresModeAdapter:modeTopresInfo:Json:"+json);
            throw e;
        }
        return new JSONArray();
    }
    /**
     * 处方列表解析
     * @param json
     * @return
     * @throws Exception
     */
    public JSONArray modeToPrescription(String json){
        try{
            JSONObject oldJson = JSONObject.parseObject(json);
            if(oldJson.getInteger("status")!=200){
                throw new RuntimeException("智业接口失败:"+oldJson.getString("msg"));
            }
            JSONObject data = oldJson.getJSONObject("data");
            JSONArray returnData = data.getJSONArray("returnData");
            String code = data.getString("CODE");
            if(StringUtils.isNotBlank(code)&&"1".equals(code)&&returnData.size()>0){
                JSONArray rs = new JSONArray();
                Iterator iterator = returnData.iterator();
                while (iterator.hasNext()){
                    JSONArray modeArray = (JSONArray) iterator.next();
                    for(int i=0;i<modeArray.size();i++){
                        JSONObject mode = (JSONObject) modeArray.get(i);
                        JSONObject p  = new JSONObject();
                        p.put("code",mode.getInteger("RECIPE_NO")+"");
                        p.put("createTime",mode.getString("APPLY_TIME"));
                        Doctor doctor =  zyDictService.getDoctByJw(mode.getString("APPLY_OPERATOR"),mode.getString("HEALTH_ORG_CODE"));
                        // "APPLY_OPERATOR_NAME": 开单医生姓名","HEALTH_ORG_CODE": "开单机构编码",
                        if(doctor!=null){
                            p.put("doctor",doctor.getCode());
                            p.put("doctorName",doctor.getName());
                            p.put("hospitalName",doctor.getHospitalName());
                            p.put("hospital",doctor.getHospital());
                        }else{
                            p.put("doctor",mode.getString("APPLY_OPERATOR"));
                            p.put("doctorName",mode.getString("APPLY_OPERATOR_NAME"));
                            p.put("hospitalName",mode.getString("HEALTH_ORG_CODE"));
                            p.put("hospital",mode.getString("HEALTH_ORG_CODE"));
                        }
                        PrescriptionDiagnosis diagnosis = new PrescriptionDiagnosis();
                        String diagnoseCode = mode.getString("DIAGNOSE_CODE");
                        String diagnoseName = mode.getString("DIAGNOSE_NAME");
//                    String diagnoseCode = "E10.100";
//                    String diagnoseName = "1型糖尿病性酮症";
                        diagnosis.setCode(diagnoseCode);//诊断代码
                        diagnosis.setName(diagnoseName);//诊断名称
                        String icd10 = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCode);
                        if(!StringUtils.isEmpty(icd10)){
                            JSONObject icd = JSONObject.parseObject(icd10);
                            diagnosis.setHealthProblemName(icd.getString("value"));//诊断名称
                            diagnosis.setHealthProblem(icd.getString("key"));//诊断代码
                        }else{
                            diagnosis.setHealthProblemName(diagnoseName);//诊断名称
                            diagnosis.setHealthProblem(diagnoseCode);//诊断代码
                        }
                        JSONArray jsonArrayDt = new JSONArray();
                        jsonArrayDt.add(diagnosis);
                        p.put("prescriptionDt",jsonArrayDt);
                        JSONArray infos = mode.getJSONArray("RECIPE_DETAIL");
                        Iterator infoIt = infos.iterator();
                        List<PrescriptionInfo> prescriptionInfos = new ArrayList<>();
                        while (infoIt.hasNext()){
                            JSONObject info = (JSONObject) infoIt.next();
                            PrescriptionInfo prescriptionInfo = new PrescriptionInfo();
                            prescriptionInfo.setRemark(info.getString("REMARK"));
                            prescriptionInfo.setBindFlag(info.getString("BIND_FLAG"));
                            prescriptionInfo.setDirection(info.getString("USAGE_NAME"));//药品用法
                            prescriptionInfo.setDrugCode(info.getString("ITEM_CODE"));//药品code
                            prescriptionInfo.setDrugName(info.getString("ITEM_NAME"));//药品名称
                            prescriptionInfo.setDrugRate(info.getString("FREQUENCY"));//吃药频率 FREQUENCY
                            prescriptionInfo.setDrugRateName(info.getString("FREQUENCY_NAME"));
                            prescriptionInfo.setDrugFormat(info.getString("ITEM_SPEC"));//药品规格
                            prescriptionInfo.setPrice(CommonUtil.doubleToInt(info.getDouble("ITEM_PRICE")));//药品单价
                            prescriptionInfo.setNum(info.getInteger("ITEM_QUANTITY"));//药品数目
                            prescriptionInfo.setJwSubCode(info.getString("RECIPE_SUB_NO"));//智业子处方号
                            prescriptionInfo.setDrugNumUnit(info.getString("ITEM_UNIT"));//数量单位编码
                            prescriptionInfo.setDrugNumUnitName(info.getString("ITEM_UNIT_NAME"));//数量单位名称
                            prescriptionInfo.setCost(CommonUtil.doubleToInt(info.getDouble("COST")));//金额
                            prescriptionInfo.setCharge(CommonUtil.doubleToInt(info.getDouble("CHARGE")));//自付
                            prescriptionInfo.setBindFlag(info.getString("BIND_FLAG"));//成组标志, 0.非成组,1.成组
                            prescriptionInfo.setDayCount(info.getInteger("DAY_COUNT"));//用药天数
                            prescriptionInfo.setDrugUsage(info.getString("USAGE"));//用药方法编码
                            prescriptionInfo.setUsageName(info.getString("USAGE_NAME"));//用药方法名称
                            prescriptionInfo.setPhysicDose(info.getString("PHYSIC_DOSE"));//用药剂量
                            prescriptionInfo.setPhysicDoseUnit(info.getString("PHYSIC_DOSE_UNIT"));//剂量单位编码
                            prescriptionInfo.setPhysicDoseUnitName(info.getString("PHYSIC_DOSE_UNIT_NAME"));//剂量单位名称
                            prescriptionInfo.setPhysicAmount(info.getString("PHYSIC_AMOUNT"));//用药总量
                            prescriptionInfo.setPhysicAmountUnit(info.getString("PHYSIC_AMOUNT_UNIT"));//总量单位编码
                            prescriptionInfo.setPhysicAmountUnitName(info.getString("PHYSIC_AMOUNT_UNIT_NAME"));//总量单位名称
                            prescriptionInfo.setPhysicInjectPlace(info.getString("PHYSIC_INJECT_PLACE"));//注射地点编码
                            prescriptionInfo.setPhysicInjectPlaceName(info.getString("PHYSIC_INJECT_PLACE_NAME"));//注射地点名称
                            prescriptionInfo.setPhysicSkinTest(info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                            prescriptionInfo.setPhysicSkinTestName(info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                            prescriptionInfos.add(prescriptionInfo);
                        }
                        p.put("prescriptionInfo",prescriptionInfos);
                        rs.add(p);
                    }
                }
                return rs;
            }
        }catch (Exception e){
            logger.info("PresModeAdapter:modeToPrescription:Json:"+json);
            throw e;
        }
        return new JSONArray();
    }
    /**
     * 处方详情转换
     * @param json
     * @return
     */
    public JSONObject modelToSinglePrescription(String json){
        try{
            JSONObject oldJson = JSONObject.parseObject(json);
            if(oldJson.getInteger("status")!=200){
                throw new RuntimeException("智业接口失败:"+oldJson.getString("msg"));
            }
            JSONObject data = oldJson.getJSONObject("data");
            JSONArray returnData = data.getJSONArray("returnData");
            String code = data.getString("CODE");
            if(StringUtils.isNotBlank(code)&&"1".equals(code)&&returnData.size()>0){
                JSONArray modeArray = returnData.getJSONArray(0);
                JSONObject mode = (JSONObject) modeArray.get(0);
                JSONObject p  = new JSONObject();
                p.put("code",mode.getInteger("RECIPE_NO")+"");
                p.put("createTime",mode.getString("APPLY_TIME"));
                Doctor doctor =  zyDictService.getDoctByJw(mode.getString("APPLY_OPERATOR"),mode.getString("HEALTH_ORG_CODE"));
                // "APPLY_OPERATOR_NAME": 开单医生姓名","HEALTH_ORG_CODE": "开单机构编码",
                if(doctor!=null){
                    p.put("doctor",doctor.getCode());
                    p.put("doctorName",doctor.getName());
                    p.put("hospitalName",doctor.getHospitalName());
                    p.put("hospital",doctor.getHospital());
                }else{
                    p.put("doctor",mode.getString("APPLY_OPERATOR"));
                    p.put("doctorName",mode.getString("APPLY_OPERATOR_NAME"));
                    p.put("hospitalName",mode.getString("HEALTH_ORG_CODE"));
                    p.put("hospital",mode.getString("HEALTH_ORG_CODE"));
                }
                JSONObject diagnosis = new JSONObject();
                String diagnoseCode = mode.getString("DIAGNOSE_CODE");
                String diagnoseName = mode.getString("DIAGNOSE_NAME");
//                String diagnoseCode = "E10.100";
//                String diagnoseName = "1型糖尿病性酮症";
                diagnosis.put("code",diagnoseCode);//诊断代码
                diagnosis.put("name",diagnoseName);//诊断名称
                String icd10 = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCode);
                if(!StringUtils.isEmpty(icd10)){
                    JSONObject icd = JSONObject.parseObject(icd10);
                    diagnosis.put("healthProblemName",icd.getString("value"));//诊断名称
                    diagnosis.put("healthProblem",icd.getString("key"));//诊断代码
                }else{
                    diagnosis.put("healthProblemName",diagnoseName);//诊断名称
                    diagnosis.put("healthProblem",diagnoseCode);//诊断代码
                }
                JSONArray jsonArrayDt = new JSONArray();
                jsonArrayDt.add(diagnosis);
                p.put("prescriptionDt",jsonArrayDt);
                JSONArray infos = mode.getJSONArray("RECIPE_DETAIL");
                Iterator infoIt = infos.iterator();
                JSONArray prescriptionInfos = new JSONArray();
                while (infoIt.hasNext()){
                    JSONObject info = (JSONObject) infoIt.next();
                    JSONObject prescriptionInfo = new JSONObject();
                    prescriptionInfo.put("Remark",info.getString("REMARK"));
                    prescriptionInfo.put("BindFlag",info.getString("BIND_FLAG"));
                    prescriptionInfo.put("direction",info.getString("USAGE_NAME"));//药品用法
                    prescriptionInfo.put("drugCode",info.getString("ITEM_CODE"));//药品code
                    prescriptionInfo.put("drugName",info.getString("ITEM_NAME"));//药品名称
                    prescriptionInfo.put("drugRate",info.getString("FREQUENCY"));//吃药频率 FREQUENCY
                    prescriptionInfo.put("drugRateName",info.getString("FREQUENCY_NAME"));
                    prescriptionInfo.put("drugFormat",info.getString("ITEM_SPEC"));//药品规格
                    prescriptionInfo.put("price",info.getDouble("ITEM_PRICE"));//药品单价
                    prescriptionInfo.put("num",info.getInteger("ITEM_QUANTITY"));//药品数目
                    prescriptionInfo.put("jwSubCode",info.getString("RECIPE_SUB_NO"));//智业子处方号
                    prescriptionInfo.put("drugNumUnit",info.getString("ITEM_UNIT"));//数量单位编码
                    prescriptionInfo.put("drugNumUnitName",info.getString("ITEM_UNIT_NAME"));//数量单位名称
                    prescriptionInfo.put("cost",info.getDouble("COST"));//金额
                    prescriptionInfo.put("charge",info.getDouble("CHARGE"));//自付
                    prescriptionInfo.put("bindFlag",info.getString("BIND_FLAG"));//成组标志, 0.非成组,1.成组
                    prescriptionInfo.put("dayCount",info.getInteger("DAY_COUNT"));//用药天数
                    prescriptionInfo.put("drugUsage",info.getString("USAGE"));//用药方法编码
                    prescriptionInfo.put("usageName",info.getString("USAGE_NAME"));//用药方法名称
                    prescriptionInfo.put("physicDose",info.getString("PHYSIC_DOSE"));//用药剂量
                    prescriptionInfo.put("physicDoseUnit",info.getString("PHYSIC_DOSE_UNIT"));//剂量单位编码
                    prescriptionInfo.put("physicDoseUnitName",info.getString("PHYSIC_DOSE_UNIT_NAME"));//剂量单位名称
                    prescriptionInfo.put("physicAmount",info.getString("PHYSIC_AMOUNT"));//用药总量
                    prescriptionInfo.put("physicAmountUnit",info.getString("PHYSIC_AMOUNT_UNIT"));//总量单位编码
                    prescriptionInfo.put("physicAmountUnitName",info.getString("PHYSIC_AMOUNT_UNIT_NAME"));//总量单位名称
                    prescriptionInfo.put("physicInjectPlace",info.getString("PHYSIC_INJECT_PLACE"));//注射地点编码
                    prescriptionInfo.put("physicInjectPlaceName",info.getString("PHYSIC_INJECT_PLACE_NAME"));//注射地点名称
                    prescriptionInfo.put("physicSkinTest",info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                    prescriptionInfo.put("physicSkinTestName",info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                    prescriptionInfos.add(prescriptionInfo);
                }
                p.put("prescriptionInfo",prescriptionInfos);
                return p;
            }
        }catch (Exception e){
            logger.info("PresModeAdapter:modelToSinglePrescription:Json:"+json);
            throw e;
        }
        return new JSONObject();
    }
}

+ 14 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/aop/ObserverRequired.java

@ -0,0 +1,14 @@
package com.yihu.wlyy.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by Trick on 2017/6/24.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ObserverRequired {
}

+ 90 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/aop/ObserverRequiredAOP.java

@ -0,0 +1,90 @@
package com.yihu.wlyy.aop;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
 * Created by Trick on 2017/6/24.
 */
@Aspect
@Component
public class ObserverRequiredAOP {
    //Controller层切点路径
    @Pointcut("execution(* com.yihu.wlyy.web..*.*(..))")
    public void controllerAspect() {
    }
    public ObserverRequiredAOP() {
        //System.out.println("Observer---------------------------------------");
    }
    @Around("controllerAspect() && @annotation(com.yihu.wlyy.aop.ObserverRequired)")
    public Object checkToken(ProceedingJoinPoint point) throws Throwable {
        Object o = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        String error = "";
        try {
            response.setCharacterEncoding("UTF-8");
            JSONObject json = getAgent(request);
            String observer = json.has("observer") ? json.getString("observer") : "";
            if(StringUtils.isNotBlank(observer)&&"1".equals(observer)){
                PrintWriter writer=response.getWriter();
                writer.write(error(403, "该操作没有权限"));
                writer.flush();
                return o;
            }
        }catch (Exception e){
            //return o;
        }
         o = point.proceed();
        return o;
    }
    public String write(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public String error(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public JSONObject getAgent(HttpServletRequest request) {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            System.out.println("userAgent:" + userAgent);
            return new JSONObject(userAgent);
        } catch (Exception e) {
            return null;
        }
    }
}

+ 59 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java

@ -0,0 +1,59 @@
package com.yihu.wlyy.config;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
/**
 * Created by chenweida on 2017/9/9.
 * 生产者配置
 */
@EnableJms
@Configuration
@Profile({"dev", "devtest", "prod", "test"})
public class ActiveMQConfig {
    @Value("${activemq.username}")
    private String username;
    @Value("${activemq.password}")
    private String password;
    @Value("${activemq.url}")
    private String url;
    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, url);
        //设置异步发送
        activeMQConnectionFactory.setUseAsyncSend(true);
        return activeMQConnectionFactory;
    }
    /**
     * 缓存session链接
     *
     * @return
     */
    @Bean
    @Primary
    public CachingConnectionFactory CachingConnectionFactory() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        //目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
        cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
        //Session缓存数量,这里属性也可以直接在这里配置
        cachingConnectionFactory.setSessionCacheSize(100);
        return cachingConnectionFactory;
    }
    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory( CachingConnectionFactory());
        return jmsTemplate;
    }
}

+ 27 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/FastDFSConfig.java

@ -0,0 +1,27 @@
package com.yihu.wlyy.config;
import com.yihu.wlyy.util.fastdfs.FastDFSClientPool;
import com.yihu.wlyy.util.fastdfs.FastDFSUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.11.27 16:08
 */
@Configuration
public class FastDFSConfig {
    @Bean
    public FastDFSClientPool fastDFSClientPool(){
        FastDFSClientPool clientPool = FastDFSClientPool.getInstance();
        return clientPool;
    }
    @Bean
    public FastDFSUtil fastDFSUtil(){
        FastDFSUtil util = new FastDFSUtil();
        return util;
    }
}

+ 80 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/MvcConfig.java

@ -0,0 +1,80 @@
package com.yihu.wlyy.config;
import com.yihu.wlyy.interceptors.DoctorInterceptor;
import com.yihu.wlyy.interceptors.GateWayInterceptor;
import com.yihu.wlyy.interceptors.PatientInterceptor;
import com.yihu.wlyy.interceptors.UserAgentFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * Created by chenweida on 2017/4/6.
 */
@Configuration
@Profile({"test", "prod"})
public class MvcConfig extends WebMvcConfigurerAdapter {
    private Logger logger = LoggerFactory.getLogger(MvcConfig.class);
    @Autowired
    private DoctorInterceptor doctorInterceptor;
    @Autowired
    private PatientInterceptor patientInterceptor;
    @Autowired
    private GateWayInterceptor gateWayInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(gateWayInterceptor).addPathPatterns("/wlyygc/**").excludePathPatterns("/wlyygc/doctor/**", "/wlyygc/patient/**");
        registry.addInterceptor(doctorInterceptor).addPathPatterns("/doctor/**", "/statistics/province/**", "/statistics/**", "wlyygc/doctor/**");
        registry.addInterceptor(patientInterceptor).addPathPatterns("/patient/**", "/wlyygc/patient/**");
        super.addInterceptors(registry);
        logger.info("init doctorInterceptor,patientInterceptor");
    }
    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new UserAgentFilter());
        registration.addUrlPatterns("/*");
        registration.setName("UserAgentFilter");
        registration.setOrder(1);
        return registration;
    }
//    /**
//     * 编码过滤
//     */
//    @Bean
//    public FilterRegistrationBean testFilterRegistration2() {
//        FilterRegistrationBean registration = new FilterRegistrationBean();
//        registration.setFilter(new UserAgentFilter());
//        registration.addUrlPatterns("/doctor/requestRealNameSoftCertAndSign");
//        registration.setName("EncodingFilter");
//        registration.setOrder(2);
//        return registration;
//    }
//    /**
//     * 为null的数据不返回
//     * @param converters
//     */
//    @Override
//    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
//        ObjectMapper objectMapper=new ObjectMapper();
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
//        converters.add(mappingJackson2HttpMessageConverter);
//    }
}

+ 199 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/SwaggerConfig.java

@ -0,0 +1,199 @@
package com.yihu.wlyy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;
@EnableSwagger2
@Configuration
public class SwaggerConfig {
    private static final String Doctor_API = "doctor";
    private static final String Patient_API = "patient";
    private static final String Other_API = "other";
    private static final String GateWay_API = "gateway";
    final String userAgent = "{\"id\":用户id,\"uid\":\"用户code\",\"openid\":\"openid\",\"token\":\"token表\",\"lastUid\":\"\",\"platform\":\"1患者APP,2医生APP,3患者微信公众号\"}";
    final String userAgentJson = "{\"id\":int,\"uid\":string,\"openid\":string,\"token\":string,\"lastUid\":string,\"platform\":int}";
    @Bean
    public Docket gatewayAPI() {
        List<Parameter> pars = addToken();
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(GateWay_API)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(or(
                        regex("/wlyygc/.*"),
                        regex("/manage_util/.*"),
                        regex("/gc/.*")
                ))
                .build()
                .globalOperationParameters(pars)
                .apiInfo(gatewayApiInfo());
    }
    private ApiInfo gatewayApiInfo() {
        ApiInfo apiInfo = new ApiInfo("三师平台API",
                "对外部应用提供功能与数据接口。",
                "1.0",
                "No terms of service",
                "admin@jkzl.com",
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }
    private List<Parameter> addToken() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        ParameterBuilder userAgentPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        userAgentPar.name("userAgent").description(userAgentJson).modelRef(new ModelRef("string")).parameterType("header").required(false).defaultValue("").build();
        tokenPar.name("accesstoken").description("accesstoken").modelRef(new ModelRef("string")).parameterType("header").required(false).defaultValue("").build();
        pars.add(tokenPar.build());
        pars.add(userAgentPar.build());
        return pars;
    }
    @Bean
    public Docket publicAPI() {
        List<Parameter> pars = addUseragent();
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(Doctor_API)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(or(regex("/doctor/.*"),
                        regex("/PC/.*")))
                .build()
                .globalOperationParameters(pars)
                .apiInfo(publicApiInfo());
    }
    private List<Parameter> addUseragent() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        tokenPar.name("userAgent").description(userAgentJson).modelRef(new ModelRef("string")).parameterType("header").required(false).defaultValue("").build();
        pars.add(tokenPar.build());
        return pars;
    }
    private ApiInfo publicApiInfo() {
        ApiInfo apiInfo = new ApiInfo("三师平台API",
                "向PC端,微信、App等应用提供功能与数据接口。",
                "1.0",
                "No terms of service",
                "admin@jkzl.com",
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }
    @Bean
    public Docket patientAPI() {
        List<Parameter> pars = addUseragent();
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(Patient_API)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(PathSelectors.regex("/patient/.*"))
                .build()
                .globalOperationParameters(pars)
                .apiInfo(patientApiInfo());
    }
    private ApiInfo patientApiInfo() {
        ApiInfo apiInfo = new ApiInfo("三师平台API",
                "向PC端,微信、App等应用提供功能与数据接口。",
                "1.0",
                "No terms of service",
                "admin@jkzl.com",
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }
    @Bean
    public Docket otherAPI() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(Other_API)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(or(
                        regex("/third/.*"),
                        regex("/statistics/.*"),
                        regex("/statistics/province/.*"),
                        regex("/job/.*"),
                        regex("/family_contract/.*"),
                        regex("/hosptail/.*"),
                        regex("/common/.*"),
                        regex("/hospitals/.*"),
                        regex("/index/.*"),
                        regex("/upload/.*"),
                        regex("/weixin/.*"),
                        regex("/wx/.*"),
                        regex("/area/.*"),
                        regex("/login/.*"),
                        regex("/loginPC/.*"),
                        regex("/qrcode/.*"),
                        regex("/onepay/.*"),
                        regex("/wlyy_service/.*"),
                        regex("/wlyy_service/.*"),
                        regex("/wechat/.*"),
                        regex("/nofilter/.*"),
                        regex("/idc10/.*"),
                        regex("/im_new/.*"),
                        regex("/version/.*"),
                        regex("/express/.*")
                ))
                .build()
                .apiInfo(otherApiInfo());
    }
    private ApiInfo otherApiInfo() {
        ApiInfo apiInfo = new ApiInfo("三师平台API",
                "向PC端,微信、App等应用提供功能与数据接口。",
                "1.0",
                "No terms of service",
                "admin@jkzl.com",
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }
}

+ 54 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/async/AsyncConfig.java

@ -0,0 +1,54 @@
package com.yihu.wlyy.config.async;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
 * Created by chenweida on 2016.10.18.
 * 启用多綫程
 */
@Configuration
@EnableAsync
public class AsyncConfig {
    /**
     * 如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程,都会给新的任务产生新的线程
     */
    private int corePoolSize = 5;
    /**
     * 如果池中的线程数=maximumPoolSize,则有空闲线程使用空闲线程,否则新任务放入queueCapacity.
     * 设定 比 系统native thread个数要大的话,会优先抛出Java.lang.OutOfMemoryError: unable to create new native thread
     */
    private int maxPoolSize = 10;
    /**
     * 缓冲队列大小
     */
    private int queueCapacity = 100;
    /**
     * 线程池维护线程所允许的空闲时间  秒
     */
    private int keepAliveSeconds = 300;
    @Bean
    public Executor wlyyExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        /** Reject策略预定义有四种:
         (1)ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。
         (2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
         (3)ThreadPoolExecutor.DiscardPolicy策略,不能执行的任务将被丢弃.
         (4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程).
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

+ 93 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java

@ -0,0 +1,93 @@
package com.yihu.wlyy.config.es;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
/**
 * Created by chenweida on 2017/6/5.
 */
@Component
public class ElasticFactory {
    private static JestClientFactory factory = null;
    @Value("${es.host}")
    private String esHost;
    @Value("${es.port}")
    private String port;
    @Value("${es.tPort}")
    private String tPort;
    @Value("${es.clusterName}")
    private String clusterName;
//-----------------------------------jestClient----------------------------------------
    /**
     * @param "http://localhost:9200"
     * @return
     */
    @PostConstruct
    public JestClient getJestClient() {
        synchronized (ElasticFactory.class) {
            if (factory == null) {
                //初始化链接
                init();
            }
        }
        return factory.getObject();
    }
    /**
     * 初始化链接
     */
    public synchronized void init() {
        // Construct a new Jest client according to configuration via factory
        factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder("http://" + esHost + ":" + port)
                .multiThreaded(true)
                .maxTotalConnection(50)// 最大链接
                .maxConnectionIdleTime(120, TimeUnit.SECONDS)//链接等待时间
                .connTimeout(30000)
                .discoveryEnabled(true)
                .readTimeout(30000)//30秒
                .build());//得到链接
    }
    //-----------------------------------TransportClient----------------------------------------
    private Client transportClient;
    public Client getTransportClient() {
        try {
            initTranClient();
            return transportClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private synchronized void initTranClient() throws UnknownHostException {
        if (transportClient == null) {
            Settings settings = Settings.settingsBuilder()
                    .put("client.transport.sniff", true)//开启嗅探功能
                    .put("cluster.name", StringUtils.isEmpty(clusterName) ? "jkzl" : clusterName)//默认集群名字是jkzl
                    .build();
            transportClient = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esHost), Integer.valueOf(tPort)));
        }
    }
}

+ 49 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java

@ -0,0 +1,49 @@
package com.yihu.wlyy.config.es;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class ElastricSearchSave {
    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
    @Autowired
    private ElasticFactory elasticFactory;
    public Boolean save(List  sms,String esIndex,String esType) {
        try {
            //得到链接
            JestClient jestClient = elasticFactory.getJestClient();
            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            for (Object obj : sms) {
                Index index = new Index.Builder(obj).build();
                bulk.addAction(index);
            }
            BulkResult br = jestClient.execute(bulk.build());
            logger.info("save data count:" + sms.size());
            logger.info("save flag:" + br.isSucceeded());
            return br.isSucceeded();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" save error :" + e.getMessage());
        }
        return null;
    }
}

+ 61 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/jpa/HealthJpa.java

@ -0,0 +1,61 @@
package com.yihu.wlyy.config.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
/**
 * Created by chenweida on 2017/4/6.
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "healthEntityManagerFactory",
        transactionManagerRef = "healthTransactionManager",
        basePackages = {"com.yihu.wlyy.health.repository"})  //设置Repository所在位置
public class HealthJpa {
    @Autowired
    private HibernateProperties hibernateProperties;
    @Bean(name = "healthDataSource")
    @ConfigurationProperties(prefix="spring.datasource.health")
    public DataSource healthDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "healthEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
            @Qualifier("healthDataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.yihu.device.entity");
        emfb.setPersistenceUnitName("health");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(vendorAdapter);
        emfb.setJpaProperties(hibernateProperties.hibProperties());
        return emfb;
    }
    @Bean(name = "healthTransactionManager")
    JpaTransactionManager transactionManagerSecondary(
            @Qualifier("healthEntityManagerFactory")EntityManagerFactory builder) {
        return new JpaTransactionManager(builder);
    }
}

+ 27 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/jpa/HibernateProperties.java

@ -0,0 +1,27 @@
package com.yihu.wlyy.config.jpa;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
 * Created by chenweida on 2017/4/6.
 */
@Component
public class HibernateProperties {
    @Value("${hibernate.dialect}")
    private String dialect;
    @Value("${hibernate.show_sql}")
    private String show_sql;
    @Value("${hibernate.ejb.naming_strategy}")
    private String naming_strategy;
    public  Properties hibProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect",dialect);
        properties.put("hibernate.show_sql", show_sql);
        properties.put("hibernate.ejb.naming_strategy", naming_strategy);
        return properties;
    }
}

+ 67 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/jpa/WlyyJpa.java

@ -0,0 +1,67 @@
package com.yihu.wlyy.config.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
/**
 * Created by chenweida on 2017/4/6.
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager",
        basePackages = {"com.yihu.wlyy.repository"})   //设置Repository所在位置
public class WlyyJpa {
    @Autowired
    private HibernateProperties hibernateProperties;
    @Bean(name = "wlyyDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.wlyy")
    public DataSource wlyyDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "wlyyEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
            @Qualifier("wlyyDataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.yihu.wlyy.entity");
        emfb.setPersistenceUnitName("wlyy");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(vendorAdapter);
        emfb.setJpaProperties(hibernateProperties.hibProperties());
        return emfb;
    }
    @Bean(name = "wlyyTransactionManager")
    @Primary
    JpaTransactionManager transactionManagerSecondary(
            @Qualifier("wlyyEntityManagerFactory") EntityManagerFactory builder) {
        return new JpaTransactionManager(builder);
    }
}

+ 48 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/security/WebSecurityConfig.java

@ -0,0 +1,48 @@
package com.yihu.wlyy.config.security;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.beans.factory.annotation.Value;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
        import org.springframework.security.config.annotation.web.builders.HttpSecurity;
        import org.springframework.security.config.annotation.web.builders.WebSecurity;
        import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
        import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * Created by Administrator on 2016.10.17.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${security.basic.username}")
    String username;
    @Value("${security.basic.password}")
    String password;
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/swagger-ui.html").authenticated()
                .antMatchers("/swagger-ui.html").authenticated()
                .antMatchers("/configuration/security").authenticated()
                .anyRequest().permitAll()
                .and()
                .headers().frameOptions().disable()
                .and()
                .csrf().disable()
                .formLogin().defaultSuccessUrl("/swagger-ui.html").failureUrl("/login") //登录成功之后的跳转
                .permitAll()
                .and()
                .logout().logoutSuccessUrl("/login")
                .permitAll();
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser(username).password(password).roles("USER");
    }
}

+ 20 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/war/ServletInitializer.java

@ -0,0 +1,20 @@
package com.yihu.wlyy.config.war;//package com.yihu.wlyy.config.war;
import com.yihu.wlyy.Application;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
 * Created by Administrator on 2016.10.14.
 */
public class ServletInitializer extends SpringBootServletInitializer {
    public ServletInitializer() {
        super();
        setRegisterErrorPageFilter(false); //报错不跳到错误页
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

+ 30 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java

@ -0,0 +1,30 @@
package com.yihu.wlyy.event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
/**
 * Created by lyr-pc on 2017/3/10.
 */
@Service
public class ApplicationEvent implements ApplicationListener<ContextRefreshedEvent> {
    private Logger logger = LoggerFactory.getLogger(ApplicationEvent.class);
//    @Autowired
//    private RedisThread redisThread;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent ContextRefreshedEvent) {
        try {
            // 启动redis 消息队列线程
            logger.info("redis message start");
//            new Thread(redisThread).start();//移到job 工程
            logger.info("redis message end");
        } catch (Exception e) {
            logger.info("redis message start failed");
        }
    }
}

+ 101 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java

@ -0,0 +1,101 @@
package com.yihu.wlyy.health.repository;
import com.yihu.device.entity.DevicePatientHealthIndex;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface DevicePatientHealthIndexDao
        extends PagingAndSortingRepository<DevicePatientHealthIndex, Long>, JpaSpecificationExecutor<DevicePatientHealthIndex> {
    List<DevicePatientHealthIndex> findByIdcardAndType(String idcard, Integer type);
    /**
     * 按录入时间和患者标识查询健康记录
     *
     * @param patientCode
     * @param date
     * @return
     */
    @Query("select a from DevicePatientHealthIndex a where a.user = ?1 and type = ?2 and a.recordDate = ?3 and a.del = '1'")
    Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date);
    @Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate between ?3 and ?4 and a.del = '1' group by recordDate order by recordDate asc")
    Iterable<DevicePatientHealthIndex> findByPatient(String user, int type, Date begin, Date end);
    @Query("select a.value1 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value1 > 0 and a.del = '1' order by recordDate desc")
    Page<String> findValue1ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value2 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value2 > 0 and a.del = '1' order by recordDate desc")
    Page<String> findValue2ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value3 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value3 > 0 and a.del = '1' order by recordDate desc")
    Page<String> findValue3ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value4 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value4 > 0 and a.del = '1' order by recordDate desc")
    Page<String> findValue4ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value5 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value5 > 0 and a.del = '1' order by recordDate desc")
    Page<String> findValue5ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value6 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value6 > 0 and a.del = '1' order by recordDate desc")
    Page<String> findValue6ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value7 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value7 > 0 and a.del = '1' order by recordDate desc")
    Page<String> findValue7ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate >= ?3 and a.recordDate <= ?4 and a.del = '1'")
	Page<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Date start, Date end, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.value2 =?3 and a.recordDate >= ?4 and a.recordDate <= ?5 and a.del = '1'")
	Page<DevicePatientHealthIndex> findIndexByPatient(String patient, int type,String gi_type, Date start, Date end, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.del = '1'")
	List<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Pageable pageRequest);
	@Query("SELECT a FROM DevicePatientHealthIndex a where a.user = ?1 and a.del = '1' order by a.recordDate desc ")
	Iterable<DevicePatientHealthIndex> findRecentByPatient(String patient);
	@Query("select DATE_FORMAT(a.recordDate,'%Y-%m-%d') from DevicePatientHealthIndex a where a.user = ?1 and a.recordDate >= ?2 and a.recordDate <= ?3 and a.del = '1' group by DATE_FORMAT(a.recordDate,'%Y-%m-%d') order by DATE_FORMAT(a.recordDate,'%Y-%m-%d') desc")
	List<String> findDateList(String patient, Date start, Date end, Pageable pageRequest);
	/**
	 * 获取患者一天血糖值
     */
	@Query("select a from DevicePatientHealthIndex a where a.type=1 and a.user = ?1 and DATE_FORMAT(a.recordDate,'%Y-%m-%d') = ?2 and a.del = '1' order by a.recordDate,a.id")
	List<DevicePatientHealthIndex> findByDate(String patient, String date);
	@Query(value = "select a.* from device.wlyy_patient_health_index a where a.user=?1 and a.type=?2 and a.del='1' order by a.record_date desc limit 0,1",nativeQuery = true)
	DevicePatientHealthIndex findLastData(String patient, Integer type);
	/**
	 * 上次血糖值
     */
	@Query(value = "select a.value1 from device.wlyy_patient_health_index a where a.type=1 and a.user = ?1 and a.id<?2 and a.value2 = ?3 and a.del = '1' order by a.sort_date desc ,record_date desc limit 0,1",nativeQuery = true)
	String getPreValue(String user,Long id,String value2);
	@Query(value = "select a.* from device.wlyy_patient_health_index a where a.user = ?1 and a.type = ?2 and a.value2 =?3 and a.record_date >= ?4 and a.record_date <= ?5 and a.del = '1' order by a.sort_date desc ,record_date desc limit ?6 ,?7",nativeQuery = true)
	List<DevicePatientHealthIndex> findIndexByPatientNative(String patient, int type,String gi_type, Date start, Date end,int currentSize,int pageSize);
	/**
	 * 获取患者某一天的血糖  普通sql写法
	 * @param patient
	 * @param date
	 * @return
	 */
	@Query(value = "select a.* from device.wlyy_patient_health_index a where a.type=1 and a.user = ?1 and DATE_FORMAT(a.record_date,'%Y-%m-%d') = ?2 and a.del = '1' order by a.record_date,a.id",nativeQuery = true)
	List<DevicePatientHealthIndex> findByDateNative(String patient, String date );
	@Query(value = "select a.* from device.wlyy_patient_health_index a where a.user = ?1 and a.type = ?2 and a.record_date >= ?3 and a.record_date <= ?4 and a.del = '1' order by a.sort_date desc ,record_date desc limit ?5 ,?6",nativeQuery = true)
	List<DevicePatientHealthIndex> findIndexByPatientNative(String patient, int type, Date start, Date end,int currentSize,int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from device.wlyy_patient_health_index a where a.user = ?1 and a.record_date >= ?2 and a.record_date <= ?3 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?4 ,?5",nativeQuery = true)
	List<String> findDateList(String patient,Date start ,Date end,int currentSize,int pageSize);
}

+ 58 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/BaseInterceptor.java

@ -0,0 +1,58 @@
package com.yihu.wlyy.interceptors;
import javax.servlet.http.HttpServletRequest;
import com.yihu.wlyy.repository.url.CudUrlDao;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import com.yihu.wlyy.repository.security.TokenDao;
abstract public class BaseInterceptor implements HandlerInterceptor {
	private Logger logger= LoggerFactory.getLogger(BaseInterceptor.class);
	@Autowired
	public TokenDao tokenDao;
	@Autowired
	public CudUrlDao cudUrlDao;
	public JSONObject getAgent(HttpServletRequest request) {
		try {
			String userAgent = request.getHeader("userAgent");
			if (StringUtils.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			logger.info("userAgent:" + userAgent);
			return new JSONObject(userAgent);
		} catch (Exception e) {
			return null;
		}
	}
	public String error(int code, String msg) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			return json.toString();
		} catch (Exception e) {
			return null;
		}
	}
	public String write(int code, String msg) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			return json.toString();
		} catch (Exception e) {
			return null;
		}
	}
}

+ 221 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/DoctorInterceptor.java

@ -0,0 +1,221 @@
package com.yihu.wlyy.interceptors;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.entity.url.CudUrl;
import com.yihu.wlyy.logs.InterfaceCallLogs;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
/**
 * 医生权限校验
 *
 * @author George
 */
@Component
public class DoctorInterceptor extends BaseInterceptor {
    private Logger logger = LoggerFactory.getLogger(DoctorInterceptor.class);
    public static String status = "1";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        if(Flag.close.getValue().equals(status)){
            return true;
        }
        try {
            request.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            request.setAttribute("log-start", new Date().getTime());
            response.setCharacterEncoding("UTF-8");
            JSONObject json = getAgent(request);
            if (json == null) {
                // 未登录
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes("UTF-8"));
                return false;
            }
            if (json.has("uid") && json.has("admin_token") && StringUtils.isNotEmpty(json.getString("admin_token"))) {
                String adminToken = SystemConf.getInstance().getSystemProperties().getProperty("admin_token");
                String adminUid = SystemConf.getInstance().getSystemProperties().getProperty("admin_uid");
                if (json.getString("uid").equals(adminUid) && json.getString("admin_token").equals(adminToken)) {
                    return true;
                }
            }
            String tokenStr = json.has("token") ? json.getString("token") : "";
            String uid = json.has("uid") ? json.getString("uid") : "";
            String imei = json.has("imei") ? json.getString("imei") : "";
            String observer = json.has("observer") ? json.getString("observer") : "";
            Integer platform = json.has("platform") ? json.getInt("platform") : 2;
            logger.debug("tokenStr:" + tokenStr);
            logger.debug("uid:" + uid);
            logger.debug("imei:" + imei);
            logger.debug("observer:" + observer);
            logger.debug("platform:" + platform);
            //如果是观察者直接返回true
            if (!org.springframework.util.StringUtils.isEmpty(observer) && observer.equals("1")) {
                Class cls = ((HandlerMethod) handler).getBeanType();
                RequestMapping clsRm = (RequestMapping) cls.getAnnotation(RequestMapping.class);
                Method method = ((HandlerMethod) handler).getMethod();
                RequestMapping mthRm = method.getAnnotation(RequestMapping.class);
                String url = "";
                String urlCls = "";
                String urlMth = "";
                if (clsRm.value() != null && clsRm.value().length > 0) {
                    urlCls = clsRm.value()[0];
                }
                if (mthRm.value() != null && mthRm.value().length > 0) {
                    urlMth = mthRm.value()[0];
                }
                if (StringUtils.isNotEmpty(urlCls)) {
                    url += urlCls.startsWith("/") ? urlCls : ("/" + urlCls);
                }
                if (StringUtils.isNotEmpty(urlMth)) {
                    url += urlMth.startsWith("/") ? urlMth : ("/" + urlMth);
                }
                url = url.replace("\\", "/").replace("//", "/");
                CudUrl cudUrl = cudUrlDao.findByUrl(url);
                if (url.equals("/doctor/consult/readed")) {
                    response.getOutputStream().write(write(200, "操作成功").getBytes());
                    return false;
                }
                if (cudUrl != null) {
                    if (StringUtils.isNotEmpty(cudUrl.getMethod()) &&
                            request.getMethod().toUpperCase().compareTo(cudUrl.getMethod()) != 0) {
                        return true;
                    } else {
                        response.getOutputStream().write(error(403, "该操作没有权限").getBytes("UTF-8"));
                        return false;
                    }
                }
                return true;
            }
            if (StringUtils.isEmpty(tokenStr) || StringUtils.isEmpty(imei) || StringUtils.isEmpty(uid)) {
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes("UTF-8"));
                return false;
            }
            Token token = null;
            Map<String, Token> tempMap = null;
            if (platform == 2) {
                tempMap = SystemData.doctorTokens;
            } else if (platform == 4) {
                tempMap = SystemData.doctorPCTokens;
            }else if(platform ==5){
                tempMap = SystemData.doctorWXTokens;
            }
            token = tempMap.get(uid);
            if (token == null) {
                token = tokenDao.findByPatient(uid, platform);
                if (token != null) {
                    // 加入缓存
                    tempMap.put(uid, token);
                }
            }
            //  2、医生端app,3、微信公众号wechat,4、医生端pc,或者 PC端取药系统  或者对外系统
            if (token == null || (token.getPlatform() != 2 && token.getPlatform() != 4&&token.getPlatform()!=5)) {
                // 未登录
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes("UTF-8"));
                flag = false;
            } else {
                if (token.getTimeout().getTime() < new Date().getTime()) {
                    // 登录超时
                    response.getOutputStream().write(error(SystemConf.LOGIN_TIMEOUT, "登录超时,请重新登录").getBytes("UTF-8"));
                    flag = false;
                } else if (!StringUtils.equals(tokenStr, token.getToken()) || !StringUtils.equals(uid, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
                    // 别处登录
                    response.getOutputStream().write(error(SystemConf.LOGIN_OTHER, "帐号在别处登录,请重新登录").getBytes("UTF-8"));
                    flag = false;
                } else {
                    // 一天只更新一次
                    if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
                        // 今天未更新,则更新缓存
                        token.setCzrq(new Date());
                        // 更新内存
                        tempMap.put(uid, token);
                        // 更新数据库
                        tokenDao.save(token);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (null == request.getAttribute("log-start")) {
            return;
        }
        long start = (long) request.getAttribute("log-start");
        long end = new Date().getTime();
        Class cls = ((HandlerMethod) handler).getBeanType();
        RequestMapping clsRm = (RequestMapping) cls.getAnnotation(RequestMapping.class);
        Method method = ((HandlerMethod) handler).getMethod();
        RequestMapping mthRm = method.getAnnotation(RequestMapping.class);
        String url = "";
        String urlCls = "";
        String urlMth = "";
        if (clsRm.value() != null && clsRm.value().length > 0) {
            urlCls = clsRm.value()[0];
        }
        if (mthRm.value() != null && mthRm.value().length > 0) {
            urlMth = mthRm.value()[0];
        }
        if (StringUtils.isNotEmpty(urlCls)) {
            url += urlCls.startsWith("/") ? urlCls : ("/" + urlCls);
        }
        if (StringUtils.isNotEmpty(urlMth)) {
            url += urlMth.startsWith("/") ? urlMth : ("/" + urlMth);
        }
        url = url.replace("\\", "/").replace("//", "/");
        JSONObject json = getAgent(request);
        String uid = json.has("uid") ? json.getString("uid") : "";
        InterfaceCallLogs.info(end - start, url, uid, new JSONObject(request.getParameterMap()).toString());
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
    public String getStatus() {
        return status;
    }
    @Value("${interceptor.doctor.status}")
    public void setStatus(String status) {
        DoctorInterceptor.status = status;
    }
}

+ 53 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/EncodingFilter.java

@ -0,0 +1,53 @@
package com.yihu.wlyy.interceptors;
import com.yihu.wlyy.util.CodeFomat;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
/**
 * Created by chenweida on 2017/8/22.
 */
@Component
public class EncodingFilter implements Filter {
    private Logger logger= LoggerFactory.getLogger(EncodingFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Map<String, String[]> params = request.getParameterMap();
        MutableHttpServletRequest newRequest = new MutableHttpServletRequest(request);
        newRequest.getParameterNames();
        for (String key : params.keySet()) {
            String[] values = params.get(key);
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                newRequest.removeAttribute(key);
//                解决%、+后中文以英文编码传入URLDecoder异常
                value = CodeFomat.dateToChinese(value);
                newRequest.addParameter(key, URLDecoder.decode((value),"utf-8"));
            }
        }
        chain.doFilter(newRequest, response);
    }
    @Override
    public void destroy() {
    }
}

+ 74 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/GateWayAOP.java

@ -0,0 +1,74 @@
package com.yihu.wlyy.interceptors;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
 * 由于用了@ResponseBody之后 拦截器返回值ModelAndView 是null 所以用线程变量解决
 */
@Aspect
@Component
public class GateWayAOP {
    private Logger logger = LoggerFactory.getLogger(GateWayAOP.class);
    //Controller层切点路径
    @Pointcut("execution(* com.yihu.wlyy.web..*.*(..))")
    public void controllerAspect() {
    }
    public GateWayAOP() {
        //System.out.println("Observer---------------------------------------");
    }
    @Around("controllerAspect()")
    public Object checkToken(ProceedingJoinPoint point) throws Throwable {
        Object obj = null;
        HttpServletRequest request = null;
        try {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            obj = point.proceed();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (request != null) {
            request.setAttribute("returnObj", obj);
        }
        return obj;
    }
}
enum Flag {
    close("0"),
    open("1");
    Flag(String value) {
        this.value = value;
    }
    private String value;
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

+ 165 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/GateWayInterceptor.java

@ -0,0 +1,165 @@
package com.yihu.wlyy.interceptors;
/**
 * Created by chenweida on 2017/8/17.
 */
import com.yihu.wlyy.entity.gateway.GcHttpLog;
import com.yihu.wlyy.entity.gateway.GcToken;
import com.yihu.wlyy.repository.gateway.GcHttpLogDao;
import com.yihu.wlyy.repository.gateway.GcTokenDao;
import com.yihu.wlyy.util.NetworkUtil;
import com.yihu.wlyy.web.third.gateway.vo.base.BaseResultModel;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
 * 对外的请求拦截
 */
@Component
public class GateWayInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(GateWayInterceptor.class);
    @Autowired
    private GcHttpLogDao httpLogDao;
    @Autowired
    private GcTokenDao gcTokenDaoDao;
    public static String status = "1";
    /**
     * preHandle:预处理回调方法
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(Flag.close.getValue().equals(status)){
            return true;
        }
        boolean flag = true;
        String accesstoken = request.getHeader("accesstoken");
        String ip = NetworkUtil.getIpAddress(request);
        //********************************判断accesstoken********************************
        try {
            if (org.springframework.util.StringUtils.isEmpty(accesstoken)) {
                saveHttpLog(ip, JSONObject.fromObject(request.getParameterMap()).toString(), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_null.getMessage());
                //没权限
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_null.getCode(), BaseResultModel.statusEm.token_null.getMessage());
                response.getOutputStream().write(JSONObject.fromObject(baseResultModel).toString().getBytes());
            }
            GcToken gcToken = gcTokenDaoDao.findByToken(accesstoken);
            if (gcToken == null) {
                saveHttpLog(ip, JSONObject.fromObject(request.getParameterMap()).toString(), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_no_power.getMessage());
                //没权限
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_no_power.getCode(), BaseResultModel.statusEm.token_no_power.getMessage());
                response.getOutputStream().write(JSONObject.fromObject(baseResultModel).toString().getBytes());
            }
            if (gcToken.getDel() == null || gcToken.getDel() == 0) {
                saveHttpLog(ip, JSONObject.fromObject(request.getParameterMap()).toString(), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_out_effect.getMessage());
                //token无效
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_out_effect.getCode(), BaseResultModel.statusEm.token_out_effect.getMessage());
                response.getOutputStream().write(JSONObject.fromObject(baseResultModel).toString().getBytes());
            }
            if (System.currentTimeMillis() > gcToken.getOutTime().getTime()) {
                saveHttpLog(ip, JSONObject.fromObject(request.getParameterMap()).toString(), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_out_time.getMessage());
                //token过期
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_out_time.getCode(), BaseResultModel.statusEm.token_out_time.getMessage());
                response.getOutputStream().write(JSONObject.fromObject(baseResultModel).toString().getBytes());
            }
        } catch (Exception e) {
            saveHttpLog(ip, JSONObject.fromObject(request.getParameterMap()).toString(), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), e.getMessage());
            return false;
        }
        //********************************判断accesstoken********************************
        return flag;
    }
    /**
     * 后处理回调方法
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String output = "";
        if (modelAndView != null) {
            output = JSONObject.fromObject(modelAndView.getModelMap()).toString();
        } else {
            Object returnObj = request.getAttribute("returnObj");
            if (returnObj != null) {
                output = JSONObject.fromObject(returnObj).toString();
            }
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
//        response.getOutputStream()
        String token = request.getHeader("accesstoken");
        String ip = NetworkUtil.getIpAddress(request);
        saveHttpLog(ip,
                JSONObject.fromObject(request.getParameterMap()).toString(),
                output,
                token,
                request.getRequestURI(),
                GcHttpLog.flagEm.success.getCode(),
                null);
    }
    /**
     * 整个请求处理完毕回调方法
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
    public void saveHttpLog(String ip, String input, String output, String token, String method, Integer flag, String message) {
        GcHttpLog gcHttpLog = new GcHttpLog();
        gcHttpLog.setCreateTime(new Date());
        gcHttpLog.setIp(ip);
        gcHttpLog.setInput(input);
        gcHttpLog.setOutput(output);
        gcHttpLog.setToken(token);
        gcHttpLog.setMethod(method);
        gcHttpLog.setFlag(flag);
        gcHttpLog.setMessage(message);
        httpLogDao.save(gcHttpLog);
    }
    public String getStatus() {
        return status;
    }
    @Value("${interceptor.accesstoken.status}")
    public void setStatus(String status) {
        DoctorInterceptor.status = status;
    }
}

+ 62 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/MutableHttpServletRequest.java

@ -0,0 +1,62 @@
package com.yihu.wlyy.interceptors;
/**
 * Created by chenweida on 2017/8/22.
 */
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
final class MutableHttpServletRequest extends HttpServletRequestWrapper {
    // holds custom header and value mapping
    private final Map<String, String> customHeaders;
    public MutableHttpServletRequest(HttpServletRequest request){
        super(request);
        this.customHeaders = new HashMap<String, String>();
    }
    public void putHeader(String name, String value){
        this.customHeaders.put(name, value);
    }
    public String getHeader(String name) {
        // check the custom headers first
        String headerValue = customHeaders.get(name);
        if (headerValue != null){
            return headerValue;
        }
        // else return from into the original wrapped object
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }
    public Enumeration<String> getHeaderNames() {
        // create a set of the custom header names
        Set<String> set = new HashSet<String>(customHeaders.keySet());
        // now add the headers from the wrapped request object
        @SuppressWarnings("unchecked")
        Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
        while (e.hasMoreElements()) {
            // add the names of the request headers into the list
            String n = e.nextElement();
            set.add(n);
        }
        // create an enumeration from the set and return
        return Collections.enumeration(set);
    }
    public void addParameter(String name , Object value) {//增加参数
        if(value != null) {
            customHeaders.put(name , String.valueOf(value));
        }
    }
}

+ 85 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/ObserverRequiredInterceptor.java

@ -0,0 +1,85 @@
package com.yihu.wlyy.interceptors;
import com.yihu.wlyy.aop.ObserverRequired;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
 * Created by Trick on 2017/6/24.
 */
public class ObserverRequiredInterceptor  implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object[] ars = mi.getArguments();
        HttpServletRequest request =null;
        HttpServletResponse response = null;
        for(Object o :ars){
            if(o instanceof HttpServletRequest){
                request = (HttpServletRequest) o;
            }
            if(o instanceof HttpServletResponse){
                response = (HttpServletResponse) o;
            }
        }
        if(request!=null&&response!=null){
            JSONObject json = getAgent(request);
            String tokenStr = json.has("token") ? json.getString("token") : "";
            String uid = json.has("uid") ? json.getString("uid") : "";
            String imei = json.has("imei") ? json.getString("imei") : "";
            String observer = json.has("observer") ? json.getString("observer") : "";
            //if(StringUtils.isNotBlank(observer)&&"1".equals(observer)){
                if(mi.getMethod().isAnnotationPresent(ObserverRequired.class)){
                    System.out.println("----------this method is added @ObserverRequired-------------------------");
                    response.getOutputStream().write(error(403, "该操作没有权限").getBytes());
                    return null;
                }
            //}
        }
        //执行被拦截的方法,切记,如果此方法不调用,则被拦截的方法不会被执行。
        return mi.proceed();
    }
    public JSONObject getAgent(HttpServletRequest request) {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            System.out.println("userAgent:" + userAgent);
            return new JSONObject(userAgent);
        } catch (Exception e) {
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public String error(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
}

+ 157 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/PatientInterceptor.java

@ -0,0 +1,157 @@
package com.yihu.wlyy.interceptors;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.logs.InterfaceCallLogs;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
/**
 * 患者权限校验
 *
 * @author George
 */
@Component
public class PatientInterceptor extends BaseInterceptor {
    private Logger logger = LoggerFactory.getLogger(PatientInterceptor.class);
    public static String status = "1";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        if(Flag.close.getValue().equals(status)){
            return true;
        }
        try {
            request.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            request.setAttribute("log-start", new Date().getTime());
            if (request.getRequestURI().contains("/patient/hosptail/getHositalByTownCode") || request.getRequestURI().contains("/patient/feedback/saveAppeal")) {
                return true;
            }
            response.setCharacterEncoding("UTF-8");
            JSONObject json = getAgent(request);
            logger.debug("userAgent:" + json);
            if (json == null) {
                // 未登录
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes("UTF-8"));
                return false;
            }
            String tokenStr = json.has("token") ? json.getString("token") : "";
            String user = json.has("uid") ? json.getString("uid") : "";
            String imei = json.has("imei") ? json.getString("imei") : "";
            String openid = json.has("openid") ? json.getString("openid") : "";
            int platform = json.has("platform") ? json.getInt("platform") : 1;
            logger.debug("tokenStr:" + tokenStr);
            logger.debug("uid:" + user);
            logger.debug("imei:" + imei);
            logger.debug("openid:" + openid);
            logger.debug("platform:" + platform);
            if (StringUtils.isEmpty(imei)) {
                imei = openid;
            }
            Token token = null;
            if (platform == 3) {
                token = SystemData.patientTokens.get(user);
            }
            if (token == null) {
                token = tokenDao.findByPatient(user, platform);
                // 加入缓存
                if (platform == 3) {
                    SystemData.patientTokens.put(user, token);
                }
            }
            if (token == null || StringUtils.isEmpty(tokenStr) || (token.getPlatform() != 1 && token.getPlatform() != 3)) {
                // 未登录
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes("UTF-8"));
                flag = false;
            } else {
                if (!StringUtils.equals(tokenStr, token.getToken()) || !StringUtils.equals(user, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
                    // 别处登录
                    response.getOutputStream().write(error(SystemConf.LOGIN_OTHER, "帐号在别处登录,请重新登录").getBytes("UTF-8"));
                    flag = false;
                } else {
                    // 一天只更新一次
                    if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
                        // 今天未更新,则更新缓存
                        token.setCzrq(new Date());
                        // 更新内存
                        if (platform == 3) {
                            SystemData.patientTokens.put(user, token);
                        }
                        // 更新数据库
                        tokenDao.save(token);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (null == request.getAttribute("log-start")) {
            return;
        }
        long start = (long) request.getAttribute("log-start");
        long end = new Date().getTime();
        Class cls = ((HandlerMethod) handler).getBeanType();
        RequestMapping clsRm = (RequestMapping) cls.getAnnotation(RequestMapping.class);
        Method method = ((HandlerMethod) handler).getMethod();
        RequestMapping mthRm = method.getAnnotation(RequestMapping.class);
        String url = "";
        String urlCls = "";
        String urlMth = "";
        if (clsRm.value() != null && clsRm.value().length > 0) {
            urlCls = clsRm.value()[0];
        }
        if (mthRm.value() != null && mthRm.value().length > 0) {
            urlMth = mthRm.value()[0];
        }
        if (StringUtils.isNotEmpty(urlCls)) {
            url += urlCls.startsWith("/") ? urlCls : ("/" + urlCls);
        }
        if (StringUtils.isNotEmpty(urlMth)) {
            url += urlMth.startsWith("/") ? urlMth : ("/" + urlMth);
        }
        url = url.replace("\\", "/").replace("//", "/");
        JSONObject json = getAgent(request);
        String uid = json.has("uid") ? json.getString("uid") : "";
        InterfaceCallLogs.info(end - start, url, uid, new JSONObject(request.getParameterMap()).toString());
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
    public  String getStatus() {
        return status;
    }
    @Value("${interceptor.patient.status}")
    public  void setStatus(String status) {
        DoctorInterceptor.status = status;
    }
}

+ 59 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/interceptors/UserAgentFilter.java

@ -0,0 +1,59 @@
package com.yihu.wlyy.interceptors;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
 * Created by chenweida on 2017/8/22.
 */
@Component
public class UserAgentFilter implements javax.servlet.Filter {
    private Logger logger= LoggerFactory.getLogger(UserAgentFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
        String is_switch = request.getParameter("userAgent_is_switch");
        if ("1".equals(is_switch)) {
            String token = request.getParameter("userAgent_token");
            String uid = request.getParameter("userAgent_uid");
            String imei = request.getParameter("userAgent_imei");
            String openid = request.getParameter("userAgent_openid");
            String platform = request.getParameter("userAgent_platform");
            String lastUid = request.getParameter("userAgent_lastUid");
            String represented = request.getParameter("userAgent_represented");
            JSONObject jo = new JSONObject();
            jo.put("token", token);
            jo.put("imei", imei);
            jo.put("openid", openid);
            jo.put("uid", uid);
            jo.put("platform", platform);
            jo.put("lastUid", lastUid);
            jo.put("represented", represented);
            mutableRequest.putHeader("userAgent", jo.toString());
            logger.info("------filter:"+jo.toString());
            chain.doFilter(mutableRequest, response);
        }else{
           // logger.info("------filter:noswitch");
            chain.doFilter(servletRequest, response);
        }
    }
    @Override
    public void destroy() {
    }
}

+ 103 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/logs/BusinessLogs.java

@ -0,0 +1,103 @@
package com.yihu.wlyy.logs;
import com.yihu.wlyy.util.DateUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 业务日志输出
 * <p>
 * Created by lyr-pc on 2017/1/19.
 */
public class BusinessLogs {
    // 日志输出
    private static Logger logger = LoggerFactory.getLogger(BusinessLogs.class);
    /**
     * 业务类型
     */
    public enum BusinessType {
        // 咨询
        consult
        // 指导
        , guidance
        // 健康教育
        , article
        // 随访
        , followup
        // 预约
        , appointment
        // 标签
        , label
        // 注册
        , register
        // 健康档案
        , archive
        // 签约
        , sign
        // 指标
        , index
    }
    /**
     * 业务日志输出
     *
     * @param type 业务类别
     * @param info 日志信息
     */
    public static void info(BusinessType type, String caller,String user, JSONObject info) {
        try {
            JSONObject log = new JSONObject();
            log.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date()));
            log.put("logType", 2);
            log.put("caller", caller);
            JSONObject data = new JSONObject();
            data.put("businessType", type.ordinal());
            data.put("patient", user);
            data.put("data", info);
            log.put("data", data);
            logger.info(log.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 业务日志输出
     *
     * @param type 业务类别
     * @param info 日志信息
     */
    public static void info(BusinessType type,String caller, String user, JSONArray info) {
        try {
            JSONObject log = new JSONObject();
            log.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date()));
            log.put("logType", 2);
            log.put("caller", caller);
            JSONObject data = new JSONObject();
            data.put("businessType", type.ordinal());
            data.put("patient", user);
            data.put("data", info);
            log.put("data", data);
            logger.info(log.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 42 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/logs/InterfaceCallLogs.java

@ -0,0 +1,42 @@
package com.yihu.wlyy.logs;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by lyr-pc on 2017/1/22.
 */
public class InterfaceCallLogs {
    // 日志输出
    private static Logger logger = LoggerFactory.getLogger(InterfaceCallLogs.class);
    /**
     * 接口调用日志输出
     *
     * @param info 日志信息
     */
    public static void info(long time, String url, String user, String info) {
        try {
            JSONObject log = new JSONObject();
            log.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date()));
            log.put("logType", 1);
            log.put("caller", user);
            JSONObject data = new JSONObject();
            data.put("responseTime", time);
            data.put("url", url);
            data.put("params", info);
            log.put("data", data);
            logger.info(log.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 101 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/redis/RedisMsgPubSubListener.java

@ -0,0 +1,101 @@
//package com.yihu.wlyy.redis;
//
//import com.yihu.wlyy.service.app.prescription.PrescriptionInfoService;
//import com.yihu.wlyy.service.app.prescription.PrescriptionService;
//import com.yihu.wlyy.util.HttpUtil;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import redis.clients.jedis.JedisPubSub;
//
///**
// * Created by Trick on 2017/8/7.
// */
//@Component
//public class RedisMsgPubSubListener extends JedisPubSub {
//
//    @Autowired
//    private PrescriptionInfoService prescriptionInfoService;
//    @Autowired
//    private PrescriptionService prescriptionService;
//
//    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
//
//    @Override
//    public void unsubscribe() {
//        super.unsubscribe();
//    }
//
//    @Override
//    public void unsubscribe(String... channels) {
//        super.unsubscribe(channels);
//    }
//
//    @Override
//    public void subscribe(String... channels) {
//        super.subscribe(channels);
//    }
//
//    @Override
//    public void psubscribe(String... patterns) {
//        super.psubscribe(patterns);
//    }
//
//    @Override
//    public void punsubscribe() {
//        super.punsubscribe();
//    }
//
//    @Override
//    public void punsubscribe(String... patterns) {
//        super.punsubscribe(patterns);
//    }
//
//    @Override
//    public void onMessage(String channel, String message) {
//        logger.info("redis_onMessage...:"+message);
//        //this.unsubscribe();
//        try{
//            JSONObject json = new JSONObject(message);
//            String title =  json.getString("title");
//            if("redisAddPrescription".equals(title)){
//                logger.info(json.toString());
//                //审核消息发送
//                prescriptionInfoService.onMesSquareState(message);
//            }else if("dispensingComplete".equals(title)){//配药完成
//                //药品配送完成,提醒取药
//                String prescriptionCode = json.getString("prescription");
//                prescriptionService.dispensingComplete(prescriptionCode);
//            }
//        }catch (Exception e){
//            logger.error("redis_error...",e);
//        }
//    }
//
//    @Override
//    public void onPMessage(String pattern, String channel, String message) {
//
//    }
//
//    @Override
//    public void onSubscribe(String channel, int subscribedChannels) {
//        //System.out.println("channel:" + channel + "is been subscribed:" + subscribedChannels);
//    }
//
//    @Override
//    public void onPUnsubscribe(String pattern, int subscribedChannels) {
//
//    }
//
//    @Override
//    public void onPSubscribe(String pattern, int subscribedChannels) {
//
//    }
//
//    @Override
//    public void onUnsubscribe(String channel, int subscribedChannels) {
//        System.out.println("channel:" + channel + "is been unsubscribed:" + subscribedChannels);
//    }
//}

+ 44 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/redis/RedisThread.java

@ -0,0 +1,44 @@
//package com.yihu.wlyy.redis;
//
//import com.yihu.wlyy.service.app.prescription.PrescriptionService;
//import com.yihu.wlyy.util.SystemConf;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.stereotype.Component;
//
///**
// * Created by Trick on 2017/8/7.
// */
//@Component
//public class RedisThread implements Runnable {
//
//    @Value("${spring.redis.host}")
//    private String url;
//    @Autowired
//    private RedisMsgPubSubListener redisMsgPubSubListener;
//    @Autowired
//    private StringRedisTemplate redisTemplate;
//    @Autowired
//    private PrescriptionService prescriptionService;
//
//    @Override
//    public void run() {
//        String key = SystemConf.getInstance().getSystemProperties().getProperty("redis_prescription_title");
//        while (true){
//            redisTemplate.watch(key);
//            String message = redisTemplate.opsForList().rightPop(key);
//            redisTemplate.unwatch();
//            if(StringUtils.isEmpty(message)){
//                try{
//                    Thread.sleep(1000L);//如果没有读取到记录,等待1秒
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            }else {
//                prescriptionService.redisMessage(message);
//            }
//        }
//    }
//}

+ 17 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/VersionsDao.java

@ -0,0 +1,17 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.wlyy.entity.Versions;
public interface VersionsDao extends PagingAndSortingRepository<Versions, Long>, JpaSpecificationExecutor<Versions> {
	Versions findByCode(String code);
}

+ 20 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/address/CityDao.java

@ -0,0 +1,20 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository.address;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.wlyy.entity.address.City;
public interface CityDao extends PagingAndSortingRepository<City, Long> {
	// 根據CODE查詢城市名稱
	@Query("select p from City p where p.code = ?1")
	City findByCode(String code);
	
	@Query("select a from City a where a.province = ?1 order by id")
	Iterable<City> findByProvince(String province);
}

+ 0 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/address/CountryDao.java


Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác