Explorar o código

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

wangzhinan %!s(int64=6) %!d(string=hai) anos
pai
achega
952b2bea6f
Modificáronse 100 ficheiros con 6450 adicións e 415 borrados
  1. 150 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/module/InterfaceDO.java
  2. 77 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/module/InterfaceErrorCodeDO.java
  3. 158 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/module/InterfaceParamDO.java
  4. 49 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/module/ModuleDO.java
  5. 148 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/notice/NoticeDO.java
  6. 85 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/notice/UserNoticeDO.java
  7. 36 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxGraphicSceneDO.java
  8. 37 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxWechatSaasDO.java
  9. 32 0
      common/common-exception/src/main/java/com/yihu/jw/exception/code/BaseErrorCode.java
  10. 62 3
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java
  11. 1 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/health/house/HealthyHouseMapping.java
  12. 73 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/InterfaceErrorCodeVO.java
  13. 123 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/InterfaceParamVO.java
  14. 146 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/InterfaceVO.java
  15. 20 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/ModuleVO.java
  16. 78 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/notice/NoticeVO.java
  17. 78 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/notice/UserNoticeVO.java
  18. 13 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/role/MenuVO.java
  19. 39 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxComboVO.java
  20. 40 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxGraphicSceneVO.java
  21. 79 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxReplySceneVO.java
  22. 263 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxTemplateConfigVO.java
  23. 51 60
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxTemplateVO.java
  24. 4 1
      common/common-util/pom.xml
  25. 15 0
      common/common-util/src/main/java/com/yihu/jw/util/http/AllowAllHostnameVerifier.java
  26. 100 0
      common/common-util/src/main/java/com/yihu/jw/util/http/CustomTrustClientClientImpl.java
  27. 336 0
      common/common-util/src/main/java/com/yihu/jw/util/http/DefaultClientImpl.java
  28. 54 0
      common/common-util/src/main/java/com/yihu/jw/util/http/HTTPClient.java
  29. 23 0
      common/common-util/src/main/java/com/yihu/jw/util/http/HTTPResponse.java
  30. 155 0
      common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientKit.java
  31. 107 0
      common/common-util/src/main/java/com/yihu/jw/util/security/RandomValidateCode.java
  32. 36 19
      gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/BasicZuulFilter.java
  33. 232 0
      gateway/ag-basic/src/main/java/com/yihu/jw/security/core/userdetails/SaltUser.java
  34. 17 0
      gateway/ag-basic/src/main/resources/application.yml
  35. 7 3
      server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java
  36. 16 5
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java
  37. 3 3
      server/svr-authentication/src/main/resources/application.yml
  38. 2 2
      svr/svr-base/src/main/java/com/yihu/jw/base/contant/MenuContant.java
  39. 19 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/InterfaceDao.java
  40. 23 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/InterfaceErrorCodeDao.java
  41. 23 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/InterfaceParamDao.java
  42. 8 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/ModuleDao.java
  43. 16 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/notice/NoticeDao.java
  44. 14 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/notice/UserNoticeDao.java
  45. 4 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/user/UserDao.java
  46. 11 14
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicMessageDao.java
  47. 11 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicSceneDao.java
  48. 20 20
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxTemplateDao.java
  49. 14 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxWechatSaasDao.java
  50. 165 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/common/FileUploadController.java
  51. 121 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/module/InterfaceEndpoint.java
  52. 56 1
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/module/ModuleEndpoint.java
  53. 123 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/notice/NoticeEndPoint.java
  54. 54 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/notice/UserNoticeEndpoint.java
  55. 38 4
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/role/MenuEndpoint.java
  56. 196 5
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WechatController.java
  57. 5 0
      svr/svr-base/src/main/java/com/yihu/jw/base/listener/ApplicationReadyListener.java
  58. 16 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/module/InterfaceErrorCodeService.java
  59. 16 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/module/InterfaceParamService.java
  60. 97 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/module/InterfaceService.java
  61. 40 1
      svr/svr-base/src/main/java/com/yihu/jw/base/service/module/ModuleService.java
  62. 184 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/notice/NoticeService.java
  63. 78 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/notice/UserNoticeService.java
  64. 2 2
      svr/svr-base/src/main/java/com/yihu/jw/base/service/role/MenuService.java
  65. 355 5
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatService.java
  66. 1 1
      svr/svr-base/src/main/java/com/yihu/jw/base/util/ErrorCodeUtil.java
  67. 79 0
      svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/DelayService.java
  68. 53 0
      svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/Notice.java
  69. 12 0
      svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/OnDelayedListener.java
  70. 196 0
      svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/RedisLock.java
  71. 59 0
      svr/svr-base/src/main/java/com/yihu/jw/base/util/threadPool/ThreadPool.java
  72. 32 0
      svr/svr-base/src/main/java/com/yihu/jw/base/util/threadPool/ThreadPoolUtil.java
  73. 36 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/RedisContext.java
  74. 34 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/WebMvcConfigurer.java
  75. 6 3
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/constant/LoginInfo.java
  76. 12 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/constant/SystemDictConstant.java
  77. 153 48
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/LoginController.java
  78. 3 4
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/dfs/FastDFSController.java
  79. 73 26
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/facilities/FacilitiesController.java
  80. 31 5
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/facilities/FacilitiesServerController.java
  81. 20 6
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/FacilityUsedRecordController.java
  82. 6 7
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/FeedBackController.java
  83. 13 3
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/NavigationServiceEvaluationController.java
  84. 206 55
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/UserController.java
  85. 2 2
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/facility/FacilityDao.java
  86. 6 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/facility/FacilityServerDao.java
  87. 1 1
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/user/FacilityUsedRecordDao.java
  88. 22 5
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/user/UserDao.java
  89. 157 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/interceptor/ActivatedInterceptor.java
  90. 49 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/job/ActivatedUserUpdateTask.java
  91. 29 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/listener/RedisKeyExpirationListener.java
  92. 13 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/facility/Facility.java
  93. 16 1
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/FacilityUsedRecord.java
  94. 34 1
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/User.java
  95. 19 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/facility/FacilityServerService.java
  96. 211 67
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/facility/FacilityService.java
  97. 1 1
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/FacilityUsedRecordService.java
  98. 87 9
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/LoginService.java
  99. 124 22
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/UserService.java
  100. 0 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/ImportDemoReader.java

+ 150 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/module/InterfaceDO.java

@ -0,0 +1,150 @@
package com.yihu.jw.entity.base.module;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.List;
/**
 * 接口
 * @author yeshijie on 2018/9/28.
 */
@Entity
@Table(name = "base_interface")
public class InterfaceDO extends UuidIdentityEntity {
    private String name;//接口名称
    private String moduleId;//模块id
    private String moduleName;//模块名称
    private String methodName;//方法名
    private Integer protocolType;//协议类型(2restful,1webservice)
    private Integer openLevel;//开发程度(1公开,2私有)
    private Integer checkLevel;//审计程度(1审计,2不审计)
    private Integer status;//状态(1生效中,0已失效)
    private String remark;//接口说明
    private String url;//https请求地址
    private List<InterfaceParamDO> entryParams;//入参
    private List<InterfaceParamDO> outParams;//出参
    private List<InterfaceErrorCodeDO> errorCodes;//错误说明
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "module_id")
    public String getModuleId() {
        return moduleId;
    }
    public void setModuleId(String moduleId) {
        this.moduleId = moduleId;
    }
    @Column(name = "module_name")
    public String getModuleName() {
        return moduleName;
    }
    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }
    @Column(name = "method_name")
    public String getMethodName() {
        return methodName;
    }
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
    @Column(name = "protocol_type")
    public Integer getProtocolType() {
        return protocolType;
    }
    public void setProtocolType(Integer protocolType) {
        this.protocolType = protocolType;
    }
    @Column(name = "open_level")
    public Integer getOpenLevel() {
        return openLevel;
    }
    public void setOpenLevel(Integer openLevel) {
        this.openLevel = openLevel;
    }
    @Column(name = "check_level")
    public Integer getCheckLevel() {
        return checkLevel;
    }
    public void setCheckLevel(Integer checkLevel) {
        this.checkLevel = checkLevel;
    }
    @Column(name = "status")
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @Column(name = "url")
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    @Transient
    public List<InterfaceParamDO> getEntryParams() {
        return entryParams;
    }
    public void setEntryParams(List<InterfaceParamDO> entryParams) {
        this.entryParams = entryParams;
    }
    @Transient
    public List<InterfaceParamDO> getOutParams() {
        return outParams;
    }
    public void setOutParams(List<InterfaceParamDO> outParams) {
        this.outParams = outParams;
    }
    @Transient
    public List<InterfaceErrorCodeDO> getErrorCodes() {
        return errorCodes;
    }
    public void setErrorCodes(List<InterfaceErrorCodeDO> errorCodes) {
        this.errorCodes = errorCodes;
    }
}

+ 77 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/module/InterfaceErrorCodeDO.java

@ -0,0 +1,77 @@
package com.yihu.jw.entity.base.module;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 接口错误说明
 * @author yeshijie on 2018/9/28.
 */
@Entity
@Table(name = "base_interface_error_code")
public class InterfaceErrorCodeDO extends UuidIdentityEntity {
    private String interfaceId;//接口id
    private String name;//错误码名称
    private String description;//错误码描述
    private String solution;//解决方案
    private Integer sort;//排序
    private Integer del;//删除标志
    @Column(name = "interface_id")
    public String getInterfaceId() {
        return interfaceId;
    }
    public void setInterfaceId(String interfaceId) {
        this.interfaceId = interfaceId;
    }
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "solution")
    public String getSolution() {
        return solution;
    }
    public void setSolution(String solution) {
        this.solution = solution;
    }
    @Column(name = "sort")
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 158 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/module/InterfaceParamDO.java

@ -0,0 +1,158 @@
package com.yihu.jw.entity.base.module;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 接口入参出参
 * @author yeshijie on 2018/9/28.
 */
@Entity
@Table(name = "base_interface_param")
public class InterfaceParamDO extends UuidIdentityEntity {
    /**
     *
     */
    public enum Type{
        entry("入参",1),
        out("出参",2);
        private String name;
        private Integer value;
        Type(String name, Integer value) {
            this.name = name;
            this.value = value;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getValue() {
            return value;
        }
        public void setValue(Integer value) {
            this.value = value;
        }
    }
    private String interfaceId;//接口id
    private String name;//参数名
    private Integer paramType;//参数类型
    private Integer dataType;//数据类型
    private Integer isRequire;//是否必填(1是,0否)
    private Integer maxLength;//最大长度
    private String description;//描述
    private String example;//示例
    private Integer type;//类型(1入参,2出参)
    private Integer sort;//排序
    private Integer del;//删除标志
    @Column(name = "interface_id")
    public String getInterfaceId() {
        return interfaceId;
    }
    public void setInterfaceId(String interfaceId) {
        this.interfaceId = interfaceId;
    }
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "param_type")
    public Integer getParamType() {
        return paramType;
    }
    public void setParamType(Integer paramType) {
        this.paramType = paramType;
    }
    @Column(name = "data_type")
    public Integer getDataType() {
        return dataType;
    }
    public void setDataType(Integer dataType) {
        this.dataType = dataType;
    }
    @Column(name = "is_require")
    public Integer getIsRequire() {
        return isRequire;
    }
    public void setIsRequire(Integer isRequire) {
        this.isRequire = isRequire;
    }
    @Column(name = "max_length")
    public Integer getMaxLength() {
        return maxLength;
    }
    public void setMaxLength(Integer maxLength) {
        this.maxLength = maxLength;
    }
    @Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "example")
    public String getExample() {
        return example;
    }
    public void setExample(String example) {
        this.example = example;
    }
    @Column(name = "type")
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    @Column(name = "sort")
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 49 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/module/ModuleDO.java

@ -46,6 +46,35 @@ public class ModuleDO extends UuidIdentityEntityWithOperator {
		}
	}
	public enum Type {
		common("通用", 0),
		doctor("医生端", 1),
		patient("居民端", 2);
		private String name;
		private Integer value;
		Type(String name, Integer value) {
			this.name = name;
			this.value = value;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Integer getValue() {
			return value;
		}
		public void setValue(Integer value) {
			this.value = value;
		}
	}
	//模块名称
	private String name;
	//模块连接
@ -60,6 +89,8 @@ public class ModuleDO extends UuidIdentityEntityWithOperator {
	private String remark;
	//0-表示有子节点,1-表示没有子节点
	private Integer isEnd ;
	//0-表示非必选,1-表示必选
	private Integer isMust ;
	//逻辑删除标志1正常,0删除
	private Integer del ;
	//子集
@ -112,6 +143,15 @@ public class ModuleDO extends UuidIdentityEntityWithOperator {
		this.url = url;
	}
	@Column(name = "type")
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	@Column(name = "is_end")
	public Integer getIsEnd() {
		return isEnd;
@ -130,6 +170,15 @@ public class ModuleDO extends UuidIdentityEntityWithOperator {
		this.del = del;
	}
	@Column(name = "is_must")
	public Integer getIsMust() {
		return isMust;
	}
	public void setIsMust(Integer isMust) {
		this.isMust = isMust;
	}
	@Transient
	public List<ModuleDO> getChildren() {
		return children;

+ 148 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/notice/NoticeDO.java

@ -0,0 +1,148 @@
package com.yihu.jw.entity.base.notice;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 公告通知
 * @author yeshijie on 2018/9/30.
 */
@Entity
@Table(name = "base_notice")
public class NoticeDO extends UuidIdentityEntityWithOperator{
    public enum Status{
        wait("待发布",1),
        released("已发布",2);
        private String name;
        private Integer value;
        Status(String name, Integer value) {
            this.name = name;
            this.value = value;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getValue() {
            return value;
        }
        public void setValue(Integer value) {
            this.value = value;
        }
    }
    public enum SendType{
        manual_release("手动发布",1),
        automatic_release("自动发布",2);
        private String name;
        private Integer value;
        SendType(String name, Integer value) {
            this.name = name;
            this.value = value;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getValue() {
            return value;
        }
        public void setValue(Integer value) {
            this.value = value;
        }
    }
    private String title;//公告标题
    private Integer status;//状态(1待发布,2已发布)
    private Date sendTime;//发布时间
    private String content;//公告内容
    private Integer sendType;//发布方式(1手动发布,2自动发布)
    private Integer del;//删除标志(1正常,0删除)
    @Column(name = "title")
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Column(name = "status")
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @Column(name = "content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Column(name = "send_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getSendTime() {
        return sendTime;
    }
    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }
    @Column(name = "send_type")
    public Integer getSendType() {
        return sendType;
    }
    public void setSendType(Integer sendType) {
        this.sendType = sendType;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    @Override
    public String toString() {
        return "NoticeDO{" +
                "title='" + title + '\'' +
                ", status=" + status +
                ", sendTime=" + sendTime +
                ", content='" + content + '\'' +
                ", sendType=" + sendType +
                ", del=" + del +
                '}';
    }
}

+ 85 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/notice/UserNoticeDO.java

@ -0,0 +1,85 @@
package com.yihu.jw.entity.base.notice;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 用户公告通知
 * @author yeshijie on 2018/9/30.
 */
@Entity
@Table(name = "base_user_notice")
public class UserNoticeDO extends UuidIdentityEntity{
    public enum Read{
        unRead("未读",0),
        read("已读",1);
        private String name;
        private Integer value;
        Read(String name, Integer value) {
            this.name = name;
            this.value = value;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getValue() {
            return value;
        }
        public void setValue(Integer value) {
            this.value = value;
        }
    }
    private String noticeId;//公告id
    private String userId;//用户id
    private Integer isRead;//是否已读(1已读,0未读)
    private Integer del;//删除标志(1正常,0删除)
    @Column(name = "notice_id")
    public String getNoticeId() {
        return noticeId;
    }
    public void setNoticeId(String noticeId) {
        this.noticeId = noticeId;
    }
    @Column(name = "user_id")
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    @Column(name = "is_read")
    public Integer getIsRead() {
        return isRead;
    }
    public void setIsRead(Integer isRead) {
        this.isRead = isRead;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 36 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxGraphicSceneDO.java

@ -0,0 +1,36 @@
package com.yihu.jw.entity.base.wx;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Administrator on 2018/10/9.
 */@Entity
@Table(name = "wx_graphic_scene")
public class WxGraphicSceneDO extends UuidIdentityEntity implements java.io.Serializable{
    private String wechatId;//所属微信
    private String scene;//场景值
    @Column(name = "wechat_id")
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    @Column(name="scene")
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
}

+ 37 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxWechatSaasDO.java

@ -0,0 +1,37 @@
package com.yihu.jw.entity.base.wx;
import com.yihu.jw.entity.UuidIdentityEntity;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Administrator on 2018/10/8.
 */
@Entity
@Table(name = "wx_wechat_saas")
public class WxWechatSaasDO extends UuidIdentityEntity implements java.io.Serializable {
    private String wechatId;
    private String saasId;
    @Column(name="wechat_id")
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    @Column(name="saas_id")
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
}

+ 32 - 0
common/common-exception/src/main/java/com/yihu/jw/exception/code/BaseErrorCode.java

@ -48,6 +48,7 @@ public class BaseErrorCode {
     */
    public static class Module{
        public static final String FINDDICTBYCODE = "-103000";
        public static final String NAME_IS_EXIST = "-103001";
    }
    /**
@ -62,6 +63,18 @@ public class BaseErrorCode {
     */
    public static class Notice{
        public static final String FINDDICTBYCODE = "-105000";
        /**
         * 请输入50个字以内的公告标题
         */
        public static final String LIMIT_TITLE = "-105001";
        /**
         * 已经发布,请不要重复发布
         */
        public static final String HAD_RELEASE = "-105002";
        /**
         * 自动发布,不允许手动发布
         */
        public static final String AUTO_RELEASE = "-105003";
    }
    /**
@ -71,6 +84,25 @@ public class BaseErrorCode {
        public static final String FINDDICTBYCODE = "-106000";
    }
    /**
     * 通知公告模块
     */
    public static class FileUpload{
        /**
         * 文件格式错误
         */
        public static final String FAIL_UPLOAD_FORMAT = "-107000";
        /**
         * 文件大小不超过{}M
         */
        public static final String FAIL_FILE_SIZE = "-107001";
        /**
         * 上传内容为空
         */
        public static final String FILE_NULL = "-107002";
    }
    /**
     * 微信模块
     */

+ 62 - 3
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java

@ -18,6 +18,7 @@ public class BaseRequestMapping {
        public static final String UPDATE = "/update";
        public static final String PAGE = "/page";
        public static final String LIST = "/list";
        public static final String FINDBYID = "/findById";
    }
    /**
@ -55,7 +56,19 @@ public class BaseRequestMapping {
     */
    public static class Module extends Basic {
        public static final String PREFIX  = "/module";
        public static final String STATUS  = "/status";
        public static final String IS_NAME_EXIST  = "/isNameExist";
        public static final String FIND_ALL  = "/findAll";
    }
    /**
     * 接口
     */
    public static class Interface extends Basic {
        public static final String PREFIX  = "/interface";
        public static final String STATUS  = "/status";
        public static final String IS_NAME_EXIST  = "/isNameExist";
        public static final String FIND_ALL  = "/findAll";
    }
    /**
@ -129,9 +142,10 @@ public class BaseRequestMapping {
    public static class Menu extends Basic {
        public static final String PREFIX  = "/menu";
        public static final String STATUS  = "/status";
        public static final String ISNAMEEXIST  = "/isNameExist";
        public static final String MOVEUP  = "/moveUp";
        public static final String MOVEDOWN  = "/moveDown";
        public static final String IS_NAME_EXIST  = "/isNameExist";
        public static final String MOVE_UP  = "/moveUp";
        public static final String MOVE_DOWN  = "/moveDown";
        public static final String FIND_ALL  = "/findAll";
    }
    /**
@ -141,6 +155,32 @@ public class BaseRequestMapping {
        public static final String PREFIX  = "/error";
    }
    /**
     * 通知公告
     */
    public static class Notice extends Basic {
        public static final String PREFIX  = "/notice";
        public static final String RELEASE  = "/release";
    }
    /**
     * 用户通知公告
     */
    public static class UserNotice extends Basic {
        public static final String PREFIX  = "/userNotice";
    }
    /**
     * 文件上传
     */
    public static class FileUpload extends Basic {
        public static final String PREFIX  = "/fileUpload";
        public static final String UPLOAD_STREAM_IMG  = "/upload_stream_img";
        public static final String UPLOAD_STREAM  = "/upload_stream";
        public static final String UPLOAD_STRING  = "/upload_string";
        public static final String UPLOAD_STREAM_ATTACHMENT  = "/upload_stream_attachment";
    }
    /**
     * 角色权限
     */
@ -155,7 +195,26 @@ public class BaseRequestMapping {
        public static final String PREFIX  = "/wechat";
        public static final String wechat_base ="/wechatBase";
        public static final String api_success ="success";
        public static final String getWechatInfos ="/getWechatInfos";
        public static final String saveWxAndSaas ="/saveWxAndSaas";
        public static final String updateWxAndSaas ="/updateWxAndSaas";
        public static final String findWechatCombo ="/findWechatCombo";
        public static final String findWechatImgGroup ="/findWechatImgGroup";
        public static final String createImgGroup ="/createImgGroup";
        public static final String updateImgGroup ="/updateImgGroup";
        public static final String deleteImgGroup ="/deleteImgGroup";
        public static final String saveImg ="/saveImg";
        public static final String findImg ="/findImg";
        public static final String saveImgGroup ="/saveImgGroup";
        public static final String saveWxReplyScene ="/saveWxReplyScene";
        public static final String findWxReplyScene ="/findWxReplyScene";
        public static final String saveWxTemp ="/saveWxTemp";
        public static final String saveWxTempConfig ="/saveWxTempConfig";
        public static final String findWxTempConfigList ="/findWxTempConfigList";
        public static final String findWxTemplateConfig ="/findWxTemplateConfig";
    }
    /**

+ 1 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/health/house/HealthyHouseMapping.java

@ -71,6 +71,7 @@ public class HealthyHouseMapping {
            public static final String GET_FACILITIESERVERS_BY_ID = "/getFacilitieServersById";
            public static final String GET_FACILITIESERVERS_BY_FIELD = "/getFacilitieServersByField";
            public static final String LIST_FACILITIESERVERS = "/list/listFacilitieServers";
            public static final String LIST_FACILITIESERVERS_BY_TYPE = "/list/listFacilitieServersByType";
        }
        //意见反馈

+ 73 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/InterfaceErrorCodeVO.java

@ -0,0 +1,73 @@
package com.yihu.jw.restmodel.base.module;
import com.yihu.jw.restmodel.UuidIdentityVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * @author yeshijie on 2018/9/28.
 */
@ApiModel(value = "InterfaceErrorCodeVO", description = "接口错误说明")
public class InterfaceErrorCodeVO extends UuidIdentityVO {
    @ApiModelProperty(value = "接口id", example = "接口id")
    private String interfaceId;
    @ApiModelProperty(value = "错误码名称", example = "错误码名称")
    private String name;
    @ApiModelProperty(value = "错误码描述", example = "错误码描述")
    private String description;
    @ApiModelProperty(value = "解决方案", example = "解决方案")
    private String solution;
    @ApiModelProperty(value = "排序", example = "1")
    private Integer sort;
    @ApiModelProperty(value = "删除标志", example = "1")
    private Integer del;
    public String getInterfaceId() {
        return interfaceId;
    }
    public void setInterfaceId(String interfaceId) {
        this.interfaceId = interfaceId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getSolution() {
        return solution;
    }
    public void setSolution(String solution) {
        this.solution = solution;
    }
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 123 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/InterfaceParamVO.java

@ -0,0 +1,123 @@
package com.yihu.jw.restmodel.base.module;
import com.yihu.jw.restmodel.UuidIdentityVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * @author yeshijie on 2018/9/28.
 */
@ApiModel(value = "InterfaceParamVO", description = "接口入参出参")
public class InterfaceParamVO extends UuidIdentityVO {
    @ApiModelProperty(value = "接口id", example = "接口id")
    private String interfaceId;
    @ApiModelProperty(value = "参数名", example = "user")
    private String name;
    @ApiModelProperty(value = "参数类型", example = "HEADER")
    private Integer paramType;
    @ApiModelProperty(value = "数据类型", example = "VERCHAR")
    private Integer dataType;
    @ApiModelProperty(value = "是否必填(1是,0否)", example = "1")
    private Integer isRequire;
    @ApiModelProperty(value = "最大长度", example = "1")
    private Integer maxLength;
    @ApiModelProperty(value = "描述", example = "")
    private String description;
    @ApiModelProperty(value = "示例", example = "")
    private String example;
    @ApiModelProperty(value = "类型(1入参,2出参)", example = "1")
    private Integer type;
    @ApiModelProperty(value = "排序", example = "1")
    private Integer sort;
    @ApiModelProperty(value = "删除标志", example = "1")
    private Integer del;
    public String getInterfaceId() {
        return interfaceId;
    }
    public void setInterfaceId(String interfaceId) {
        this.interfaceId = interfaceId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getParamType() {
        return paramType;
    }
    public void setParamType(Integer paramType) {
        this.paramType = paramType;
    }
    public Integer getDataType() {
        return dataType;
    }
    public void setDataType(Integer dataType) {
        this.dataType = dataType;
    }
    public Integer getIsRequire() {
        return isRequire;
    }
    public void setIsRequire(Integer isRequire) {
        this.isRequire = isRequire;
    }
    public Integer getMaxLength() {
        return maxLength;
    }
    public void setMaxLength(Integer maxLength) {
        this.maxLength = maxLength;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getExample() {
        return example;
    }
    public void setExample(String example) {
        this.example = example;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 146 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/InterfaceVO.java

@ -0,0 +1,146 @@
package com.yihu.jw.restmodel.base.module;
import com.yihu.jw.restmodel.UuidIdentityVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
 * @author yeshijie on 2018/9/28.
 */
@ApiModel(value = "InterfaceVO", description = "接口")
public class InterfaceVO extends UuidIdentityVO {
    @ApiModelProperty(value = "接口名称", example = "接口1")
    private String name;
    @ApiModelProperty(value = "模块id", example = "模块1d")
    private String moduleId;
    @ApiModelProperty(value = "模块名称", example = "模块名称")
    private String moduleName;
    @ApiModelProperty(value = "方法名", example = "方法1")
    private String methodName;
    @ApiModelProperty(value = "协议类型(2restful,1webservice)", example = "1")
    private Integer protocolType;
    @ApiModelProperty(value = "开发程度(1公开,2私有)", example = "1")
    private Integer openLevel;
    @ApiModelProperty(value = "审计程度(1审计,2不审计)", example = "1")
    private Integer checkLevel;
    @ApiModelProperty(value = "状态(1生效中,0已失效)", example = "1")
    private Integer status;
    @ApiModelProperty(value = "接口说明", example = "明")
    private String remark;
    @ApiModelProperty(value = "https请求地址", example = "")
    private String url;
    @ApiModelProperty(value = "入参", example = "")
    private List<InterfaceParamVO> entryParams;
    @ApiModelProperty(value = "出参", example = "")
    private List<InterfaceParamVO> outParams;
    @ApiModelProperty(value = "错误说明", example = "")
    private List<InterfaceErrorCodeVO> errorCodes;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getModuleId() {
        return moduleId;
    }
    public void setModuleId(String moduleId) {
        this.moduleId = moduleId;
    }
    public String getModuleName() {
        return moduleName;
    }
    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }
    public String getMethodName() {
        return methodName;
    }
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
    public Integer getProtocolType() {
        return protocolType;
    }
    public void setProtocolType(Integer protocolType) {
        this.protocolType = protocolType;
    }
    public Integer getOpenLevel() {
        return openLevel;
    }
    public void setOpenLevel(Integer openLevel) {
        this.openLevel = openLevel;
    }
    public Integer getCheckLevel() {
        return checkLevel;
    }
    public void setCheckLevel(Integer checkLevel) {
        this.checkLevel = checkLevel;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public List<InterfaceParamVO> getEntryParams() {
        return entryParams;
    }
    public void setEntryParams(List<InterfaceParamVO> entryParams) {
        this.entryParams = entryParams;
    }
    public List<InterfaceParamVO> getOutParams() {
        return outParams;
    }
    public void setOutParams(List<InterfaceParamVO> outParams) {
        this.outParams = outParams;
    }
    public List<InterfaceErrorCodeVO> getErrorCodes() {
        return errorCodes;
    }
    public void setErrorCodes(List<InterfaceErrorCodeVO> errorCodes) {
        this.errorCodes = errorCodes;
    }
}

+ 20 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/module/ModuleVO.java

@ -20,12 +20,16 @@ public class ModuleVO extends UuidIdentityVOWithOperator {
    private String parentId;
    @ApiModelProperty(value = "url", example = "/doctor/*")
    private String url;
    @ApiModelProperty(value = "类型", example = "0通用,1医生端你,2居民端")
    private String type;
    @ApiModelProperty(value = "状态", example = "1有效,0失效")
    private Integer status;
    @ApiModelProperty(value = "备注", example = "我是备注")
    private String remark;
    @ApiModelProperty(value = "节点信息(0-表示有子节点,1-表示没有子节点)", example = "1")
    private Integer isEnd ;
    @ApiModelProperty(value = "节点信息(0-表示非必选,1-表示必选)", example = "1")
    private Integer isMust ;
    @ApiModelProperty(value = "子集")
    private List<ModuleVO> children = new ArrayList<>();
@ -77,6 +81,22 @@ public class ModuleVO extends UuidIdentityVOWithOperator {
        this.isEnd = isEnd;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Integer getIsMust() {
        return isMust;
    }
    public void setIsMust(Integer isMust) {
        this.isMust = isMust;
    }
    public List<ModuleVO> getChildren() {
        return children;
    }

+ 78 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/notice/NoticeVO.java

@ -0,0 +1,78 @@
package com.yihu.jw.restmodel.base.notice;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.restmodel.UuidIdentityVOWithOperator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
/**
 *
 * @author yeshijie on 2018/9/30.
 */
@ApiModel(value = "NoticeVO", description = "公告通知")
public class NoticeVO extends UuidIdentityVOWithOperator {
    @ApiModelProperty(value = "公告标题", example = "标题")
    private String title;
    @ApiModelProperty(value = "状态(1待发布,2已发布)", example = "1")
    private Integer status;
    @ApiModelProperty(value = "发布时间", example = "2019-01-01 12:20:59")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date sendTime;
    @ApiModelProperty(value = "公告内容", example = "内容")
    private String content;
    @ApiModelProperty(value = "发布方式(1手动发布,2自动发布)", example = "1")
    private Integer sendType;
    @ApiModelProperty(value = "删除标志(1正常,0删除)", example = "1")
    private Integer del;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Date getSendTime() {
        return sendTime;
    }
    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getSendType() {
        return sendType;
    }
    public void setSendType(Integer sendType) {
        this.sendType = sendType;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 78 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/notice/UserNoticeVO.java

@ -0,0 +1,78 @@
package com.yihu.jw.restmodel.base.notice;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
/**
 *
 * @author yeshijie on 2018/9/30.
 */
@ApiModel(value = "UserNoticeVO", description = "用户公告通知")
public class UserNoticeVO extends UuidIdentityEntity{
    @ApiModelProperty(value = "公告id", example = "公告id")
    private String noticeId;
    @ApiModelProperty(value = "用户id", example = "用户id")
    private String userId;
    @ApiModelProperty(value = "是否已读(1已读,0未读)", example = "1")
    private Integer isRead;
    @ApiModelProperty(value = "删除标志(1正常,0删除)", example = "1")
    private Integer del;
    @ApiModelProperty(value = "公告标题", example = "标题")
    private String title;
    @ApiModelProperty(value = "发布时间", example = "2019-01-01 12:20:59")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date sendTime;
    public String getNoticeId() {
        return noticeId;
    }
    public void setNoticeId(String noticeId) {
        this.noticeId = noticeId;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public Integer getIsRead() {
        return isRead;
    }
    public void setIsRead(Integer isRead) {
        this.isRead = isRead;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Date getSendTime() {
        return sendTime;
    }
    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }
}

+ 13 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/role/MenuVO.java

@ -4,6 +4,9 @@ import com.yihu.jw.restmodel.UuidIdentityVOWithOperator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
/**
 * @author yeshijie on 2018/9/26.
 */
@ -24,6 +27,8 @@ public class MenuVO extends UuidIdentityVOWithOperator {
    private Integer status;
    @ApiModelProperty(value = "备注", example = "说明")
    private String remark;
    @ApiModelProperty(value = "子集")
    private List<MenuVO> children = new ArrayList<>();
    public String getName() {
        return name;
@ -72,4 +77,12 @@ public class MenuVO extends UuidIdentityVOWithOperator {
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public List<MenuVO> getChildren() {
        return children;
    }
    public void setChildren(List<MenuVO> children) {
        this.children = children;
    }
}

+ 39 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxComboVO.java

@ -0,0 +1,39 @@
package com.yihu.jw.restmodel.base.wx;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by Administrator on 2018/10/9.
 */
public class WxComboVO {
    @ApiModelProperty(value = "微信id")
    private String id;
    @ApiModelProperty(value = "微信公众号")
    private String name;
    @ApiModelProperty(value = "原始id")
    private String appOriginId;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAppOriginId() {
        return appOriginId;
    }
    public void setAppOriginId(String appOriginId) {
        this.appOriginId = appOriginId;
    }
}

+ 40 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxGraphicSceneVO.java

@ -0,0 +1,40 @@
package com.yihu.jw.restmodel.base.wx;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by Administrator on 2018/10/9.
 */
public class WxGraphicSceneVO {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "所属微信")
    private String wechatId;//所属微信
    @ApiModelProperty(value = "场景值")
    private String scene;//场景值
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
}

+ 79 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxReplySceneVO.java

@ -0,0 +1,79 @@
package com.yihu.jw.restmodel.base.wx;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by Administrator on 2018/10/9.
 */
public class WxReplySceneVO {
    @ApiModelProperty(value = "微信id(唯一)")
    private String wechatId;//微信id(唯一)
    @ApiModelProperty(value = "原始ID(唯一)")
    private String appOriginId;//原始ID(唯一)
    @ApiModelProperty(value = "微信消息类型:text,event,image,voice,video,shortvideo,location,link")
    private String msgType;//微信消息类型:text,event,image,voice,video,shortvideo,location,link
    @ApiModelProperty(value = "微信事件类型:SCAN,LOCATION,CLICK,subscribe,unsubscribe")
    private String event;//微信事件类型:SCAN,LOCATION,CLICK,subscribe,unsubscribe
    @ApiModelProperty(value = "图文消息/自定义消息,分组场景,微信的eventKey")
    private String scene;//图文消息/自定义消息,分组场景,微信的eventKey
    @ApiModelProperty(value = "居民回复内容,消息字段")
    private String content;//居民回复内容,消息字段
    @ApiModelProperty(value = "状态(-1删除 0 冻结 1可用")
    private Integer status;//状态(-1删除 0 冻结 1可用
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    public String getAppOriginId() {
        return appOriginId;
    }
    public void setAppOriginId(String appOriginId) {
        this.appOriginId = appOriginId;
    }
    public String getMsgType() {
        return msgType;
    }
    public void setMsgType(String msgType) {
        this.msgType = msgType;
    }
    public String getEvent() {
        return event;
    }
    public void setEvent(String event) {
        this.event = event;
    }
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 263 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxTemplateConfigVO.java

@ -0,0 +1,263 @@
package com.yihu.jw.restmodel.base.wx;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
/**
 * Created by Administrator on 2018/10/10.
 */
public class WxTemplateConfigVO {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "微信id")
    private String wechatId;//微信id
    @ApiModelProperty(value = "微信模板id")
    private String templateId;//微信模板id
    @ApiModelProperty(value = "自定义模板名称")
    private String templateName;//自定义模板名称
    @ApiModelProperty(value = "使用场景值")
    private String scene;//使用场景值
    @ApiModelProperty(value = "使用场景描述")
    private String sceneDescription;//使用场景描述
    @ApiModelProperty(value = "头部")
    private String first;//头部,
    @ApiModelProperty(value = "跳转链接")
    private String url;//跳转链接
    @ApiModelProperty(value = "备注")
    private String remark;//备注
    @ApiModelProperty(value = "项目")
    private String keyword1;//项目
    @ApiModelProperty(value = "项目")
    private String keyword2;//项目
    @ApiModelProperty(value = "项目")
    private String keyword3;//项目
    @ApiModelProperty(value = "项目")
    private String keyword4;//项目
    @ApiModelProperty(value = "项目")
    private String keyword5;//项目
    @ApiModelProperty(value = "项目")
    private String keyword6;//项目
    @ApiModelProperty(value = "项目")
    private String keyword7;//项目
    @ApiModelProperty(value = "跳转小程序的appid")
    private String appid;//跳转小程序的appid
    @ApiModelProperty(value = "跳转小程序路径")
    private String pagepath;//跳转小程序路径
    @ApiModelProperty(value = "状态 -1删除 0 冻结 1可用")
    private Integer status;  //状态 -1删除 0 冻结 1可用
    @ApiModelProperty(value = "创建人")
    private String createUser;//创建人
    @ApiModelProperty(value = "创建人名")
    private String createUserName;//创建人名
    @ApiModelProperty(value = "创建时间")
    private Date createTime;//创建时间
    @ApiModelProperty(value = "修改人")
    private String updateUser;//修改人
    @ApiModelProperty(value = "修改人名称")
    private String updateUserName;//修改人名称
    @ApiModelProperty(value = "修改时间")
    private Date updateTime;//修改时间
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    public String getTemplateId() {
        return templateId;
    }
    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }
    public String getTemplateName() {
        return templateName;
    }
    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
    public String getSceneDescription() {
        return sceneDescription;
    }
    public void setSceneDescription(String sceneDescription) {
        this.sceneDescription = sceneDescription;
    }
    public String getFirst() {
        return first;
    }
    public void setFirst(String first) {
        this.first = first;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public String getKeyword1() {
        return keyword1;
    }
    public void setKeyword1(String keyword1) {
        this.keyword1 = keyword1;
    }
    public String getKeyword2() {
        return keyword2;
    }
    public void setKeyword2(String keyword2) {
        this.keyword2 = keyword2;
    }
    public String getKeyword3() {
        return keyword3;
    }
    public void setKeyword3(String keyword3) {
        this.keyword3 = keyword3;
    }
    public String getKeyword4() {
        return keyword4;
    }
    public void setKeyword4(String keyword4) {
        this.keyword4 = keyword4;
    }
    public String getKeyword5() {
        return keyword5;
    }
    public void setKeyword5(String keyword5) {
        this.keyword5 = keyword5;
    }
    public String getKeyword6() {
        return keyword6;
    }
    public void setKeyword6(String keyword6) {
        this.keyword6 = keyword6;
    }
    public String getKeyword7() {
        return keyword7;
    }
    public void setKeyword7(String keyword7) {
        this.keyword7 = keyword7;
    }
    public String getAppid() {
        return appid;
    }
    public void setAppid(String appid) {
        this.appid = appid;
    }
    public String getPagepath() {
        return pagepath;
    }
    public void setPagepath(String pagepath) {
        this.pagepath = pagepath;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    public String getUpdateUserName() {
        return updateUserName;
    }
    public void setUpdateUserName(String updateUserName) {
        this.updateUserName = updateUserName;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

+ 51 - 60
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/wx/WxTemplateVO.java

@ -1,5 +1,8 @@
package com.yihu.jw.restmodel.base.wx;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -9,23 +12,36 @@ import java.util.Map;
 * Created by Administrator on 2017/5/20 0020.
 */
public class WxTemplateVO {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "模板标题")
    private String title;//模板标题
    private String name;//用于模板列表渲染
    private String wechatCode;//关联的微信code 关联表 Wx_Wechat
    private String wechatName;//关联的微信名
    @ApiModelProperty(value = "关联的微信code 关联表 Wx_Wechat")
    private String wechatId;//关联的微信code 关联表 Wx_Wechat
    @ApiModelProperty(value = "微信模板id")
    private String templateId;//微信模板id
    @ApiModelProperty(value = "模板名称(模板检索名称)")
    private String templateName;//模板名称(模板检索名称)
    @ApiModelProperty(value = "模板内容")
    private String content;//模板内容
    @ApiModelProperty(value = "remark")
    private String remark;
    @ApiModelProperty(value = "状态 -1删除 0 冻结 1可用")
    private Integer status;  //状态 -1删除 0 冻结 1可用
    @ApiModelProperty(value = "创建人")
    private String createUser;//创建人
    @ApiModelProperty(value = "创建人名")
    private String createUserName;//创建人名
    @ApiModelProperty(value = "创建时间")
    private Date createTime;//创建时间
    @ApiModelProperty(value = "修改人")
    private String updateUser;//修改人
    @ApiModelProperty(value = "修改人名称")
    private String updateUserName;//修改人名称
    @ApiModelProperty(value = "修改时间")
    private Date updateTime;//修改时间
    private String remark;
    private List<Map<String,Object>> children = new ArrayList<>();
    private String state;
    private Integer status;  //状态 -1删除 0 冻结 1可用
    public String getId() {
        return id;
@ -35,23 +51,6 @@ public class WxTemplateVO {
        this.id = id;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getTitle() {
        return title;
    }
@ -60,20 +59,12 @@ public class WxTemplateVO {
        this.title = title;
    }
    public String getWechatCode() {
        return wechatCode;
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatCode(String wechatCode) {
        this.wechatCode = wechatCode;
    }
    public String getWechatName() {
        return wechatName;
    }
    public void setWechatName(String wechatName) {
        this.wechatName = wechatName;
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    public String getTemplateId() {
@ -84,6 +75,14 @@ public class WxTemplateVO {
        this.templateId = templateId;
    }
    public String getTemplateName() {
        return templateName;
    }
    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
    public String getContent() {
        return content;
    }
@ -92,6 +91,22 @@ public class WxTemplateVO {
        this.content = content;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getCreateUser() {
        return createUser;
    }
@ -139,28 +154,4 @@ public class WxTemplateVO {
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getName() {
        return title;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Map<String, Object>> getChildren() {
        return children;
    }
    public void setChildren(List<Map<String, Object>> children) {
        this.children = children;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
}

+ 4 - 1
common/common-util/pom.xml

@ -61,6 +61,9 @@
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>
    </dependencies>
</project>

+ 15 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/AllowAllHostnameVerifier.java

@ -0,0 +1,15 @@
package com.yihu.jw.util.http;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
/**
 * @author Air
 * @version 1.0
 * @created 2015.07.02 15:48
 */
public class AllowAllHostnameVerifier implements HostnameVerifier {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

+ 100 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/CustomTrustClientClientImpl.java

@ -0,0 +1,100 @@
package com.yihu.jw.util.http;
import okhttp3.OkHttpClient;
import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
/**
 * 用于非受信证书的HTTPS访问
 *
 * @created Airhead 2016/8/24.
 */
class CustomTrustClientClientImpl extends DefaultClientImpl {
    CustomTrustClientClientImpl() {
        try {
            final TrustManager[] trustManagers = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }
                        @Override
                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };
            final SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(socketFactory, (X509TrustManager) trustManagers[0])
                    .hostnameVerifier(new AllowAllHostnameVerifier()).build();
            setHttpClient(httpClient);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }
    CustomTrustClientClientImpl(String path, String password) {
        try {
            InputStream inputStream = new FileInputStream(new File(path));
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(inputStream);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream in = null;
            keyStore.load(in, password.toCharArray());
            int index = 0;
            for (Certificate certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificate);
            }
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password.toCharArray());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(inputStream, password.toCharArray());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509KeyManager)) {
                throw new IllegalStateException("Unexpectd default trust managers:" + Arrays.toString(trustManagers));
            }
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(socketFactory, (X509TrustManager) trustManagers[0])
                    .hostnameVerifier(new AllowAllHostnameVerifier()).build();
            setHttpClient(httpClient);
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException | KeyManagementException | UnrecoverableKeyException e) {
            e.printStackTrace();
        }
    }
}

+ 336 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/DefaultClientImpl.java

@ -0,0 +1,336 @@
package com.yihu.jw.util.http;
import okhttp3.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @author Airhead
 * @since 2016/8/24.
 */
class DefaultClientImpl implements HTTPClient {
    private static final Log log = LogFactory.getLog(DefaultClientImpl.class);
    private OkHttpClient httpClient;
    DefaultClientImpl() {
        this.httpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS).build();
    }
    public HTTPResponse get(String url) {
        return get(url, null);
    }
    public HTTPResponse get(String url, Map<String, String> params) {
        return get(url, params, null);
    }
    public HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(formatURL(url, params))
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            // ?? 怎么把异常处理了??  应该交由调用者处理
            ex.printStackTrace();
            log.error(ex.getMessage());
            return new HTTPResponse(417,ex.getMessage());
        }
    }
    public HTTPResponse post(String url) {
        return post(url, (Map<String, String>) null);
    }
    public HTTPResponse post(String url, Map<String, String> params) {
        return post(url, params, null);
    }
    public HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            FormBody.Builder fromBodyBuilder = new FormBody.Builder();
            if (params != null) {
                params.forEach(fromBodyBuilder::add);
            }
            RequestBody requestBody = fromBodyBuilder
                    .build();
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(url)
                    .post(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            //讲异常信息返回,交由调用者处理
            log.error(ex.getMessage());
            return new HTTPResponse(417,ex.getMessage());
        }
    }
    @Override
    public HTTPResponse post(String url, String json, Map<String, String> headers) {
        try {
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = builder
                    .url(url)
                    .post(body)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse postFile(String url, String path) {
        return postFile(url, path, null);
    }
    public HTTPResponse postFile(String url, String path, Map<String, String> params) {
        return postFile(url, path, params, null);
    }
    public HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers) {
        try {
            File file = new File(path);
            final MediaType type = MediaType.parse("application/zip");
            Request.Builder requestBuilder = new Request.Builder();
            if (headers != null) {
                requestBuilder.headers(Headers.of(headers));
            }
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
            multipartBuilder.setType(MultipartBody.FORM)
                    .addFormDataPart("pack", file.getName(), RequestBody.create(type, file));
            for (String key : params.keySet()) {
                multipartBuilder.addFormDataPart(key, params.get(key));
            }
            Request request = requestBuilder
                    .url(url)
                    .post(multipartBuilder.build())
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    @Override
    public HTTPResponse postFile(String url, String key, String path, String contentType) {
        try {
            File file = new File(path);
            final MediaType type = MediaType.parse(contentType);
            Request.Builder requestBuilder = new Request.Builder();
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
            multipartBuilder.setType(MultipartBody.FORM)
                    .addFormDataPart(key, file.getName(), RequestBody.create(type, file));
            Request request = requestBuilder
                    .url(url)
                    .post(multipartBuilder.build())
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse put(String url) {
        return put(url, (Map<String, String>) null);
    }
    public HTTPResponse put(String url, Map<String, String> params) {
        return put(url, params, null);
    }
    @Override
    public HTTPResponse put(String url, String json) {
        try {
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .put(body)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            FormBody.Builder fromBodyBuilder = new FormBody.Builder();
            if (params != null) {
                params.forEach(fromBodyBuilder::add);
            }
            RequestBody requestBody = fromBodyBuilder
                    .build();
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(url)
                    .put(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse delete(String url) {
        return delete(url, (Map<String, String>) null);
    }
    public HTTPResponse delete(String url, Map<String, String> params) {
        return delete(url, params, null);
    }
    @Override
    public HTTPResponse delete(String url, String json) {
        try {
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .delete(body)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            FormBody.Builder fromBodyBuilder = new FormBody.Builder();
            if (params != null) {
                params.forEach(fromBodyBuilder::add);
            }
            RequestBody requestBody = fromBodyBuilder
                    .build();
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(url)
                    .delete(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers) {
        if (method.equals(POST)) {
            return post(url, params, headers);
        }
        if (method.equals(GET)) {
            return get(url, params, headers);
        }
        if (method.equals(PUT)) {
            return put(url, params, headers);
        }
        if (method.equals(DELETE)) {
            return delete(url, params, headers);
        }
        return get(url, params, headers);
    }
    protected void setHttpClient(OkHttpClient okHttpClient) {
        this.httpClient = okHttpClient;
    }
    private String formatURL(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }
        final String[] query = {""};
        params.forEach((name, value) -> {
            try {
                query[0] += "&" + name + "=" + URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("encode url ");
            }
        });
        if (url.contains("?")) {
            return url + query[0];
        }
        return url + "?" + query[0].substring(1);
    }
}

+ 54 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/HTTPClient.java

@ -0,0 +1,54 @@
package com.yihu.jw.util.http;
import java.util.Map;
/**
 * @created Airhead 2016/8/24.
 */
public interface HTTPClient {
    //主要的几种方法,其他的暂时未使用
    String GET = "GET";
    String POST = "POST";
    String PUT = "PUT";
    String DELETE = "DELETE";
    HTTPResponse get(String url);
    HTTPResponse get(String url, Map<String, String> params);
    HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse post(String url);
    HTTPResponse post(String url, Map<String, String> params);
    HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse post(String url, String json, Map<String, String> headers);
    HTTPResponse postFile(String url, String path);
    HTTPResponse postFile(String url, String path, Map<String, String> params);
    HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers);
    HTTPResponse postFile(String url, String key, String path, String contentType);
    HTTPResponse put(String url);
    HTTPResponse put(String url, Map<String, String> params);
    HTTPResponse put(String url, String json);
    HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse delete(String url);
    HTTPResponse delete(String url, Map<String, String> params);
    HTTPResponse delete(String url, String json);
    HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers);
}

+ 23 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/HTTPResponse.java

@ -0,0 +1,23 @@
package com.yihu.jw.util.http;
/**
 * @created Airhead 2016/8/24.
 */
public class HTTPResponse {
    private final int statusCode;// e.g. 200
    private final String body;
    public HTTPResponse(int statusCode, String body) {
        this.statusCode = statusCode;
        this.body = body;
    }
    public int getStatusCode() {
        return statusCode;
    }
    public String getBody() {
        return body;
    }
}

+ 155 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientKit.java

@ -0,0 +1,155 @@
package com.yihu.jw.util.http;
import javafx.util.Pair;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import java.util.HashMap;
import java.util.Map;
/**
 * @created Airhead 2016/8/24.
 */
public class HttpClientKit {
    private static Map<String, Pair<String, String>> keyStoreMap = new HashMap<>();
    private static Map<String, SSLConnectionSocketFactory> keyStoreSSLMap = new HashMap<>();
    /**
     * 用于HTTP和受信HTTPS
     *
     * @return
     */
    public static HTTPClient use() {
        return new DefaultClientImpl();
    }
    /**
     * 用于非受信HTTPS
     *
     * @param host host正常情况是不需要包含端口号的。
     *             但在非域名(或开发)时,不同的端口会使用不同证书,
     *             在添加host时,可以增加端口号
     *             格式:
     *             1.ip:port
     *             2.domain
     * @return
     */
    public static HTTPClient custom(String host) {
        if (host != null) {
            Pair<String, String> keyStore = keyStoreMap.get(host);
            if (keyStore != null) {
                return new CustomTrustClientClientImpl(keyStore.getKey(), keyStore.getValue());
            }
        }
        return new CustomTrustClientClientImpl();
    }
    public static void addKeyStore(String host, String file, String password) throws Exception {
        keyStoreMap.put(host, new Pair<>(file, password));
    }
    public static void addKeyStoreSSL(String host, SSLConnectionSocketFactory sslConnectionSocketFactory) throws Exception {
        keyStoreSSLMap.put(host, sslConnectionSocketFactory);
    }
    public static HTTPResponse get(String url) {
        return use().get(url);
    }
    public static HTTPResponse get(String url, Map<String, String> params) {
        return use().get(url, params);
    }
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers) {
        return use().get(url, params, headers);
    }
    public static HTTPResponse post(String url) {
        return use().post(url);
    }
    public static HTTPResponse post(String url, Map<String, String> params) {
        return use().post(url, params);
    }
    public static HTTPResponse post(String url, String json) {
        return use().post(url, json, null);
    }
    public static HTTPResponse post(String url, String json, Map<String, String> headers) {
        return use().post(url, json, headers);
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers) {
        return use().post(url, params, headers);
    }
    public static HTTPResponse postFile(String url, String path) {
        return use().postFile(url, path);
    }
    public static HTTPResponse postFile(String url, String path, Map<String, String> params) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, path, params);
        } else {
            return use().postFile(url, path, params);
        }
    }
    public static HTTPResponse postFile(String url, String key, String path, String contentType) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, key, path, contentType);
        } else {
            return use().postFile(url, key, path, contentType);
        }
    }
    public static HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, path, params, headers);
        } else {
            return use().postFile(url, path, params, headers);
        }
    }
    public static HTTPResponse put(String url) {
        return use().put(url);
    }
    public static HTTPResponse put(String url, Map<String, String> params) {
        return use().put(url, params);
    }
    public static HTTPResponse put(String url, String json) {
        return use().put(url, json);
    }
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers) {
        return use().put(url, params, headers);
    }
    public static HTTPResponse delete(String url) {
        return use().delete(url);
    }
    public static HTTPResponse delete(String url, Map<String, String> params) {
        return use().delete(url, params);
    }
    public static HTTPResponse delete(String url, String json) {
        return use().delete(url, json);
    }
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers) {
        return use().delete(url, params, headers);
    }
    public static HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers) {
        if (url.startsWith("https")) {
            return custom(url).request(method, url, params, headers);
        } else {
            return use().request(method, url, params, headers);
        }
    }
}

+ 107 - 0
common/common-util/src/main/java/com/yihu/jw/util/security/RandomValidateCode.java

@ -0,0 +1,107 @@
package com.yihu.jw.util.security;
/**
 * Created by progr1mmer on 2018/2/5.
 */
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
 * @author Yingjie Chen
 * @date 2016/5/24
 */
public class RandomValidateCode {
    public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
    private Random random = new Random();
    private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
    private int width = 80;//图片宽
    private int height = 26;//图片高
    private int lineSize = 40;//干扰线数量
    private int stringNum = 4;//随机产生字符数量
    /*
     * 获得字体
     */
    private Font getFont(){
        return new Font("Fixedsys", Font.CENTER_BASELINE,18);
    }
    /*
     * 获得颜色
     */
    private Color getRandColor(int fc,int bc){
        if(fc > 255)
            fc = 255;
        if(bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc-fc-16);
        int g = fc + random.nextInt(bc-fc-14);
        int b = fc + random.nextInt(bc-fc-18);
        return new Color(r,g,b);
    }
    /**
     * 生成随机图片
     */
    public void getRandcode(HttpServletRequest request,
                            HttpServletResponse response) {
        HttpSession session = request.getSession();
        //BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();//产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
        g.setColor(getRandColor(110, 133));
        //绘制干扰线
        for(int i=0;i<=lineSize;i++){
            drowLine(g);
        }
        //绘制随机字符
        String randomString = "";
        for(int i = 1; i <= stringNum; i++){
            randomString= drowString(g, randomString,i);
        }
        session.removeAttribute(RANDOMCODEKEY);
        session.setAttribute(RANDOMCODEKEY, randomString);
        System.out.println(randomString);
        response.addCookie(new Cookie(RANDOMCODEKEY,randomString));
        g.dispose();
        try {
            ImageIO.write(image, "JPEG", response.getOutputStream());//将内存中的图片通过流动形式输出到客户端
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * 绘制字符串
     */
    private String drowString(Graphics g,String randomString,int i){
        g.setFont(getFont());
        g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
        String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
        randomString +=rand;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 13*i, 16);
        return randomString;
    }
    /*
     * 绘制干扰线
     */
    private void drowLine(Graphics g){
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x+xl, y+yl);
    }
    /*
     * 获取随机的字符
     */
    public String getRandomString(int num){
        return String.valueOf(randString.charAt(num));
    }
}

+ 36 - 19
gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/BasicZuulFilter.java

@ -10,12 +10,14 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@ -34,6 +36,8 @@ public class BasicZuulFilter extends ZuulFilter {
    private ObjectMapper objectMapper;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public String filterType() {
@ -64,6 +68,13 @@ public class BasicZuulFilter extends ZuulFilter {
        return this.authenticate(ctx, request, url);
    }
    /**
     * 验证token 权限地址
     * @param ctx
     * @param request
     * @param path
     * @return
     */
    private Object authenticate(RequestContext ctx, HttpServletRequest request, String path) {
        String accessToken = this.extractToken(request);
        if (null == accessToken) {
@ -76,26 +87,32 @@ public class BasicZuulFilter extends ZuulFilter {
        if (oAuth2AccessToken.isExpired()) {
            return this.forbidden(ctx, HttpStatus.PAYMENT_REQUIRED.value(), "expired token"); //返回402 登陆过期
        }
//        //将token的认证信息附加到请求中,转发给下游微服务
//        OAuth2Authentication auth = tokenStore.readAuthentication(accessToken);
//        ctx.addZuulRequestHeader("x-auth-name", auth.getName());
//        //以下代码取消注释可开启Oauth2应用资源授权验证
        //将token的认证信息附加到请求中,转发给下游微服务
        OAuth2Authentication auth = tokenStore.readAuthentication(accessToken);
        ctx.addZuulRequestHeader("x-auth-name", auth.getName());
        //以下代码取消注释可开启Oauth2应用资源授权验证
//        Set<String> resourceIds = auth.getOAuth2Request().getResourceIds();
//        for (String resourceId : resourceIds) {
//            if (resourceId.equals("*")) {
//                return true;
//            }
//            if (!resourceId.startsWith("/")) {
//                resourceId = "/" + resourceId;
//            }
//            path = path.toLowerCase();
//            if (path.startsWith(resourceId)
//                    && (path.length() == resourceId.length() || path.charAt(resourceId.length()) == '/')) {
//                return true;
//            }
//        }
//        return this.forbidden(ctx, HttpStatus.FORBIDDEN.value(), "invalid token does not contain request resource " + path);
        return true;
        String urls = redisTemplate.opsForValue().get("wlyy2:auth:token:"+accessToken);
        if(StringUtils.isEmpty(urls)){
           return this.forbidden(ctx, HttpStatus.FORBIDDEN.value(), "invalid token does not contain request resource " + path);
        }
        //获取所有token资源
        String resourceIds[] = urls.split(",");
        for (String resourceId : resourceIds) {
            if (resourceId.equals("/**")) {
                return true;
            }
            if (!resourceId.startsWith("/")) {
                resourceId = "/" + resourceId;
            }
            path = path.toLowerCase();
            if (path.startsWith(resourceId)
                    && (path.length() == resourceId.length() || path.charAt(resourceId.length()) == '/')) {
                return true;
            }
        }
        return this.forbidden(ctx, HttpStatus.FORBIDDEN.value(), "invalid token does not contain request resource " + path);
    }
    private String extractToken(HttpServletRequest request) {

+ 232 - 0
gateway/ag-basic/src/main/java/com/yihu/jw/security/core/userdetails/SaltUser.java

@ -0,0 +1,232 @@
package com.yihu.jw.security.core.userdetails;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
import java.io.Serializable;
import java.util.*;
/**
 * Created by progr1mmer on 2018/8/29.
 */
public class SaltUser implements UserDetails, CredentialsContainer {
    private static final long serialVersionUID = 420L;
    private String password;
    private final String username;
    private final Set<GrantedAuthority> authorities;
    private final boolean accountNonExpired;
    private final boolean accountNonLocked;
    private final boolean credentialsNonExpired;
    private final boolean enabled;
    private final String salt;
    public SaltUser(String username, String password, String salt, Collection<? extends GrantedAuthority> authorities) {
        this(username, password, salt, true, true, true, true, authorities);
    }
    public SaltUser(String username, String password, String salt, boolean enabled, boolean locked, Collection<? extends GrantedAuthority> authorities) {
        this(username, password, salt, enabled, true, true, !locked, authorities);
    }
    public SaltUser(String username, String password, String salt, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        if(username != null && !"".equals(username) && password != null) {
            this.username = username;
            this.password = password;
            this.salt = salt;
            this.enabled = enabled;
            this.accountNonExpired = accountNonExpired;
            this.credentialsNonExpired = credentialsNonExpired;
            this.accountNonLocked = accountNonLocked;
            this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
        } else {
            throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
        }
    }
    public Collection<GrantedAuthority> getAuthorities() {
        return this.authorities;
    }
    public String getPassword() {
        return this.password;
    }
    public String getUsername() {
        return this.username;
    }
    public String getSalt() {
        return salt;
    }
    public boolean isEnabled() {
        return this.enabled;
    }
    public boolean isAccountNonExpired() {
        return this.accountNonExpired;
    }
    public boolean isAccountNonLocked() {
        return this.accountNonLocked;
    }
    public boolean isCredentialsNonExpired() {
        return this.credentialsNonExpired;
    }
    public void eraseCredentials() {
        this.password = null;
    }
    private static SortedSet<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities) {
        Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
        SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet(new SaltUser.AuthorityComparator());
        Iterator var2 = authorities.iterator();
        while(var2.hasNext()) {
            GrantedAuthority grantedAuthority = (GrantedAuthority)var2.next();
            Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
            sortedAuthorities.add(grantedAuthority);
        }
        return sortedAuthorities;
    }
    public boolean equals(Object rhs) {
        return rhs instanceof SaltUser ?this.username.equals(((SaltUser)rhs).username):false;
    }
    public int hashCode() {
        return this.username.hashCode();
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString()).append(": ");
        sb.append("Username: ").append(this.username).append("; ");
        sb.append("Password: [PROTECTED]; ");
        sb.append("Enabled: ").append(this.enabled).append("; ");
        sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");
        sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; ");
        sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");
        if(!this.authorities.isEmpty()) {
            sb.append("Granted Authorities: ");
            boolean first = true;
            Iterator var3 = this.authorities.iterator();
            while(var3.hasNext()) {
                GrantedAuthority auth = (GrantedAuthority)var3.next();
                if(!first) {
                    sb.append(",");
                }
                first = false;
                sb.append(auth);
            }
        } else {
            sb.append("Not granted any authorities");
        }
        return sb.toString();
    }
    public static SaltUser.UserBuilder withUsername(String username) {
        return (new SaltUser.UserBuilder()).username(username);
    }
    public static class UserBuilder {
        private String username;
        private String password;
        private List<GrantedAuthority> authorities;
        private boolean accountExpired;
        private boolean accountLocked;
        private boolean credentialsExpired;
        private boolean disabled;
        private UserBuilder() {
        }
        private SaltUser.UserBuilder username(String username) {
            Assert.notNull(username, "username cannot be null");
            this.username = username;
            return this;
        }
        public SaltUser.UserBuilder password(String password) {
            Assert.notNull(password, "password cannot be null");
            this.password = password;
            return this;
        }
        public SaltUser.UserBuilder roles(String... roles) {
            List<GrantedAuthority> authorities = new ArrayList(roles.length);
            String[] var3 = roles;
            int var4 = roles.length;
            for(int var5 = 0; var5 < var4; ++var5) {
                String role = var3[var5];
                Assert.isTrue(!role.startsWith("ROLE_"), role + " cannot start with ROLE_ (it is automatically added)");
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
            }
            return this.authorities((List)authorities);
        }
        public SaltUser.UserBuilder authorities(GrantedAuthority... authorities) {
            return this.authorities(Arrays.asList(authorities));
        }
        public SaltUser.UserBuilder authorities(List<? extends GrantedAuthority> authorities) {
            this.authorities = new ArrayList(authorities);
            return this;
        }
        public SaltUser.UserBuilder authorities(String... authorities) {
            return this.authorities(AuthorityUtils.createAuthorityList(authorities));
        }
        public SaltUser.UserBuilder accountExpired(boolean accountExpired) {
            this.accountExpired = accountExpired;
            return this;
        }
        public SaltUser.UserBuilder accountLocked(boolean accountLocked) {
            this.accountLocked = accountLocked;
            return this;
        }
        public SaltUser.UserBuilder credentialsExpired(boolean credentialsExpired) {
            this.credentialsExpired = credentialsExpired;
            return this;
        }
        public SaltUser.UserBuilder disabled(boolean disabled) {
            this.disabled = disabled;
            return this;
        }
        public UserDetails build() {
            return new User(this.username, this.password, !this.disabled, !this.accountExpired, !this.credentialsExpired, !this.accountLocked, this.authorities);
        }
    }
    private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {
        private static final long serialVersionUID = 420L;
        private AuthorityComparator() {
        }
        public int compare(GrantedAuthority g1, GrantedAuthority g2) {
            return g2.getAuthority() == null?-1:(g1.getAuthority() == null?1:g1.getAuthority().compareTo(g2.getAuthority()));
        }
    }
}

+ 17 - 0
gateway/ag-basic/src/main/resources/application.yml

@ -19,6 +19,15 @@ spring:
    test-while-idle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
    min-evictable-idle-time-millis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
    time-between-eviction-runs-millis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
  redis:
    database: 0 # Database index used by the connection factory.
    timeout: 0 # Connection timeout in milliseconds.
    pool:
      max-active: 8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
      max-idle: 8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
      max-wait: -1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
      min-idle: 1 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
#  sleuth:
#    sampler:
#      percentage: 1.0 #采用需要的请求的百分比 默认是0.1 即 10%
@ -37,6 +46,10 @@ zuul:
    svr-authentication:
      path: /auth/**
      serviceId: svr-authentication
    svr-healthy-house:
      path: /healthyHouse/**
      serviceId: svr-healthy-house
---
spring:
@ -45,6 +58,10 @@ spring:
    url: jdbc:mysql://172.19.103.77/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true
    username: root
    password: 123456
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
#    password: jkzl_ehr
#  zipkin:
#    base-url: http://localhost:9411 #日志追踪的地址

+ 7 - 3
server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java

@ -5,7 +5,7 @@ import com.yihu.jw.security.model.WlyyUserDetails;
import com.yihu.jw.security.model.WlyyUserSimple;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.core.GrantedAuthority;
@ -13,6 +13,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@ -22,6 +23,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * Service - 用户信息
@ -243,10 +245,12 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
    }
    public boolean setRolePhth(String loginType, String token, String id, RedisTemplate redisTemplate){
    public boolean setRolePhth(String loginType, OAuth2AccessToken token, String id, StringRedisTemplate redisTemplate){
        if(org.apache.commons.lang.StringUtils.isBlank(loginType)||"1".equals(loginType)){ //1或默认查找user表,为平台管理员账号
            String key = "wlyy2:auth:token:"+token.getValue();
            redisTemplate.opsForValue().set(key,"/**");
            redisTemplate.expire(key,token.getExpiresIn(), TimeUnit.SECONDS);
        }else if("2".equals(loginType)){//2.为医生账号
        }else if("3".equals(loginType)){ //3.患者账号

+ 16 - 5
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java

@ -1,23 +1,27 @@
package com.yihu.jw.security.oauth2.provider.endpoint;
import com.yihu.jw.security.core.userdetails.jdbc.WlyyUserDetailsService;
import com.yihu.jw.security.model.Captcha;
import com.yihu.jw.security.model.Oauth2Envelop;
import com.yihu.jw.security.model.PublicKey;
import com.yihu.jw.security.model.WlyyUserSimple;
import com.yihu.jw.security.oauth2.core.redis.WlyyRedisVerifyCodeService;
import com.yihu.jw.security.oauth2.provider.error.WlyyOAuth2ExceptionTranslator;
import com.yihu.jw.security.oauth2.provider.WlyyTokenGranter;
import com.yihu.jw.security.core.userdetails.jdbc.WlyyUserDetailsService;
import com.yihu.jw.security.model.Oauth2Envelop;
import com.yihu.jw.security.model.WlyyUserSimple;
import com.yihu.jw.security.oauth2.provider.error.WlyyOAuth2ExceptionTranslator;
import com.yihu.utils.security.RSAUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.endpoint.AbstractEndpoint;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
@ -80,6 +84,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    private RestTemplate restTemplate;
    @Autowired
    private WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostConstruct
    private void init() {
@ -149,6 +155,11 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        wlyyUserSimple.setRefreshToken(token.getRefreshToken().getValue());
        wlyyUserSimple.setUser(parameters.get("username"));
        wlyyUserSimple.setState(parameters.get("state"));
        String loginType = parameters.get("login_type");
        userDetailsService.setRolePhth(loginType,token,wlyyUserSimple.getId(),redisTemplate);
        return getResponse(wlyyUserSimple);
    }

+ 3 - 3
server/svr-authentication/src/main/resources/application.yml

@ -32,7 +32,7 @@ spring:
    username: root
    password: 123456
  redis:
    host: 172.19.103.47
    port: 6379
    password: redis!@456
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
#    password: jkzl_ehr

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/contant/MenuContant.java

@ -1,10 +1,10 @@
package com.yihu.jw.base.contant;
/**
 * 菜单常量
 * 常量
 * @author yeshijie on 2018/9/27.
 */
public class MenuContant {
public class CommonContant {
    /**
     * 默认父类id 0

+ 19 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/InterfaceDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.base.dao.module;
import com.yihu.jw.entity.base.module.InterfaceDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 接口
 * @author yeshijie on 2018/9/28.
 */
public interface InterfaceDao extends PagingAndSortingRepository<InterfaceDO, String>, JpaSpecificationExecutor<InterfaceDO> {
    @Modifying
    @Query("update InterfaceDO p set p.status=?2 where p.id=?1")
    void updateStatus(String id,Integer status);
}

+ 23 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/InterfaceErrorCodeDao.java

@ -0,0 +1,23 @@
package com.yihu.jw.base.dao.module;
import com.yihu.jw.entity.base.module.InterfaceErrorCodeDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 接口错误说明
 * @author yeshijie on 2018/9/28.
 */
public interface InterfaceErrorCodeDao extends PagingAndSortingRepository<InterfaceErrorCodeDO, String>, JpaSpecificationExecutor<InterfaceErrorCodeDO> {
    @Query("from InterfaceErrorCodeDO w where w.interfaceId =?1 and w.del=1")
    List<InterfaceErrorCodeDO> findByInterfaceId(String interfaceId);
    @Modifying
    @Query("delete from InterfaceErrorCodeDO p where p.interfaceId=?1")
    void deleteByInterfaceId(String interfaceId);
}

+ 23 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/InterfaceParamDao.java

@ -0,0 +1,23 @@
package com.yihu.jw.base.dao.module;
import com.yihu.jw.entity.base.module.InterfaceParamDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 接口入参出参
 * @author yeshijie on 2018/9/28.
 */
public interface InterfaceParamDao extends PagingAndSortingRepository<InterfaceParamDO, String>, JpaSpecificationExecutor<InterfaceParamDO> {
    @Query("from InterfaceParamDO w where w.interfaceId =?1 and w.del=1")
    List<InterfaceParamDO> findByInterfaceId(String interfaceId);
    @Modifying
    @Query("delete from InterfaceParamDO p where p.interfaceId=?1")
    void deleteByInterfaceId(String interfaceId);
}

+ 8 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/module/ModuleDao.java

@ -2,6 +2,8 @@ package com.yihu.jw.base.dao.module;
import com.yihu.jw.entity.base.module.ModuleDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
@ -10,4 +12,10 @@ import org.springframework.data.repository.PagingAndSortingRepository;
 */
public interface ModuleDao extends PagingAndSortingRepository<ModuleDO, String>, JpaSpecificationExecutor<ModuleDO> {
    @Modifying
    @Query("update ModuleDO p set p.status=?2 where p.id=?1")
    void updateStatus(String id,Integer status);
    @Query("select count(*) from ModuleDO a where a.name = ?1 ")
    int isExistName(String name);
}

+ 16 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/notice/NoticeDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.base.dao.notice;
import com.yihu.jw.entity.base.notice.NoticeDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 公告通知
 * @author yeshijie on 2018/9/30.
 */
public interface NoticeDao extends PagingAndSortingRepository<NoticeDO, String>, JpaSpecificationExecutor<NoticeDO> {
    List<NoticeDO> findByStatusAndSendType(Integer status,Integer sendType);
}

+ 14 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/notice/UserNoticeDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.base.dao.notice;
import com.yihu.jw.entity.base.notice.UserNoticeDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 用户公告通知
 * @author yeshijie on 2018/9/30.
 */
public interface UserNoticeDao extends PagingAndSortingRepository<UserNoticeDO, String>, JpaSpecificationExecutor<UserNoticeDO> {
}

+ 4 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/user/UserDao.java

@ -4,9 +4,13 @@ import com.yihu.jw.entity.base.user.UserDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Dao - 后台管理员
 * Created by progr1mmer on 2018/8/20.
 */
public interface UserDao extends PagingAndSortingRepository<UserDO, String>, JpaSpecificationExecutor<UserDO> {
    List<UserDO> findByEnabled(boolean enabled);
}

+ 11 - 14
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicMessageDao.java

@ -1,15 +1,12 @@
package com.yihu.jw.base.dao.wx;//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.base.wx.WxGraphicMessageDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//public interface WxGraphicMessageDao extends PagingAndSortingRepository<WxGraphicMessageDO, String>, JpaSpecificationExecutor<WxGraphicMessageDO> {
//
//    @Query("from WxGraphicMessageDO w where w.id =?1 and w.status!=-1")
//    WxGraphicMessageDO findById(String id);
//}
import com.yihu.jw.entity.base.wx.WxGraphicMessageDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
public interface WxGraphicMessageDao extends PagingAndSortingRepository<WxGraphicMessageDO, String>, JpaSpecificationExecutor<WxGraphicMessageDO> {
}

+ 11 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicSceneDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxGraphicSceneDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2018/10/9.
 */
public interface WxGraphicSceneDao extends PagingAndSortingRepository<WxGraphicSceneDO, String>, JpaSpecificationExecutor<WxGraphicSceneDO> {
}

+ 20 - 20
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxTemplateDao.java

@ -1,21 +1,21 @@
package com.yihu.jw.base.dao.wx;//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.base.wx.WxTemplateDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//public interface WxTemplateDao extends PagingAndSortingRepository<WxTemplateDO, String>, JpaSpecificationExecutor<WxTemplateDO> {
//
//
//    @Query("from WxTemplateDO w where w.id = ?1 and w.status =1")
//    WxTemplateDO findById(String id);
//
//    @Query("from WxTemplateDO w where w.wechatId = ?1 and w.status =1")
//    List<WxTemplateDO> findByWxId(String wechatId);
//}
import com.yihu.jw.entity.base.wx.WxTemplateDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
public interface WxTemplateDao extends PagingAndSortingRepository<WxTemplateDO, String>, JpaSpecificationExecutor<WxTemplateDO> {
    @Query("from WxTemplateDO w where w.id = ?1 and w.status =1")
    WxTemplateDO findById(String id);
    @Query("from WxTemplateDO w where w.wechatId = ?1 and w.status =1")
    List<WxTemplateDO> findByWxId(String wechatId);
}

+ 14 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxWechatSaasDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxWechatSaasDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2018/10/8.
 */
public interface WxWechatSaasDao  extends PagingAndSortingRepository<WxWechatSaasDO, String>, JpaSpecificationExecutor<WxWechatSaasDO> {
    List<WxWechatSaasDO> findByWechatId(String wechatId);
}

+ 165 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/common/FileUploadController.java

@ -0,0 +1,165 @@
package com.yihu.jw.base.endpoint.common;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.base.util.ErrorCodeUtil;
import com.yihu.jw.exception.code.BaseErrorCode;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Base64;
/**
 * 文件上传不在微服务中处理
 * @author yeshijie on 2017/12/7.
 */
@RestController
@RequestMapping(BaseRequestMapping.FileUpload.PREFIX)
@Api(tags = "文件上传相关操作", description = "文件上传相关操作")
public class FileUploadController extends EnvelopRestEndpoint {
    @Autowired
    private FastDFSUtil fastDFSHelper;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Autowired
    private ErrorCodeUtil errorCodeUtil;
    @PostMapping(value = BaseRequestMapping.FileUpload.UPLOAD_STREAM_IMG)
    @ApiOperation(value = "文件流上传图片", notes = "文件流上传图片")
    public ObjEnvelop<UploadVO> uploadImg(@ApiParam(value = "文件", required = true)
                                       @RequestParam(value = "file", required = true) MultipartFile file) throws Exception{
        // 得到文件的完整名称  xxx.txt
        String fullName = file.getOriginalFilename();
        if(StringUtils.isBlank(fullName)){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FAIL_UPLOAD_FORMAT), ObjEnvelop.class);
        }
        //得到文件类型
        String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
        if(StringUtils.isBlank(fileType)||!"jpg,jpeg,png".contains(fileType)){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FAIL_UPLOAD_FORMAT), ObjEnvelop.class);
        }
        long size = file.getSize();
        long max = 5*1024*1024;
        if(size>max){
            String msg = String.format(BaseErrorCode.FileUpload.FAIL_FILE_SIZE, 5);
            return failed(msg, ObjEnvelop.class);
        }
        String fileName = fullName.substring(0, fullName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return success("上传成功", uploadVO);
    }
    @PostMapping(value = BaseRequestMapping.FileUpload.UPLOAD_STREAM_ATTACHMENT)
    @ApiOperation(value = "文件流上传附件", notes = "文件流上传附件")
    public ObjEnvelop<UploadVO> uploadAttachment(@ApiParam(value = "文件", required = true)
                                       @RequestParam(value = "file", required = true) MultipartFile file) throws Exception{
        // 得到文件的完整名称  xxx.txt
        String fullName = file.getOriginalFilename();
        if(StringUtils.isBlank(fullName)){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FAIL_UPLOAD_FORMAT), ObjEnvelop.class);
        }
        //得到文件类型
        String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
        if(StringUtils.isBlank(fileType)||!"doc、docx、pdf、xls、xlsx、jpg、jpeg、png".contains(fileType)){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FAIL_UPLOAD_FORMAT), ObjEnvelop.class);
        }
        long size = file.getSize();
        long max = 5*1024*1024;
        if(size>max){
            String msg = String.format(BaseErrorCode.FileUpload.FAIL_FILE_SIZE, 5);
            return failed(msg, ObjEnvelop.class);
        }
        String fileName = fullName.substring(0, fullName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return success("上传成功", uploadVO);
    }
    @PostMapping(value = BaseRequestMapping.FileUpload.UPLOAD_STREAM)
    @ApiOperation(value = "文件流上传文件", notes = "文件流上传文件")
    public ObjEnvelop<UploadVO> uploadStream(@ApiParam(value = "文件", required = true)
        @RequestParam(value = "file", required = true) MultipartFile file) throws Exception{
        // 得到文件的完整名称  xxx.txt
        String fullName = file.getOriginalFilename();
        //得到文件类型
        String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
        String fileName = fullName.substring(0, fullName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return success("上传成功", uploadVO);
    }
    @PostMapping(value = BaseRequestMapping.FileUpload.UPLOAD_STRING)
    @ApiOperation(value = "base64上传图片",notes = "base64上传图片")
    public ObjEnvelop<UploadVO> uploadImages(@ApiParam(name = "jsonData", value = "头像转化后的输入流")
                                                 @RequestBody String jsonData) throws Exception {
        if(jsonData == null){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FILE_NULL), ObjEnvelop.class);
        }
        String date = URLDecoder.decode(jsonData,"UTF-8");
        String[] fileStreams = date.split(",");
        String is = URLDecoder.decode(fileStreams[1],"UTF-8").replace(" ","+");
        byte[] in = Base64.getDecoder().decode(is);
        String pictureName = fileStreams[0].substring(0,fileStreams[0].length()-1);
        String fileExtension = pictureName.substring(pictureName.lastIndexOf(".") + 1).toLowerCase();
        String description = null;
        if ((pictureName != null) && (pictureName.length() > 0)) {
            int dot = pictureName.lastIndexOf('.');
            if ((dot > -1) && (dot < (pictureName.length()))) {
                description = pictureName.substring(0, dot);
            }
        }
        InputStream inputStream = new ByteArrayInputStream(in);
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, "png", "");
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(remoteFileName);
        uploadVO.setFileType(groupName);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        //返回文件路径
        return success("上传成功", uploadVO);
    }
}

+ 121 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/module/InterfaceEndpoint.java

@ -0,0 +1,121 @@
package com.yihu.jw.base.endpoint.module;
import com.yihu.jw.base.service.module.InterfaceService;
import com.yihu.jw.base.util.ErrorCodeUtil;
import com.yihu.jw.entity.base.module.InterfaceDO;
import com.yihu.jw.exception.code.BaseErrorCode;
import com.yihu.jw.restmodel.base.module.InterfaceVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * 接口
 * @author yeshijie on 2018/9/29.
 */
@RestController
@RequestMapping(value = BaseRequestMapping.Interface.PREFIX)
@Api(value = "接口管理", description = "接口管理服务接口", tags = {"基础服务 - 接口管理服务接口"})
public class InterfaceEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private InterfaceService interfaceService;
    @Autowired
    private ErrorCodeUtil errorCodeUtil;
    @PostMapping(value = BaseRequestMapping.Interface.CREATE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建")
    public ObjEnvelop<InterfaceVO> create (
            @ApiParam(name = "json_data", value = "Json数据", required = true)
            @RequestBody String jsonData) throws Exception {
        InterfaceDO interfaceDO = toEntity(jsonData, InterfaceDO.class);
        interfaceDO = interfaceService.addInterface(interfaceDO);
        return success(interfaceDO, InterfaceVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Interface.FINDBYID)
    @ApiOperation(value = "按id查找")
    public ObjEnvelop<InterfaceVO> findById (
            @ApiParam(name = "id", value = "id", required = true)
            @RequestParam(value = "id") String id) throws Exception {
        InterfaceDO interfaceDO = interfaceService.findById(id);
        return success(interfaceDO, InterfaceVO.class);
    }
    @PostMapping(value = BaseRequestMapping.Interface.STATUS)
    @ApiOperation(value = "生效/失效")
    public Envelop status(
            @ApiParam(name = "id", value = "id", required = true)
            @RequestParam(value = "id") String id,
            @ApiParam(name = "status", value = "1生效,0失效", required = true)
            @RequestParam(value = "status") Integer status) {
        interfaceService.updateStatus(id, status);
        return success("修改成功");
    }
    @PostMapping(value = BaseRequestMapping.Interface.DELETE)
    @ApiOperation(value = "删除")
    public Envelop delete(
            @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true)
            @RequestParam(value = "ids") String ids) {
        interfaceService.delete(ids.split(","));
        return success("删除成功");
    }
    @PostMapping(value = BaseRequestMapping.Interface.UPDATE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新")
    public ObjEnvelop<InterfaceVO> update (
            @ApiParam(name = "json_data", value = "Json数据", required = true)
            @RequestBody String jsonData) throws Exception {
        InterfaceDO interfaceDO = toEntity(jsonData, InterfaceDO.class);
        if (null == interfaceDO.getId()) {
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Common.ID_IS_NULL), ObjEnvelop.class);
        }
        interfaceDO = interfaceService.addInterface(interfaceDO);
        return success(interfaceDO, InterfaceVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Interface.PAGE)
    @ApiOperation(value = "获取分页")
    public PageEnvelop<InterfaceVO> page (
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        List<InterfaceDO> modules = interfaceService.search(fields, filters, sorts, page, size);
        int count = (int)interfaceService.getCount(filters);
        return success(modules, count, page, size, InterfaceVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Interface.LIST)
    @ApiOperation(value = "获取列表")
    public ListEnvelop<InterfaceVO> list (
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        List<InterfaceDO> interfaceDOs = interfaceService.search(fields, filters, sorts);
        return success(interfaceDOs, InterfaceVO.class);
    }
}

+ 56 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/module/ModuleEndpoint.java

@ -1,5 +1,6 @@
package com.yihu.jw.base.endpoint.module;
import com.yihu.jw.base.contant.CommonContant;
import com.yihu.jw.base.service.module.ModuleService;
import com.yihu.jw.base.util.ErrorCodeUtil;
import com.yihu.jw.entity.base.module.ModuleDO;
@ -14,11 +15,15 @@ import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * Endpoint - 模块
@ -40,10 +45,33 @@ public class ModuleEndpoint extends EnvelopRestEndpoint {
            @ApiParam(name = "json_data", value = "Json数据", required = true)
            @RequestBody String jsonData) throws Exception {
        ModuleDO module = toEntity(jsonData, ModuleDO.class);
        module = moduleService.save(module);
        int count = moduleService.isExistName(module.getName());
        if(count>0){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Module.NAME_IS_EXIST), ObjEnvelop.class);
        }
        module = moduleService.addModule(module);
        return success(module, ModuleVO.class);
    }
    @PostMapping(value = BaseRequestMapping.Module.STATUS)
    @ApiOperation(value = "生效/失效")
    public Envelop status(
            @ApiParam(name = "id", value = "id", required = true)
            @RequestParam(value = "id") String id,
            @ApiParam(name = "status", value = "1生效,0失效", required = true)
            @RequestParam(value = "status") Integer status) {
        moduleService.updateStatus(id, status);
        return success("修改成功");
    }
    @GetMapping(value = BaseRequestMapping.Module.IS_NAME_EXIST)
    @ApiOperation(value = "名称是否存在",notes = "返回值中的obj=1表示名称已经存在,0表示名称不存在")
    public ObjEnvelop isNameExist(
            @ApiParam(name = "name", value = "名称", required = true)
            @RequestParam(value = "name") String name) {
        return success(moduleService.isExistName(name));
    }
    @PostMapping(value = BaseRequestMapping.Module.DELETE)
    @ApiOperation(value = "删除")
    public Envelop delete(
@ -62,6 +90,10 @@ public class ModuleEndpoint extends EnvelopRestEndpoint {
        if (null == module.getId()) {
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Common.ID_IS_NULL), ObjEnvelop.class);
        }
        int count = moduleService.isExistName(module.getName());
        if(count > 1){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Module.NAME_IS_EXIST), ObjEnvelop.class);
        }
        module = moduleService.save(module);
        return success(module, ModuleVO.class);
    }
@ -97,4 +129,27 @@ public class ModuleEndpoint extends EnvelopRestEndpoint {
        return success(modules, ModuleVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Module.FIND_ALL)
    @ApiOperation(value = "获取列表")
    public ListEnvelop<ModuleVO> findAll (
            @ApiParam(name = "status", value = "状态")
            @RequestParam(value = "status", required = false) String status) throws Exception {
        String filters = null;
        if(StringUtils.isNotBlank(status)){
            filters = "status="+status;
        }
        List<ModuleDO> modules = moduleService.search(null, filters, null);
        List<ModuleVO> moduleVOs = convertToModels(modules,new ArrayList<>(modules.size()),ModuleVO.class);
        Map<String,List<ModuleVO>> map = moduleVOs.stream().collect(Collectors.groupingBy(ModuleVO::getParentId));
        moduleVOs.forEach(module->{
            List<ModuleVO> tmp = map.get(module.getId());
            module.setChildren(tmp);
        });
        moduleVOs = moduleVOs.stream()
                .filter(module -> CommonContant.DEFAULT_PARENTID.equals(module.getParentId()))
                .collect(Collectors.toList());
        return success(moduleVOs);
    }
}

+ 123 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/notice/NoticeEndPoint.java

@ -0,0 +1,123 @@
package com.yihu.jw.base.endpoint.notice;
import com.yihu.jw.base.service.notice.NoticeService;
import com.yihu.jw.base.util.ErrorCodeUtil;
import com.yihu.jw.entity.base.notice.NoticeDO;
import com.yihu.jw.exception.code.BaseErrorCode;
import com.yihu.jw.restmodel.base.notice.NoticeVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * 公告通知
 * @author yeshijie on 2018/10/9.
 */
@RestController
@RequestMapping(value = BaseRequestMapping.Notice.PREFIX)
@Api(value = "公告通知管理", description = "公告通知管理服务接口", tags = {"基础服务 - 公告通知管理服务接口"})
public class NoticeEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private ErrorCodeUtil errorCodeUtil;
    @PostMapping(value = BaseRequestMapping.Notice.CREATE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建")
    public ObjEnvelop<NoticeVO> create (
            @ApiParam(name = "json_data", value = "Json数据", required = true)
            @RequestBody String jsonData) throws Exception {
        NoticeDO noticeDO = toEntity(jsonData, NoticeDO.class);
        if(StringUtils.isBlank(noticeDO.getTitle())||noticeDO.getTitle().length()>50){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Notice.LIMIT_TITLE), ObjEnvelop.class);
        }
        noticeDO = noticeService.addNotice(noticeDO);
        return success(noticeDO, NoticeVO.class);
    }
    @PostMapping(value = BaseRequestMapping.Notice.DELETE)
    @ApiOperation(value = "删除")
    public Envelop delete(
            @ApiParam(name = "id", value = "id", required = true)
            @RequestParam(value = "id") String id) {
        noticeService.deleteNotice(id);
        return success("删除成功");
    }
    @PostMapping(value = BaseRequestMapping.Notice.RELEASE)
    @ApiOperation(value = "发布")
    public Envelop release(
            @ApiParam(name = "id", value = "id", required = true)
            @RequestParam(value = "id") String id) {
        NoticeDO noticeDO = noticeService.findById(id);
        if (NoticeDO.Status.released.getValue().equals(noticeDO.getStatus())){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Notice.HAD_RELEASE), Envelop.class);
        }
        if (NoticeDO.SendType.automatic_release.getValue().equals(noticeDO.getSendType())){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Notice.AUTO_RELEASE), Envelop.class);
        }
        noticeService.release(noticeDO);
        return success("发布成功");
    }
    @PostMapping(value = BaseRequestMapping.Notice.UPDATE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新")
    public ObjEnvelop<NoticeVO> update (
            @ApiParam(name = "json_data", value = "Json数据", required = true)
            @RequestBody String jsonData) throws Exception {
        NoticeDO noticeDO = toEntity(jsonData, NoticeDO.class);
        if (null == noticeDO.getId()) {
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Common.ID_IS_NULL), ObjEnvelop.class);
        }
        if(StringUtils.isBlank(noticeDO.getTitle())||noticeDO.getTitle().length()>50){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Notice.LIMIT_TITLE), ObjEnvelop.class);
        }
        noticeDO = noticeService.updateNotice(noticeDO);
        return success(noticeDO, NoticeVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Notice.PAGE)
    @ApiOperation(value = "获取分页")
    public PageEnvelop<NoticeVO> page (
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        List<NoticeDO> noticeDOs = noticeService.search(fields, filters, sorts, page, size);
        int count = (int)noticeService.getCount(filters);
        return success(noticeDOs, count, page, size, NoticeVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Notice.LIST)
    @ApiOperation(value = "获取列表")
    public ListEnvelop<NoticeVO> list (
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        List<NoticeDO> noticeDOs = noticeService.search(fields, filters, sorts);
        return success(noticeDOs, NoticeVO.class);
    }
}

+ 54 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/notice/UserNoticeEndpoint.java

@ -0,0 +1,54 @@
package com.yihu.jw.base.endpoint.notice;
import com.yihu.jw.base.service.notice.UserNoticeService;
import com.yihu.jw.entity.base.notice.NoticeDO;
import com.yihu.jw.restmodel.base.notice.NoticeVO;
import com.yihu.jw.restmodel.base.notice.UserNoticeVO;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 *
 * @author yeshijie on 2018/10/9.
 */
@RestController
@RequestMapping(value = BaseRequestMapping.UserNotice.PREFIX)
@Api(value = "用户公告通知管理", description = "用户公告通知管理服务接口", tags = {"基础服务 - 用户公告通知管理服务接口"})
public class UserNoticeEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private UserNoticeService userNoticeService;
    @GetMapping(value = BaseRequestMapping.Module.FINDBYID)
    @ApiOperation(value = "查看文章详情")
    public ObjEnvelop<NoticeVO> findById(
            @ApiParam(name = "id", value = "id", required = true)
            @RequestParam(value = "id") String id) {
        NoticeDO noticeDO = userNoticeService.findNoticeDetail(id);
        return success(noticeDO, NoticeVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Module.PAGE)
    @ApiOperation(value = "获取分页")
    public PageEnvelop<UserNoticeVO> page (
            @ApiParam(name = "userId", value = "用户id")
            @RequestParam(value = "userId", required = true) String userId,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        return userNoticeService.queryPage(page,size,userId);
    }
}

+ 38 - 4
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/role/MenuEndpoint.java

@ -1,5 +1,6 @@
package com.yihu.jw.base.endpoint.role;
import com.yihu.jw.base.contant.CommonContant;
import com.yihu.jw.base.service.role.MenuService;
import com.yihu.jw.base.util.ErrorCodeUtil;
import com.yihu.jw.entity.base.role.MenuDO;
@ -14,11 +15,15 @@ import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @author yeshijie on 2018/9/26.
@ -40,11 +45,15 @@ public class MenuEndpoint extends EnvelopRestEndpoint {
            @ApiParam(name = "json_data", value = "Json数据", required = true)
            @RequestBody String jsonData) throws Exception {
        MenuDO menuDO = toEntity(jsonData, MenuDO.class);
        menuDO = menuService.save(menuDO);
        int count = menuService.isExistName(menuDO.getName());
        if(count>0){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Menu.NAME_IS_EXIST), ObjEnvelop.class);
        }
        menuDO = menuService.addMenu(menuDO);
        return success(menuDO, MenuVO.class);
    }
    @PostMapping(value = BaseRequestMapping.Menu.MOVEDOWN)
    @PostMapping(value = BaseRequestMapping.Menu.MOVE_DOWN)
    @ApiOperation(value = "下移")
    public Envelop moveDown(
            @ApiParam(name = "id", value = "id", required = true)
@ -53,7 +62,7 @@ public class MenuEndpoint extends EnvelopRestEndpoint {
        return success("修改成功");
    }
    @PostMapping(value = BaseRequestMapping.Menu.MOVEUP)
    @PostMapping(value = BaseRequestMapping.Menu.MOVE_UP)
    @ApiOperation(value = "上移")
    public Envelop moveUp(
            @ApiParam(name = "id", value = "id", required = true)
@ -73,7 +82,7 @@ public class MenuEndpoint extends EnvelopRestEndpoint {
        return success("修改成功");
    }
    @GetMapping(value = BaseRequestMapping.Menu.ISNAMEEXIST)
    @GetMapping(value = BaseRequestMapping.Menu.IS_NAME_EXIST)
    @ApiOperation(value = "名称是否存在",notes = "返回值中的obj=1表示名称已经存在,0表示名称不存在")
    public ObjEnvelop isNameExist(
            @ApiParam(name = "name", value = "菜单名称", required = true)
@ -90,6 +99,10 @@ public class MenuEndpoint extends EnvelopRestEndpoint {
        if (null == menuDO.getId()) {
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Common.ID_IS_NULL), Envelop.class);
        }
        int count = menuService.isExistName(menuDO.getName());
        if(count>1){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.Menu.NAME_IS_EXIST), ObjEnvelop.class);
        }
        menuDO = menuService.save(menuDO);
        return success(menuDO);
    }
@ -125,5 +138,26 @@ public class MenuEndpoint extends EnvelopRestEndpoint {
        return success(menuDOS, MenuVO.class);
    }
    @GetMapping(value = BaseRequestMapping.Module.FIND_ALL)
    @ApiOperation(value = "获取列表")
    public ListEnvelop<MenuVO> findAll (
            @ApiParam(name = "status", value = "状态")
            @RequestParam(value = "status", required = false) String status) throws Exception {
        String filters = null;
        if(StringUtils.isNotBlank(status)){
            filters = "status="+status;
        }
        List<MenuDO> menuDOs = menuService.search(null, filters, null);
        List<MenuVO> menuVOs = convertToModels(menuDOs,new ArrayList<>(menuDOs.size()),MenuVO.class);
        Map<String,List<MenuVO>> map = menuVOs.stream().collect(Collectors.groupingBy(MenuVO::getParentId));
        menuVOs.forEach(menu->{
            List<MenuVO> tmp = map.get(menu.getId());
            menu.setChildren(tmp);
        });
        menuVOs = menuVOs.stream()
                .filter(menu -> CommonContant.DEFAULT_PARENTID.equals(menu.getParentId()))
                .collect(Collectors.toList());
        return success(menuVOs);
    }
}

+ 196 - 5
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WechatController.java

@ -1,18 +1,22 @@
package com.yihu.jw.base.endpoint.wx;
import com.alibaba.fastjson.JSONArray;
import com.yihu.jw.base.service.wx.WechatService;
import com.yihu.jw.entity.base.wx.*;
import com.yihu.jw.restmodel.base.wx.WxReplySceneVO;
import com.yihu.jw.restmodel.base.wx.WxTemplateConfigVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * Created by Trick on 2018/9/26.
@ -25,6 +29,8 @@ public class WechatController extends EnvelopRestEndpoint {
    @Autowired
    private WechatService wechatService;
    //====================微信与租户管理=======================
    @GetMapping(value = BaseRequestMapping.WeChat.getWechatInfos)
    @ApiOperation(value = "获取微信基本信息列表", notes = "获取微信基本信息列表")
    public MixEnvelop getWxWechatList(@ApiParam(name = "name", value = "微信名称")
@ -41,4 +47,189 @@ public class WechatController extends EnvelopRestEndpoint {
                                      @RequestParam(value = "size", required = true) Integer size) {
        return wechatService.getWxWechatList(name, saasName, status, publicType, page, size);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.saveWxAndSaas)
    @ApiOperation(value = "保存微信信息", notes = "保存微信信息")
    public Envelop saveWxAndSaas(@ApiParam(name = "wxWechatJson", value = "微信基本信息")
                                 @RequestParam(value = "wxWechatJson", required = true)String wxWechatJson,
                                 @ApiParam(name = "wxWechatSaasDOs", value = "微信租户关联")
                                 @RequestParam(value = "wxWechatSaasDOs", required = false)String wxWechatSaasDOs)throws Exception{
        WxWechatDO wxWechatDO = toEntity(wxWechatJson, WxWechatDO.class);
        List<WxWechatSaasDO> list = (List<WxWechatSaasDO>) JSONArray.parseArray(wxWechatSaasDOs, WxWechatSaasDO.class);
        return wechatService.saveWxAndSaas(wxWechatDO,list);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.updateWxAndSaas)
    @ApiOperation(value = "修改微信信息", notes = "修改微信信息")
    public Envelop updateWxAndSaas(@ApiParam(name = "wxWechatJson", value = "微信基本信息")
                                   @RequestParam(value = "wxWechatJson", required = true)String wxWechatJson,
                                   @ApiParam(name = "wxWechatSaasDOs", value = "微信租户关联")
                                   @RequestParam(value = "wxWechatSaasDOs", required = false)String wxWechatSaasDOs)throws Exception {
        WxWechatDO wxWechat = toEntity(wxWechatJson, WxWechatDO.class);
        List<WxWechatSaasDO> list = (List<WxWechatSaasDO>) JSONArray.parseArray(wxWechatSaasDOs, WxWechatSaasDO.class);
        return wechatService.updateWxAndSaas(wxWechat,list);
    }
    @GetMapping(value = BaseRequestMapping.WeChat.findWechatCombo)
    @ApiOperation(value = "微信信息下拉框", notes = "微信信息下拉框")
    public MixEnvelop findWechatCombo() {
        return wechatService.findWechatCombo();
    }
    //====================微信与租户管理end=======================
    //====================图文素材管理============================
    @GetMapping(value = BaseRequestMapping.WeChat.findWechatImgGroup)
    @ApiOperation(value = "获取图文素材分组", notes = "获取图文素材分组")
    public MixEnvelop findWechatImgGroup(@ApiParam(name = "wechatId", value = "微信ID")
                                         @RequestParam(value = "wechatId", required = true)String wechatId,
                                         @ApiParam(name = "page", value = "第几页")
                                         @RequestParam(value = "page", required = false)Integer page,
                                         @ApiParam(name = "size", value = "每页条数")
                                         @RequestParam(value = "size", required = false)Integer size) {
        return wechatService.findWechatImgGroup(wechatId,page,size);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.createImgGroup)
    @ApiOperation(value = "创建图文素材分组", notes = "创建图文素材分组")
    public Envelop createImgGroup(@ApiParam(name = "wxGraphicSceneJson", value = "图文分组JSON")
                                  @RequestParam(value = "wxGraphicSceneJson", required = true)String wxGraphicSceneJson)throws Exception {
        WxGraphicSceneDO wxWechatScene = toEntity(wxGraphicSceneJson, WxGraphicSceneDO.class);
        return wechatService.createImgGroup(wxWechatScene);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.updateImgGroup)
    @ApiOperation(value = "修改图文素材分组", notes = "修改图文素材分组")
    public Envelop updateImgGroup(@ApiParam(name = "id", value = "id")
                                  @RequestParam(value = "id", required = true)String id,
                                  @ApiParam(name = "scene", value = "分组名称(场景值)")
                                  @RequestParam(value = "scene", required = true)String scene) {
        return wechatService.updateImgGroup(id,scene);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.deleteImgGroup)
    @ApiOperation(value = "删除图文素材分组", notes = "删除图文素材分组")
    public Envelop deleteImgGroup(@ApiParam(name = "id", value = "id")
                                  @RequestParam(value = "id", required = true)String id) {
        return wechatService.deleteImgGroup(id);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.saveImg)
    @ApiOperation(value = "保存图文素材", notes = "保存图文素材")
    public Envelop saveImg(@ApiParam(name = "id", value = "id")
                           @RequestParam(value = "id", required = true)String wxGraphicMessageJson)throws Exception {
        WxGraphicMessageDO WxGraphicMessage = toEntity(wxGraphicMessageJson, WxGraphicMessageDO.class);
        return wechatService.saveImg(WxGraphicMessage);
    }
    @GetMapping(value = BaseRequestMapping.WeChat.findImg)
    @ApiOperation(value = "获取图文素材", notes = "获取图文素材")
    public MixEnvelop findImg(@ApiParam(name = "wechatId", value = "微信id")
                              @RequestParam(value = "wechatId", required = true)String wechatId,
                              @ApiParam(name = "title", value = "素材标题")
                              @RequestParam(value = "title", required = false)String title,
                              @ApiParam(name = "scene", value = "场景值")
                              @RequestParam(value = "scene", required = false)String scene,
                              @ApiParam(name = "page", value = "第几页")
                              @RequestParam(value = "page", required = true)Integer page,
                              @ApiParam(name = "size", value = "每页几条")
                              @RequestParam(value = "size", required = true)Integer size) {
        return wechatService.findImg(wechatId, title, scene, page, size);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.saveImgGroup)
    @ApiOperation(value = "分组图文素材", notes = "分组图文素材")
    public Envelop saveImgGroup(@ApiParam(name = "groups", value = "微信id")
                                @RequestParam(value = "groups", required = true)String groups) {
        List<WxGraphicSceneGroupDO> list = (List<WxGraphicSceneGroupDO>) JSONArray.parseArray(groups, WxGraphicSceneGroupDO.class);
        return wechatService.saveImgGroup(list);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.saveWxReplyScene)
    @ApiOperation(value = "事件配置场景", notes = "事件配置场景")
    public Envelop saveWxReplyScene(@ApiParam(name = "wxReplySceneJson", value = "事件配置json")
                                    @RequestParam(value = "wxReplySceneJson", required = true)String wxReplySceneJson) throws Exception{
        WxReplySceneDO wxReplyScene = toEntity(wxReplySceneJson, WxReplySceneDO.class);
        return wechatService.saveWxReplyScene(wxReplyScene);
    }
    @GetMapping(value = BaseRequestMapping.WeChat.findWxReplyScene)
    @ApiOperation(value = "获取消息配置场景", notes = "获取消息配置场景")
    public MixEnvelop<WxReplySceneVO,WxReplySceneVO> findWxReplyScene(@ApiParam(name = "wechatId", value = "微信id")
                                       @RequestParam(value = "wechatId", required = true)String wechatId,
                                                       @ApiParam(name = "msgType", value = "消息类型")
                                       @RequestParam(value = "msgType", required = false)String msgType,
                                                       @ApiParam(name = "event", value = "事件类型")
                                       @RequestParam(value = "event", required = false)String event,
                                                       @ApiParam(name = "content", value = "回复内容")
                                       @RequestParam(value = "content", required = false)String content,
                                                       @ApiParam(name = "page", value = "页数")
                                       @RequestParam(value = "page", required = true)Integer page,
                                                       @ApiParam(name = "size", value = "每页大小")
                                       @RequestParam(value = "size", required = true)Integer size) {
        return wechatService.findWxReplyScene(wechatId, msgType, event, content, page, size);
    }
    //====================图文素材管理end============================
    //===================模板消息==========================================
    @PostMapping(value = BaseRequestMapping.WeChat.saveWxTemp)
    @ApiOperation(value = "保存微信模板消息基础信息", notes = "保存微信模板消息基础信息")
    public Envelop saveWxTemp(@ApiParam(name = "wxTemplateJson", value = "微信模板消息基础信息json")
                              @RequestParam(value = "wxTemplateJson", required = true)String wxTemplateJson)throws Exception {
        WxTemplateDO wxTemplate = toEntity(wxTemplateJson, WxTemplateDO.class);
        return wechatService.saveWxTemp(wxTemplate);
    }
    @GetMapping(value = BaseRequestMapping.WeChat.saveWxTemp)
    @ApiOperation(value = "获取微信模板消息基础信息(列表)", notes = "获取微信模板消息基础信息(列表)")
    public MixEnvelop findWxtemp(@ApiParam(name = "wechatId", value = "微信id")
                                 @RequestParam(value = "wechatId", required = true)String wechatId,
                                 @ApiParam(name = "status", value = "状态")
                                 @RequestParam(value = "status", required = true)Integer status,
                                 @ApiParam(name = "name", value = "微信模板名称")
                                 @RequestParam(value = "name", required = true)String name,
                                 @ApiParam(name = "key", value = "模板id或标题模糊匹配")
                                 @RequestParam(value = "key", required = true)String key,
                                 @ApiParam(name = "page", value = "页码")
                                 @RequestParam(value = "page", required = true)Integer page,
                                 @ApiParam(name = "size", value = "分页大小")
                                 @RequestParam(value = "size", required = true)Integer size) {
        return wechatService.findWxtemp(wechatId, status, name, key, page, size);
    }
    @PostMapping(value = BaseRequestMapping.WeChat.saveWxTempConfig)
    @ApiOperation(value = "保存微信模板消息信息", notes = "保存微信模板消息信息")
    public Envelop saveWxTempConfig(@ApiParam(name = "wxTemplateConfigJosn", value = "微信模板消息信息json")
                                    @RequestParam(value = "wxTemplateConfigJosn", required = true)String wxTemplateConfigJosn)throws Exception {
        WxTemplateConfigDO WxTemplateConfig = toEntity(wxTemplateConfigJosn, WxTemplateConfigDO.class);
        return wechatService.saveWxTempConfig(WxTemplateConfig);
    }
    @GetMapping(value = BaseRequestMapping.WeChat.findWxTempConfigList)
    @ApiOperation(value = "获取微信模板列表", notes = "获取微信模板列表")
    public MixEnvelop<WxTemplateConfigVO,WxTemplateConfigVO> findWxTempConfigList(@ApiParam(name = "wechatId", value = "微信id")
                                           @RequestParam(value = "wechatId", required = true)String wechatId,
                                           @ApiParam(name = "scene", value = "微信场景值")
                                           @RequestParam(value = "scene", required = true)String scene,
                                           @ApiParam(name = "page", value = "第几页")
                                           @RequestParam(value = "page", required = true)Integer page,
                                           @ApiParam(name = "size", value = "分页大小")
                                           @RequestParam(value = "size", required = true)Integer size) {
        return wechatService.findWxTempConfigList(wechatId, scene, page, size);
    }
    @GetMapping(value = BaseRequestMapping.WeChat.findWxTemplateConfig)
    @ApiOperation(value = "获取微信模板列表(单条)", notes = "获取微信模板列表(单条)")
    public ObjEnvelop<WxTemplateConfigVO>  findWxTemplateConfig(@ApiParam(name = "wechatId", value = "微信id")
                                                   @RequestParam(value = "wechatId", required = true)String wechatId,
                                                                          @ApiParam(name = "name", value = "模板名称")
                                                   @RequestParam(value = "name", required = true)String name,
                                                                          @ApiParam(name = "scene", value = "场景值")
                                                   @RequestParam(value = "scene", required = true)String scene) {
        return success(wechatService.findWxTemplateConfig(wechatId,name,scene), WxTemplateConfigVO.class);
    }
    //===================模板消息end==========================================
}

+ 5 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/listener/ApplicationReadyListener.java

@ -2,6 +2,7 @@ package com.yihu.jw.base.listener;
import com.yihu.jw.base.activemq.MessageManager;
import com.yihu.jw.base.service.errorCode.ErrorCodeService;
import com.yihu.jw.base.service.notice.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
@ -18,6 +19,8 @@ public class ApplicationReadyListener implements ApplicationListener<Application
    private MessageManager messageManager;
    @Autowired
    private ErrorCodeService errorCodeService;
    @Autowired
    private NoticeService noticeService;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
@ -25,6 +28,8 @@ public class ApplicationReadyListener implements ApplicationListener<Application
        messageManager.initConsumer();
        //初始化错误码
        errorCodeService.initErrorCode();
        //初始化延迟队列
        noticeService.initDelayNotice();
    }
}

+ 16 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/module/InterfaceErrorCodeService.java

@ -0,0 +1,16 @@
package com.yihu.jw.base.service.module;
import com.yihu.jw.base.dao.module.InterfaceErrorCodeDao;
import com.yihu.jw.entity.base.module.InterfaceErrorCodeDO;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
/**
 * 接口错误说明
 * @author yeshijie on 2018/9/28.
 */
@Service
public class InterfaceErrorCodeService extends BaseJpaService<InterfaceErrorCodeDO, InterfaceErrorCodeDao> {
}

+ 16 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/module/InterfaceParamService.java

@ -0,0 +1,16 @@
package com.yihu.jw.base.service.module;
import com.yihu.jw.base.dao.module.InterfaceParamDao;
import com.yihu.jw.entity.base.module.InterfaceParamDO;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
/**
 * 接口入参出参
 * @author yeshijie on 2018/9/28.
 */
@Service
public class InterfaceParamService extends BaseJpaService<InterfaceParamDO, InterfaceParamDao> {
    
}

+ 97 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/module/InterfaceService.java

@ -0,0 +1,97 @@
package com.yihu.jw.base.service.module;
import com.yihu.jw.base.dao.module.InterfaceDao;
import com.yihu.jw.base.dao.module.InterfaceErrorCodeDao;
import com.yihu.jw.base.dao.module.InterfaceParamDao;
import com.yihu.jw.entity.base.module.InterfaceDO;
import com.yihu.jw.entity.base.module.InterfaceErrorCodeDO;
import com.yihu.jw.entity.base.module.InterfaceParamDO;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 接口
 * @author yeshijie on 2018/9/28.
 */
@Service
public class InterfaceService extends BaseJpaService<InterfaceDO, InterfaceDao> {
    @Autowired
    private InterfaceDao interfaceDao;
    @Autowired
    private InterfaceParamDao interfaceParamDao;
    @Autowired
    private InterfaceErrorCodeDao interfaceErrorCodeDao;
    /**
     * 返回接口
     * @param id
     * @return
     */
    public InterfaceDO findById(String id){
        InterfaceDO interfaceDO = interfaceDao.findOne(id);
        List<InterfaceParamDO> paramDOList = interfaceParamDao.findByInterfaceId(id);
        List<InterfaceParamDO> entryParams = paramDOList.stream()
                .filter(interfaceParamDO -> InterfaceParamDO.Type.entry.getValue().equals(interfaceParamDO.getType()))
                .collect(Collectors.toList());
        List<InterfaceParamDO> outParams = paramDOList.stream()
                .filter(interfaceParamDO -> InterfaceParamDO.Type.out.getValue().equals(interfaceParamDO.getType()))
                .collect(Collectors.toList());
        List<InterfaceErrorCodeDO> errorCodeDOList = interfaceErrorCodeDao.findByInterfaceId(id);
        interfaceDO.setErrorCodes(errorCodeDOList);
        interfaceDO.setEntryParams(entryParams);
        interfaceDO.setOutParams(outParams);
        return interfaceDO;
    }
    /**
     * 新增接口
     * @param interfaceDO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public InterfaceDO addInterface(InterfaceDO interfaceDO){
        if(StringUtils.isNotBlank(interfaceDO.getId())){
            interfaceParamDao.deleteByInterfaceId(interfaceDO.getId());
            interfaceErrorCodeDao.deleteByInterfaceId(interfaceDO.getId());
        }
        List<InterfaceParamDO> entryParams = interfaceDO.getEntryParams();
        List<InterfaceParamDO> outParams = interfaceDO.getOutParams();
        List<InterfaceErrorCodeDO> errorCodes = interfaceDO.getErrorCodes();
        interfaceDao.save(interfaceDO);
        entryParams.forEach(interfaceParamDO -> {
            interfaceParamDO.setInterfaceId(interfaceDO.getId());
        });
        outParams.forEach(interfaceParamDO -> {
            interfaceParamDO.setInterfaceId(interfaceDO.getId());
        });
        errorCodes.forEach(interfaceErrorCodeDO -> {
            interfaceErrorCodeDO.setInterfaceId(interfaceDO.getId());
        });
        interfaceParamDao.save(entryParams);
        interfaceParamDao.save(outParams);
        interfaceErrorCodeDao.save(errorCodes);
        return interfaceDO;
    }
    /**
     * 设置生效和失效
     * @param id
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(String id,Integer status){
        interfaceDao.updateStatus(id,status);
    }
}

+ 40 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/service/module/ModuleService.java

@ -1,10 +1,13 @@
package com.yihu.jw.base.service.module;
import com.yihu.jw.entity.base.module.ModuleDO;
import com.yihu.jw.base.contant.CommonContant;
import com.yihu.jw.base.dao.module.ModuleDao;
import com.yihu.jw.entity.base.module.ModuleDO;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Service - 模块
@ -16,4 +19,40 @@ public class ModuleService extends BaseJpaService<ModuleDO, ModuleDao> {
    @Autowired
    private ModuleDao moduleDao;
    /**
     * 新增模块
     * @param moduleDO
     * @return
     */
    public ModuleDO addModule(ModuleDO moduleDO){
        if(StringUtils.isBlank(moduleDO.getParentId())){
            moduleDO.setParentId(CommonContant.DEFAULT_PARENTID);
        }
        moduleDao.save(moduleDO);
        //若新增某必选业务模块,则需为所有已创建的租户和租户类型添加此业务模块
        return moduleDO;
    }
    /**
     * 设置生效和失效
     * @param id
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(String id,Integer status){
        moduleDao.updateStatus(id,status);
        //若原业务模块为失效/生效,操作生效/失效后的变更逻辑如以下流程图所示
    }
    /**
     * 名称是否存在
     * @param name
     * @return
     */
    public int isExistName(String name){
        return moduleDao.isExistName(name);
    }
}

+ 184 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/notice/NoticeService.java

@ -0,0 +1,184 @@
package com.yihu.jw.base.service.notice;
import com.yihu.jw.base.dao.notice.NoticeDao;
import com.yihu.jw.base.dao.notice.UserNoticeDao;
import com.yihu.jw.base.dao.user.UserDao;
import com.yihu.jw.base.util.threadPool.ThreadPoolUtil;
import com.yihu.jw.base.util.delay.DelayService;
import com.yihu.jw.base.util.delay.Notice;
import com.yihu.jw.base.util.delay.OnDelayedListener;
import com.yihu.jw.base.util.delay.RedisLock;
import com.yihu.jw.entity.base.notice.NoticeDO;
import com.yihu.jw.entity.base.notice.UserNoticeDO;
import com.yihu.jw.entity.base.user.UserDO;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.yihu.jw.entity.base.notice.NoticeDO.Status.released;
/**
 * 公告通知
 * @author yeshijie on 2018/9/30.
 */
@Service
public class NoticeService extends BaseJpaService<NoticeDO, NoticeDao> {
    @Autowired
    private NoticeDao noticeDao;
    @Autowired
    private UserNoticeDao userNoticeDao;
    @Autowired
    private DelayService delayService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolUtil threadPoolUtil;
    /**
     * redis锁的key
     */
    private final String rediskey = "notice:";
    /**
     * 发布公告
     * @param noticeDO
     */
    @Transactional(rollbackFor = Exception.class)
    public void release(NoticeDO noticeDO){
        noticeDO.setStatus(NoticeDO.Status.released.getValue());
        noticeDO.setSendTime(new Date());
        List<UserDO> userDOList = userDao.findByEnabled(true);
        List<UserNoticeDO> userNoticeDOs = new ArrayList<>(userDOList.size());
        userDOList.forEach(userDO -> {
            UserNoticeDO userNoticeDO = new UserNoticeDO();
            userNoticeDO.setDel(1);
            userNoticeDO.setIsRead(UserNoticeDO.Read.unRead.getValue());
            userNoticeDO.setNoticeId(noticeDO.getId());
            userNoticeDO.setUserId(userDO.getId());
            userNoticeDOs.add(userNoticeDO);
        });
        userNoticeDao.save(userNoticeDOs);
        noticeDao.save(noticeDO);
    }
    /**
     * 按id查找
     * @param id
     * @return
     */
    public NoticeDO findById(String id){
        return noticeDao.findOne(id);
    }
    /**
     * 新增消息公告
     * @param noticeDO
     * @return
     */
    public NoticeDO addNotice(NoticeDO noticeDO){
        noticeDO.setDel(1);
        noticeDO.setStatus(NoticeDO.Status.wait.getValue());
        noticeDao.save(noticeDO);
        //自动发布
        if(NoticeDO.SendType.automatic_release.getValue().equals(noticeDO.getSendType())){
            Notice notice = new Notice(noticeDO.getId(), noticeDO.getSendTime().getTime());
            delayService.add(notice);
        }
        return noticeDO;
    }
    /**
     * 修改公告
     * @param noticeDO
     * @return
     */
    public NoticeDO updateNotice(NoticeDO noticeDO){
        NoticeDO noticeOld = noticeDao.findOne(noticeDO.getId());
        if(released.getValue().equals(noticeDO.getStatus())){
            //已发布的不能修改
            return noticeDO;
        }
        if(!noticeOld.getSendType().equals(noticeDO.getSendType())){
            if(NoticeDO.SendType.automatic_release.getValue().equals(noticeDO.getSendType())){
                //自动发布
                Notice notice = new Notice(noticeDO.getId(), noticeDO.getSendTime().getTime());
                delayService.add(notice);
            }else {
                //手动发布
                delayService.remove(noticeDO.getId());
            }
        }
        noticeOld.setContent(noticeDO.getContent());
        noticeOld.setTitle(noticeDO.getTitle());
        noticeOld.setSendTime(noticeDO.getSendTime());
        noticeOld.setSendType(noticeDO.getSendType());
        noticeDao.save(noticeOld);
        return noticeDO;
    }
    /**
     * 删除
     * @param noticeId
     */
    public void deleteNotice(String noticeId){
        NoticeDO noticeDO = noticeDao.findOne(noticeId);
        noticeDO.setDel(0);
        noticeDao.save(noticeDO);
    }
    /**
     * 初始化延迟队列,项目启动的时候吧数据库的数据重新加入到队列中
     */
    public void initDelayNotice(){
        //启动监听
        delayService.start(new OnDelayedListener() {
            @Override
            public void onDelayedArrived(final Notice notice) {
                //异步来做
                threadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        String noticeId = notice.getNoticeId();
                        //分布式事务锁,防止代码在多台机器上执行
                        RedisLock lock = new RedisLock(redisTemplate, rediskey+noticeId, 10000, 20000);
                        try {
                            if(lock.lock()) {
                                //需要加锁的代码
                                NoticeDO noticeDO = noticeDao.findOne(noticeId);
                                if (NoticeDO.Status.wait.getValue().equals(noticeDO.getStatus())
                                        &&NoticeDO.SendType.automatic_release.getValue().equals(noticeDO.getSendType())){
                                    release(noticeDO);
                                }
                            }
                        } catch (InterruptedException e){
                            e.printStackTrace();
                        } finally {
                            lock.unlock();
                        }
                    }
                });
            }
        });
        //查找需要加入队列的数据
        List<NoticeDO> noticeDOList = noticeDao.findByStatusAndSendType(NoticeDO.Status.wait.getValue(),
                NoticeDO.SendType.automatic_release.getValue());
        noticeDOList.forEach(noticeDO -> {
            Notice notice = new Notice(noticeDO.getId(), noticeDO.getSendTime().getTime());
            delayService.add(notice);
        });
    }
}

+ 78 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/notice/UserNoticeService.java

@ -0,0 +1,78 @@
package com.yihu.jw.base.service.notice;
import com.yihu.jw.base.dao.notice.NoticeDao;
import com.yihu.jw.base.dao.notice.UserNoticeDao;
import com.yihu.jw.entity.base.notice.NoticeDO;
import com.yihu.jw.entity.base.notice.UserNoticeDO;
import com.yihu.jw.restmodel.base.notice.UserNoticeVO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 用户公告通知
 * @author yeshijie on 2018/9/30.
 */
@Service
public class UserNoticeService extends BaseJpaService<UserNoticeDO, UserNoticeDao> {
    @Autowired
    private UserNoticeDao userNoticeDao;
    @Autowired
    private NoticeDao noticeDao;
    @Autowired
    private JdbcTemplate jdbcTempalte;
    /**
     * 查看文章详情
     * @param id
     * @return
     */
    public NoticeDO findNoticeDetail(String id){
        UserNoticeDO userNoticeDO = userNoticeDao.findOne(id);
        if(UserNoticeDO.Read.unRead.getValue().equals(userNoticeDO.getIsRead())){
            userNoticeDO.setIsRead(UserNoticeDO.Read.read.getValue());
            userNoticeDao.save(userNoticeDO);
        }
        NoticeDO noticeDO = noticeDao.findOne(userNoticeDO.getNoticeId());
        return noticeDO;
    }
    /**
     * 按类型分页查找
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public PageEnvelop<UserNoticeVO> queryPage(Integer page, Integer size, String userId){
        StringBuffer sql = new StringBuffer("SELECT n.id noticeId,n.title,n.send_time sendTime,u.id,u.is_read isRead,u.user_id userId from base_notice n , base_user_notice u WHERE n.del = '1' ");
        StringBuffer sqlCount = new StringBuffer("SELECT COUNT(*) count from base_notice n , base_user_notice u WHERE n.del = '1' ");
        List<Object> args = new ArrayList<>();
        if(StringUtils.isNotBlank(userId)){
            sql.append(" and u.user_id=? ");
            sqlCount.append(" and u.user_id='").append(userId).append("' ");
            args.add(userId);
        }
        sql.append(" and u.notice_id = n.id and u.del = '1' ");
        sqlCount.append(" and u.notice_id = n.id and u.del = '1'");
        sql.append(" ORDER BY n.send_time desc limit ").append((page-1)*size).append(",").append(size);
        List<UserNoticeVO> list = jdbcTempalte.query(sql.toString(),args.toArray(),new BeanPropertyRowMapper(UserNoticeVO.class));
        List<Map<String,Object>> countList = jdbcTempalte.queryForList(sqlCount.toString());
        long count = Long.valueOf(countList.get(0).get("count").toString());
        return PageEnvelop.getSuccessListWithPage("查找成功",list, page, size,count);
    }
}

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/service/role/MenuService.java

@ -1,6 +1,6 @@
package com.yihu.jw.base.service.role;
import com.yihu.jw.base.contant.MenuContant;
import com.yihu.jw.base.contant.CommonContant;
import com.yihu.jw.base.dao.role.MenuDao;
import com.yihu.jw.entity.base.role.MenuDO;
import com.yihu.mysql.query.BaseJpaService;
@ -38,7 +38,7 @@ public class MenuService extends BaseJpaService<MenuDO, MenuDao> {
     */
    public MenuDO addMenu(MenuDO menuDO){
        if(StringUtils.isBlank(menuDO.getParentId())){
            menuDO.setParentId(MenuContant.DEFAULT_PARENTID);
            menuDO.setParentId(CommonContant.DEFAULT_PARENTID);
        }
        int sort = menuDao.countMenuByParentId(menuDO.getParentId())+1;
        menuDO.setSort(sort);

+ 355 - 5
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatService.java

@ -1,12 +1,12 @@
package com.yihu.jw.base.service.wx;
import com.yihu.jw.restmodel.base.saas.SaasVO;
import com.yihu.jw.restmodel.base.wx.WxSaasVO;
import com.yihu.jw.restmodel.base.wx.WxWechatVO;
import com.yihu.jw.base.dao.wx.*;
import com.yihu.jw.entity.base.wx.*;
import com.yihu.jw.restmodel.base.wx.*;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.rm.base.BaseRequestMapping;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
@ -16,6 +16,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
 * Created by trick on 2017/5/20 0020.
@ -26,6 +27,24 @@ public class WechatService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private WxWechatSaasDao wxWechatSaasDao;
    @Autowired
    private WxGraphicSceneDao wxGraphicSceneDao;
    @Autowired
    private WxGraphicSceneGroupDao wxGraphicSceneGroupDao;
    @Autowired
    private WxGraphicMessageDao wxGraphicMessageDao;
    @Autowired
    private WxReplySceneDao wxReplySceneDao;
    @Autowired
    private WxTemplateDao wxTemplateDao;
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    //====================微信与租户管理=======================
    public MixEnvelop getWxWechatList(String name,String saasName,Integer status,Integer publicType,Integer page,Integer size){
@ -91,7 +110,7 @@ public class WechatService {
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccessListWithPage(SpecialistMapping.api_success, list, page, size, count);
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }
    public List<WxSaasVO> getWxSaasVOs(String id){
@ -106,4 +125,335 @@ public class WechatService {
        List<WxSaasVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxSaasVO.class));
        return list;
    }
    public Envelop saveWxAndSaas(WxWechatDO wxWechatDO, List<WxWechatSaasDO> wxWechatSaasDOs){
        String uuid = UUID.randomUUID().toString();
        wxWechatDO.setId(uuid);
        wechatDao.save(wxWechatDO);
        if(wxWechatSaasDOs!=null&&wxWechatSaasDOs.size()>0){
            for(WxWechatSaasDO wxs:wxWechatSaasDOs){
                wxs.setWechatId(uuid);
            }
            wxWechatSaasDao.save(wxWechatSaasDOs);
        }
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public Envelop updateWxAndSaas(WxWechatDO wxWechatDO, List<WxWechatSaasDO> wxWechatSaasDOs) {
        wechatDao.save(wxWechatDO);
        List<WxWechatSaasDO> ws = wxWechatSaasDao.findByWechatId(wxWechatDO.getId());
        wxWechatSaasDao.delete(ws);
        if(wxWechatSaasDOs!=null&&wxWechatSaasDOs.size()>0){
            for(WxWechatSaasDO wxs:wxWechatSaasDOs){
                wxs.setWechatId(wxWechatDO.getId());
            }
            wxWechatSaasDao.save(wxWechatSaasDOs);
        }
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    //====================微信与租户管理end=======================
    //====================图文素材管理============================
    public MixEnvelop findWechatCombo(){
        String sql ="SELECT t.id,t.`name`,t.app_origin_id AS appOriginId from wx_wechat t";
        List<WxComboVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxComboVO.class));
        return MixEnvelop.getSuccessList(BaseRequestMapping.WeChat.api_success,list);
    }
    public MixEnvelop findWechatImgGroup(String wechatId,Integer page,Integer size){
        String totalSql ="SELECT COUNT(1) AS total from wx_graphic_scene g WHERE g.wechat_id ='"+wechatId+"'";
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        String sql = "SELECT " +
                " g.id,g.wechat_id AS wechatId,g.scene " +
                " FROM " +
                " wx_graphic_scene g " +
                " WHERE " +
                " g.wechat_id = '"+wechatId+"' " +
                " LIMIT  " + (page - 1) * size + "," + size + "";
        List<WxGraphicSceneVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxGraphicSceneVO.class));
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }
    public Envelop createImgGroup(WxGraphicSceneDO wxGraphicSceneDO){
        wxGraphicSceneDao.save(wxGraphicSceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public Envelop updateImgGroup(String id,String scene){
        WxGraphicSceneDO wxGraphicSceneDO = wxGraphicSceneDao.findOne(id);
        List<WxGraphicSceneGroupDO> list = wxGraphicSceneGroupDao.findByWechatIdAndScene(wxGraphicSceneDO.getWechatId(),wxGraphicSceneDO.getScene());
        if(list!=null&&list.size()>0){
            for(WxGraphicSceneGroupDO group:list){
                group.setScene(scene);
            }
            wxGraphicSceneGroupDao.save(list);
        }
        wxGraphicSceneDO.setScene(scene);
        wxGraphicSceneDao.save(wxGraphicSceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public Envelop deleteImgGroup(String id){
        WxGraphicSceneDO wxGraphicSceneDO = wxGraphicSceneDao.findOne(id);
        List<WxGraphicSceneGroupDO> list = wxGraphicSceneGroupDao.findByWechatIdAndScene(wxGraphicSceneDO.getWechatId(),wxGraphicSceneDO.getScene());
        if(list!=null&&list.size()>0){
            wxGraphicSceneGroupDao.delete(list);
        }
        wxGraphicSceneDao.delete(wxGraphicSceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public Envelop saveImg(WxGraphicMessageDO wxGraphicMessageDO){
        wxGraphicMessageDao.save(wxGraphicMessageDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public MixEnvelop findImg(String wechatId,String title,String scene,Integer page,Integer size){
        String sqlTotal = "SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wx_graphic_message m ";
                if(StringUtils.isNotBlank(scene)){
                    sqlTotal+= " JOIN wx_graphic_scene_group g ON g.graphic_id = m.id ";
                }
        sqlTotal+= " WHERE " +
                " m.wechat_id = '"+wechatId+"' " +
                " m.status =1" ;
                if(StringUtils.isNotBlank(title)){
                    sqlTotal += " AND m.title LIKE '%"+title+"%' " ;
                }
                if(StringUtils.isNotBlank(scene)){
                    sqlTotal+= "AND g.scene = '"+scene+"'";
                }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlTotal);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        String sql = "SELECT " +
                " m.id, " +
                " m.wechat_id AS wechatId, " +
                " m.`code` AS code, " +
                " m.title, " +
                " m.description, " +
                " m.url, " +
                " m.pic_url AS picUrl, " +
                " m.remark, " +
                " m.`status` " +
                " FROM " +
                " wx_graphic_message m ";
        if(StringUtils.isNotBlank(scene)){
            sql+= " JOIN wx_graphic_scene_group g ON g.graphic_id = m.id ";
        }
        sql+=" WHERE m.wechat_id = '"+wechatId+"' " +
                " m.status =1" ;
        if(StringUtils.isNotBlank(title)){
            sql += " AND m.title LIKE '%"+title+"%' " ;
        }
        if(StringUtils.isNotBlank(scene)){
            sql+= "AND g.scene = '"+scene+"'";
        }
        sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
        List<WxGraphicMessageVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxGraphicMessageVO.class));
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }
    public Envelop saveImgGroup(List<WxGraphicSceneGroupDO> groups){
        List<WxGraphicSceneGroupDO> gs = wxGraphicSceneGroupDao.findByWechatIdAndScene(groups.get(0).getWechatId(),groups.get(0).getScene());
        if(gs!=null&&gs.size()>0){
            wxGraphicSceneGroupDao.delete(gs);
        }
        wxGraphicSceneGroupDao.save(groups);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public Envelop saveWxReplyScene(WxReplySceneDO wxReplySceneDO){
        wxReplySceneDao.save(wxReplySceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public MixEnvelop findWxReplyScene(String wechatId,String msgType,String event,String content,Integer page,Integer size){
        String totalSql = "SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wx_reply_scene s " +
                " WHERE " +
                " s.wechat_id = '"+wechatId+"'";
        if(StringUtils.isNotBlank(msgType)){
            totalSql += " AND s.msg_type ='"+msgType+"'";
        }
        if(StringUtils.isNotBlank(event)){
            totalSql += " AND s.event ='"+event+"'";
        }
        if(StringUtils.isNotBlank(content)){
            totalSql += " AND s.content like '%"+content+"%'";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        String sql = "SELECT " +
                " s.wechat_id AS wechatId," +
                " s.scene, " +
                " s.`status`, " +
                " s.id, " +
                " s.content, " +
                " s.app_origin_id AS appOriginId, " +
                " s.`event`, " +
                " s.msg_type AS msgType" +
                " FROM " +
                " wx_reply_scene s " +
                " WHERE " +
                " s.wechat_id = '"+wechatId+"'";
        if(StringUtils.isNotBlank(msgType)){
            sql += " AND s.msg_type ='"+msgType+"'";
        }
        if(StringUtils.isNotBlank(event)){
            sql += " AND s.event ='"+event+"'";
        }
        if(StringUtils.isNotBlank(content)){
            sql += " AND s.content like '%"+content+"%'";
        }
        sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
        List<WxReplySceneVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxReplySceneVO.class));
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }
    //===================图文素材管理end====================================
    //===================模板消息==========================================
    public Envelop saveWxTemp(WxTemplateDO wxTemplateDO){
        wxTemplateDao.save(wxTemplateDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public MixEnvelop findWxtemp(String wechatId,Integer status,String name,String key,Integer page,Integer size){
        String totalSql = "SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wx_template t" +
                " WHERE t.wechat_id= '"+wechatId+"' ";
        if(status!=null){
            totalSql+= " AND t.status = "+ status;
        }
        if(StringUtils.isNotBlank(name)){
            totalSql+= " AND t.template_name ='"+name+"'";
        }
        if(StringUtils.isNotBlank(key)){
            totalSql+= " AND (t.template_id ='"+key+"' OR t.title like'%"+key+"%')";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        String sql = "SELECT " +
                " t.id, " +
                " t.title, " +
                " t.wechat_id AS wechatId, " +
                " t.template_id AS templateId, " +
                " t.template_name AS templateName, " +
                " t.content, " +
                " t.`status` " +
                " FROM " +
                " wx_template t" +
                " WHERE t.wechat_id= '"+wechatId+"' ";
        if(status!=null){
            sql+= " AND t.status = "+ status;
        }
        if(StringUtils.isNotBlank(name)){
            sql+= " AND t.template_name ='"+name+"'";
        }
        if(StringUtils.isNotBlank(key)){
            sql+= " AND (t.template_id ='"+key+"' OR t.title like'%"+key+"%')";
        }
        sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
        List<WxTemplateVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxTemplateVO.class));
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }
    public Envelop saveWxTempConfig(WxTemplateConfigDO wxTemplateConfigDO){
        wxTemplateConfigDao.save(wxTemplateConfigDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }
    public MixEnvelop findWxTempConfigList(String wechatId,String scene,Integer page,Integer size){
        String totalSql ="SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wx_template_config g " +
                " WHERE " +
                " g.wechat_id ='"+wechatId+"'";
        if(StringUtils.isNotBlank(scene)){
            totalSql += " AND g.scene = '"+scene+"'";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        String sql ="SELECT " +
                " g.id, " +
                " g.wechat_id AS wechatId, " +
                " g.template_id AS templateId, " +
                " g.template_name AS template_name, " +
                " g.scene, " +
                " g.scene_description AS sceneDescription, " +
                " g.`first`, " +
                " g.url, " +
                " g.remark, " +
                " g.keyword1, " +
                " g.keyword2, " +
                " g.keyword3, " +
                " g.keyword4, " +
                " g.keyword5, " +
                " g.keyword6, " +
                " g.keyword7, " +
                " g.create_time AS createTime, " +
                " g.create_user AS createUser, " +
                " g.create_user_name AS createUserName, " +
                " g.update_time AS updateTime, " +
                " g.update_user AS updateUser, " +
                " g.update_user_name AS updateUserName " +
                " FROM " +
                " wx_template_config g " +
                " WHERE " +
                " g.wechat_id ='"+wechatId+"'";
        if(StringUtils.isNotBlank(scene)){
            sql += " AND g.scene = '"+scene+"'";
        }
        sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
        List<WxTemplateConfigVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxTemplateConfigVO.class));
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }
    public WxTemplateConfigDO findWxTemplateConfig(String wechatId,String name,String scene){
        WxTemplateConfigDO wxTemplateConfigDO =  wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene(wechatId,name,scene);
        return wxTemplateConfigDO;
    }
    //===================模板消息end=======================================
}

+ 1 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/util/ErrorCodeUtil.java

@ -21,6 +21,6 @@ public class ErrorCodeUtil {
     * @return
     */
    public String getErrorMsg(String errorCode){
        return redisTemplate.opsForValue().get(BaseErrorCode.PREFIX+errorCode);
        return redisTemplate.opsForValue().get(BaseErrorCode.PREFIX + errorCode);
    }
}

+ 79 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/DelayService.java

@ -0,0 +1,79 @@
package com.yihu.jw.base.util.delay;
import com.yihu.jw.base.util.threadPool.ThreadPoolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.DelayQueue;
/**
 * @author yeshijie on 2018/9/29.
 */
@Component
public class DelayService {
    private final Logger log = LoggerFactory.getLogger(DelayService.class);
    @Autowired
    private ThreadPoolUtil threadPoolUtil;
    private boolean start;
    private OnDelayedListener listener;
    public DelayQueue<Notice> delayQueue = new DelayQueue<Notice>();
    public void start(OnDelayedListener listener) {
        if (start) {
            return;
        }
        log.info("DelayService 启动");
        start = true;
        this.listener = listener;
        threadPoolUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        Notice notice = delayQueue.take();
                        if (DelayService.this.listener != null) {
                            DelayService.this.listener.onDelayedArrived(notice);
                        }
                        log.info("执行任务+"+notice.getNoticeId()+","+notice.getStartTime());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void add(Notice notice) {
        delayQueue.put(notice);
    }
    public boolean remove(Notice notice) {
        return delayQueue.remove(notice);
    }
    public void add(String noticeId,long startTime) {
        delayQueue.put(new Notice(noticeId, startTime));
    }
    public void remove(String noticeId) {
        Notice[] array = delayQueue.toArray(new Notice[]{});
        if (array == null || array.length <= 0) {
            return;
        }
        Notice target = null;
        for (Notice notice : array) {
            if (notice.getNoticeId().equals(noticeId)) {
                target = notice;
                break;
            }
        }
        if (target != null) {
            delayQueue.remove(target);
        }
    }
}

+ 53 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/Notice.java

@ -0,0 +1,53 @@
package com.yihu.jw.base.util.delay;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
 * 消息公告的延迟队列
 * @author yeshijie on 2018/10/9.
 */
public class Notice implements Delayed {
    private String noticeId;
    private long startTime;
    public Notice(String noticeId, long timeout){
        this.noticeId = noticeId;
        this.startTime = timeout;
    }
    @Override
    public int compareTo(Delayed other) {
        if (other == this) {
            return 0;
        }
        if (other instanceof Notice) {
            Notice otherRequest = (Notice) other;
            long otherStartTime = otherRequest.getStartTime();
            return (int) (this.startTime - otherStartTime);
        }
        return 0;
    }
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(startTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }
    public String getNoticeId() {
        return noticeId;
    }
    public void setNoticeId(String noticeId) {
        this.noticeId = noticeId;
    }
    public long getStartTime() {
        return startTime;
    }
    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }
}

+ 12 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/OnDelayedListener.java

@ -0,0 +1,12 @@
package com.yihu.jw.base.util.delay;
/**
 * @author yeshijie on 2018/10/9.
 */
public interface OnDelayedListener {
    /**
     * 延迟时间到了,执行处理订单
     * @param notice
     */
    void onDelayedArrived(Notice notice);
}

+ 196 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/util/delay/RedisLock.java

@ -0,0 +1,196 @@
package com.yihu.jw.base.util.delay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.util.concurrent.TimeUnit;
/**
 * @author yeshijie on 2018/10/9.
 */
public class RedisLock {
    private static Logger logger = LoggerFactory.getLogger(RedisLock.class);
    private RedisTemplate redisTemplate;
    private static final int DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 100;
    /**
     * Lock key path.
     */
    private String lockKey;
    /**
     * 锁超时时间,防止线程在入锁以后,无限的执行等待
     */
    private int expireMsecs = 60 * 1000;
    /**
     * 锁等待时间,防止线程饥饿
     */
    private int timeoutMsecs = 10 * 1000;
    private volatile boolean locked = false;
    /**
     * Detailed constructor with default acquire timeout 10000 msecs and lock expiration of 60000 msecs.
     *
     * @param lockKey lock key (ex. account:1, ...)
     */
    public RedisLock(RedisTemplate redisTemplate, String lockKey) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey + "_lock";
    }
    /**
     * Detailed constructor with default lock expiration of 60000 msecs.
     *
     */
    public RedisLock(RedisTemplate redisTemplate, String lockKey, int timeoutMsecs) {
        this(redisTemplate, lockKey);
        this.timeoutMsecs = timeoutMsecs;
    }
    /**
     * Detailed constructor.
     *
     */
    public RedisLock(RedisTemplate redisTemplate, String lockKey, int timeoutMsecs, int expireMsecs) {
        this(redisTemplate, lockKey, timeoutMsecs);
        this.expireMsecs = expireMsecs;
    }
    /**
     * @return lock key
     */
    public String getLockKey() {
        return lockKey;
    }
    private String get(final String key) {
        Object obj = null;
        try {
            obj = redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    StringRedisSerializer serializer = new StringRedisSerializer();
                    byte[] data = connection.get(serializer.serialize(key));
                    connection.close();
                    if (data == null) {
                        return null;
                    }
                    return serializer.deserialize(data);
                }
            });
        } catch (Exception e) {
            logger.error("get redis error, key : {}", key);
        }
        return obj != null ? obj.toString() : null;
    }
    private boolean setNX(final String key, final String value) {
        Object obj = null;
        try {
            obj = redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    StringRedisSerializer serializer = new StringRedisSerializer();
                    Boolean success = connection.setNX(serializer.serialize(key), serializer.serialize(value));
                    connection.close();
                    return success;
                }
            });
        } catch (Exception e) {
            logger.error("setNX redis error, key : {}", key);
        }
        return obj != null ? (Boolean) obj : false;
    }
    private String getSet(final String key, final String value) {
        Object obj = null;
        try {
            obj = redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    StringRedisSerializer serializer = new StringRedisSerializer();
                    byte[] ret = connection.getSet(serializer.serialize(key), serializer.serialize(value));
                    connection.close();
                    return serializer.deserialize(ret);
                }
            });
        } catch (Exception e) {
            logger.error("setNX redis error, key : {}", key);
        }
        return obj != null ? (String) obj : null;
    }
    /**
     * 获得 lock.
     * 实现思路: 主要是使用了redis 的setnx命令,缓存了锁.
     * reids缓存的key是锁的key,所有的共享, value是锁的到期时间(注意:这里把过期时间放在value了,没有时间上设置其超时时间)
     * 执行过程:
     * 1.通过setnx尝试设置某个key的值,成功(当前没有这个锁)则返回,成功获得锁
     * 2.锁已经存在则获取锁的到期时间,和当前时间比较,超时的话,则设置新的值
     *
     * @return true if lock is acquired, false acquire timeouted
     * @throws InterruptedException in case of thread interruption
     */
    public synchronized boolean lock() throws InterruptedException {
        int timeout = timeoutMsecs;
        while (timeout >= 0) {
            long expires = System.currentTimeMillis() + expireMsecs + 1;
            //锁到期时间
            String expiresStr = String.valueOf(expires);
            if (this.setNX(lockKey, expiresStr)) {
                // lock acquired
                locked = true;
                return true;
            }
            //redis里的时间
            String currentValueStr = this.get(lockKey);
            if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
                //判断是否为空,不为空的情况下,如果被其他线程设置了值,则第二个条件判断是过不去的
                // lock is expired
                String oldValueStr = this.getSet(lockKey, expiresStr);
                //获取上一个锁到期时间,并设置现在的锁到期时间,
                //只有一个线程才能获取上一个线上的设置时间,因为jedis.getSet是同步的
                if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
                    //防止误删(覆盖,因为key是相同的)了他人的锁——这里达不到效果,这里值会被覆盖,但是因为什么相差了很少的时间,所以可以接受
                    //[分布式的情况下]:如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁
                    // lock acquired
                    locked = true;
                    return true;
                }
            }
            timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS;
            /*
                延迟100 毫秒,  这里使用随机时间可能会好一点,可以防止饥饿进程的出现,即,当同时到达多个进程,
                只会有一个进程获得锁,其他的都用同样的频率进行尝试,后面有来了一些进行,也以同样的频率申请锁,这将可能导致前面来的锁得不到满足.
                使用随机的等待时间可以一定程度上保证公平性
             */
            TimeUnit.MILLISECONDS.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS);
        }
        return false;
    }
    /**
     * Acqurired lock release.
     */
    public synchronized void unlock() {
        if (locked) {
            redisTemplate.delete(lockKey);
            locked = false;
        }
    }
}

+ 59 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/util/threadPool/ThreadPool.java

@ -0,0 +1,59 @@
package com.yihu.jw.base.util.threadPool;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @author yeshijie on 2018/10/10.
 */
@Configuration
public class ThreadPool {
    /**
     * 线程池核心线程数
     */
    private int CORE_POOL_SIZE = 5;
    /**
     * 线程池最大线程数
     */
    private int MAX_POOL_SIZE = 100;
    /**
     * 额外线程空状态生存时间
     */
    private int KEEP_ALIVE_TIME = 10000;
    /**
     * 额外线程空状态生存时间单位秒
     */
    private TimeUnit unit = TimeUnit.SECONDS;
    /**
     * 阻塞队列。当核心线程都被占用,且阻塞队列已满的情况下,才会开启额外线程。
     */
    private BlockingQueue workQueue = new ArrayBlockingQueue(10);
    /**
     * 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
     */
    private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
    /**
     * 线程工厂
     */
    private ThreadFactory threadFactory = new ThreadFactory() {
        private final AtomicInteger integer = new AtomicInteger();
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "myThreadPool thread:" + integer.getAndIncrement());
        }
    };
    @Bean
    ThreadPoolUtil threadPoolUtil(){
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
                unit, workQueue, threadFactory ,rejectedExecutionHandler);
        ThreadPoolUtil threadPoolUtil = new ThreadPoolUtil(threadPool);
        return threadPoolUtil;
    }
}

+ 32 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/util/threadPool/ThreadPoolUtil.java

@ -0,0 +1,32 @@
package com.yihu.jw.base.util.threadPool;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * @author yeshijie on 2018/9/30.
 */
public class ThreadPoolUtil {
    /**
     * 线程池
     */
    private ThreadPoolExecutor threadPool;
    public ThreadPoolUtil(ThreadPoolExecutor threadPool) {
        this.threadPool = threadPool;
    }
    public void execute(Runnable runnable) {
        threadPool.execute(runnable);
    }
    public void execute(FutureTask futureTask) {
        threadPool.execute(futureTask);
    }
    public void cancel(FutureTask futureTask) {
        futureTask.cancel(true);
    }
}

+ 36 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/RedisContext.java

@ -0,0 +1,36 @@
package com.yihu.jw.healthyhouse.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.11.25 17:33
 */
@Configuration
public class RedisContext {
    @Bean
    RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Serializable.class));
        redisTemplate.setHashValueSerializer(new GenericToStringSerializer<>(Long.class));
        return redisTemplate;
    }
//    @Bean
//    public static ConfigureRedisAction configureRedisAction() {
//        return ConfigureRedisAction.NO_OP;
//    }
}

+ 34 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/WebMvcConfigurer.java

@ -0,0 +1,34 @@
package com.yihu.jw.healthyhouse.config;
import com.yihu.jw.healthyhouse.interceptor.ActivatedInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
 * @author HZY
 * @created 2018/10/9 9:24
 */
//@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
//        registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**");
//        super.addInterceptors(registry);
//    }
    @Bean
    public ActivatedInterceptor authenticationInterceptor() {
        return new ActivatedInterceptor();
    }
}

+ 6 - 3
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/constant/LoginInfo.java

@ -5,6 +5,7 @@ package com.yihu.jw.healthyhouse.constant;
 * @created 2018/9/19 9:10
 */
public class LoginInfo {
    public static final String USER_INFO = "userInfo";
    public static final String IS_LOGIN = "isLogin";
    public static final String LOGIN_NAME = "loginName";
    public static final String LOGIN_CODE = "loginCode";
@ -16,10 +17,12 @@ public class LoginInfo {
    //用户创建
    public static final String SAVE_TYPE_IJK = "ijkLogin";  //i健康登录注册
    public static final String SAVE_TYPE_PHONE = "phoneLogin";//手机登录注册
    public static final String SAVE_TYPE_IDCARDNO= "idCardNoLogin";  //身份证登录注册
    //用户类型
    public static final String USER_TYPE_PATIENT = "Patient";//居民
    public static final String USER_TYPE_AdminManager = "AdminManager";//超管
    public static final String USER_TYPE_Server = "Server";//运营维护
    public static final String USER_TYPE_PATIENT = "patient";//居民
    public static final String USER_TYPE_SUPER_AdminManager = "superAdmin";//超管
    public static final String USER_TYPE_Server = "admin";//运营维护
}

+ 12 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/constant/SystemDictConstant.java

@ -0,0 +1,12 @@
package com.yihu.jw.healthyhouse.constant;
/**
 * @author zdm
 * @created 2018/10/8 9:10
 */
public class SystemDictConstant {
    //设施服务
    public static final String FACILITIE_SERVERS_TYPE_DICT_ID = "7";
}

+ 153 - 48
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/LoginController.java

@ -4,9 +4,12 @@ import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.healthyhouse.cache.WlyyRedisVerifyCodeService;
import com.yihu.jw.healthyhouse.model.user.User;
import com.yihu.jw.healthyhouse.service.user.LoginService;
import com.yihu.jw.healthyhouse.service.user.UserService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.wlyy.HouseUserContant;
import com.yihu.jw.util.security.RandomValidateCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -18,6 +21,7 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.HashMap;
@ -35,20 +39,28 @@ public class LoginController extends EnvelopRestEndpoint {
    private RestTemplate restTemplate;
    @Autowired
    private WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService;
    @Autowired
    private UserService userService;
    /******************************************    用户相关    **********************************/
    @ApiOperation(value = "发送短信验证码")
    @GetMapping(value = "/captcha/send")
    public ResponseEntity<HashMap> captcha(
            @ApiParam(name = "clientId", value = "应用id",defaultValue = "EwC0iRSrcS", required = true)@RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "msgType", value = "消息类型(login:登录验证,checkPhone:验证安全手机,resetPhone:重设安全手机", required = true)@RequestParam(required = true, name = "msgType") String msgType,
            @ApiParam(name = "username", value = "手机账号", required = true)@RequestParam(required = true, name = "username") String username ) throws  Exception{
            @ApiParam(name = "clientId", value = "应用id", defaultValue = "EwC0iRSrcS", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "msgType", value = "消息类型(login:登录验证,checkPhone:验证安全手机,resetPhone:重设安全手机", required = true) @RequestParam(required = true, name = "msgType") String msgType,
            @ApiParam(name = "userType", value = "账号类型(patient:普通账号,superAdmin:炒鸡管理员", required = true) @RequestParam(required = true, name = "userType") String userType,
            @ApiParam(name = "username", value = "手机账号", required = true) @RequestParam(required = true, name = "username") String username) throws Exception {
        if (StringUtils.isEmpty(clientId)) {
            throw new InvalidRequestException("clientId");
            failed("clientId 为空!");
        }
        if (StringUtils.isEmpty(username)) {
            failed("username 为空!");
        }
        if (StringUtils.isEmpty(username)){
            throw new InvalidRequestException("username");
        //验证用户是否被冻结
        User user = userService.findByTelephoneAndUserType(username,userType);
        if (HouseUserContant.activated_lock.equals(user)) {
            failed("该用户已被冻结,无法发送验证码!");
        }
        //验证请求间隔超时,防止频繁获取验证码
//        if (!wlyyRedisVerifyCodeService.isIntervalTimeout(clientId, username)) {
@ -60,56 +72,107 @@ public class LoginController extends EnvelopRestEndpoint {
    }
    @PostMapping("/captcha/check")
    @ApiOperation(value = "验证短信验证码")
    public Envelop checkCaptcha(
            HttpServletRequest request,
            @ApiParam(name = "clientId", value = "应用id", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "登录账号", required = true) @RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(required = true, name = "captcha") String captcha) throws ManageException, ParseException {
        if (wlyyRedisVerifyCodeService.verification(clientId, username, captcha)) {
            return success("验证码正确");
        } else {
            return failed("验证码错误");
        }
    }
    @PostMapping("/mobile/login")
    @ApiOperation(value = "【普通用户】-手机登录注册")
    public ObjEnvelop<User> mobileLogin(
    public Envelop mobileLogin(
            HttpServletRequest request,
            @ApiParam(name = "clientId", value = "应用id", required = true)@RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true)@RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "captcha", value = "短信验证码", required = true)@RequestParam(required = true, name = "captcha") String captcha) throws ManageException, ParseException {
            @ApiParam(name = "clientId", value = "应用id", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true) @RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(required = true, name = "captcha") String captcha) throws ParseException {
        if (wlyyRedisVerifyCodeService.verification(clientId, username, captcha)) {
            User user = loginService.phoneLogin(request,username);
//            ObjEnvelop envelop = new ObjEnvelop();
//            envelop.setStatus(200);
//            envelop.setMessage("登录成功");
//            envelop.setObj(user);
            User user = null;
            try {
                user = loginService.phoneLogin(request, username);
            } catch (ManageException e) {
                return failed(e.getMessage());
            }
            return success(user);
        } else {
            return ObjEnvelop.getError("验证码错误");
            return failed("验证码错误");
        }
    }
    @PostMapping("/ijk/login")
    @ApiOperation(value = "【普通用户】-i健康用户登陆")
    public ObjEnvelop ijkLogin(
    public Envelop ijkLogin(
            HttpServletRequest request,
            @ApiParam(name = "clientId", value = "应用id", required = true)@RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true)@RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "password", value = "密码", required = true)@RequestParam(required = true, name = "password") String password) throws ManageException {
        User user = loginService.iJklogin(request,clientId,username, password);
        if (user !=null) {
            ObjEnvelop envelop = new ObjEnvelop();
            envelop.setStatus(200);
            envelop.setMessage("登录成功");
            envelop.setObj(user);
            return envelop;
        }else {
            return ObjEnvelop.getError("登录失败");
            @ApiParam(name = "clientId", value = "应用id", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true) @RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "password", value = "密码", required = true) @RequestParam(required = true, name = "password") String password) {
        User user = null;
        try {
            user = loginService.iJklogin(request, clientId, username, password);
        } catch (ManageException e) {
            failed(e.getMessage());
        }
        if (user != null) {
            return success("登录成功", user);
        } else {
            return failed("登录失败");
        }
    }
    @PostMapping("/idCard/register")
    @ApiOperation(value = "【普通用户】-身份证认证注册")
    public Envelop idCardNoRegister(
            HttpServletRequest request,
            @ApiParam(name = "name", value = "用户姓名", required = true) @RequestParam(required = true, name = "name") String name,
            @ApiParam(name = "idCardNo", value = "身份证号码", required = true) @RequestParam(required = true, name = "idCardNo") String idCardNo) {
        try {
            loginService.idCardRegister(request,name, idCardNo);
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
        return success("用户认证完成!");
    }
    @PostMapping("/idCard/login")
    @ApiOperation(value = "【普通用户】-身份证登录")
    public Envelop idCardLogin(
            HttpServletRequest request,
            @ApiParam(name = "username", value = "账号", required = true) @RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "password", value = "密码", required = true) @RequestParam(required = true, name = "password") String password) {
        User user = null;
        try {
            user = loginService.idCardlogin(request, username, password);
        } catch (ManageException e) {
            failed(e.getMessage());
        }
        if (user != null) {
            return success("登录成功", user);
        } else {
            return failed("登录失败");
        }
    }
    @PostMapping("/loginout")
    @ApiOperation(value = "登出")
    public Envelop loginout(
            HttpServletRequest request,
            @ApiParam(name = "userCode", value = "用户code", required = true)@RequestParam(required = true, name = "userCode") String userCode) {
            @ApiParam(name = "userCode", value = "用户code", required = true) @RequestParam(required = true, name = "userCode") String userCode) {
        try {
            //修改用户状态  离线
           return ObjEnvelop.getSuccess("登出成功");
            return success("登出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("登出成功:" + e.getMessage(), -1);
            return failed("登出失败");
        }
    }
@ -118,31 +181,73 @@ public class LoginController extends EnvelopRestEndpoint {
    @PostMapping("/mobile/manage/login")
    @ApiOperation(value = "【管理员】-手机验证登录")
    public ObjEnvelop administratorMobileLogin(
    public Envelop administratorMobileLogin(
            HttpServletRequest request,
            @ApiParam(name = "clientId", value = "应用id", required = true)@RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true)@RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "captcha", value = "短信验证码", required = true)@RequestParam(required = true, name = "captcha") String captcha) throws ManageException, ParseException {
            @ApiParam(name = "clientId", value = "应用id", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true) @RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(required = true, name = "captcha") String captcha) throws ParseException {
        if (wlyyRedisVerifyCodeService.verification(clientId, username, captcha)) {
            User user = loginService.managerPhoneLogin(request,username);
            return ObjEnvelop.getSuccess("登录成功",user);
            User user = null;
            try {
                user = loginService.managerPhoneLogin(request, username);
            } catch (ManageException e) {
                return failed(e.getMessage());
            }
            return success("登录成功", user);
        } else {
            return ObjEnvelop.getError("验证码错误");
            return failed("验证码错误");
        }
    }
    @PostMapping("/manage/login")
    @ApiOperation(value = "【管理员】-用户账号登陆")
    public ObjEnvelop administratorLogin(
    public Envelop administratorLogin(
            HttpServletRequest request,
            @ApiParam(name = "clientId", value = "应用id", required = true)@RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true)@RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "password", value = "密码", required = true)@RequestParam(required = true, name = "password") String password) throws ManageException {
        User user = loginService.managerLogin(request,clientId,username, password);
        if (user !=null) {
            return ObjEnvelop.getSuccess("登录成功",user);
        }else {
            return ObjEnvelop.getError("登录失败");
            @ApiParam(name = "clientId", value = "应用id", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "username", value = "账号", required = true) @RequestParam(required = true, name = "username") String username,
            @ApiParam(name = "password", value = "密码", required = true) @RequestParam(required = true, name = "password") String password) {
        try {
            User user = loginService.managerLogin(request, clientId, username, password);
            if (user != null) {
                return success("登录成功", user);
            } else {
                return failed("登录失败");
            }
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
    }
    @GetMapping(value = "/getRandomImageCode")
    @ApiOperation(value = "修改密码时生成图形验证码", notes = "修改密码时生成图形验证码")
    public Envelop getImageCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCode randomValidateCode = new RandomValidateCode();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
            return success("获取验证码成功");
        } catch (Exception e) {
            return failed("获取验证码失败");
        }
    }
    @PostMapping(value = "/checkRandomImageCode")
    @ApiOperation(value = "检验图片验证码", notes = "检验图片验证码")
    public Envelop checkImageCode(@ApiParam(name = "code", value = "输入的验证码") @RequestParam(value = "code", required = true) String code,
                                  HttpServletRequest request) {
        if (StringUtils.isEmpty(code)) {
            return failed("请输入验证码!");
        }
        String codeRescource = String.valueOf(request.getSession().getAttribute(RandomValidateCode.RANDOMCODEKEY));
        if (code.toLowerCase().equals(codeRescource.toLowerCase())) {
            request.getSession().removeAttribute(RandomValidateCode.RANDOMCODEKEY);
            return success("验证码正确!");
        } else {
            return failed("验证码错误!");
        }
    }

+ 3 - 4
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/dfs/FastDFSController.java

@ -75,7 +75,7 @@ public class FastDFSController extends EnvelopRestEndpoint {
        fileResource.setCreateUser(creator);
        fileResource=  fileResourceService.save(fileResource);
        path = groupName.substring(1, groupName.length() - 1) + "/" + remoteFileName.substring(1, remoteFileName.length() - 1);
        fileResource.setStoragePath( fastdfs_file_url + path);
        fileResource.setStoragePath(path);
        return success(fileResource);
    }
@ -107,14 +107,13 @@ public class FastDFSController extends EnvelopRestEndpoint {
        String path = groupName.substring(1, groupName.length() - 1) + ":" + remoteFileName.substring(1, remoteFileName.length() - 1);
        //路径存储到mysql数据库
        FileResource fileResource =new FileResource();
        //TODO
        fileResource.setObjectId("111");
        fileResource.setObjectId(paramMap.get("object"));
        fileResource.setStoragePath(path);
        fileResource.setFileSize(String.valueOf(fileSize));
        fileResource.setFileName(fileName);
        fileResource=  fileResourceService.save(fileResource);
         path = groupName.substring(1, groupName.length() - 1) + "/" + remoteFileName.substring(1, remoteFileName.length() - 1);
        fileResource.setStoragePath( fastdfs_file_url + path);
        fileResource.setStoragePath( path);
        return success(fileResource);
    }

+ 73 - 26
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/facilities/FacilitiesController.java

@ -7,6 +7,7 @@ import com.yihu.jw.healthyhouse.model.facility.FacilityServerRelation;
import com.yihu.jw.healthyhouse.service.facility.FacilityServerRelationService;
import com.yihu.jw.healthyhouse.service.facility.FacilityServerService;
import com.yihu.jw.healthyhouse.service.facility.FacilityService;
import com.yihu.jw.healthyhouse.util.ImportDemoReader;
import com.yihu.jw.healthyhouse.util.facility.FacilityMsgReader;
import com.yihu.jw.healthyhouse.util.facility.msg.FacilityMsg;
import com.yihu.jw.healthyhouse.util.poi.AExcelReader;
@ -65,8 +66,13 @@ public class FacilitiesController extends EnvelopRestEndpoint {
            @RequestParam(value = "size", required = false) Integer size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page) throws Exception {
        if (StringUtils.isNotEmpty(filters)) {
            filters = filters + "deleteFlag=0;";
        } else {
            filters = "deleteFlag=0;";
        }
        List<Facility> facilityList = facilityService.search(fields, filters, sorts, page, size);
        int count = (int)facilityService.getCount(filters);
        int count = (int) facilityService.getCount(filters);
        return success(facilityList, count, page, size);
    }
@ -77,7 +83,7 @@ public class FacilitiesController extends EnvelopRestEndpoint {
            @ApiParam(name = "facility", value = "设施JSON结构")
            @RequestParam(value = "facility") String facility,
            @ApiParam(name = "facilityServerJson", value = "设施关联的服务字符串用,号隔开")
            @RequestParam(value = "facilityServerJson") String facilityServerJson) throws IOException {
            @RequestParam(value = "facilityServerJson") String facilityServerJson) throws Exception {
        Facility facility1 = toEntity(facility, Facility.class);
        List<Facility> facilityList = null;
        if (StringUtils.isEmpty(facility1.getCode())) {
@ -105,6 +111,7 @@ public class FacilitiesController extends EnvelopRestEndpoint {
        if (StringUtils.isEmpty(facility1.getCategory().toString())) {
            return failed("设施类别不正确,请参考系统字典:设施类别!", ObjEnvelop.class);
        }
        facility1.setDeleteFlag("0");
        Facility facilityBack = facilityService.save(facility1);
        List<FacilityServerRelation> facilityServerRelationList = createRelationByServerCode(facility1, facilityServerJson);
        facilityBack.setFacilityServerRelation(facilityServerRelationList);
@ -120,28 +127,30 @@ public class FacilitiesController extends EnvelopRestEndpoint {
            @ApiParam(name = "facilityServerJson", value = "设施关联的服务字符串用,号隔开")
            @RequestParam(value = "facilityServerJson") String facilityServerJson) throws Exception {
        Facility facility1 = toEntity(facility, Facility.class);
        List<Facility> facilityList = null;
        List<Facility> faList = facilityService.findByField("id", facility1.getId());
        if (!(faList != null && faList.size() > 0)) {
        Facility facility2 = facilityService.findById(facility1.getId());
        if (null == facility2) {
            return failed("设施不存在!", ObjEnvelop.class);
        }
        facility1.setCreateTime(facility2.getCreateTime());
        if (StringUtils.isNotEmpty(facility1.getId())) {
            //删除设施,设施关联关系,设施服务使用设施数
            deleteFacilityByCode(facility1);
        }
        if (StringUtils.isEmpty(facility1.getCode())) {
            return failed("设施编码不能为空!", ObjEnvelop.class);
        } else {
            facilityList = facilityService.findByField("code", facility1.getCode());
            if (null != facilityList && facilityList.size() > 0) {
            boolean existFlag = facilityService.checkFacilityByFacilityId(facility1.getId(), "code", facility1.getCode());
            if (existFlag) {
                return failed("设施编码已存在!", ObjEnvelop.class);
            }
        }
        if (StringUtils.isEmpty(facility1.getName())) {
            return failed("设施名称不能为空!", ObjEnvelop.class);
        } else {
            facilityList = facilityService.findByField("name", facility1.getName());
            if (null != facilityList && facilityList.size() > 0) {
            boolean existFlag = facilityService.checkFacilityByFacilityId(facility1.getId(), "name", facility1.getName());
            ;
            if (existFlag) {
                return failed("设施名称已存在!", ObjEnvelop.class);
            }
        }
@ -154,6 +163,7 @@ public class FacilitiesController extends EnvelopRestEndpoint {
        if (StringUtils.isEmpty(facility1.getCategory().toString())) {
            return failed("设施类别不正确,请参考系统字典:设施类别!", ObjEnvelop.class);
        }
        facility1.setDeleteFlag("0");
        Facility facilityBack = facilityService.save(facility1);
        List<FacilityServerRelation> facilityServerRelationList = createRelationByServerCode(facility1, facilityServerJson);
        facilityBack.setFacilityServerRelation(facilityServerRelationList);
@ -210,6 +220,7 @@ public class FacilitiesController extends EnvelopRestEndpoint {
        if (StringUtils.isEmpty(facility.getCategory().toString())) {
            return failed("设施类别不正确,请参考系统字典:设施类别!", ObjEnvelop.class);
        }
        facility.setDeleteFlag("0");
        facility = facilityService.save(facility);
        return success(facility);
    }
@ -223,7 +234,10 @@ public class FacilitiesController extends EnvelopRestEndpoint {
        if (null == facility) {
            return failed("设施不存在!");
        }
        deleteFacilityByCode(facility);
        facility.setDeleteFlag("1");
        //将设施状态改成关闭,在用户历史行程中做提示使用
        facility.setStatus("1");
        facilityService.save(facility);
        return success("success");
    }
@ -232,7 +246,7 @@ public class FacilitiesController extends EnvelopRestEndpoint {
    public ObjEnvelop<Long> countFacilities(
            @ApiParam(name = "totalCountFlag", value = "设施总数:true;今日新增设施:false", defaultValue = "true")
            @RequestParam(value = "totalCountFlag") boolean totalCountFlag) throws Exception {
        String filters = "";
        String filters = "deleteFlag=0;";
        long count;
        //设施总数:true
        if (totalCountFlag) {
@ -241,7 +255,7 @@ public class FacilitiesController extends EnvelopRestEndpoint {
            //今日新增设施:false
            String todayStart = DateUtil.getStringDateShort() + " " + "00:00:00";
            String todayEnd = DateUtil.getStringDateShort() + " " + "23:59:59";
            filters = "createTime>=" + todayStart + ";createTime<=" + todayEnd;
            filters = filters + "createTime>=" + todayStart + ";createTime<=" + todayEnd;
            count = facilityService.getCount(filters);
        }
        return success("success", count);
@ -287,11 +301,10 @@ public class FacilitiesController extends EnvelopRestEndpoint {
    @PostMapping(value = "/batchImport")
    @ApiOperation(value = "设施列表导入(经纬度重复的不导入)")
    public ObjEnvelop importData(
    public Envelop importData(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestPart(value = "file") MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException, ManageException {
            HttpServletRequest request) throws IOException, ManageException {
        try {
            request.setCharacterEncoding("UTF-8");
            AExcelReader excelReader = new FacilityMsgReader();
@ -299,13 +312,14 @@ public class FacilitiesController extends EnvelopRestEndpoint {
            List<FacilityMsg> dataList = excelReader.getCorrectLs();
            if (dataList.size() > 0) {
                Map<String, Object> result = facilityService.batchInsertFacility(dataList);
                return ObjEnvelop.getSuccess("导入成功!", result);
                return success("导入成功!", result);
            }
        } catch (Exception e) {
            throw new ManageException("导入设施列表异常!", e);
            e.printStackTrace();
            return failed("导入异常,请检查导入文件格式"+e.getMessage());
        }
        return ObjEnvelop.getError("导入失败");
        return failed("导入失败");
    }
    @ApiOperation(value = "获取设施列表--不分页(app)", responseContainer = "List")
@ -328,16 +342,25 @@ public class FacilitiesController extends EnvelopRestEndpoint {
        if (StringUtils.isNotEmpty(facilityServerCodes)) {
            String[] faServerCodes = facilityServerCodes.split(",");
            List<String> facilityCodeList = facilityService.getFacilityCodeByServerCode(faServerCodes);
            facilityList = facilityService.getFacilityByFacilityCode(facilityCodeList);
            if (null != facilityCodeList && facilityCodeList.size() > 0) {
                facilityList = facilityService.getFacilityByFacilityCode(facilityCodeList);
            }
        } else if (StringUtils.isNotEmpty(facilityServerType)) {
            //设施编码为空,设施服务类型不为空,按设施服务类型获取设施
            List<String> facilityCodeList = facilityService.getFacilityCodeByServerType(facilityServerType);
            facilityList = facilityService.getFacilityByFacilityCode(facilityCodeList);
            if (null != facilityCodeList && facilityCodeList.size() > 0) {
                facilityList = facilityService.getFacilityByFacilityCode(facilityCodeList);
            }
        } else if (StringUtils.isNotEmpty(facilityCategory)) {
            //设施编码为空,设施服务类型为空,按照设施分类获取按设施服务类型获取设施
            filters = "category=" + facilityCategory;
            filters = "deleteFlag=0;category=" + facilityCategory + ";status=0;";
            facilityList = facilityService.search(fields, filters, sorts);
        } else {
            if (StringUtils.isEmpty(filters)) {
                filters = "deleteFlag=0;status=0;";
            } else {
                filters = filters + ";status=0;deleteFlag=0;";
            }
            facilityList = facilityService.search(fields, filters, sorts);
        }
        return success(facilityList);
@ -351,15 +374,15 @@ public class FacilitiesController extends EnvelopRestEndpoint {
        //今日使用设施数
        long countUsedFacilitieToday = facilityServerRelationService.countDistinctByFacilitieCodeAndCreateTimeBetween();
        map.put("countUsedFacilitieToday", countUsedFacilitieToday);
        long countAllFacilitie = facilityService.getCount("");
        long countAllFacilitie = facilityService.getCount("deleteFlag=0;");
        map.put("countAllFacilitie", countAllFacilitie);
        //今日新增设施:false
        String todayStart = DateUtil.getStringDateShort() + " " + "00:00:00";
        String todayEnd = DateUtil.getStringDateShort() + " " + "23:59:59";
        String filters = "createTime>=" + todayStart + ";createTime<=" + todayEnd;
        String filters = "deleteFlag=0;createTime>=" + todayStart + ";createTime<=" + todayEnd;
        long countCreatedFacilitieToday = facilityService.getCount(filters);
        map.put("countCreatedFacilitieToday", countCreatedFacilitieToday);
        return ObjEnvelop.getSuccess("获取成功", map);
        return success("获取成功", map);
    }
@ -397,7 +420,6 @@ public class FacilitiesController extends EnvelopRestEndpoint {
            }
        }
        facilityServerRelationService.deleteByFacilitieCode(facility.getCode());
        facilityService.delete(facility);
    }
    /**
@ -407,7 +429,7 @@ public class FacilitiesController extends EnvelopRestEndpoint {
     * @param facilityServerJson 设施服务编码
     * @return
     */
    public List<FacilityServerRelation> createRelationByServerCode(Facility facility1, String facilityServerJson) {
    public List<FacilityServerRelation> createRelationByServerCode(Facility facility1, String facilityServerJson) throws Exception {
        List<FacilityServerRelation> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(facilityServerJson)) {
            //设施编码
@ -439,4 +461,29 @@ public class FacilitiesController extends EnvelopRestEndpoint {
    }
    @PostMapping(value = "/demoImport")
    @ApiOperation(value = "导入设施列表临时接口")
    public Envelop demoImport(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestPart(value = "file") MultipartFile file,
            HttpServletRequest request) throws IOException, ManageException {
        try {
            request.setCharacterEncoding("UTF-8");
            AExcelReader excelReader = new ImportDemoReader();
            excelReader.read(file);
            List<Map<String,String>> dataList = excelReader.getCorrectLs();
            if (dataList.size() > 0) {
                //TODO 导入
                facilityService.batchInsertDemo(dataList);
                System.out.println(dataList);
                return success("导入成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed("导入异常,请检查导入文件格式"+e.getMessage());
        }
        return failed("导入失败");
    }
}

+ 31 - 5
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/facilities/FacilitiesServerController.java

@ -1,6 +1,9 @@
package com.yihu.jw.healthyhouse.controller.facilities;
import com.yihu.jw.healthyhouse.constant.SystemDictConstant;
import com.yihu.jw.healthyhouse.model.dict.SystemDictEntry;
import com.yihu.jw.healthyhouse.model.facility.FacilityServer;
import com.yihu.jw.healthyhouse.service.dict.SystemDictEntryService;
import com.yihu.jw.healthyhouse.service.facility.FacilityServerService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
@ -17,7 +20,9 @@ import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -31,9 +36,11 @@ public class FacilitiesServerController extends EnvelopRestEndpoint {
    @Autowired
    private FacilityServerService facilityServerService;
    @Autowired
    private SystemDictEntryService systemDictEntryService;
    @ApiOperation(value = "获取设施服务列表", responseContainer = "List")
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FacilitiesServer.PAGE )
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FacilitiesServer.PAGE)
    public PageEnvelop<FacilityServer> getFacilitiesServer(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
@ -46,12 +53,12 @@ public class FacilitiesServerController extends EnvelopRestEndpoint {
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page) throws Exception {
        List<FacilityServer> facilityServerList = facilityServerService.search(fields, filters, sorts, page, size);
        int count = (int)facilityServerService.getCount(filters);
        return success(facilityServerList,count, page, size);
        int count = (int) facilityServerService.getCount(filters);
        return success(facilityServerList, count, page, size);
    }
    @ApiOperation(value = "创建设施服务")
    @PostMapping(value = HealthyHouseMapping.HealthyHouse.FacilitiesServer.CREATE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = HealthyHouseMapping.HealthyHouse.FacilitiesServer.CREATE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ObjEnvelop<FacilityServer> createFacilitiesServer(
            @ApiParam(name = "FacilityServer", value = "设施服务JSON结构")
            @RequestBody FacilityServer facilityServer) throws IOException {
@ -134,7 +141,7 @@ public class FacilitiesServerController extends EnvelopRestEndpoint {
    }
    @ApiOperation(value = "获取设施服务列表", responseContainer = "List")
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FacilitiesServer.LIST_FACILITIESERVERS )
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FacilitiesServer.LIST_FACILITIESERVERS)
    public ListEnvelop<FacilityServer> getFacilitiesServer(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
@ -146,5 +153,24 @@ public class FacilitiesServerController extends EnvelopRestEndpoint {
        return success(facilityServerList);
    }
    @ApiOperation(value = "app按照分类获取-设施服务列表", responseContainer = "List")
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FacilitiesServer.LIST_FACILITIESERVERS_BY_TYPE)
    public ObjEnvelop<Map> getFacilitiesServerByType() throws Exception {
        Map<String, List<FacilityServer>> map = new HashMap<>();
        List<FacilityServer> facilityServerList;
        //获取系统字典-设施服务类型
        List<SystemDictEntry> systemDictEntryList = systemDictEntryService.getDictEntryCodeAndValueByDictId(SystemDictConstant.FACILITIE_SERVERS_TYPE_DICT_ID);
        for (Object object : systemDictEntryList) {
            Object[] obj=(Object[])object;
            if(null!=obj[0]&&StringUtils.isNotEmpty(obj[0].toString()) ){
                String filters = "type=" + obj[0].toString();
                facilityServerList = facilityServerService.search("", filters, "");
                map.put(obj[0].toString(), facilityServerList);
            }
        }
        return success(map);
    }
}

+ 20 - 6
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/FacilityUsedRecordController.java

@ -67,7 +67,7 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page) throws Exception {
        List<FacilityUsedRecord> facilityUsedRecordList = facilityUsedRecordService.search(fields, filters, sorts, page, size);
        int count = (int)facilityUsedRecordService.getCount(filters);
        int count = (int) facilityUsedRecordService.getCount(filters);
        return success(facilityUsedRecordList, count, page, size);
    }
@ -77,6 +77,7 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
    public ObjEnvelop<FacilityUsedRecord> createFacilityUsedRecord(
            @ApiParam(name = "facilityUsedRecord", value = "用户使用导航记录JSON结构")
            @RequestBody FacilityUsedRecord facilityUsedRecord) throws IOException, ManageException {
        facilityUsedRecord.setUserId(facilityUsedRecord.getCreateUser());
        facilityUsedRecord = facilityUsedRecordService.save(facilityUsedRecord);
        userService.updateFacilityUse(facilityUsedRecord.getCreateUser());
        return success(facilityUsedRecord);
@ -128,7 +129,9 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
        FacilityUsedRecord facilityUsedRecord;
        if (nearbyFlag) {
            if (StringUtils.isNotEmpty(filters)) {
                filters = "name?" + filters + " g1;cityName?" + filters + " g1;countyName?" + filters + " g1;street?" + filters + " g1";
                filters = "deleteFlag=0;status=0;" + "name?" + filters + " g1;cityName?" + filters + " g1;countyName?" + filters + " g1;street?" + filters + " g1;address?" + filters + " g1;";
            } else {
                filters = "deleteFlag=0;status=0;";
            }
            //获取所有设施,并根据设施编码及用户id查找使用次数
            List<Facility> facilityList = facilityService.search(filters);
@ -140,7 +143,9 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
                facilityUsedRecord.setFacilitieLatitudes(facility.getLatitude());
                facilityUsedRecord.setFacilitieAddr(facility.getAddress());
                facilityUsedRecord.setCreateUser(userId);
                facilityUsedRecord.setUserId(userId);
                facilityUsedRecord.setFacilitieId(facility.getId());
                facilityUsedRecord.setFacilitieStatus(facility.getStatus());
                long count = facilityUsedRecordService.countByFacilitieCodeAndUserId(facility.getCode(), userId);
                facilityUsedRecord.setNum((int) count);
                facilityUsedRecordList.add(facilityUsedRecord);
@ -151,6 +156,9 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
            for (FacilityUsedRecord facilityUsedRecord1 : facilityUsedRecordList) {
                long count = facilityUsedRecordService.countByFacilitieCodeAndUserId(facilityUsedRecord1.getFacilitieCode(), userId);
                facilityUsedRecord1.setNum((int) count);
                //获取设施状态
                Facility facility = facilityService.findByCode(facilityUsedRecord1.getFacilitieCode());
                facilityUsedRecord1.setFacilitieStatus(facility.getStatus());
            }
        }
        return success(facilityUsedRecordList);
@ -179,11 +187,14 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
    public ObjEnvelop facilityUsedRecordDetail(
            @ApiParam(name = "id", value = "使用记录ID", defaultValue = "")
            @RequestParam(value = "id") String id) throws Exception {
        if (id == null) {
            throw new ManageException("使用记录ID为空!");
        }
        Map<String, Object> usedRecordDetail = facilityUsedRecordService.getUsedRecordDetail(id);
        return success(usedRecordDetail);
    }
    @ApiOperation(value = "获取用户使用导航记录列表--分页(app)", responseContainer = "List")
    @ApiOperation(value = "我的行程-获取用户使用导航记录列表--分页(app)", responseContainer = "List")
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FacilityUsedRecord.PAGE_FACILITY_USED_RECORD_BY_USERID)
    public PageEnvelop<FacilityUsedRecord> getFacilityUsedRecordsByUserId(
            @ApiParam(name = "userId", value = "必输参数:登录用户id", defaultValue = "")
@ -195,13 +206,13 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page) throws Exception {
        String filters = "createUser=" + userId;
        sorts = "-createTime";
        List<FacilityUsedRecord> facilityUsedRecordList = facilityUsedRecordService.search("", filters, sorts, page, size);
        for (FacilityUsedRecord record : facilityUsedRecordList) {
            //根据设施编码获取关联服务的名称
            String facilityCode = record.getFacilitieCode();
            List<FacilityServerRelation> facilityServerRelations = facilityServerRelationService.findByField("facilitieCode", facilityCode);
            List<String> services = facilityServerRelations.stream().map(FacilityServerRelation::getServiceName).collect(Collectors.toList());
            String servicesValue = Joiner.on("、").join(services);
            String servicesValue = facilityServerRelations.stream().map(FacilityServerRelation::getServiceName).collect(Collectors.joining("、"));
            record.setFacilityRelationServiceName(servicesValue);
            //根据记录获取评价记录
            NavigationServiceEvaluation comment = navigationServiceEvaluationService.findByUseRecordId(record.getId());
@ -210,8 +221,11 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
            } else {
                record.setNavigationServiceEvaluationFlag("已评价");
            }
            //根据设施编码获取 设施状态
            Facility facility = facilityService.findByCode(facilityCode);
            record.setFacilitieStatus(facility.getStatus());
        }
        int count = (int)facilityUsedRecordService.getCount(filters);
        int count = (int) facilityUsedRecordService.getCount(filters);
        return success(facilityUsedRecordList, count, page, size);
    }

+ 6 - 7
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/FeedBackController.java

@ -53,8 +53,8 @@ public class FeedBackController extends EnvelopRestEndpoint {
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page) throws Exception {
        List<FeedBack> feedBackList = feedBackService.search(fields, filters, sorts, page, size);
        int count = (int)feedBackService.getCount(filters);
        return success(feedBackList,count, page, size);
        int count = (int) feedBackService.getCount(filters);
        return success(feedBackList, count, page, size);
    }
    @ApiOperation(value = "创建/更新(id存在)意见反馈")
@ -62,6 +62,7 @@ public class FeedBackController extends EnvelopRestEndpoint {
    public ObjEnvelop<FeedBack> createFeedBack(
            @ApiParam(name = "feedBack", value = "意见反馈JSON结构")
            @RequestBody FeedBack feedBack) throws IOException {
        feedBack.setFlag(1);
        feedBack = feedBackService.save(feedBack);
        return success(feedBack);
    }
@ -79,7 +80,7 @@ public class FeedBackController extends EnvelopRestEndpoint {
    }
    @ApiOperation(value = "管理员根据id获取/或回复意见反馈,需改变意见反馈回复状态")
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FeedBack.UPDATE_FEEDBACKS_BY_ID)
    @PostMapping(value = HealthyHouseMapping.HealthyHouse.FeedBack.UPDATE_FEEDBACKS_BY_ID)
    public ObjEnvelop<FeedBack> getFeedBackAndUpdate(
            @ApiParam(name = "id", value = "意见反馈ID(必要)", defaultValue = "")
            @RequestParam(value = "id", required = true) String id,
@ -94,9 +95,7 @@ public class FeedBackController extends EnvelopRestEndpoint {
            feedBackOld.setFlag(2);
            feedBackOld.setReplyContent(feedBack.getReplyContent());
            feedBackOld.setUpdateUser(feedBack.getUpdateUser());
        } else {
            //根据id获取意见反馈,打开待反馈信息
            feedBackOld.setFlag(1);
            feedBackOld.setUpdateUserName(feedBack.getUpdateUserName());
        }
        feedBackOld = feedBackService.save(feedBackOld);
        return success(feedBackOld);
@ -134,7 +133,7 @@ public class FeedBackController extends EnvelopRestEndpoint {
            @ApiParam(name = "sorts", value = "排序", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts) throws ManageException, ParseException {
        List<FeedBack> feedBackList = feedBackService.search(fields, filters, sorts);
        feedBackService.exportUsersExcel(response,feedBackList);
        feedBackService.exportUsersExcel(response, feedBackList);
    }
}

+ 13 - 3
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/NavigationServiceEvaluationController.java

@ -46,8 +46,8 @@ public class NavigationServiceEvaluationController extends EnvelopRestEndpoint {
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page) throws Exception {
        List<NavigationServiceEvaluation> navigationServiceEvaluationList = navigationServiceEvaluationService.search(fields, filters, sorts, page, size);
        int count = (int)navigationServiceEvaluationService.getCount(filters);
        return success(navigationServiceEvaluationList,count, page, size);
        int count = (int) navigationServiceEvaluationService.getCount(filters);
        return success(navigationServiceEvaluationList, count, page, size);
    }
    @ApiOperation(value = "创建/更新(id存在)服务评价")
@ -55,7 +55,17 @@ public class NavigationServiceEvaluationController extends EnvelopRestEndpoint {
    public ObjEnvelop<NavigationServiceEvaluation> createNavigationServiceEvaluation(
            @ApiParam(name = "navigationServiceEvaluation", value = "服务评价JSON结构")
            @RequestBody NavigationServiceEvaluation navigationServiceEvaluation) throws IOException {
        navigationServiceEvaluation = navigationServiceEvaluationService.save(navigationServiceEvaluation);
        //判断该导航记录是否已经评价
        NavigationServiceEvaluation navi = navigationServiceEvaluationService.findByUseRecordId(navigationServiceEvaluation.getUseRecordId());
        if (null != navi) {
            navi.setScore(navigationServiceEvaluation.getScore());
            navi.setRemark(navigationServiceEvaluation.getRemark());
            navigationServiceEvaluation = navigationServiceEvaluationService.save(navi);
        } else {
            navigationServiceEvaluation = navigationServiceEvaluationService.save(navigationServiceEvaluation);
        }
        return success(navigationServiceEvaluation);
    }

+ 206 - 55
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/UserController.java

@ -2,6 +2,7 @@ package com.yihu.jw.healthyhouse.controller.user;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.healthyhouse.cache.WlyyRedisVerifyCodeService;
import com.yihu.jw.healthyhouse.constant.LoginInfo;
import com.yihu.jw.healthyhouse.model.facility.Facility;
import com.yihu.jw.healthyhouse.model.user.User;
import com.yihu.jw.healthyhouse.service.user.UserService;
@ -10,11 +11,13 @@ import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.wlyy.HouseUserContant;
import com.yihu.jw.rm.health.house.HealthyHouseMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.write.Colour;
import jxl.write.WritableCellFormat;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.spi.ErrorCode;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@ -34,14 +37,15 @@ import java.util.Map;
import java.util.regex.Pattern;
/**
 *  用户相关 接口
 * 用户相关 接口
 *
 * @author HZY
 * @created 2018/9/19 17:29
 */
@Api(value = "UserController", description = "用户管理信息", tags = {"2用户管理"})
@RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class UserController  extends EnvelopRestEndpoint {
public class UserController extends EnvelopRestEndpoint {
    @Autowired
    private UserService userService;
@ -61,20 +65,20 @@ public class UserController  extends EnvelopRestEndpoint {
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) Integer size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page ) throws ManageException, ParseException {
            @RequestParam(value = "page", required = false) Integer page) throws ManageException, ParseException {
        List<User> userList = userService.search(fields, filters, sorts, page, size);
        int count = (int)userService.getCount(filters);
        return success(userList,count, page, size);
        int count = (int) userService.getCount(filters);
        return success(userList, count, page, size);
    }
    @GetMapping("/userDetail")
    @ApiOperation(value = "获取用户详情")
    public ObjEnvelop userDetail(
            @ApiParam(name = "userId", value = "用户id", required = true)@RequestParam(required = true, name = "userId") String userId ) {
            @ApiParam(name = "userId", value = "用户id", required = true) @RequestParam(required = true, name = "userId") String userId) {
        User user = userService.findById(userId);
        return ObjEnvelop.getSuccess("获取成功",user);
        return success("获取成功", user);
    }
@ -82,89 +86,236 @@ public class UserController  extends EnvelopRestEndpoint {
    @ApiOperation(value = "获取用户统计信息")
    public ObjEnvelop usedFacilityCount() {
        Map<String, Long> userStatistics = userService.findUserStatistics();
        return ObjEnvelop.getSuccess("获取成功",userStatistics);
        return success("获取成功", userStatistics);
    }
    @PostMapping("/activateUser")
    @ApiOperation(value = "用户激活")
    public Envelop activeUser(
            @ApiParam(name = "userId", value = "用户id", required = true)@RequestParam(required = true, name = "userId") String userId ,
            @ApiParam(name = "operator", value = "操作者ID", required = true)@RequestParam(required = true, name = "operator") String operator ) throws ManageException {
         userService.updateStatus(userId,operator, HouseUserContant.activated_active,null);
        return ObjEnvelop.getSuccess("激活成功");
    @ApiOperation(value = "新增/更新(idy已存在)用户信息")
    @PostMapping(value = "saveOrUpdate")
    public ObjEnvelop<User> saveOrUpdateUser(
            @ApiParam(name = "user", value = "用户JSON结构")
            @RequestBody User user) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isEmpty(user.getName())) {
            return failed("用户名称不能为空!", ObjEnvelop.class);
        }
        user = userService.save(user);
        return success(user);
    }
    @PostMapping("/updateUserActivated")
    @ApiOperation(value = "更改用户状态")
    public Envelop updateUserStatus(
            @ApiParam(name = "userId", value = "用户id", required = true) @RequestParam(required = true, name = "userId") String userId,
            @ApiParam(name = "status", value = "用户状态(0:冻结,1:在线,2:离线)", required = true) @RequestParam(required = true, name = "status") Integer status,
            @ApiParam(name = "operator", value = "操作者ID", required = true) @RequestParam(required = true, name = "operator") String operator) {
        try {
            userService.updateStatus(userId, operator, status, null);
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
        return success("冻结成功");
    }
    @PostMapping("/freezeUser")
    @ApiOperation(value = "用户冻结")
    public Envelop freezeUser(
            @ApiParam(name = "userId", value = "用户id", required = true)@RequestParam(required = true, name = "userId") String userId ,
            @ApiParam(name = "reason", value = "冻结原因", required = true)@RequestParam(required = true, name = "reason") String reason ,
            @ApiParam(name = "operator", value = "操作者ID", required = true)@RequestParam(required = true, name = "operator") String operator ) throws ManageException {
            @ApiParam(name = "userId", value = "用户id", required = true) @RequestParam(required = true, name = "userId") String userId,
            @ApiParam(name = "reason", value = "冻结原因", required = true) @RequestParam(required = true, name = "reason") String reason,
            @ApiParam(name = "operator", value = "操作者ID", required = true) @RequestParam(required = true, name = "operator") String operator) {
        userService.updateStatus(userId,operator, HouseUserContant.activated_lock,reason);
        return ObjEnvelop.getSuccess("冻结成功");
        try {
            userService.updateStatus(userId, operator, HouseUserContant.activated_lock, reason);
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
        return success("冻结成功");
    }
    @PostMapping("/activateUser")
    @ApiOperation(value = "用户激活")
    public Envelop activeUser(
            @ApiParam(name = "userId", value = "用户id", required = true) @RequestParam(required = true, name = "userId") String userId,
            @ApiParam(name = "operator", value = "操作者ID", required = true) @RequestParam(required = true, name = "operator") String operator) {
        try {
            userService.updateStatus(userId, operator, HouseUserContant.activated_active, null);
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
        return success("激活成功");
    }
    @PostMapping("/updatePwd")
    @ApiOperation(value = "更新密码")
    public Envelop updatePwd(
            @ApiParam(name = "userId", value = "用户Id", required = true)@RequestParam(required = true, name = "userId") String userId ,
            @ApiParam(name = "oldPwd", value = "原密码", required = true)@RequestParam(required = true, name = "oldPwd") String oldPwd ,
            @ApiParam(name = "newPwd", value = "新密码", required = true)@RequestParam(required = true, name = "newPwd") String newPwd ) throws ManageException {
            @ApiParam(name = "userId", value = "用户Id", required = true) @RequestParam(required = true, name = "userId") String userId,
            @ApiParam(name = "oldPwd", value = "原密码", required = true) @RequestParam(required = true, name = "oldPwd") String oldPwd,
            @ApiParam(name = "newPwd", value = "新密码", required = true) @RequestParam(required = true, name = "newPwd") String newPwd) {
        userService.updatePwd(userId,oldPwd,newPwd);
        return ObjEnvelop.getSuccess("更新密码成功");
        try {
            userService.updatePwd(userId, oldPwd, newPwd);
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
        return success("更新密码成功");
    }
    @PostMapping("/updatePhone")
    @ApiOperation(value = "更新安全手机号码")
    @ApiOperation(value = "【app端普通用户】更新安全手机号码")
    public Envelop updatePhone(
            @ApiParam(name = "clientId", value = "应用id", required = true)@RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "userId", value = "用户Id", required = true)@RequestParam(required = true, name = "userId") String userId ,
            @ApiParam(name = "newPhone", value = "新安全手机号", required = true)@RequestParam(required = true, name = "newPhone") String newPhone ,
            @ApiParam(name = "captcha", value = "短信验证码", required = true)@RequestParam(required = true, name = "captcha") String captcha ) throws ManageException {
        //验证码
        if (wlyyRedisVerifyCodeService.verification(clientId, newPhone, captcha)) {
            userService.updateSecurePhone(userId,newPhone);
            return ObjEnvelop.getSuccess("更新安全手机号码成功");
        } else {
            return ObjEnvelop.getError("验证码错误");
            @ApiParam(name = "clientId", value = "应用id", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "userId", value = "用户Id", required = true) @RequestParam(required = true, name = "userId") String userId,
            @ApiParam(name = "oldPhone", value = "旧安全手机号", required = true) @RequestParam(required = true, name = "oldPhone") String oldPhone,
            @ApiParam(name = "newPhone", value = "新安全手机号", required = true) @RequestParam(required = true, name = "newPhone") String newPhone,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(required = true, name = "captcha") String captcha) {
        try {
            User user = userService.findByTelephoneAndUserType(newPhone, LoginInfo.USER_TYPE_PATIENT);
            if (user != null) {
                return failed("手机号:" + newPhone + "已被绑定,可更换新手机号或直接登录!");
            }
            //验证码
            if (wlyyRedisVerifyCodeService.verification(clientId, newPhone, captcha)) {
                userService.updateSecurePhone(userId, newPhone);
                return success("更新安全手机号码成功");
            } else {
                return failed("验证码错误");
            }
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
    }
    @PostMapping("/updateAdminPhone")
    @ApiOperation(value = "【web端管理员】更新安全手机号码")
    public Envelop updateAdminPhone(
            @ApiParam(name = "clientId", value = "应用id", required = true) @RequestParam(required = true, name = "clientId") String clientId,
            @ApiParam(name = "userId", value = "用户Id", required = true) @RequestParam(required = true, name = "userId") String userId,
            @ApiParam(name = "newPhone", value = "新安全手机号", required = true) @RequestParam(required = true, name = "newPhone") String newPhone,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(required = true, name = "captcha") String captcha) {
        try {
            User user = userService.findByTelephoneAndUserType(newPhone, LoginInfo.USER_TYPE_SUPER_AdminManager);
            if (user != null) {
                return failed("手机号:" + newPhone + "已被绑定,可更换新手机号或直接登录!");
            }
            //验证码
            if (wlyyRedisVerifyCodeService.verification(clientId, newPhone, captcha)) {
                userService.updateAdministorSecurePhone(userId, newPhone);
                return success("更新安全手机号码成功");
            } else {
                return failed("验证码错误");
            }
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
    }
    @PostMapping("/checkIdCardNo")
    @ApiOperation(value = "用户身份证号码认证")
    @ApiOperation(value = "用户实名认证")
    public Envelop checkIdCardNo(
            @ApiParam(name = "userId", value = "用户Id", required = true)@RequestParam(required = true, name = "userId") String userId ,
            @ApiParam(name = "idCardNo", value = "身份证号码", required = true)@RequestParam(required = true, name = "idCardNo") String idCardNo ) throws ManageException {
            @ApiParam(name = "userId", value = "用户Id", required = true) @RequestParam(required = true, name = "userId") String userId,
            @ApiParam(name = "name", value = "用户姓名", required = true) @RequestParam(required = true, name = "name") String name,
            @ApiParam(name = "idCardNo", value = "身份证号码", required = true) @RequestParam(required = true, name = "idCardNo") String idCardNo) {
        try {
            userService.checkIdCardNo(userId, name, idCardNo);
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
        return success("用户实名认证完成!");
    }
    @GetMapping("/existence")
    @ApiOperation(value = "【管理员】-验证管理员是否存在")
    public Envelop existence(
            @ApiParam(name = "telephone", value = "管理员账号", required = true) @RequestParam(required = true, name = "telephone") String telephone) {
        try {
            boolean b = userService.checkManageUser(telephone);
            if (b) {
                return success("该管理员账号存在!", b);
            } else {
                return failed("该管理员账号不存在!");
            }
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
    }
    @GetMapping("/findUserByPhoneOrName")
    @ApiOperation(value = "根据手机号或者用户查询用户", notes = "找回密码时验证")
    public Envelop findUserByPhoneOrName(
            @ApiParam(name = "loginName", value = "管理员登录账号", required = true) @RequestParam(required = true, name = "loginName") String loginName) {
        User user = userService.findByLoginCodeAndUserType(loginName, LoginInfo.USER_TYPE_SUPER_AdminManager);
        if (user != null) {
            return success("该管理员账号存在!", user);
        } else {
            return failed("该管理员账号不存在!");
        }
    }
    @PostMapping(value = "/resetPassWord")
    @ApiOperation(value = "重设密码", notes = "根基传入的用户id和新的密码重设用户的密码")
    public Envelop resetPassWord(
            @ApiParam(name = "userId", value = "用户ID", defaultValue = "")
            @RequestParam(value = "userId") String userId,
            @ApiParam(name = "password", value = "密码", defaultValue = "")
            @RequestParam(value = "password") String password) {
        try {
            String resetPwd = userService.resetPwd(userId, password);
            return success("重设密码成功", password);
        } catch (ManageException e) {
            return failed(e.getMessage());
        }
        userService.checkIdCardNo(userId, idCardNo);
        return ObjEnvelop.getSuccess("身份证认证完成!");
    }
    @GetMapping("/exportToExcel")
    @ApiOperation(value = "用户列表导出excel")
    public void exportToExcel(
    public Envelop exportToExcel(
            HttpServletResponse response,
            @ApiParam(name = "city", value = "所在市区", required = false)@RequestParam(required = false, name = "city") String city,
            @ApiParam(name = "activated", value = "用户状态", required = false)@RequestParam(required = false, name = "activated") String activated ,
            @ApiParam(name = "name", value = "姓名/手机号", required = false)@RequestParam(required = false, name = "name") String name ,
            @ApiParam(name = "sort", value = "使用次数排序", required = false)@RequestParam(required = false, name = "sort") String sort) throws ManageException {
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts) {
        response.setCharacterEncoding("UTF-8");
        //获取用户数据
        Map<String, String> map = new HashMap<>();
        map.put("cityCode",city);
        map.put("activated",activated);
        map.put("name",name);
        map.put("telephone",name);
        List<User> userList = userService.userList( map, sort);
        userService.exportUsersExcel(response,userList);
        try {
            //获取用户数据
            List<User> userList = userService.search(fields, filters, sorts);
            userService.exportUsersExcel(response, userList);
            return success("导出成功");
        } catch (ManageException e) {
            return failed(e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @PostMapping(value = "/heartbeat")
    @ApiOperation(value = "用户在线-心跳接口", notes = "心跳接口")
    public Envelop heartbeat(
            @ApiParam(name = "userId", value = "用户ID", defaultValue = "")
            @RequestParam(value = "userId") String userId) {
        try {
            userService.setUserActivated(userId, 40);//客户端30s发送一次心跳,
            return success("心跳正常");
        } catch (Exception e) {
            return failed("心跳异常");
        }
    }
}

+ 2 - 2
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/facility/FacilityDao.java

@ -18,11 +18,11 @@ public interface FacilityDao extends JpaRepository<Facility, String> {
    Facility findById(String id);
    Facility findByLongitudeAndLatitude(double longitude, double latitude);
    List<Facility> findByLongitudeAndLatitude(double longitude, double latitude);
    Facility findByCode(String code);
    @Query("select f from Facility f where f.code in :code ")
    @Query("select f from Facility f where f.deleteFlag=0 and f.status = 0 and f.code in (:code) ")
    List<Facility> findByCode(@Param("code") List<String> code);
}

+ 6 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/facility/FacilityServerDao.java

@ -3,6 +3,8 @@ package com.yihu.jw.healthyhouse.dao.facility;
import com.yihu.jw.healthyhouse.model.facility.FacilityServer;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
 * 设施服务dao
 * @author zdm
@ -12,5 +14,9 @@ import org.springframework.data.jpa.repository.JpaRepository;
public interface FacilityServerDao extends JpaRepository<FacilityServer, Long> {
    FacilityServer findById(String id);
    FacilityServer findByCode(String code);
    List<FacilityServer> findByNameIn(List<String> name);
}

+ 1 - 1
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/user/FacilityUsedRecordDao.java

@ -14,7 +14,7 @@ public interface FacilityUsedRecordDao extends JpaRepository<FacilityUsedRecord,
    FacilityUsedRecord findById(String id);
    Long countByUserId(String userId);
    Long countAllByUserIdIsNotNull();
    Long countAllByCreateUserIsNotNull();
    long countByFacilitieCodeAndCreateUser(String facilitieCode,String createUser);
}

+ 22 - 5
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/user/UserDao.java

@ -7,7 +7,9 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
 * @author HZY
@ -15,11 +17,14 @@ import java.util.Date;
 */
public interface UserDao extends PagingAndSortingRepository<User, String>, JpaSpecificationExecutor<User> {
    User findByIdAAndActivated(String id,String activated);
    User findByIdAndActivated(String id,String activated);
    User findById(String id);
    @Query("from User u where u.loginCode=?1 and u.activated<>0 ")
    User findByLoginCodeAndActivated(String loginCode,String activated);
    User findByLoginCode(String loginCode);
    @Query("from User u where u.name=?1 and u.activated=?2 ")
    User findByNameAAndActivated(String name,String activated);
@ -32,12 +37,24 @@ public interface UserDao extends PagingAndSortingRepository<User, String>, JpaSp
    @Query("select sum (u.facilityUsedCount) from User u")
    Long sumFacilityUseCout();
    Long countAllByActivated(Integer activated);
    Long countAllByActivatedAndUserType(Integer activated,String userType);
    Long countAllByUserType(String userType);
    Long countAllByCreateTimeBetween(Date start,Date end);
    Long countAllByUserTypeAndCreateTimeBetween(String userType,Date start,Date end);
    User findByLoginCodeAndUserType(String loginCode,String userType);
    @Query("from User u where u.userType=?1 and (u.telephone=?2 or u.loginCode=?3 ) ")
    User findByUserTypeAndTelephoneOrLoginCode(String userType,String telephone,String loginCode);
    User findByTelephoneAndUserType(String telephone,String userType);
    @Transactional
    @Modifying
    @Query("update User u set u.activated = 2 where u.activated = 1 and u.id not in ?1")
    void updateUserOffLine(List<Serializable> ids);
    @Transactional
    @Modifying
    @Query("update User u set u.activated = 1 where u.activated = 2 and u.id in ?1")
    void updateUserOnLine(List<Serializable> ids);
}

+ 157 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/interceptor/ActivatedInterceptor.java

@ -0,0 +1,157 @@
package com.yihu.jw.healthyhouse.interceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.healthyhouse.constant.LoginInfo;
import com.yihu.jw.healthyhouse.model.user.User;
import com.yihu.jw.healthyhouse.service.user.UserService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.wlyy.HouseUserContant;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import net.sf.json.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
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 javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
 *  用户在线状态验证拦截器
 * @author HZY
 * @created 2018/10/9 9:19
 */
//@Aspect
//@Component
public class ActivatedInterceptor  {
    private static final Logger logger = LoggerFactory.getLogger(ActivatedInterceptor.class);
    @Autowired
    private UserService userService;
//    @Around("execution(* com.yihu.jw.healthyhouse.controller..*.*(..))")
//    public Object logAround(ProceedingJoinPoint  joinPoint) throws Throwable{
//        ObjectMapper objectMapper = new ObjectMapper();
//        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
//        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
//        HttpServletRequest request = sra.getRequest();
//        HttpSession session = request.getSession();
//        String method = request.getMethod();
//        String queryString = request.getQueryString();
//
//        String classType = joinPoint.getTarget().getClass().getName();
//        Class<?> clazz = Class.forName(classType);
//        String clazzName = clazz.getName();
//        String methodName = joinPoint.getSignature().getName(); //获取方法名称
//        Object[] args = joinPoint.getArgs();//参数
//
//        String params = "";
//        //获取请求参数集合并进行遍历拼接
//        if(args.length>0){
//            if("POST".equals(method)){
//                Object object = args[0];
//                Map map = getFieldsName(this.getClass(), clazzName, methodName,args);
//                params = objectMapper.writeValueAsString(map);
//            }else if("GET".equals(method)){
//                Map<String, String[]> parameterMap = request.getParameterMap();
//                params = objectMapper.writeValueAsString(parameterMap);;
//            }
//        }
//        //获取参数名称和值
////        Map<String,Object > nameAndArgs = getFieldsName(this.getClass(), clazzName, methodName,args);
//        System.out.println(params);
//        return  joinPoint.proceed();
//
//    }
    @Around("execution(* com.yihu.jw.healthyhouse.controller..*.*(..))")
    public Object activatedAround(ProceedingJoinPoint  joinPoint) throws Throwable{
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        HttpServletResponse response = sra.getResponse();
        HttpSession session = request.getSession();
        Object userId = session.getAttribute(LoginInfo.USER_ID);
        if (userId == null ){
            response.setStatus(402);
            return  joinPoint.proceed();
//            return failed("用户未登录,请登录!",-10000);
        }
        User user = userService.findById(userId.toString());
        if (user == null ){
            response.setStatus(402);
            return  joinPoint.proceed();
//            return failed("用户不存在,请重新登录!",-10000);
        }else if (HouseUserContant.activated_lock.equals(user.getActivated())){
            response.setStatus(402);
//           return failed("用户已被冻结,请联系管理员!",-10000);
        }else if (HouseUserContant.activated_offline.equals(user.getActivated())){
            response.setStatus(402);
//            return failed("用户已离线,请重新登录!",-10000);
        }else {
//            return  joinPoint.proceed();
        }
        return  joinPoint.proceed();
    }
    private Map<String, Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
        Map<String, Object> map = new HashMap<String, Object>();
        ClassPool pool = ClassPool.getDefault();
        //ClassClassPath classPath = new ClassClassPath(this.getClass());
        ClassClassPath classPath = new ClassClassPath(cls);
        pool.insertClassPath(classPath);
        CtClass cc = pool.get(clazzName);
        CtMethod cm = cc.getDeclaredMethod(methodName);
        MethodInfo methodInfo = cm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
        if (attr == null) {
            // exception
        }
        // String[] paramNames = new String[cm.getParameterTypes().length];
        int pos = Modifier.isStatic(cm.getModifiers()) ? 1 : 2;
        for (int i = 0; i < cm.getParameterTypes().length; i++) {
            map.put(attr.variableName(i + pos), args[i]);//paramNames即参数名
        }
        return map;
    }
    protected Envelop failed (String message, int status) {
        Envelop envelop = new Envelop();
        envelop.setMessage(message);
        envelop.setStatus(status);
        return envelop;
    }
}

+ 49 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/job/ActivatedUserUpdateTask.java

@ -0,0 +1,49 @@
package com.yihu.jw.healthyhouse.job;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.healthyhouse.service.user.UserService;
import com.yihu.jw.healthyhouse.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.*;
/**
 * Task - 定时检查集群状态,提高解析任务容错率
 * Created by progr1mmer on 2017/12/15.
 */
@Component
public class ActivatedUserUpdateTask {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private UserService userService;
    @Scheduled(cron = "0/30 * * * * ?")
    private void startTask() {
        List<String> keys = new ArrayList<>();
        String pattern = "healthyHouse:*:activated";
        Set<String> keys1 = redisClient.keys(pattern);
        List<Serializable> ids = redisClient.multiGet(keys1);
        try {
            if (ids!=null && ids.size()>0) {
                userService.updateUserOffLine(ids);
            }
        } catch (ManageException e) {
            e.printStackTrace();
        }
    }
}

+ 29 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/listener/RedisKeyExpirationListener.java

@ -0,0 +1,29 @@
package com.yihu.jw.healthyhouse.listener;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
 *  redis key 过期通知监听
 * @author HZY
 * @created 2018/10/8 15:11
 */
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
//      System.out.println(new String(message.getBody()));
//      System.out.println(new String(message.getChannel()));
//      System.out.println(new String(pattern));
//      super.onMessage(message, pattern);
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        System.out.println(expiredKey);
    }
}

+ 13 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/facility/Facility.java

@ -86,6 +86,10 @@ public class Facility extends UuidIdentityEntityWithOperator {
    @Column(name = "img_path")
    private String imgPath;
    //设施是否删除:默认0为未删除、1为已删除
    @Column(name = "delete_flag")
    private String deleteFlag;
    private String statusName;
    private String  categoryValue ;
    private List<FacilityServerRelation> facilityServerRelation;
@ -317,4 +321,13 @@ public class Facility extends UuidIdentityEntityWithOperator {
//        }
//        return address;
//    }
    public String getDeleteFlag() {
        return deleteFlag;
    }
    public void setDeleteFlag(String deleteFlag) {
        this.deleteFlag = deleteFlag;
    }
}

+ 16 - 1
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/FacilityUsedRecord.java

@ -11,6 +11,7 @@ import java.util.List;
/**
 * 用户导航记录
 *
 * @author zdm
 * @version 1.0
 * @created 2018.09.21
@ -65,6 +66,9 @@ public class FacilityUsedRecord extends UuidIdentityEntityWithOperator {
    //设施关联的服务名称
    private String facilityRelationServiceName;
    //设施状态
    private String facilitieStatus;
    //评价记录
    private String navigationServiceEvaluationFlag;
@ -179,14 +183,16 @@ public class FacilityUsedRecord extends UuidIdentityEntityWithOperator {
    public void setFacilitieId(String facilitieId) {
        this.facilitieId = facilitieId;
    }
    @Transient
    public String getFacilityRelationServiceName() {
        return facilityRelationServiceName;
    }
    public void setFacilityRelationServiceName(String facilityRelationServiceName) {
        this.facilityRelationServiceName =facilityRelationServiceName;
        this.facilityRelationServiceName = facilityRelationServiceName;
    }
    @Transient
    public String getNavigationServiceEvaluationFlag() {
        return navigationServiceEvaluationFlag;
@ -195,4 +201,13 @@ public class FacilityUsedRecord extends UuidIdentityEntityWithOperator {
    public void setNavigationServiceEvaluationFlag(String navigationServiceEvaluationFlag) {
        this.navigationServiceEvaluationFlag = navigationServiceEvaluationFlag;
    }
    @Transient
    public String getFacilitieStatus() {
        return facilitieStatus;
    }
    public void setFacilitieStatus(String facilitieStatus) {
        this.facilitieStatus = facilitieStatus;
    }
}

+ 34 - 1
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/User.java

@ -46,6 +46,8 @@ public class User extends UuidIdentityEntityWithOperator {
    private String activatedContent;       //账户冻结原因
    @Column(name = "province_code", nullable = false)
    private String provinceCode;    //省编码
    @Column(name = "province_name", nullable = false)
    private String provinceName;    //省名称
    @Column(name = "city_code", nullable = false)
    private String cityCode;        //市编码
    @Column(name = "city_name", nullable = false)
@ -59,7 +61,7 @@ public class User extends UuidIdentityEntityWithOperator {
    @Column(name = "salt")
    private String salt; //加密种子
    @Column(name = "facility_used_count")
    @Column(name = "facility_used_count",columnDefinition="int default 1")
    private Integer facilityUsedCount;//设施使用次数
    @Column(name = "realname_authentication")
@ -69,6 +71,10 @@ public class User extends UuidIdentityEntityWithOperator {
    @Column(name = "ijk_authentication")
    private String ijkAuthentication;//i健康认证
    @Column(name = "organization_code")
    private String organizationCode;//机构编码
    @Column(name = "organization_name")
    private String organizationName;//机构名称
    public String getLoginCode() {
        return loginCode;
@ -254,9 +260,28 @@ public class User extends UuidIdentityEntityWithOperator {
        this.ijkAuthentication = ijkAuthentication;
    }
    public String getOrganizationCode() {
        return organizationCode;
    }
    public void setOrganizationCode(String organizationCode) {
        this.organizationCode = organizationCode;
    }
    public String getOrganizationName() {
        return organizationName;
    }
    public void setOrganizationName(String organizationName) {
        this.organizationName = organizationName;
    }
    @Transient
    public String getAddress() {
        String address = "";
        if (this.getProvinceName() != null) {
            address += this.getProvinceName();
        }
        if (this.getCityName() != null) {
            address += this.getCityName();
        }
@ -281,4 +306,12 @@ public class User extends UuidIdentityEntityWithOperator {
        }
        return genderValue;
    }
    public String getProvinceName() {
        return provinceName;
    }
    public void setProvinceName(String provinceName) {
        this.provinceName = provinceName;
    }
}

+ 19 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/facility/FacilityServerService.java

@ -31,5 +31,24 @@ public class FacilityServerService extends BaseJpaService<FacilityServer, Facili
        return  facilityServerDao.findById(id);
    }
    public List<FacilityServer> findByNameIn (List<String> names) {
       return facilityServerDao.findByNameIn(names);
    }
    /**
     * 设施服务编码生成
     *
     * @return
     */
    public String genFacilityServerCode() {
        String code = "HFHS" + randomString(5);
        FacilityServer facility = facilityServerDao.findByCode(code);
        while (facility != null) {
            code = "HFHS" + randomString(5);
            facility = facilityServerDao.findByCode(code);
        }
        return code;
    }
}

+ 211 - 67
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/facility/FacilityService.java

@ -1,13 +1,19 @@
package com.yihu.jw.healthyhouse.service.facility;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.healthyhouse.dao.facility.FacilityDao;
import com.yihu.jw.healthyhouse.dao.facility.FacilityServerRelationDao;
import com.yihu.jw.healthyhouse.model.facility.Facility;
import com.yihu.jw.healthyhouse.model.facility.FacilityServer;
import com.yihu.jw.healthyhouse.model.facility.FacilityServerRelation;
import com.yihu.jw.healthyhouse.service.area.BaseCityService;
import com.yihu.jw.healthyhouse.service.area.BaseTownService;
import com.yihu.jw.healthyhouse.service.dict.SystemDictEntryService;
import com.yihu.jw.healthyhouse.util.facility.msg.FacilityMsg;
import com.yihu.jw.healthyhouse.util.poi.ExcelUtils;
import com.yihu.jw.util.http.HTTPResponse;
import com.yihu.jw.util.http.HttpClientKit;
import com.yihu.mysql.query.BaseJpaService;
import jxl.write.Colour;
import jxl.write.WritableCellFormat;
@ -17,18 +23,15 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.*;
/**
 * 设施管理器.
@ -49,23 +52,28 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
    private BaseTownService baseTownService;
    @Autowired
    private SystemDictEntryService systemDictEntryService;
    @Autowired
    private FacilityServerService facilityServerService;
    @Autowired
    private FacilityServerRelationDao facilityServerRelationDao;
    public Facility findById(String id) {
        return  facilityDao.findById(id);
        return facilityDao.findById(id);
    }
    public boolean isHasFacility(double longitude,double latitude){
    public boolean isHasFacility(double longitude, double latitude) {
        boolean flag = false;
        Facility facility = facilityDao.findByLongitudeAndLatitude(longitude, latitude);
        if (facility!=null) {
        List<Facility> facilitys = facilityDao.findByLongitudeAndLatitude(longitude, latitude);
        if (facilitys != null && facilitys.size() > 0) {
            flag = true;
        }
        return flag;
    }
    //excel中添加固定内容
    private void addStaticCell(Sheet sheet){
    private void addStaticCell(Sheet sheet) {
        //设置样式
        Workbook workbook = sheet.getWorkbook();
        CellStyle style = workbook.createCellStyle();
@ -76,41 +84,40 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
        style.setFont(font);
        ExcelUtils.addCellData(sheet,0,0,"序号",style);
        ExcelUtils.addCellData(sheet,1,0,"设施编码",style);
        ExcelUtils.addCellData(sheet,2,0,"设施类型名称",style);
        ExcelUtils.addCellData(sheet,3,0,"设施详细地址",style);
        ExcelUtils.addCellData(sheet,4,0,"联系人",style);
        ExcelUtils.addCellData(sheet,5,0,"联系方式",style);
        ExcelUtils.addCellData(sheet,6,0,"所在省",style);
        ExcelUtils.addCellData(sheet,7,0,"所在市",style);
        ExcelUtils.addCellData(sheet,8,0,"所在区",style);
        ExcelUtils.addCellData(sheet,9,0,"所在街道",style);
        ExcelUtils.addCellData(sheet,10,0,"运营状态",style);
        ExcelUtils.addCellData(sheet,2,0,"设施名称",style);
        ExcelUtils.addCellData(sheet,3,0,"设施类型名称",style);
        ExcelUtils.addCellData(sheet,4,0,"设施详细地址",style);
        ExcelUtils.addCellData(sheet,5,0,"联系人",style);
        ExcelUtils.addCellData(sheet,6,0,"联系方式",style);
        ExcelUtils.addCellData(sheet,7,0,"所在省",style);
        ExcelUtils.addCellData(sheet,8,0,"所在市",style);
        ExcelUtils.addCellData(sheet,9,0,"所在区",style);
        ExcelUtils.addCellData(sheet,10,0,"所在街道",style);
        ExcelUtils.addCellData(sheet,11,0,"运营状态",style);
    }
    /**
     *  导出设施列表excel
     * @param response  响应体
     * @param facilityList  用户列表
     * 导出设施列表excel
     *
     * @param response     响应体
     * @param facilityList 用户列表
     * @throws ManageException
     */
    public void exportFacilityExcel(HttpServletResponse response, List<Facility> facilityList) throws ManageException {
        try {
            String fileName = "健康小屋-设施列表";
            //设置下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" )+".xlsx");
                    + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            OutputStream os = response.getOutputStream();
            //获取导出数据集
            JSONObject order = new JSONObject();
            order.put("id","asc");
            //写excel
            Workbook workbook = new XSSFWorkbook();
            int k=0;
            int k = 0;
            Facility metaData = null;
            int row=0;
            int row = 0;
            //创建Excel工作表 指定名称和位置
            String streetName = "健康小屋-设施列表";
            Sheet sheet = workbook.createSheet(streetName);
@ -118,20 +125,21 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
            //添加数据元信息
            WritableCellFormat wc = new WritableCellFormat();
            wc.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, Colour.SKY_BLUE);//边框
            for(int j=0;k<facilityList.size(); j++,k++){
            for (int j = 0; k < facilityList.size(); j++, k++) {
                metaData = facilityList.get(k);
                row=j+1;
                ExcelUtils.addCellData(sheet,0,row,j+1+"");//序号
                ExcelUtils.addCellData(sheet,1,row, metaData.getCode());//设施编码
                ExcelUtils.addCellData(sheet,2,row, metaData.getCategory().toString());//类型名称
                ExcelUtils.addCellData(sheet,3,row, metaData.getAddress());//信息地址
                ExcelUtils.addCellData(sheet,4,row, metaData.getUserName());//联系人
                ExcelUtils.addCellData(sheet,5,row, metaData.getUserTelephone());//联系电话
                ExcelUtils.addCellData(sheet,6,row, metaData.getProvinceId());//省
                ExcelUtils.addCellData(sheet,7,row, metaData.getCityName());//市
                ExcelUtils.addCellData(sheet,8,row, metaData.getCountyName());//区县
                ExcelUtils.addCellData(sheet,9,row, metaData.getStreet());//街道
                ExcelUtils.addCellData(sheet,10,row, metaData.getStatus());//运营状态
                row = j + 1;
                ExcelUtils.addCellData(sheet, 0, row, j + 1 + "");//序号
                ExcelUtils.addCellData(sheet, 1, row, metaData.getCode());//设施编码
                ExcelUtils.addCellData(sheet, 2, row, metaData.getName());//设施名称
                ExcelUtils.addCellData(sheet, 3, row, metaData.getCategoryValue());//类型名称
                ExcelUtils.addCellData(sheet, 4, row, metaData.getAddress());//信息地址
                ExcelUtils.addCellData(sheet, 5, row, metaData.getUserName());//联系人
                ExcelUtils.addCellData(sheet, 6, row, metaData.getUserTelephone());//联系电话
                ExcelUtils.addCellData(sheet, 7, row, metaData.getProvinceId());//省
                ExcelUtils.addCellData(sheet, 8, row, metaData.getCityName());//市
                ExcelUtils.addCellData(sheet, 9, row, metaData.getCountyName());//区县
                ExcelUtils.addCellData(sheet, 10, row, metaData.getStreet());//街道
                ExcelUtils.addCellData(sheet, 11, row, metaData.getStatusName());//运营状态
            }
@ -141,17 +149,18 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
            os.flush();
            os.close();
        } catch (Exception e) {
            throw new ManageException("导出设施列表异常",e);
            throw new ManageException("导出设施列表异常", e);
        }
    }
    /**
     * 批量导入设施的集合
     * @param facilities    设施列表
     *
     * @param facilities 设施列表
     */
    public Map<String,Object> batchInsertFacility(List<FacilityMsg> facilities) throws ManageException{
        Map<String,Object> result = new HashMap<>();
    public Map<String, Object> batchInsertFacility(List<FacilityMsg> facilities) throws ManageException {
        Map<String, Object> result = new HashMap<>();
        //批量存储的集合
        int correctCount = 0;
        List<Facility> corrects = new ArrayList<>();
@ -159,14 +168,15 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
        Facility facility = null;
        //批量存储
        for(FacilityMsg facilityMsg : facilities) {
        for (FacilityMsg facilityMsg : facilities) {
            facility = new Facility();
            Double longitude = StringUtils.isEmpty(facilityMsg.getLongitude()) ? null :Double.parseDouble(facilityMsg.getLongitude());
            Double latitude = StringUtils.isEmpty(facilityMsg.getLongitude()) ? null :Double.parseDouble(facilityMsg.getLongitude());
            Double longitude = StringUtils.isEmpty(facilityMsg.getLongitude()) ? null : Double.parseDouble(facilityMsg.getLongitude());
            Double latitude = StringUtils.isEmpty(facilityMsg.getLongitude()) ? null : Double.parseDouble(facilityMsg.getLongitude());
            String cityCode = baseCityService.getCodeByname(facilityMsg.getCity());
            String townCode = baseTownService.getCodeByname(facilityMsg.getCounty());
            Integer categoryCode = systemDictEntryService.getDictEntryCodeByName("FacilityType",facilityMsg.getCategory());
            Integer categoryCode = systemDictEntryService.getDictEntryCodeByName("FacilityType", facilityMsg.getCategory());
            facility.setCode(genFacilityCode());
            facility.setName(facilityMsg.getName());
            facility.setCategory(categoryCode);
            facility.setCategoryValue(facilityMsg.getCategory());
            facility.setUserName(facilityMsg.getUserName());
@ -177,6 +187,7 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
            facility.setCountyCode(townCode);
            facility.setCountyName(facilityMsg.getCounty());
            facility.setStreet(facilityMsg.getStreet());
            facility.setAddress(facilityMsg.getCity() + facilityMsg.getCounty() + facilityMsg.getStreet());
            facility.setStatus(facilityMsg.getStatus());
            facility.setOrgName(facilityMsg.getOrgName());
            facility.setServiceDay(facilityMsg.getServiceDate());
@ -185,58 +196,191 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
            facility.setLongitude(longitude);
            facility.setLatitude(latitude);
            if (isHasFacility(longitude,latitude)) {
            if (isHasFacility(longitude, latitude)) {
                errors.add(facility);
            }else {
            } else {
                corrects.add(facility);
            }
            if (corrects.size()>100){
            if (corrects.size() > 100) {
                facilityDao.save(corrects);
                correctCount +=corrects.size();
                correctCount += corrects.size();
                corrects.clear();
            }
        }
        if(!corrects.isEmpty()) {
        if (!corrects.isEmpty()) {
            facilityDao.save(corrects);
            correctCount +=corrects.size();
            correctCount += corrects.size();
        }
        result.put("correctCount",correctCount);
        result.put("errors",errors);
        result.put("correctCount", correctCount);
        result.put("errors", errors);
        return result;
    }
    /**
     * 设施编码生成
     *
     * @return
     */
    public String genFacilityCode(){
        return "CSHF" + randomString(5);
    public String genFacilityCode() {
        String code = "CSHF" + randomString(5);
        Facility facility = facilityDao.findByCode(code);
        while (facility != null) {
            code = "CSHF" + randomString(5);
            facility = facilityDao.findByCode(code);
        }
        return code;
    }
    /**
     * 根据服务类型获取设施
     */
    public List<String> getFacilityCodeByServerType(String type){
    public List<String> getFacilityCodeByServerType(String type) {
        Session s = currentSession();
        String hql = "(SELECT  DISTINCT fsr.facilitie_code FROM  facility_server_relation fsr,facility_server fs WHERE fsr.service_code=fs.code and fs.type=:type)";
        Query query = s.createSQLQuery(hql);
        query.setParameter("type",type);
        query.setParameter("type", type);
        return query.list();
    }
    public List<String> getFacilityCodeByServerCode( String[] codes)
    {
        String sql =  "(SELECT  DISTINCT fsr.facilitie_code FROM  facility_server_relation fsr WHERE fsr.service_code IN(:codes))";
    public List<String> getFacilityCodeByServerCode(String[] codes) {
        String sql = "(SELECT  DISTINCT fsr.facilitie_code FROM  facility_server_relation fsr WHERE fsr.service_code IN(:codes))";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameterList("codes", codes);
        return sqlQuery.list();
    }
    public List<Facility> getFacilityByFacilityCode( List<String> facilityCodes){
    public List<Facility> getFacilityByFacilityCode(List<String> facilityCodes) {
        return facilityDao.findByCode(facilityCodes);
    }
    public boolean checkFacilityByFacilityId(String id, String fild, String value) {
        SQLQuery sqlQuery;
        String sql = "";
        if (fild.equals("code")) {
            //验证编码
            sql = "select count(1) from facility f where  f.status = 0 and f.code =:code and f.id !=:id";
            sqlQuery = currentSession().createSQLQuery(sql);
            sqlQuery.setParameter("id", id);
            sqlQuery.setParameter("code", value);
            BigInteger count = (BigInteger) sqlQuery.uniqueResult();
            return count.compareTo(new BigInteger("0")) > 0;
        } else {
            //验证名称
            sql = "select count(1) from facility f where  f.status = 0 and f.name =:name and f.id !=:id";
            sqlQuery = currentSession().createSQLQuery(sql);
            sqlQuery.setParameter("id", id);
            sqlQuery.setParameter("name", value);
            BigInteger count = (BigInteger) sqlQuery.uniqueResult();
            return count.compareTo(new BigInteger("0")) > 0;
        }
    }
    public Facility findByCode(String code) {
        return facilityDao.findByCode(code);
    }
    /**
     *  //TODO 临时方法
     * 批量导入设施的集合
     *
     * @param facilities 设施列表
     */
    public Map<String, Object> batchInsertDemo(List<Map<String,String> > facilities) throws ManageException, IOException {
        Map<String, Object> result = new HashMap<>();
        //批量存储的集合
        int correctCount = 0;
        List<Facility> corrects = new ArrayList<>();
        List<Facility> errors = new ArrayList<>();
        Facility facility = null;
        //批量存储
        for (Map<String,String> facilityMsg : facilities) {
            facility = new Facility();
            facility.setCode(genFacilityCode());
            facility.setName(facilityMsg.get("street")+"_健康小屋");
            facility.setCategory(1);
            facility.setCategoryValue("健康小屋");
            facility.setProvinceId("350000");
            facility.setCityCode("350200");
            facility.setCityName("厦门市");
            facility.setCountyCode(baseTownService.getCodeByname(facilityMsg.get("county")));
            facility.setCountyName(facilityMsg.get("county"));
            facility.setStreet(facilityMsg.get("street"));
            if (!facilityMsg.get("address").contains("厦门市")) {
                facility.setAddress("厦门市" + facilityMsg.get("address"));
            }else {
                facility.setAddress(facilityMsg.get("address"));
            }
            facility.setStatus("0");
            facility.setDeleteFlag("0");
            getLatAndlon(facility);//获取经纬度
            //已添加过的经纬度不再次导入
            if (isHasFacility(facility.getLongitude(), facility.getLatitude())) {
                errors.add(facility);
            } else {
                //获取设施服务
                String servies = facilityMsg.get("service");
                String[] serviceArr= servies.split("、");
                List<FacilityServer> facilityServers = facilityServerService.findByNameIn(Arrays.asList(serviceArr));
                if (facilities!=null ){
                    List<FacilityServerRelation> relations = new ArrayList<>();
                    for (FacilityServer facilityServer : facilityServers) {
                        //遍历添加设施项目
                        FacilityServerRelation relation = new FacilityServerRelation();
                        relation.setFacilitieCode(facility.getCode());
                        relation.setFacilitieName(facility.getName());
                        relation.setServiceCode(facilityServer.getCode());
                        relation.setServiceName(facilityServer.getName());
                        relation.setServiceName(facilityServer.getName());
                        relations.add(relation);
                    }
                    facilityServerRelationDao.save(relations);
                }
                corrects.add(facility);
            }
            if (corrects.size() > 100) {
                facilityDao.save(corrects);
                correctCount += corrects.size();
                corrects.clear();
            }
        }
        if (!corrects.isEmpty()) {
            facilityDao.save(corrects);
            correctCount += corrects.size();
        }
        result.put("correctCount", correctCount);
        result.put("errors", errors);
        return result;
    }
    /**
     *  //TODO  临时方法
     * 获取经纬度
     * @param facility
     * @throws IOException
     */
    public void getLatAndlon(Facility facility) throws IOException {
        String url = "http://api.map.baidu.com/geocoder/v2/?address="+ facility.getAddress() + "&output=json&ak=465443b4e84fb6823359e5921915e8dc";
        HTTPResponse httpResponse = HttpClientKit.get(url);
        if (httpResponse.getStatusCode() == 200) {
            String result = httpResponse.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String,Object> map = objectMapper.readValue(result,Map.class);
            Map result1 = (Map) map.get("result");
            Map<String,Double> location = (Map<String, Double>) result1.get("location");
            facility.setLatitude(location.get("lat"));
            facility.setLongitude(location.get("lng"));
            System.out.println(result);
        }
    }
}

+ 1 - 1
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/FacilityUsedRecordService.java

@ -58,7 +58,7 @@ public class FacilityUsedRecordService extends BaseJpaService<FacilityUsedRecord
    }
    public Long countAll() {
        return facilityUsedRecordDao.countAllByUserIdIsNotNull();
        return facilityUsedRecordDao.countAllByCreateUserIsNotNull();
    }
    //根据用户id及设施编码统计历史导航记录总数

+ 87 - 9
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/LoginService.java

@ -1,13 +1,14 @@
package com.yihu.jw.healthyhouse.service.user;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.base.sms.SmsGatewayDO;
import com.sun.org.apache.bcel.internal.generic.I2F;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.healthyhouse.cache.WlyyRedisVerifyCodeService;
import com.yihu.jw.healthyhouse.constant.LoginInfo;
import com.yihu.jw.healthyhouse.constant.UserConstant;
import com.yihu.jw.healthyhouse.model.user.User;
import com.yihu.jw.restmodel.wlyy.HouseUserContant;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.security.MD5;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
@ -25,7 +26,6 @@ import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -64,6 +64,11 @@ public class LoginService  extends BaseJpaService {
            // 更新身份证验证字段
            user.setPhoneAuthentication(UserConstant.AUTHORIZED);
            user.setPassword(LoginInfo.DEFAULT_PASSWORD);
            user.setUserType(LoginInfo.USER_TYPE_PATIENT);
        }
        if (HouseUserContant.activated_lock.equals(user.getActivated())) {
            throw new ManageException("该用户已被冻结!");
        }
        //已注册用户更改用户状态
        user.setActivated(HouseUserContant.activated_active);
@ -73,7 +78,7 @@ public class LoginService  extends BaseJpaService {
        request.getSession().setAttribute(LoginInfo.LOGIN_CODE, user.getLoginCode());
        request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
        user.setLastLoginTime(new Date());
        userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_PHONE);
        user= userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_PHONE);
        return user;
    }
@ -101,6 +106,8 @@ public class LoginService  extends BaseJpaService {
                user.setGender((String) data.get("gender"));
                user.setIdCardNo((String) data.get("idcard"));
                user.setTelephone((String) data.get("mobile"));
                user.setUserType(LoginInfo.USER_TYPE_PATIENT);
                user.setIjkAuthentication(UserConstant.AUTHORIZED);
            } else {
                String message = "账号不存在";
@ -117,7 +124,7 @@ public class LoginService  extends BaseJpaService {
        request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
        user.setActivated(HouseUserContant.activated_active);
        user.setLastLoginTime(new Date());
        userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_IJK);
        user= userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_IJK);
        return user;
    }
@ -177,7 +184,7 @@ public class LoginService  extends BaseJpaService {
        request.getSession().removeAttribute(LoginInfo.LOGIN_NAME);
        request.getSession().removeAttribute(LoginInfo.USER_ID);
        user.setActivated(HouseUserContant.activated_offline);
        userService.saveOrUpdate(user, "systemLogin");
        user= userService.saveOrUpdate(user, "systemLogin");
        return user;
    }
@ -264,10 +271,13 @@ public class LoginService  extends BaseJpaService {
    @Transactional(noRollbackForClassName = "ManageException")
    public User managerPhoneLogin(HttpServletRequest request, String loginCode) throws ManageException {
        //判断管理员用户信息是否存在
        User user = userService.findByLoginCodeAndUserType(loginCode, LoginInfo.USER_TYPE_AdminManager);
        User user = userService.findByTelephoneAndUserType(loginCode, LoginInfo.USER_TYPE_SUPER_AdminManager);
        if (user == null) {
            throw new ManageException("该管理员账号不存在!");
        } else {
            if (HouseUserContant.activated_lock.equals(user.getActivated())) {
                throw new ManageException("该用户已被冻结!");
            }
            //已注册用户更改用户状态
            user.setActivated(HouseUserContant.activated_active);
            request.getSession().setAttribute(LoginInfo.IS_LOGIN, true);
@ -276,7 +286,7 @@ public class LoginService  extends BaseJpaService {
            request.getSession().setAttribute(LoginInfo.LOGIN_CODE, user.getLoginCode());
            request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
            user.setLastLoginTime(new Date());
            userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_PHONE);
            user=  userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_PHONE);
        }
        return user;
    }
@ -294,11 +304,15 @@ public class LoginService  extends BaseJpaService {
    @Transactional(noRollbackForClassName = "ManageException")
    public User managerLogin(HttpServletRequest request, String clientId, String loginCode, String password) throws ManageException {
        //判断登陆信息是否正确
        User user = userService.findByCode(loginCode);
        User user = userService.findByLoginCodeAndUserType(loginCode, LoginInfo.USER_TYPE_SUPER_AdminManager);
        if (user == null) {
            String message = "该管理员账号不存在!";
            throw new ManageException(message);
        } else {
            if (HouseUserContant.activated_lock.equals(user.getActivated())) {
                throw new ManageException("该用户已被冻结!");
            }
            if (!user.getPassword().equals(MD5.GetMD5Code(password + user.getSalt()))) {
                String message = "密码错误";
                throw new ManageException(message);
@ -309,10 +323,74 @@ public class LoginService  extends BaseJpaService {
            request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
            user.setActivated(HouseUserContant.activated_active);
            user.setLastLoginTime(new Date());
            userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_IJK);
            user= userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_IJK);
            return user;
        }
    }
    /**
     *  //TODO 体验版本方法,后续可能删除
     * 身份证登录
     *
     * @param loginCode
     * @param password
     * @return
     * @throws Exception
     */
    @Transactional(noRollbackForClassName = "ManageException")
    public User idCardlogin(HttpServletRequest request, String loginCode, String password) throws ManageException {
        //判断登陆信息是否正确
        User user = userService.findByCode(loginCode);
        if (user == null) {
            String message = "账号不存在";
            throw new ManageException(message);
        }
        if (!user.getPassword().equals(MD5.GetMD5Code(password + user.getSalt()))) {
            String message = "密码错误";
            throw new ManageException(message);
        }
        request.getSession().setAttribute(LoginInfo.IS_LOGIN, true);
        request.getSession().setAttribute(LoginInfo.TOKEN, ""); //TODO token是否添加
        request.getSession().setAttribute(LoginInfo.LOGIN_NAME, user.getName());
        request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
        user.setActivated(HouseUserContant.activated_active);
        user.setLastLoginTime(new Date());
        user= userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_IDCARDNO);
        return user;
    }
    @Transactional(noRollbackForClassName = "ManageException")
    public User idCardRegister(HttpServletRequest request, String name, String idCardNo) throws ManageException {
        if(!IdCardUtil.cardCodeVerifySimple(idCardNo)){
            throw new ManageException("身份证号格式有误");
        }
        User user = userService.findByLoginCodeAndUserType(idCardNo,LoginInfo.USER_TYPE_PATIENT);
        if (user==null) {
            //新增账号
            user = new User();
            String password = idCardNo.substring(idCardNo.length()-6,idCardNo.length());
            user.setPassword(password);
            user.setLoginCode(idCardNo);
            user.setName(name);
            user.setIdCardNo(idCardNo);
            user.setUserType(LoginInfo.USER_TYPE_PATIENT);
        }
        // 更新身份证验证字段
        user.setRealnameAuthentication(UserConstant.AUTHORIZED);
        user.setName(name);
        request.getSession().setAttribute(LoginInfo.IS_LOGIN, true);
        request.getSession().setAttribute(LoginInfo.TOKEN, ""); //TODO token是否添加
        request.getSession().setAttribute(LoginInfo.LOGIN_NAME, user.getName());
        request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
        user.setActivated(HouseUserContant.activated_active);
        user.setLastLoginTime(new Date());
        user= userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_IDCARDNO);
        return user;
    }
}

+ 124 - 22
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/UserService.java

@ -3,12 +3,9 @@ package com.yihu.jw.healthyhouse.service.user;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.healthyhouse.constant.LoginInfo;
import com.yihu.jw.healthyhouse.constant.UserConstant;
import com.yihu.jw.healthyhouse.dao.facility.FacilityDao;
import com.yihu.jw.healthyhouse.dao.user.UserDao;
import com.yihu.jw.healthyhouse.model.facility.Facility;
import com.yihu.jw.healthyhouse.model.user.User;
import com.yihu.jw.healthyhouse.util.poi.ExcelUtils;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.wlyy.HouseUserContant;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
@ -24,6 +21,7 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springside.modules.persistence.DynamicSpecifications;
@ -32,8 +30,9 @@ import org.springside.modules.persistence.SearchFilter;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.*;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
/**
 * @author HZY
@ -41,12 +40,30 @@ import java.util.regex.Pattern;
 */
@Service
public class UserService extends BaseJpaService<User, UserDao> {
    private final String KEY_PREFIX = "healthyHouse:";
    private final String KEY_SUFFIX = ":activated";
    private final RedisTemplate redisTemplate;
    @Autowired
    private UserDao userDao;
    @Autowired
    private FacilityUsedRecordService facilityUsedRecordService;
    public UserService(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    /**
     * 设置用户在线状态
     * @param userId
     * @param expire
     */
    public void setUserActivated ( String userId, int expire) {
        String key =  KEY_PREFIX + userId + KEY_SUFFIX;
        redisTemplate.opsForValue().set(key, userId);
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }
    public User findById(String id) {
        return userDao.findById(id);
    }
@ -56,9 +73,12 @@ public class UserService extends BaseJpaService<User, UserDao> {
    }
    public User findByLoginCodeAndUserType(String loginCode,String userType) {
        return userDao.findByLoginCodeAndUserType(loginCode,userType);
        return userDao.findByUserTypeAndTelephoneOrLoginCode(userType,loginCode,loginCode);
    }
    public User findByTelephoneAndUserType(String telephone,String userType) {
        return userDao.findByTelephoneAndUserType(telephone,userType);
    }
    /**
     * 分页获取用户列表
@ -175,7 +195,8 @@ public class UserService extends BaseJpaService<User, UserDao> {
     * @return
     * @throws ManageException
     */
    public Envelop saveOrUpdate(User user, String userCode) throws ManageException {
    @Transactional
    public User saveOrUpdate(User user, String userCode) throws ManageException {
        User loginUser = userDao.findByLoginCode(userCode);
        if (user.getId() == null) {//保存
            //判断登陆账号是否存在
@ -190,20 +211,28 @@ public class UserService extends BaseJpaService<User, UserDao> {
            user.setCreateUser(userCode);
            user.setCreateTime(new Date());
            user.setActivated(1);
            userDao.save(user);
            return Envelop.getSuccess("保存成功");
            user.setFacilityUsedCount(0);
            user=userDao.save(user);
            return user;
        } else {//修改
            if (loginUser != null) {
                String userName = loginUser.getName();
                user.setUpdateUserName(userName);
            }
            user.setUpdateUser(userCode);
            userDao.save(user);
            return Envelop.getSuccess("修改成功");
            user=userDao.save(user);
            return user;
        }
    }
    /**
     *  修改密码
     * @param userId    用户ID
     * @param oldPwd    原密码
     * @param newPwd    新密码
     * @throws ManageException
     */
    @Transactional
    public void updatePwd(String userId, String oldPwd,String newPwd) throws ManageException {
        User user = findById(userId);
@ -222,19 +251,62 @@ public class UserService extends BaseJpaService<User, UserDao> {
        userDao.save(user);
    }
    /**
     *  重设密码
     * @param userId    用户ID
     * @param newPwd    新密码
     * @throws ManageException
     */
    @Transactional
    public String resetPwd(String userId, String newPwd) throws ManageException {
        User user = findById(userId);
        if (user==null) {
            throw new ManageException("该账号不存在");
        }
        String password = MD5.GetMD5Code(newPwd + user.getSalt());
        user.setPassword(password);
        userDao.save(user);
        return newPwd;
    }
    /**
     * 普通用户密保手机修改
     * @param userId    普通用户id
     * @param phone     手机号
     * @throws ManageException
     */
    @Transactional
    public void updateSecurePhone(String userId, String phone) throws ManageException {
        User user = findById(userId);
        if (user==null) {
            throw new ManageException("该账号不存在");
        }
        user.setLoginCode(phone);
        user.setTelephone(phone);
        userDao.save(user);
    }
    /**
     * 修改管理员密保手机
     * @param userId    用户id
     * @param phone     密保手机
     * @throws ManageException
     */
    @Transactional
    public void updateAdministorSecurePhone(String userId, String phone) throws ManageException {
        User user = findById(userId);
        if (user==null) {
            throw new ManageException("该账号不存在");
        }
        user.setTelephone(phone);
        userDao.save(user);
    }
    /**
     * 获取 用户统计信息
     * 获取 健康小屋用户统计信息
     *
     * @return
     */
@ -245,9 +317,9 @@ public class UserService extends BaseJpaService<User, UserDao> {
        //今日新增数
        Date start = DateUtil.getDateStart();
        Date end = DateUtil.getDateEnd();
        Long newCount = userDao.countAllByCreateTimeBetween(start, end);
        Long newCount = userDao.countAllByUserTypeAndCreateTimeBetween(LoginInfo.USER_TYPE_PATIENT,start, end);
        //在线用户数
        Long activeCount = userDao.countAllByActivated(HouseUserContant.activated_active);
        Long activeCount = userDao.countAllByActivatedAndUserType(HouseUserContant.activated_active,LoginInfo.USER_TYPE_PATIENT);
        //用户设施使用总次数
        Long usePricilityCount = facilityUsedRecordService.countAll();
        result.put("totalCount",totalCount);
@ -258,12 +330,13 @@ public class UserService extends BaseJpaService<User, UserDao> {
    }
    /**
     *  用户身份证认证
     *  用户实名认证
     * @param userId    用户ID
     * @param name  用户姓名
     * @param idCardNo  身份证
     * @throws ManageException
     */
    public void checkIdCardNo(String userId, String idCardNo) throws ManageException {
    public void checkIdCardNo(String userId,String name, String idCardNo) throws ManageException {
        User user1 = findById(userId);
        if (user1==null) {
            throw new ManageException("该账号不存在");
@ -273,10 +346,27 @@ public class UserService extends BaseJpaService<User, UserDao> {
        }
        // 更新身份证验证字段
        user1.setRealnameAuthentication(UserConstant.AUTHORIZED);
        user1.setIdCardNo(idCardNo);
        user1.setName(name);
        userDao.save(user1);
    }
   
    /**
     *  验证管理员是否存在
     * @param userCode   登录账号
     * @throws ManageException
     */
    public boolean checkManageUser(String userCode) throws ManageException {
        User user1 = findByLoginCodeAndUserType(userCode, LoginInfo.USER_TYPE_SUPER_AdminManager);
        if (user1==null) {
            return false;
        }else {
            return true;
        }
    }
    //excel中添加固定内容
    private void addStaticCell(Sheet sheet){
        //设置样式
@ -309,14 +399,11 @@ public class UserService extends BaseJpaService<User, UserDao> {
        try {
            String fileName = "健康小屋-用户列表";
            //设置下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" )+".xlsx");
            OutputStream os = response.getOutputStream();
            //获取导出数据集
            JSONObject order = new JSONObject();
            order.put("id","asc");
            //写excel
            Workbook workbook = new XSSFWorkbook();
            int k=0;
@ -338,7 +425,7 @@ public class UserService extends BaseJpaService<User, UserDao> {
                ExcelUtils.addCellData(sheet,2,row, metaData.getLoginCode());//登录名
                ExcelUtils.addCellData(sheet,3,row, metaData.getName());//名称
                ExcelUtils.addCellData(sheet,4,row, metaData.getIdCardNo());//身份证
                ExcelUtils.addCellData(sheet,5,row, metaData.getGender());//性别
                ExcelUtils.addCellData(sheet,5,row, metaData.getGenderValue());//性别
                ExcelUtils.addCellData(sheet,6,row, metaData.getTelephone());//电话
                ExcelUtils.addCellData(sheet,7,row, metaData.getAddress());//地区
                ExcelUtils.addCellData(sheet,8,row, metaData.getFacilityUsedCount().toString());//使用设施次数
@ -370,6 +457,21 @@ public class UserService extends BaseJpaService<User, UserDao> {
        userDao.save(user1);
    }
    /**
     * 更新用户在线状态
     * @param ids
     * @throws ManageException
     */
    @Transactional
    public void updateUserOffLine(List<Serializable> ids) throws ManageException {
        userDao.updateUserOnLine(ids);//更新在线
        userDao.updateUserOffLine(ids);//更新离线
    }
}

+ 0 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/ImportDemoReader.java


Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio