Browse Source

Merge branch 'dev' of liuwenbin/jw2.0 into dev

huangwenjie 7 years ago
parent
commit
916ae5d892
86 changed files with 6209 additions and 4411 deletions
  1. 10 0
      common/common-entity/src/main/java/com/yihu/jw/base/base/SaasDO.java
  2. 10 10
      common/common-entity/src/main/java/com/yihu/jw/base/sms/BaseSmsDO.java
  3. 38 0
      common/common-entity/src/main/java/com/yihu/jw/base/user/BaseEmployDO.java
  4. 6 0
      common/common-fegin/src/main/java/com/yihu/jw/fegin/base/base/SaasFeign.java
  5. 51 0
      common/common-fegin/src/main/java/com/yihu/jw/fegin/base/login/LoginFeign.java
  6. 34 0
      common/common-fegin/src/main/java/com/yihu/jw/fegin/base/sms/RegisterSmsFeign.java
  7. 6 1
      common/common-fegin/src/main/java/com/yihu/jw/fegin/base/user/EmployFeign.java
  8. 25 0
      common/common-fegin/src/main/java/com/yihu/jw/fegin/common/security/LoginSmsFeign.java
  9. 5 0
      common/common-fegin/src/main/java/com/yihu/jw/fegin/fallbackfactory/base/base/SaasFeignFallbackFactory.java
  10. 4 0
      common/common-fegin/src/main/java/com/yihu/jw/fegin/fallbackfactory/base/user/EmployeeFeignFallbackFactory.java
  11. 5 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseLoginRequestMapping.java
  12. 15 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseSecurityRequestMapping.java
  13. 1 1
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseSmsRequestMapping.java
  14. 31 0
      common/common-util/pom.xml
  15. 168 0
      common/common-util/src/main/java/com/yihu/jw/util/common/ConvertToSpellUtils.java
  16. 148 0
      common/common-util/src/main/java/com/yihu/jw/util/common/IdCardUtil.java
  17. 43 0
      common/common-util/src/main/java/com/yihu/jw/util/common/MobileUtils.java
  18. 58 0
      common/common-util/src/main/java/com/yihu/jw/util/common/NetworkUtil.java
  19. 39 0
      common/common-util/src/main/java/com/yihu/jw/util/common/SmsValidateCodeUtils.java
  20. 221 0
      common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtil.java
  21. 72 0
      common/common-util/src/main/java/com/yihu/jw/vo/ValidateCode.java
  22. BIN
      data/elasticsearch/nodes/0/_state/global-0.st
  23. 0 0
      data/elasticsearch/nodes/0/node.lock
  24. 2 1
      server/svr-discovery/pom.xml
  25. 27 10
      svr/svr-base/pom.xml
  26. 9 0
      svr/svr-base/src/main/java/com/yihu/jw/SvrBaseApplication.java
  27. 2 1
      svr/svr-base/src/main/java/com/yihu/jw/business/base/controller/ModuleFunController.java
  28. 2 1
      svr/svr-base/src/main/java/com/yihu/jw/business/base/service/ModuleFunService.java
  29. 117 0
      svr/svr-base/src/main/java/com/yihu/jw/business/login/contorller/LoginController.java
  30. 27 27
      svr/svr-base/src/main/java/com/yihu/jw/business/login/dao/BaseLoginAccountDao.java
  31. 11 11
      svr/svr-base/src/main/java/com/yihu/jw/business/login/dao/BaseLoginLogDao.java
  32. 75 75
      svr/svr-base/src/main/java/com/yihu/jw/business/login/service/BaseLoginAccountService.java
  33. 131 0
      svr/svr-base/src/main/java/com/yihu/jw/business/login/service/LoginService.java
  34. 69 0
      svr/svr-base/src/main/java/com/yihu/jw/business/sms/controller/SMSController.java
  35. 0 103
      svr/svr-base/src/main/java/com/yihu/jw/business/sms/controller/SmsController.java
  36. 9 0
      svr/svr-base/src/main/java/com/yihu/jw/business/sms/dao/SmsDao.java
  37. 20 20
      svr/svr-base/src/main/java/com/yihu/jw/business/sms/dao/SmsGatewayDao.java
  38. 68 68
      svr/svr-base/src/main/java/com/yihu/jw/business/sms/service/SmsGatewayService.java
  39. 166 5
      svr/svr-base/src/main/java/com/yihu/jw/business/sms/service/SmsService.java
  40. 49 0
      svr/svr-base/src/main/java/com/yihu/jw/business/sms/vo/SMSHttpVo.java
  41. 95 95
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseMenuController.java
  42. 220 220
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseRoleController.java
  43. 203 203
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployController.java
  44. 28 28
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/PatientController.java
  45. 32 32
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseMenuDao.java
  46. 28 28
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleDao.java
  47. 26 26
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleMenuDao.java
  48. 24 24
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployRoleDao.java
  49. 137 137
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseMenuService.java
  50. 154 154
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleMenuService.java
  51. 174 174
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleService.java
  52. 152 152
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployRoleService.java
  53. 7 3
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployService.java
  54. 125 125
      svr/svr-base/src/main/java/com/yihu/jw/business/version/controller/UserVersionController.java
  55. 14 14
      svr/svr-base/src/main/java/com/yihu/jw/business/version/dao/BaseUserVersionDao.java
  56. 41 41
      svr/svr-base/src/main/java/com/yihu/jw/business/version/service/BaseUserVersionService.java
  57. 644 644
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/WechatResponse.java
  58. 138 138
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WechatConfigController.java
  59. 47 47
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxAccessTokenController.java
  60. 164 164
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxGraphicMessageController.java
  61. 236 236
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxMenuController.java
  62. 188 188
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxTemplateController.java
  63. 27 27
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WechatDao.java
  64. 17 17
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxAccessTokenDao.java
  65. 15 15
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxGraphicMessageDao.java
  66. 47 47
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxMenuDao.java
  67. 21 21
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxTemplateDao.java
  68. 114 114
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatService.java
  69. 96 96
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxAccessTokenService.java
  70. 177 177
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxGraphicMessageService.java
  71. 357 356
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxMenuService.java
  72. 157 157
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxTemplateService.java
  73. 11 4
      svr/svr-base/src/main/java/com/yihu/jw/config/jpa/HibernateProperties.java
  74. 33 15
      svr/svr-base/src/main/resources/application.yml
  75. 9 2
      svr/svr-base/src/main/resources/bootstrap.yml
  76. 11 6
      web-gateway/pom.xml
  77. 3 1
      web-gateway/src/main/java/com/yihu/jw/WebGateWayAppliaction.java
  78. 2 2
      web-gateway/src/main/java/com/yihu/jw/aspect/LogAspect.java
  79. 55 39
      web-gateway/src/main/java/com/yihu/jw/config/security/ClientService.java
  80. 49 48
      web-gateway/src/main/java/com/yihu/jw/config/security/RbasService.java
  81. 63 59
      web-gateway/src/main/java/com/yihu/jw/config/security/UserService.java
  82. 100 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/login/LoginContorller.java
  83. 40 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/login/RegisterSmsContorller.java
  84. 134 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/security/TokenController.java
  85. 18 0
      web-gateway/src/main/resources/application.yml
  86. 2 1
      web-gateway/src/main/resources/bootstrap.yml

+ 10 - 0
common/common-entity/src/main/java/com/yihu/jw/base/base/SaasDO.java

@ -20,6 +20,7 @@ public class SaasDO extends IdEntityWithOperation implements java.io.Serializabl
	private String name;//名称
	private Integer status;//状态 -1 已删除 0待审核 1审核通过 2 审核不通过
	private String remark;//备注
	private String familyTel;
	// Constructors
	/** default constructor */
@ -53,4 +54,13 @@ public class SaasDO extends IdEntityWithOperation implements java.io.Serializabl
	public void setRemark(String remark) {
		this.remark = remark;
	}
	@Column(name = "family_tel", length = 100)
	public String getFamilyTel() {
		return familyTel;
	}
	public void setFamilyTel(String familyTel) {
		this.familyTel = familyTel;
	}
}

+ 10 - 10
common/common-entity/src/main/java/com/yihu/jw/base/sms/BaseSmsDO.java

@ -21,11 +21,11 @@ public class BaseSmsDO extends IdEntityWithOperation implements java.io.Serializ
	private String mobile;	//电话号码
	private String ip;	//发送短信的ip地址
	private Integer type;	//发送短信的类别
	private String captcha;	//验证码 1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录
	private String captcha;	//验证码 1居民端注册,2居民端找回密码,3医生端找回密码,4居民登录,5医生登录
	private String content;	// 短信内容
	private Date deadline;	//过期时间
	private Integer status;	//短信状态 状态,0未发送,1已发送
	private Date czrq;//操作日期
//	private Date czrq;//操作日期
	// Constructors
@ -133,12 +133,12 @@ public class BaseSmsDO extends IdEntityWithOperation implements java.io.Serializ
		this.status = status;
	}
	@Column(name = "czrq")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
//	@Column(name = "czrq")
//	public Date getCzrq() {
//		return czrq;
//	}
//
//	public void setCzrq(Date czrq) {
//		this.czrq = czrq;
//	}
}

+ 38 - 0
common/common-entity/src/main/java/com/yihu/jw/base/user/BaseEmployDO.java

@ -20,12 +20,16 @@ public class BaseEmployDO extends IdEntityWithOperation implements java.io.Seria
	private String saasId; //saasIDF
	private String name; //名字
	private String pyCode; //拼音
	private String ssc;//医保卡号
	private String sex; //性别
	private String photo; //头像
	private String skill;//专长
	private String workPortal;//医生门户首页
	private String email;//邮箱
	private String phone;//联系电话
	private String password;//账户密码
	private String salt;//账户密码的盐
	private String idcard;//身份证号
	private String secondPhone;//备用电话
	private String familyTel;//家庭电话(固)
	private String officeTel;//办公电话(固)
@ -211,5 +215,39 @@ public class BaseEmployDO extends IdEntityWithOperation implements java.io.Seria
		this.status = status;
	}
	@Column(name = "password")
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Column(name = "salt")
	public String getSalt() {
		return salt;
	}
	public void setSalt(String salt) {
		this.salt = salt;
	}
	@Column(name = "idcard")
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	@Column(name = "ssc")
	public String getSsc() {
		return ssc;
	}
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
}

+ 6 - 0
common/common-fegin/src/main/java/com/yihu/jw/fegin/base/base/SaasFeign.java

@ -4,7 +4,10 @@ import com.yihu.jw.fegin.fallbackfactory.base.base.SaasFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.cloud.netflix.feign.FeignClient;
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;
@ -19,4 +22,7 @@ public interface SaasFeign {
    @GetMapping(value = BaseRequestMapping.Saas.api_getSaassNoPage)
    Envelop getList(@RequestParam(value = "fields",required = false)String fields,@RequestParam(value = "filters",required = false) String filters,@RequestParam(value = "sorts",required = false) String sorts);
    @GetMapping(value = BaseRequestMapping.Saas.api_getById, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Envelop findByCode(@RequestParam(value = "id", required = true) String id);
}

+ 51 - 0
common/common-fegin/src/main/java/com/yihu/jw/fegin/base/login/LoginFeign.java

@ -0,0 +1,51 @@
package com.yihu.jw.fegin.base.login;
import com.yihu.jw.fegin.fallbackfactory.base.base.FunctionFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by 刘文彬 on 2018/4/20.
 */
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
//        ,fallbackFactory  = FunctionFeignFallbackFactory.class
)
@RequestMapping(value = BaseLoginRequestMapping.api_common)
public interface LoginFeign {
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_checkoutInfo, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Envelop checkoutInfo();
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_accountSub, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Envelop register(
            @RequestParam(value = "mobilePhone", required = true) String mobilePhone,
            @RequestParam(value = "saasId", required = true) String saasId,
            @RequestParam(value = "type", required = true) int type,
            @RequestParam(value = "captcha", required = true) String captcha,
            @RequestParam(value = "name", required = true) String name,
            @RequestParam(value = "password", required = true) String password,
            @RequestParam(value = "idcard", required = true) String idcard,
            @RequestParam(value = "ssc", required = true) String ssc);
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_login, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Envelop login(@RequestParam(value = "mobilePhone", required = false) String mobilePhone,
                           @RequestParam(value = "password", required = false) String password,
                           @RequestParam(value = "saasId", required = true) String saasId,
                           @RequestParam(value = "captcha", required = false) String captcha);
}

+ 34 - 0
common/common-fegin/src/main/java/com/yihu/jw/fegin/base/sms/RegisterSmsFeign.java

@ -0,0 +1,34 @@
package com.yihu.jw.fegin.base.sms;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
import io.swagger.annotations.ApiParam;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created by 刘文彬 on 2018/4/23.
 */
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
)
@RequestMapping(value = BaseSmsRequestMapping.api_common)
public interface RegisterSmsFeign {
    @PostMapping(value = BaseSmsRequestMapping.Sms.api_sms_send, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    BaseEnvelop send(@ApiParam(name = "mobile", value = "手机号码", required = true) @RequestParam(value = "mobile", required = true) String mobile,
                     @ApiParam(name = "type", value = "短信验证码类型", required = true) @RequestParam(value = "type", required = true) int type,
                     @ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) throws IOException ;
    }

+ 6 - 1
common/common-fegin/src/main/java/com/yihu/jw/fegin/base/user/EmployFeign.java

@ -6,6 +6,8 @@ import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@ -17,7 +19,7 @@ import org.springframework.web.bind.annotation.*;
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = EmployeeFeignFallbackFactory.class
)
@RequestMapping(value = BaseRequestMapping.api_base_common)
@RequestMapping(value = BaseUserRequestMapping.api_user_common)
public interface EmployFeign {
    @RequestMapping(value = BaseUserRequestMapping.BaseEmploy.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
@ -57,5 +59,8 @@ public interface EmployFeign {
    @RequestMapping(value = BaseUserRequestMapping.BaseEmployRole.api_getListNoPage,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop getRoleList(@RequestBody String jsonData) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getByPhone)
    Envelop getEmployeeByPhoneAndSaasId(@RequestParam(value = "phone", required = true) String phone,@RequestParam(value = "saasId", required = true) String saasId);
}

+ 25 - 0
common/common-fegin/src/main/java/com/yihu/jw/fegin/common/security/LoginSmsFeign.java

@ -0,0 +1,25 @@
package com.yihu.jw.fegin.common.security;
import com.yihu.jw.fegin.fallbackfactory.base.base.SaasFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.rm.base.BaseRequestMapping;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by 刘文彬 on 2018/4/23.
 */
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
)
@RequestMapping(value = BaseRequestMapping.api_base_common)
public interface LoginSmsFeign {
    @GetMapping(BaseLoginRequestMapping.BaseLoginAccount.mobileSendSms)
    void createCode(HttpServletRequest request,HttpServletResponse response)throws Exception;
}

+ 5 - 0
common/common-fegin/src/main/java/com/yihu/jw/fegin/fallbackfactory/base/base/SaasFeignFallbackFactory.java

@ -16,6 +16,11 @@ public class SaasFeignFallbackFactory implements FallbackFactory<SaasFeign> {
            public Envelop getList(@RequestParam(value = "fields") String fields, @RequestParam(value = "filters") String filters, @RequestParam(value = "sorts") String sorts) {
                return null;
            }
            @Override
            public Envelop findByCode(@RequestParam(value = "id") String id) {
                return null;
            }
        };
    }
}

+ 4 - 0
common/common-fegin/src/main/java/com/yihu/jw/fegin/fallbackfactory/base/user/EmployeeFeignFallbackFactory.java

@ -97,6 +97,10 @@ public class EmployeeFeignFallbackFactory  implements FallbackFactory<EmployFeig
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getEmployeeByPhoneAndSaasId(String phone, String saasId){
                return null;
            }
        };
    }
}

+ 5 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseLoginRequestMapping.java

@ -2,6 +2,7 @@ package com.yihu.jw.rm.base;
public class BaseLoginRequestMapping {
    public static final String api_common = BaseRequestMapping.api_base_common + "/login";
    public static final String api_gateway_common = BaseRequestMapping.api_base_common + "/gateway/login";
    /**
     * 用户账号类型
@ -12,6 +13,10 @@ public class BaseLoginRequestMapping {
        public static final String api_delete = "/baseLoginAccount/{ids}";
        public static final String api_getById = "/baseLoginAccount/{id}";
        public static final String api_getOne="/baseLoginAccount";
        public static final String mobileSendSms = "/code/sms";
        public static final String api_checkoutInfo = "/register/checkInfo";
        public static final String api_accountSub = "/register/accountSub";
        public static final String api_login= "/authentication/form";
        public static final String message_success_create = "baseLoginAccount create success";
        public static final String message_success_update = "baseLoginAccount update success";

+ 15 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseSecurityRequestMapping.java

@ -0,0 +1,15 @@
package com.yihu.jw.rm.base;
/**
 * Created by 刘文彬 on 2018/5/4.
 */
public class BaseSecurityRequestMapping {
    public static final String api_common=BaseRequestMapping.api_base_common+"/security";
    public static class BaseToken {
        public static final String api_update_token_expiration_time = "/update/tokenExpiration/time";
        public static final String api_update_token_expiration_second = "/update/tokenExpiration/second";
        public static final String api_update_token_expiration_second2 = "/update/tokenExpiration/second2";
        public static final String api_update_token_expiration = "/update/tokenExpiration";
    }
}

+ 1 - 1
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseSmsRequestMapping.java

@ -21,7 +21,7 @@ public class BaseSmsRequestMapping {
        public static final String message_fail_id_is_null="id is null";
        public static final String api_create="sms";
        public static final String api_sms_send="send";
        public static final String api_update="sms";
        public static final String api_getSmss="getSmss";

+ 31 - 0
common/common-util/pom.xml

@ -18,5 +18,36 @@
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.stuxuhai</groupId>
            <artifactId>jpinyin</artifactId>
            <version>1.1.8</version>
        </dependency>
    </dependencies>
</project>

+ 168 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/ConvertToSpellUtils.java

@ -0,0 +1,168 @@
package com.yihu.jw.util.common;
import com.github.stuxuhai.jpinyin.ChineseHelper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
/**
 * Created by 刘文彬 on 2018/4/18.
 */
public class ConvertToSpellUtils {
    /**
     * 转换为有声调的拼音字符串
     * @param pinYinStr 汉字
     * @return 有声调的拼音字符串
     */
    public static String changeToMarkPinYin(String pinYinStr){
        String tempStr = null;
        try
        {
            tempStr =  PinyinHelper.convertToPinyinString(pinYinStr,  " ", PinyinFormat.WITH_TONE_MARK);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return tempStr;
    }
    /**
     * 转换为数字声调字符串
     * @param pinYinStr 需转换的汉字
     * @return 转换完成的拼音字符串
     */
    public static String changeToNumberPinYin(String pinYinStr){
        String tempStr = null;
        try
        {
            tempStr = PinyinHelper.convertToPinyinString(pinYinStr, " ", PinyinFormat.WITH_TONE_NUMBER);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return tempStr;
    }
    /**
     * 转换为不带音调的拼音字符串
     * @param pinYinStr 需转换的汉字
     * @return 拼音字符串
     */
    public static String changeToTonePinYin(String pinYinStr){
        String tempStr = null;
        try
        {
            tempStr =  PinyinHelper.convertToPinyinString(pinYinStr, " ", PinyinFormat.WITHOUT_TONE);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return tempStr;
    }
    /**
     * 转换为每个汉字对应拼音首字母字符串
     * @param pinYinStr 需转换的汉字
     * @return 拼音字符串
     */
    public static String changeToGetShortPinYin(String pinYinStr){
        String tempStr = null;
        try
        {
            tempStr = PinyinHelper.getShortPinyin(pinYinStr);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return tempStr;
    }
    /**
     * 检查汉字是否为多音字
     * @param pinYinStr 需检查的汉字
     * @return true 多音字,false 不是多音字
     */
    public static boolean checkPinYin(char pinYinStr){
        boolean check  = false;
        try
        {
            check = PinyinHelper.hasMultiPinyin(pinYinStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return check;
    }
    /**
     * 简体转换为繁体
     * @param pinYinStr
     * @return
     */
    public static String changeToTraditional(String pinYinStr){
        String tempStr = null;
        try
        {
            tempStr = ChineseHelper.convertToTraditionalChinese(pinYinStr);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return tempStr;
    }
    /**
     * 繁体转换为简体
     * @param pinYinSt
     * @return
     */
    public static String changeToSimplified(String pinYinSt){
        String tempStr = null;
        try
        {
            tempStr = ChineseHelper.convertToSimplifiedChinese(pinYinSt);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return tempStr;
    }
    public static void main(String[] args) {
      String str = "我是谁";
      System.out.println(ConvertToSpellUtils.changeToTonePinYin(str));
      System.out.println(ConvertToSpellUtils.checkPinYin('重'));
    }
    //汉字转首字母大写的拼音
    public static String changeToInitialPinYin(String pinYinStr){
        String origin = changeToTonePinYin(pinYinStr);
        String[] perChinese =  origin.split("\\s+");
        String result ="";
        for(String one : perChinese){
            result += one.toUpperCase();
        }
        return result;
    }
}

+ 148 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/IdCardUtil.java

@ -0,0 +1,148 @@
package com.yihu.jw.util.common;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
 * Created by Administrator on 2016.08.17.
 * 身份证工具类
 */
public class IdCardUtil {
//    /**
//     * 根据身份证的号码算出当前身份证持有者的年龄
//     *
//     * @param
//     * @throws Exception
//     */
//    public static int getAgeForIdcard(String card)
//            throws Exception {
//        int age = 0;
//        if (card.length() == 18) {
//            String year = card.substring(6).substring(0, 4);// 得到年份
//            String yue = card.substring(10).substring(0, 2);// 得到月份
//            // String day=CardCode.substring(12).substring(0,2);//得到日
//            Date date = new Date();// 得到当前的系统时间
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            String fyear = format.format(date).substring(0, 4);// 当前年份
//            String fyue = format.format(date).substring(5, 7);// 月份
//            if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
//                age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
//            } else {// 当前用户还没过生
//                age = Integer.parseInt(fyear) - Integer.parseInt(year);
//            }
//        } else if (card.length() == 15) {
//            String uyear = "19" + card.substring(6, 8);// 年份
//            String uyue = card.substring(8, 10);// 月份
//            Date date = new Date();// 得到当前的系统时间
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            String fyear = format.format(date).substring(0, 4);// 当前年份
//            String fyue = format.format(date).substring(5, 7);// 月份
//            // String fday=format.format(date).substring(8,10);
//            if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
//                age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
//            } else {// 当前用户还没过生
//                age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
//            }
//
//        }
//        return age;
//    }
    /**
     * 根据身份证的号码算出当前身份证持有者的年龄
     *
     * @param
     * @throws Exception
     */
    public static int getAgeForIdcard(String idcard) {
        try {
            int age = 0;
            if (StringUtils.isEmpty(idcard)) {
                return age;
            }
            String birth = "";
            if (idcard.length() == 18) {
                birth = idcard.substring(6, 14);
            } else if (idcard.length() == 15) {
                birth = "19" + idcard.substring(6, 12);
            }
            int year = Integer.valueOf(birth.substring(0, 4));
            int month = Integer.valueOf(birth.substring(4, 6));
            int day = Integer.valueOf(birth.substring(6));
            Calendar cal = Calendar.getInstance();
            age = cal.get(Calendar.YEAR) - year;
            //周岁计算
            if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
                age--;
            }
            return age;
        } catch (Exception e) {
        }
        return -1;
    }
    /**
     * 身份证提取出身日期
     *
     * @param card
     * @return
     * @throws Exception
     */
    public static Date getBirthdayForIdcard(String card)
            throws Exception {
        Date b = null;
        if (card.length() == 18) {
            String year = card.substring(6).substring(0, 4);// 得到年份
            String yue = card.substring(10).substring(0, 2);// 得到月份
            String ri = card.substring(12).substring(0, 2);// 得到日
            // String day=CardCode.substring(12).substring(0,2);//得到日
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            b = format.parse(year + "-" + yue + "-" + ri);
        } else if (card.length() == 15) {
            String uyear = "19" + card.substring(6, 8);// 年份
            String uyue = card.substring(8, 10);// 月份
            String uri = card.substring(10, 12);// 得到日
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            b = format.parse(uyear + "-" + uyue + "-" + uri);
        }
        return b;
    }
//    public static
//    if (cardId.length() == 15 || cardId.length() == 18) {
//        if (!this.cardCodeVerifySimple(cardId)) {
//            error.put("cardId", "15位或18位身份证号码不正确");
//        } else {
//            if (cardId.length() == 18 && !this.cardCodeVerify(cardId)) {
//                error.put("cardId", "18位身份证号码不符合国家规范");
//            }
//        }
//    } else {
//        error.put("cardId", "身份证号码长度必须等于15或18位");
//    }
    private boolean cardCodeVerifySimple(String cardcode) {
        //第一代身份证正则表达式(15位)
        String isIDCard1 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
        //第二代身份证正则表达式(18位)
        String isIDCard2 ="^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z])$";
        //验证身份证
        if (cardcode.matches(isIDCard1) || cardcode.matches(isIDCard2)) {
            return true;
        }
        return false;
    }
}

+ 43 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/MobileUtils.java

@ -0,0 +1,43 @@
package com.yihu.jw.util.common;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by 刘文彬 on 2018/4/23.
 */
public class MobileUtils {
    public static Boolean checkMobile(String mobile) {
        return checkCellphone(mobile);
    }
    /**
     * 验证手机号码
     * <p>
     * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
     * 联通号码段:130、131、132、136、185、186、145
     * 电信号码段:133、153、180、189,181
     *
     * @param cellphone
     * @return
     */
    public static boolean checkCellphone(String cellphone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,1,5-9]))\\d{8}$";
        return check(cellphone, regex);
    }
    /**
     * 使用正则表达式进行表单验证
     */
    public static boolean check(String str, String regex) {
        boolean flag = false;
        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
}

+ 58 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/NetworkUtil.java

@ -0,0 +1,58 @@
package com.yihu.jw.util.common;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/** 
 * 常用获取客户端信息的工具 
 *  
 */
public final class NetworkUtil {
	/**
	 * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public final static String getIpAddress(HttpServletRequest request) throws IOException {
		// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}
}

+ 39 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/SmsValidateCodeUtils.java

@ -0,0 +1,39 @@
package com.yihu.jw.util.common;
import com.yihu.jw.vo.ValidateCode;
import org.springframework.web.context.request.ServletWebRequest;
import java.util.Random;
/**
 * Created by 刘文彬 on 2018/4/23.
 */
public class SmsValidateCodeUtils {
    /**
     *
     * @param length 短信验证码长度
     * @param expireIn 短信验证码过期时间
     * @return
     */
    public static ValidateCode generate(int length,int expireIn) {
        String code = getFixLenthString(length);
        ValidateCode validateCode = new ValidateCode(code, expireIn);
        return validateCode;
    }
    /*
 * 返回长度为【strLength】的随机数,在前面补0
 */
    private static String getFixLenthString(int strLength) {
        Random rm = new Random();
        // 获得随机数
        double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
        // 将获得的获得随机数转化为字符串
        String fixLenthString = String.valueOf(pross);
        // 返回固定的长度的随机数
        return fixLenthString.substring(1, strLength + 1);
    }
}

+ 221 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtil.java

@ -0,0 +1,221 @@
package com.yihu.jw.util.http;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Component
public class HttpClientUtil {
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param chatSet 编码格式
     * @return
     */
    public  String post(String url, List<NameValuePair> params, String chatSet) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(params, chatSet);
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 发送get请求
     *
     * @param url     请求地址
     * @param chatSet 编码格式
     * @return
     */
    public  String get(String url, String chatSet) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * http调用方法,(健康之路开放平台)
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public  String httpPost(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null && params.size() > 0) {
                List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
                    valuePairs.add(nameValuePair);
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
                httpPost.setEntity(formEntity);
            }
            CloseableHttpResponse resp = httpclient.execute(httpPost);
            try {
                HttpEntity entity = resp.getEntity();
                String respContent = EntityUtils.toString(entity, "UTF-8").trim();
                return respContent;
            } finally {
                resp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            httpclient.close();
        }
    }
    /**
     * 获取加密后参数集合(健康之路开放平台)
     *
     * @param params
     * @return
     */
    public  Map<String, String> getSecretParams(Map<String, String> params, String appId, String secret) {
        String timestamp = Long.toString(System.currentTimeMillis());
        params.put("timestamp", timestamp);
        StringBuilder stringBuilder = new StringBuilder();
        // 对参数名进行字典排序  
        String[] keyArray = params.keySet().toArray(new String[0]);
        Arrays.sort(keyArray);
        // 拼接有序的参数名-值串  
        stringBuilder.append(appId);
        for (String key : keyArray) {
            stringBuilder.append(key).append(params.get(key));
        }
        String codes = stringBuilder.append(secret).toString();
        String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
        // 添加签名,并发送请求  
        params.put("appId", appId);
        params.put("sign", sign);
        return params;
    }
    public static String postBody(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("Accept", MediaType.ALL_VALUE.toString());
        headers.add("Cache-Control", "no-cache");
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    public  void putBody(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        restTemplate.put(url, formEntity, String.class);
    }
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @return
     */
    public String iotPostBody(String url, String params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params, headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
}

+ 72 - 0
common/common-util/src/main/java/com/yihu/jw/vo/ValidateCode.java

@ -0,0 +1,72 @@
package com.yihu.jw.vo;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
 * Created by 刘文彬 on 2018/4/23.
 */
public class ValidateCode implements Serializable {
    private String code;
    private LocalDateTime expireTime;
    private LocalDateTime createTime=LocalDateTime.now();
    public ValidateCode() {
    }
    public ValidateCode(String code, int expireIn) {
        this.code = code;
        this.expireTime = LocalDateTime.now().plusMinutes(expireIn);
    }
    public ValidateCode(String code, LocalDateTime expireTime) {
        this.code = code;
        this.expireTime = expireTime;
    }
    public boolean isExpried() {
        return LocalDateTime.now().isAfter(expireTime);
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public LocalDateTime getExpireTime() {
        return expireTime;
    }
    public void setExpireTime(LocalDateTime expireTime) {
        this.expireTime = expireTime;
    }
    public String getExpireTimeString() {
        return expireTime.format(DateTimeFormatter.ISO_DATE_TIME);
    }
    public void setExpireTimeString(String strTime) {
        expireTime = LocalDateTime.parse(strTime, DateTimeFormatter.ISO_DATE_TIME);
    }
    public LocalDateTime getCreateTime() {
        return createTime;
    }
    public String getCreateTimeString() {
        return createTime.format(DateTimeFormatter.ISO_DATE_TIME);
    }
    public void setCreateTimeString(String createTime) {
        this.createTime = LocalDateTime.parse(createTime, DateTimeFormatter.ISO_DATE_TIME);
    }
}

BIN
data/elasticsearch/nodes/0/_state/global-0.st


+ 0 - 0
data/elasticsearch/nodes/0/node.lock


+ 2 - 1
server/svr-discovery/pom.xml

@ -18,7 +18,8 @@
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <!--<artifactId>spring-cloud-starter-eureka-server</artifactId>-->
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>

+ 27 - 10
svr/svr-base/pom.xml

@ -19,6 +19,18 @@
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.yihu.base</groupId>
                    <artifactId>common-data-es</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>common-data-es-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
@ -53,24 +65,24 @@
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
            <!--<exclusions>-->
                <!--<exclusion>-->
                    <!--<groupId>org.springframework.boot</groupId>-->
                    <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
                <!--</exclusion>-->
            <!--</exclusions>-->
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
        <!--<dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>8.5.28</version>
            <!--tomcat 启动时 打开注释 end-->
        </dependency>
            &lt;!&ndash;tomcat 启动时 打开注释 end&ndash;&gt;
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
@ -97,7 +109,7 @@
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
@ -150,6 +162,11 @@
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-fegin</artifactId>
            <version>1.0.0</version>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-data-redis</artifactId>-->

+ 9 - 0
svr/svr-base/src/main/java/com/yihu/jw/SvrBaseApplication.java

@ -1,9 +1,14 @@
package com.yihu.jw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ -19,6 +24,10 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
        transactionManagerRef = "baseTransactionManager"
)
@ComponentScan(basePackages={"com"})
@EnableJpaAuditing
@EnableAutoConfiguration(exclude = {
        ElasticsearchRepositoriesAutoConfiguration.class
})
public class SvrBaseApplication {
    public static void main(String[] args) {

+ 2 - 1
svr/svr-base/src/main/java/com/yihu/jw/business/base/controller/ModuleFunController.java

@ -6,6 +6,7 @@ import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@ -31,7 +32,7 @@ public class ModuleFunController extends EnvelopRestController {
    @PutMapping(value =  BaseRequestMapping.ModuleFun.api_changeFun,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "模块更新功能")
    public Envelop changeFun (@RequestBody String jsonData) {
    public Envelop changeFun (@RequestBody String jsonData) throws JSONException {
        moduleFunService.changeFun(jsonData);
        return Envelop.getSuccess("更新成功",null);
    }

+ 2 - 1
svr/svr-base/src/main/java/com/yihu/jw/business/base/service/ModuleFunService.java

@ -6,6 +6,7 @@ import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.rm.base.BaseRequestMapping;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -43,7 +44,7 @@ public class ModuleFunService extends BaseJpaService<ModuleFunctionDO, ModuleFun
     * 更改模块关联的功能
     * @param jsonData
     */
    public void changeFun(String jsonData) {
    public void changeFun(String jsonData) throws JSONException {
        JSONObject jsonObject =  new JSONObject(jsonData);
        if(!jsonObject.has("moduleCode")){
            throw new ApiException(BaseRequestMapping.ModuleFun.moduleId_is_null, ExceptionCode.common_error_params_code);

+ 117 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/login/contorller/LoginController.java

@ -0,0 +1,117 @@
package com.yihu.jw.business.login.contorller;
//import com.yihu.base.security.properties.SecurityProperties;
//import com.yihu.base.security.sms.mobile.MobileCheck;
//import com.yihu.base.security.sms.process.SmsValidateCodeProcessor;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.business.login.service.LoginService;
import com.yihu.jw.business.user.dao.EmployDao;
import com.yihu.jw.business.user.service.EmployService;
import com.yihu.jw.fegin.common.security.LoginSmsFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import com.yihu.jw.util.common.ConvertToSpellUtils;
import com.yihu.jw.util.security.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.util.UUID;
/**
 * Created by 刘文彬 on 2018/4/11.
 */
@RestController
@RequestMapping(BaseLoginRequestMapping.api_common)
@Api(description = "注册账户(医生端、微信端、用户端)")
public class LoginController extends EnvelopRestController {
    @Autowired
    private LoginService loginService;
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_checkoutInfo, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "注册校验信息", notes = "注册校验姓名、身份证、医保卡号信息")
    public BaseEnvelop checkoutInfo(){
        //校验姓名、身份证以及医保卡号信息是否正确
        return null;
    }
    /**
     * 注册账号-提交
     * @param mobilePhone
     * @param saasId
     * @param type
     * @param captcha
     * @param name
     * @param password
     * @param idcard
     * @param ssc
     * @return
     */
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_accountSub, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "注册账号", notes = "注册校验姓名、身份证、医保卡号信息")
    public Envelop register(
            @ApiParam(name = "mobilePhone", value = "电话号码(账号)", required = true) @RequestParam(value = "mobilePhone", required = true) String mobilePhone,
            @ApiParam(name = "saasId", value = "saasID", required = true) @RequestParam(value = "saasId", required = true) String saasId,
            @ApiParam(name = "type", value = "1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录", required = true) @RequestParam(value = "type", required = true) int type,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(value = "captcha", required = true) String captcha,
            @ApiParam(name = "name", value = "姓名", required = true) @RequestParam(value = "name", required = true) String name,
            @ApiParam(name = "password", value = "账户密码", required = true) @RequestParam(value = "password", required = true) String password,
            @ApiParam(name = "idcard", value = "身份证", required = true) @RequestParam(value = "idcard", required = true) String idcard,
            @ApiParam(name = "ssc", value = "医保卡号", required = true) @RequestParam(value = "ssc", required = true) String ssc){
        try {
            //判断验证码是否正确
            Envelop envelop = new Envelop();//smsService.checkSms(mobilePhone,saasId,type,captcha);
            if(true){//if(envelop.getStatus()==200){
                return loginService.register(mobilePhone,password,saasId,name,idcard,ssc);
            }else{
                return envelop;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Envelop();
    }
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_login, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Envelop login(@ApiParam(name = "mobilePhone", value = "电话号码(账号)", required = false) @RequestParam(value = "mobilePhone", required = false) String mobilePhone,
                      @ApiParam(name = "password", value = "password", required = false) @RequestParam(value = "password", required = false) String password,
                      @ApiParam(name = "saasId", value = "saasID", required = true) @RequestParam(value = "saasId", required = true) String saasId,
                         @ApiParam(name = "captcha", value = "短信验证码", required = false) @RequestParam(value = "captcha", required = false) String captcha){
       return loginService.login(mobilePhone,password,saasId,captcha);
    }
    @PostMapping("/logout")
    public Envelop logout(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "*/*");
        headers.add("Cache-Control", "no-cache");
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        //设置http请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        restTemplate.postForObject("http://localhost:8088/logout", requestEntity, String.class);
        return new Envelop();
    }
}

+ 27 - 27
svr/svr-base/src/main/java/com/yihu/jw/business/login/dao/BaseLoginAccountDao.java

@ -1,27 +1,27 @@
package com.yihu.jw.business.login.dao;
import com.yihu.jw.base.login.BaseLoginAccountDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by LiTaohong on 2017/12/05.
 * 账户表,识别用户类型,医生,行政人员等
 */
public interface BaseLoginAccountDao extends PagingAndSortingRepository<BaseLoginAccountDO, String>, JpaSpecificationExecutor<BaseLoginAccountDO> {
    /**
     * 删除用户账号
     * @param id
     */
    @Query("update BaseLoginAccountDO ba set ba.accountStatus = -1 where ba.id = ?1")
    void deleteAccount(String id);
    /**
     * 锁定用户账号
     * @param id
     */
    @Query("update BaseLoginAccountDO ba set ba.accountStatus = -2 where ba.id = ?1")
    void updateAccount(String id);
}
//package com.yihu.jw.business.login.dao;
//
//import com.yihu.jw.base.login.BaseLoginAccountDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by LiTaohong on 2017/12/05.
// * 账户表,识别用户类型,医生,行政人员等
// */
//public interface BaseLoginAccountDao extends PagingAndSortingRepository<BaseLoginAccountDO, String>, JpaSpecificationExecutor<BaseLoginAccountDO> {
//
//    /**
//     * 删除用户账号
//     * @param id
//     */
//    @Query("update BaseLoginAccountDO ba set ba.accountStatus = -1 where ba.id = ?1")
//    void deleteAccount(String id);
//
//    /**
//     * 锁定用户账号
//     * @param id
//     */
//    @Query("update BaseLoginAccountDO ba set ba.accountStatus = -2 where ba.id = ?1")
//    void updateAccount(String id);
//}

+ 11 - 11
svr/svr-base/src/main/java/com/yihu/jw/business/login/dao/BaseLoginLogDao.java

@ -1,11 +1,11 @@
package com.yihu.jw.business.login.dao;
import com.yihu.jw.base.login.BaseLoginLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/20.
 */
public interface BaseLoginLogDao extends PagingAndSortingRepository<BaseLoginLogDO, String>, JpaSpecificationExecutor<BaseLoginLogDO> {
}
//package com.yihu.jw.business.login.dao;
//
//import com.yihu.jw.base.login.BaseLoginLogDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by chenweida on 2017/6/20.
// */
//public interface BaseLoginLogDao extends PagingAndSortingRepository<BaseLoginLogDO, String>, JpaSpecificationExecutor<BaseLoginLogDO> {
//}

+ 75 - 75
svr/svr-base/src/main/java/com/yihu/jw/business/login/service/BaseLoginAccountService.java

@ -1,75 +1,75 @@
package com.yihu.jw.business.login.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.login.BaseLoginAccountDO;
import com.yihu.jw.business.login.dao.BaseLoginAccountDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
/**
 * Created by LiTaohong on 2017/12/5.
 * 用户账户功能
 */
@Service
public class BaseLoginAccountService extends BaseJpaService<BaseLoginAccountDO,BaseLoginAccountDao> {
    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    /**
     * 创建账户
     * @param baseLoginAccountDO
     * @return
     */
    @Transactional
    public BaseLoginAccountDO createBaseLoginAccount(BaseLoginAccountDO baseLoginAccountDO){
        if (StringUtils.isEmpty(baseLoginAccountDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseLoginAccountDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseLoginAccountDao.save(baseLoginAccountDO);
    }
    /**
     * 修改账户
     * @param baseLoginAccountDO
     * @return
     */
    @Transactional
    public BaseLoginAccountDO updateBaseLoginAccount(BaseLoginAccountDO baseLoginAccountDO){
        return this.baseLoginAccountDao.save(baseLoginAccountDO);
    }
    /**
     * 锁定账户
     * @param id
     * @return
     */
    @Transactional
    public void lockBaseLoginAccount(String id){
         this.baseLoginAccountDao.updateAccount(id);
    }
    /**
     * 删除账户
     * @param id
     * @return
     */
    @Transactional
    public void deleteBaseLoginAccount(String id){
         this.baseLoginAccountDao.deleteAccount(id);
    }
}
//package com.yihu.jw.business.login.service;
//
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.base.login.BaseLoginAccountDO;
//import com.yihu.jw.business.login.dao.BaseLoginAccountDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//
///**
// * Created by LiTaohong on 2017/12/5.
// * 用户账户功能
// */
//@Service
//public class BaseLoginAccountService extends BaseJpaService<BaseLoginAccountDO,BaseLoginAccountDao> {
//
//    @Autowired
//    private BaseLoginAccountDao baseLoginAccountDao;
//
//    /**
//     * 创建账户
//     * @param baseLoginAccountDO
//     * @return
//     */
//    @Transactional
//    public BaseLoginAccountDO createBaseLoginAccount(BaseLoginAccountDO baseLoginAccountDO){
//        if (StringUtils.isEmpty(baseLoginAccountDO.getId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseLoginAccountDO.getSaasId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.baseLoginAccountDao.save(baseLoginAccountDO);
//    }
//
//
//    /**
//     * 修改账户
//     * @param baseLoginAccountDO
//     * @return
//     */
//    @Transactional
//    public BaseLoginAccountDO updateBaseLoginAccount(BaseLoginAccountDO baseLoginAccountDO){
//        return this.baseLoginAccountDao.save(baseLoginAccountDO);
//    }
//
//
//    /**
//     * 锁定账户
//     * @param id
//     * @return
//     */
//    @Transactional
//    public void lockBaseLoginAccount(String id){
//         this.baseLoginAccountDao.updateAccount(id);
//    }
//
//    /**
//     * 删除账户
//     * @param id
//     * @return
//     */
//    @Transactional
//    public void deleteBaseLoginAccount(String id){
//         this.baseLoginAccountDao.deleteAccount(id);
//    }
//
//
//
//
//}

+ 131 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/login/service/LoginService.java

@ -0,0 +1,131 @@
package com.yihu.jw.business.login.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.login.BaseLoginAccountDO;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.business.user.dao.EmployDao;
import com.yihu.jw.business.user.service.EmployService;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.util.common.ConvertToSpellUtils;
import com.yihu.jw.util.security.MD5;
import io.swagger.annotations.ApiParam;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import java.beans.Transient;
import java.util.UUID;
/**
 * Created by 刘文彬 on 2018/4/26.
 */
@Service
public class LoginService  extends BaseJpaService<BaseEmployDO,EmployDao> {
    @Autowired
    private EmployDao employDao;
    @Autowired
    private EmployService employService;
    @Value("${server.web-gateway-port}")
    private String port;
    public BaseEnvelop checkoutInfo(){
        //校验姓名、身份证以及医保卡号信息是否正确
        return null;
    }
    @Transactional
    public Envelop register(String mobilePhone,String password,String saasId,String name,String idcard,String ssc){
        //判断账号是否重复
        BaseEmployDO baseEmployDO = employDao.findByPhoneAndSaasId(mobilePhone,saasId);
        if(baseEmployDO!=null){
            return Envelop.getError("该手机号已注册!");
        }
        //保存账户基础信息
        BaseEmployDO employeeDO = new BaseEmployDO();
        employeeDO.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        employeeDO.setSaasId(saasId);
        employeeDO.setName(name);
        employeeDO.setPyCode(ConvertToSpellUtils.changeToInitialPinYin(name));
        employeeDO.setIdcard(idcard);
        employeeDO.setSsc(ssc);
        employeeDO.setPhone(mobilePhone);
        String salt= UUID.randomUUID().toString().replace("-","");
        employeeDO.setSalt(salt);
        employeeDO.setPassword(MD5.GetMD5Code(password + salt));
        employService.createBaseEmployDO(employeeDO);
        return login(employeeDO.getPhone(),employeeDO.getPassword(),saasId,"");
    }
    public Envelop login(String mobilePhone,String password,String saasId,String captcha){
        BaseEmployDO baseEmployDO = employService.findByPhoneAndSaasId(mobilePhone,saasId);
        if(baseEmployDO==null){
            return Envelop.getError("该账户不存在!");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "*/*");
        headers.add("Cache-Control", "no-cache");
        //client_id:client_securt
        byte[] a = Base64.encode((saasId+":").getBytes());
        String client_id = new String(a);
        headers.add("Authorization","Basic "+client_id);//MTox
        String token = "";
        //传参数JSON格式
        //  封装参数,千万不要替换为Map与HashMap,否则参数无法传递
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        //判断是短信登录还是账号密码登录
        if(StringUtils.isEmpty(captcha)){
            //  也支持中文
            params.add("username", mobilePhone+","+saasId);
            params.add("password", MD5.GetMD5Code(password+baseEmployDO.getSalt()));
            //设置http请求实体
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
            RestTemplate restTemplate = new RestTemplate();
            token = restTemplate.postForObject("http://localhost:"+port+"/authentication/form", requestEntity, String.class);
        }else{
            params.add("mobile", mobilePhone+","+saasId);
            params.add("sms", captcha);
            //设置http请求实体
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
            RestTemplate restTemplate = new RestTemplate();
            token = restTemplate.postForObject("http://localhost:"+port+"/authentication/mobile", requestEntity, String.class);
        }
        if(!StringUtils.isEmpty(token)){
            return Envelop.getSuccess("登录成功!",token);
        }else{
            return Envelop.getError("登录失败!");
        }
    }
//    public Envelop logout(){
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Accept", "*/*");
//        headers.add("Cache-Control", "no-cache");
//        RestTemplate restTemplate = new RestTemplate();
//        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
//        //设置http请求实体
//        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
//        restTemplate.postForObject("http://localhost:"+port+"/logout", requestEntity, String.class);
//    }
}

+ 69 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/sms/controller/SMSController.java

@ -0,0 +1,69 @@
package com.yihu.jw.business.sms.controller;
import com.yihu.jw.base.sms.BaseSmsDO;
import com.yihu.jw.business.sms.service.SmsService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.base.sms.SmsVO;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
import com.yihu.jw.util.common.MobileUtils;
import com.yihu.jw.util.common.NetworkUtil;
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.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/5/19.
 * 注册发送短信验证码
 */
@RestController
@RequestMapping(BaseSmsRequestMapping.api_common)
@Api(value = "短信模块", description = "短信模块接口管理")
public class SMSController extends EnvelopRestController {
    @Autowired
    private SmsService smsService;
    @ApiOperation(value = "(注册、找回密码)发送校验码")
    @PostMapping(value = BaseSmsRequestMapping.Sms.api_sms_send, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseEnvelop send(@ApiParam(name = "mobile", value = "手机号码", required = true) @RequestParam(value = "mobile", required = true) String mobile,
                            @ApiParam(name = "type", value = "短信验证码类型", required = true) @RequestParam(value = "type", required = true) int type,
                            @ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId,
                            HttpServletRequest request) throws IOException {
        try {
            if (type > 10 || type < 1) {
                return BaseEnvelop.getError("无效的请求!");
            }
            if (StringUtils.isEmpty(mobile)) {
                return BaseEnvelop.getError("手机号码不允许为空!");
            }
            if(!MobileUtils.checkCellphone(mobile)){
                return BaseEnvelop.getError("手机号码格式不正确!");
            }
            // 获取ip地址
            String ip = NetworkUtil.getIpAddress(request);
            if (StringUtils.isEmpty(ip)) {
                return  BaseEnvelop.getError("无效的ip请求!");
            }
            BaseEnvelop envelop1 = smsService.send(mobile,ip,type,saasId);
            return envelop1;
        } catch (Exception e) {
            error(e);
            return  BaseEnvelop.getError("手机号有误,无法发送验证!");
        }
    }
}

+ 0 - 103
svr/svr-base/src/main/java/com/yihu/jw/business/sms/controller/SmsController.java

@ -1,103 +0,0 @@
package com.yihu.jw.business.sms.controller;
import com.yihu.jw.base.sms.BaseSmsDO;
import com.yihu.jw.business.sms.service.SmsService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.base.sms.SmsVO;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/5/19.
 */
@RestController
@RequestMapping(BaseSmsRequestMapping.api_common)
@Api(value = "短信模块", description = "短信模块接口管理")
public class SmsController extends EnvelopRestController {
    @Autowired
    private SmsService smsService;
    @PostMapping(value = BaseSmsRequestMapping.Sms.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建短信", notes = "创建单个短信")
    public Envelop createSms(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            BaseSmsDO sms = toEntity(jsonData, BaseSmsDO.class);
            return Envelop.getSuccess(BaseSmsRequestMapping.Sms.message_success_create, smsService.createSms(sms));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PutMapping(value = BaseSmsRequestMapping.Sms.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改短信", notes = "修改短信")
    public Envelop updateSms(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            BaseSmsDO sms = toEntity(jsonData, BaseSmsDO.class);
            return Envelop.getSuccess(BaseSmsRequestMapping.Sms.message_success_update, smsService.updateSms(sms));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @RequestMapping(value = BaseSmsRequestMapping.Sms.api_getSmss, method = RequestMethod.GET)
    @ApiOperation(value = "获取短信列表(分页)")
    public Envelop getSmss(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "code,name,saasId,parentCode,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            //code like 1,name大于aa ,code 等于1 , defaultValue = "code?1;name>aa;code=1"
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //得到list数据
        List<BaseSmsDO> list = smsService.search(fields, filters, sorts, page, size);
        //获取总数
        long count = smsService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<SmsVO> mSmss = convertToModels(list, new ArrayList<>(list.size()), SmsVO.class, fields);
        return Envelop.getSuccessListWithPage(BaseSmsRequestMapping.Sms.message_success_find_smss, mSmss, page, size, count);
    }
    @GetMapping(value = BaseSmsRequestMapping.Sms.api_getSmssNoPage)
    @ApiOperation(value = "获取短信列表,不分页")
    public Envelop getAppsNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "code,name,saasId,parentCode,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        //得到list数据
        List<BaseSmsDO> list = smsService.search(fields, filters, sorts);
        //封装返回格式
        List<SmsVO> mSmss = convertToModels(list, new ArrayList<>(list.size()), SmsVO.class, fields);
        return Envelop.getSuccessList(BaseSmsRequestMapping.Sms.message_success_find_smss, mSmss);
    }
}

+ 9 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/sms/dao/SmsDao.java

@ -2,8 +2,17 @@ package com.yihu.jw.business.sms.dao;
import com.yihu.jw.base.sms.BaseSmsDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface SmsDao extends PagingAndSortingRepository<BaseSmsDO, String>, JpaSpecificationExecutor<BaseSmsDO> {
    @Query("select count(a.id) from BaseSmsDO a where a.mobile = ?1 and a.createTime  between ?2 and ?3 ")
    int countByMobile(String mobile,Date begin, Date end);
    @Query("select a from BaseSmsDO a where a.mobile = ?1 and a.type = ?2 and a.saasId= ?3 order by a.createTime desc")
    List<BaseSmsDO> findByMobileType(String mobile, int type,String saasId);
}

+ 20 - 20
svr/svr-base/src/main/java/com/yihu/jw/business/sms/dao/SmsGatewayDao.java

@ -1,20 +1,20 @@
package com.yihu.jw.business.sms.dao;
import com.yihu.jw.base.sms.BaseSmsGatewayDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/5/22.
 */
public interface SmsGatewayDao extends PagingAndSortingRepository<BaseSmsGatewayDO, String>, JpaSpecificationExecutor<BaseSmsGatewayDO> {
    @Query("from BaseSmsGatewayDO f where f.name=?1 and f.status=1")
    BaseSmsGatewayDO findByName(String name);
    @Query("from BaseSmsGatewayDO f where f.name=?1 and f.status=1 and f.id != ?2")
    BaseSmsGatewayDO findByNameExcludeCode(String name, String code);
    @Query("from BaseSmsGatewayDO f where f.id=?1 and f.status=1")
    BaseSmsGatewayDO findById(String id);
}
//package com.yihu.jw.business.sms.dao;
//
//import com.yihu.jw.base.sms.BaseSmsGatewayDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by chenweida on 2017/5/22.
// */
//public interface SmsGatewayDao extends PagingAndSortingRepository<BaseSmsGatewayDO, String>, JpaSpecificationExecutor<BaseSmsGatewayDO> {
//    @Query("from BaseSmsGatewayDO f where f.name=?1 and f.status=1")
//    BaseSmsGatewayDO findByName(String name);
//
//    @Query("from BaseSmsGatewayDO f where f.name=?1 and f.status=1 and f.id != ?2")
//    BaseSmsGatewayDO findByNameExcludeCode(String name, String code);
//
//    @Query("from BaseSmsGatewayDO f where f.id=?1 and f.status=1")
//    BaseSmsGatewayDO findById(String id);
//}

+ 68 - 68
svr/svr-base/src/main/java/com/yihu/jw/business/sms/service/SmsGatewayService.java

@ -1,68 +1,68 @@
package com.yihu.jw.business.sms.service;
import com.yihu.jw.base.sms.BaseSmsGatewayDO;
import com.yihu.jw.business.sms.dao.SmsGatewayDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
/**
 * Created by chenweida on 2017/5/22.
 */
@Service
public class SmsGatewayService extends BaseJpaService<BaseSmsGatewayDO, SmsGatewayDao> {
    @Autowired
    private SmsGatewayDao smsGatewayDao;
    @Transactional
    public BaseSmsGatewayDO createSmsGateway(BaseSmsGatewayDO smsGateway) throws ApiException {
        if (StringUtils.isEmpty(smsGateway.getId())) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(smsGateway.getName())) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_is_null, ExceptionCode.common_error_params_code);
        }
        BaseSmsGatewayDO smsGatewayTmp = smsGatewayDao.findByName(smsGateway.getName());
        if (smsGatewayTmp != null) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_exist, ExceptionCode.common_error_params_code);
        }
        return smsGatewayDao.save(smsGateway);
    }
    @Transactional
    public BaseSmsGatewayDO updateSmsGateway(BaseSmsGatewayDO smsGateway) {
        if (StringUtils.isEmpty(smsGateway.getName())) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(smsGateway.getId())) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        BaseSmsGatewayDO smsGatewayTmp = smsGatewayDao.findByNameExcludeCode(smsGateway.getName(), smsGateway.getId());
        if (smsGatewayTmp != null) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_exist, ExceptionCode.common_error_params_code);
        }
        return smsGatewayDao.save(smsGateway);
    }
    public BaseSmsGatewayDO findById(String id) {
        BaseSmsGatewayDO smsGateway = smsGatewayDao.findById(id);
        if (smsGateway == null) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
        }
        return smsGateway;
    }
    @Transactional
    public void deleteSmsGateway(String id) {
        BaseSmsGatewayDO smsGateway = smsGatewayDao.findById(id);
        if (smsGateway == null) {
            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
        }
        smsGateway.setStatus(-1);
    }
}
//package com.yihu.jw.business.sms.service;
//
//import com.yihu.jw.base.sms.BaseSmsGatewayDO;
//import com.yihu.jw.business.sms.dao.SmsGatewayDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.BaseSmsRequestMapping;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//
///**
// * Created by chenweida on 2017/5/22.
// */
//@Service
//public class SmsGatewayService extends BaseJpaService<BaseSmsGatewayDO, SmsGatewayDao> {
//    @Autowired
//    private SmsGatewayDao smsGatewayDao;
//
//    @Transactional
//    public BaseSmsGatewayDO createSmsGateway(BaseSmsGatewayDO smsGateway) throws ApiException {
//        if (StringUtils.isEmpty(smsGateway.getId())) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(smsGateway.getName())) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_is_null, ExceptionCode.common_error_params_code);
//        }
//        BaseSmsGatewayDO smsGatewayTmp = smsGatewayDao.findByName(smsGateway.getName());
//        if (smsGatewayTmp != null) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_exist, ExceptionCode.common_error_params_code);
//        }
//        return smsGatewayDao.save(smsGateway);
//    }
//
//    @Transactional
//    public BaseSmsGatewayDO updateSmsGateway(BaseSmsGatewayDO smsGateway) {
//        if (StringUtils.isEmpty(smsGateway.getName())) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(smsGateway.getId())) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        BaseSmsGatewayDO smsGatewayTmp = smsGatewayDao.findByNameExcludeCode(smsGateway.getName(), smsGateway.getId());
//        if (smsGatewayTmp != null) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_name_exist, ExceptionCode.common_error_params_code);
//        }
//        return smsGatewayDao.save(smsGateway);
//    }
//
//    public BaseSmsGatewayDO findById(String id) {
//        BaseSmsGatewayDO smsGateway = smsGatewayDao.findById(id);
//        if (smsGateway == null) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
//        }
//        return smsGateway;
//    }
//
//    @Transactional
//    public void deleteSmsGateway(String id) {
//        BaseSmsGatewayDO smsGateway = smsGatewayDao.findById(id);
//        if (smsGateway == null) {
//            throw new ApiException(BaseSmsRequestMapping.SmsGateway.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
//        }
//        smsGateway.setStatus(-1);
//    }
//}

+ 166 - 5
svr/svr-base/src/main/java/com/yihu/jw/business/sms/service/SmsService.java

@ -2,11 +2,35 @@ package com.yihu.jw.business.sms.service;
import com.yihu.jw.base.sms.BaseSmsDO;
import com.yihu.jw.business.sms.dao.SmsDao;
import com.yihu.jw.business.sms.vo.SMSHttpVo;
import com.yihu.jw.exception.ApiException;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.util.common.SmsValidateCodeUtils;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.vo.ValidateCode;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2017/5/22.
@ -15,16 +39,153 @@ import org.springframework.transaction.annotation.Transactional;
public class SmsService  extends BaseJpaService<BaseSmsDO, SmsDao> {
    @Autowired
    private SmsDao smsDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private SMSHttpVo smsHttpVo;
//    @Transactional
//    public BaseSmsDO createSms(BaseSmsDO sms) throws ApiException {
//
//        return smsDao.save(sms);
//    }
//
//    @Transactional
//    public BaseSmsDO updateSms(BaseSmsDO sms) {
//        return smsDao.save(sms);
//    }
    /**
     * 发送验证码(不走权限判断,包括:注册、找回密码)
     * @param mobile
     * @param ip
     * @param type
     * @return
     * @throws Exception
     */
    @Transactional
    public BaseSmsDO createSms(BaseSmsDO sms) throws ApiException {
    public BaseEnvelop send(String mobile, String ip, int type,String saasId) throws Exception {
        // 1、同一手机一天不允许超过5条短信
        //1.1获取一天的开始和结束时间
        String today = DateUtil.getStringDateShort();
        Date begin = DateUtil.strToDate(today + " 00:00:00", DateUtil.YYYY_MM_DD_HH_MM_SS);
        Date end = DateUtil.strToDate(today + " 23:59:59", DateUtil.YYYY_MM_DD_HH_MM_SS);
        int smsCount = smsDao.countByMobile(mobile,begin,end);
        if(smsCount>=5){
            return Envelop.getError("您的验证码次数已用完,请明天再尝试!",-1);
        }
        // 2、60秒之内不允许重复发送
//        PageRequest pageRequest = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "id"));
        List<BaseSmsDO> page = smsDao.findByMobileType(mobile,type,saasId);
        if (page.size()>0) {
//            for (BaseSmsDO sms : page) {
//                if (sms == null) {
//                    continue;
//                }
                // 计算间隔时间
                Date temp = DateUtil.getNextMin(page.get(0).getCreateTime(), 1);
                long leftTime = (temp.getTime() - System.currentTimeMillis()) / 1000;
                if (leftTime > 0) {
                    return BaseEnvelop.getError("发送短信验证码间隔时间为:60秒!");
                }
//            }
        }
        //3、生成验证码
        ValidateCode vc = SmsValidateCodeUtils.generate(6,1);
        return smsDao.save(sms);
        //4、保存验证码(1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录)
        BaseSmsDO sms = new BaseSmsDO();
        sms.setMobile(mobile);
        sms.setIp(ip);
        sms.setType(type);
        sms.setCaptcha(vc.getCode());
        switch (type){
            case 1:sms.setContent("您的注册验证码为:"+vc.getCode());break;
            case 2:sms.setContent("您找回密码验证码为:"+vc.getCode());break;
            case 3:sms.setContent("您找回密码验证码为:"+vc.getCode());break;
        }
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        sms.setDeadline(s.parse(vc.getCreateTimeString()));
        sms.setStatus(1);
        sms.setSaasId(saasId);
        //5、 调用发送信息的接口
//        String result = httpClientUtil.post(smsHttpVo.getUrl(), buildSmsParams(sms.getContent(), mobile), "GBK");
//        JSONObject json = toJson(result);
//        if (json == null) {
//            // 发送失败
//            return BaseEnvelop.getError("短信接口请求失败!");
//        } else if (json.getInt("result") != 0) {
//            return BaseEnvelop.getError(json.getString("description"));
//        } else {
//            //发送成功,保存到数据库
//        }
        smsDao.save(sms);
        if(smsCount>=2&&smsCount<=5){
           return  BaseEnvelop.getSuccess("今日可重发验证码剩余"+(5-smsCount)+"次,请尽快完成验证。!");
        }
        return BaseEnvelop.getSuccess("验证码发送成功!");
    }
    @Transactional
    public BaseSmsDO updateSms(BaseSmsDO sms) {
        return smsDao.save(sms);
    //封装发送短信的参数
    public  List<NameValuePair> buildSmsParams(String content, String mobile) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("SpCode", smsHttpVo.getCode()));
        params.add(new BasicNameValuePair("LoginName", smsHttpVo.getName()));
        params.add(new BasicNameValuePair("Password", smsHttpVo.getPassword()));
        params.add(new BasicNameValuePair("MessageContent", content));
        params.add(new BasicNameValuePair("UserNumber", mobile));
        params.add(new BasicNameValuePair("SerialNumber", String.valueOf(System.currentTimeMillis())));
        params.add(new BasicNameValuePair("ScheduleTime", ""));
        params.add(new BasicNameValuePair("f", "1"));
        return params;
    }
    //校验验证码是否正确
    public Envelop checkSms(String mobile,String saasId,int type,String captcha){
        PageRequest pageRequest = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "id"));
        List<BaseSmsDO> page = smsDao.findByMobileType(mobile,type,saasId);
//        if (page != null) {
//            for (BaseSmsDO sms : page) {
                BaseSmsDO sms = page.get(0);
                String toCaptcha = sms.getCaptcha();
                Date deadline = sms.getDeadline();
                if(new Date().before(deadline)){
                    //对比校验码是否正确
                    if(captcha.equals(toCaptcha)){
                        Envelop.getSuccess("验证码校验成功!");
                    }else{
                        return Envelop.getError("验证码错误!");
                    }
                }else{
                    //过期
                    return Envelop.getError("验证码过期!");
                }
//            }
//        }
        return Envelop.getError("未发送验证码!");
    }
    //解析短信返回的json数据
    public JSONObject toJson(String result) {
        JSONObject json = new JSONObject();
        try {
            String[] temps = result.split("&");
            for (String temp : temps) {
                if (temp.split("=").length != 2) {
                    continue;
                }
                String key = temp.split("=")[0];
                String value = temp.split("=")[1];
                json.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
}

+ 49 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/sms/vo/SMSHttpVo.java

@ -0,0 +1,49 @@
package com.yihu.jw.business.sms.vo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * Created by 刘文彬 on 2018/4/13.
 */
@Component
@ConfigurationProperties(prefix = "jw.sms")
public class SMSHttpVo {
    private String url;
    private String code;
    private String name;
    private String password;
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

+ 95 - 95
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseMenuController.java

@ -1,95 +1,95 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.service.BaseMenuService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
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.*;
/**
 * Created by LiTaohong on 2017/11/28.
 */
@RestController
@RequestMapping(BaseUserRequestMapping.api_user_common)
@Api(description = "基础菜单")
public class BaseMenuController extends EnvelopRestController {
    @Autowired
    private BaseMenuService baseMenuService;
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建菜单", notes = "创建单个菜单")
    public Envelop createBaseMenu(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,baseMenuService.createBaseMenu(baseMenuDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改菜单", notes = "修改菜单")
    public Envelop updateBaseMenu(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_update,baseMenuService.updateBaseMenuDO(baseMenuDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getOne, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询单个菜单", notes = "根据菜单id查询菜单信息")
    public Envelop getOneMenuById(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.findById(baseMenuDO.getId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getchildren, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询单个菜单的所有子菜单信息", notes = "根据平台和菜单名称查询菜单信息")
    public Envelop getChlidrenMenuList(@ApiParam(name = "saasId", value = "", defaultValue = "") @RequestParam String saasId,
                                       @ApiParam(name = "parentId", value = "", defaultValue = "") @RequestParam String parentId){
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.getChlidrenMenuList(saasId,parentId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getList, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询多个菜单", notes = "根据平台saasId查询所有菜单信息")
    public Envelop getMenuListBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.findAllBySaasId(baseMenuDO.getSaasId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "批量删除菜单", notes = "删除某一平台saasId下所有菜单信息")
    public Envelop deleteMenusBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            baseMenuService.deleteBaseMenusBySaasId(baseMenuDO.getSaasId());
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete);
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}
//package com.yihu.jw.business.user.contorller;
//
//import com.yihu.jw.base.user.BaseMenuDO;
//import com.yihu.jw.base.user.BaseRoleDO;
//import com.yihu.jw.business.user.service.BaseMenuService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//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.*;
//
///**
// * Created by LiTaohong on 2017/11/28.
// */
//@RestController
//@RequestMapping(BaseUserRequestMapping.api_user_common)
//@Api(description = "基础菜单")
//public class BaseMenuController extends EnvelopRestController {
//
//    @Autowired
//    private BaseMenuService baseMenuService;
//
//    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建菜单", notes = "创建单个菜单")
//    public Envelop createBaseMenu(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,baseMenuService.createBaseMenu(baseMenuDO));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改菜单", notes = "修改菜单")
//    public Envelop updateBaseMenu(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_update,baseMenuService.updateBaseMenuDO(baseMenuDO));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getOne, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "查询单个菜单", notes = "根据菜单id查询菜单信息")
//    public Envelop getOneMenuById(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.findById(baseMenuDO.getId()));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getchildren, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "查询单个菜单的所有子菜单信息", notes = "根据平台和菜单名称查询菜单信息")
//    public Envelop getChlidrenMenuList(@ApiParam(name = "saasId", value = "", defaultValue = "") @RequestParam String saasId,
//                                       @ApiParam(name = "parentId", value = "", defaultValue = "") @RequestParam String parentId){
//        try{
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.getChlidrenMenuList(saasId,parentId));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getList, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "查询多个菜单", notes = "根据平台saasId查询所有菜单信息")
//    public Envelop getMenuListBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.findAllBySaasId(baseMenuDO.getSaasId()));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "批量删除菜单", notes = "删除某一平台saasId下所有菜单信息")
//    public Envelop deleteMenusBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
//            baseMenuService.deleteBaseMenusBySaasId(baseMenuDO.getSaasId());
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete);
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//}

+ 220 - 220
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseRoleController.java

@ -1,220 +1,220 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.base.user.BaseRoleMenuDO;
import com.yihu.jw.business.user.service.BaseRoleMenuService;
import com.yihu.jw.business.user.service.BaseRoleService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.restmodel.base.user.BaseEmployVO;
import com.yihu.jw.restmodel.base.user.BaseRoleVO;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
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.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by LiTaohong on 2017/11/28.
 */
@RestController
@RequestMapping(BaseUserRequestMapping.api_user_common)
@Api(description = "基础角色")
public class BaseRoleController extends EnvelopRestController {
    @Autowired
    private BaseRoleService baseRoleService;
    @Autowired
    private BaseRoleMenuService baseRoleMenuService;
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建角色", notes = "创建单个角色")
    public Envelop createRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_create,baseRoleService.createBaseRole(baseRoleDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改角色", notes = "修改角色")
    public Envelop updateBaseRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_update,baseRoleService.updateBaseRole(baseRoleDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_getById, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询单个角色", notes = "根据角色id查询角色信息")
    public Envelop getOneRoleById(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findById(baseRoleDO.getId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_getOne, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询单个角色", notes = "根据平台和角色名称查询角色信息")
    public Envelop getOneRoleBySaasIdAndName(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findBySaasIdAndName(baseRoleDO.getName(),baseRoleDO.getSaasId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_getlistNoPage, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询多个角色", notes = "根据平台id查询所有角色信息,不分页")
    public Envelop getRoleListBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findAllBySaasId(baseRoleDO.getSaasId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据指定条件查询所有角色列表,分页")
    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getListPage)
    public Envelop getRoleListPage(@ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,remark") @RequestParam(value = "fields", required = false) String fields,
                                              @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                                              @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime") @RequestParam(value = "sorts", required = false) String sorts,
                                              @ApiParam(name = "size", value = "分页大小", defaultValue = "15") @RequestParam(value = "size", required = false) int size,
                                              @ApiParam(name = "page", value = "页码", defaultValue = "1") @RequestParam(value = "page", required = false) int page,
                                              HttpServletRequest request, HttpServletResponse response) throws ParseException {
        if (StringUtils.isBlank(filters)) {
            return Envelop.getError(BaseUserRequestMapping.BaseRole.message_fail_params_not_present, ExceptionCode.common_error_params_code);
        } else {
            filters = "status<>-1;" + filters;
        }
        if (StringUtils.isBlank(sorts)) {
            sorts = "-updateTime";
        }
        //得到list数据
        List<BaseRoleVO> list = baseRoleService.search(fields, filters, sorts, page, size);
        //获取总数
        long count = baseRoleService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<BaseRoleVO> mFunctions = convertToModels(list, new ArrayList<>(list.size()), BaseRoleVO.class, fields);
        return Envelop.getSuccessListWithPage(BaseUserRequestMapping.BaseRole.message_success_find, mFunctions, page, size, count);
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "删除角色", notes = "根据角色id删除角色")
    public Envelop deleteRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            baseRoleService.deleteBaseRole(baseRoleDO);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_delete);
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_deleteBySaasId, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "批量删除角色", notes = "删除某一平台下所有角色信息")
    public Envelop deleteRolesBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            baseRoleService.deleteBaseRolesBySaasId(baseRoleDO.getSaasId());
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_delete);
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "給角色添加菜单", notes = "給角色添加菜单")
    @PostMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Envelop addMenuForRole(@ApiParam(name = "roleId", value = "", defaultValue = "") @RequestBody String roleId,
                                  @ApiParam(name = "menuIds", value = "", defaultValue = "") @RequestBody String menuIds){
        try{
            String[] menuIdArray = menuIds.split(",");
            List<BaseRoleMenuDO> list = new ArrayList<>();
            for(String menuId:menuIdArray){
                BaseRoleMenuDO baseRoleMenuDO = new BaseRoleMenuDO();
                baseRoleMenuDO.setRoleId(roleId);
                baseRoleMenuDO.setRoleId(menuId);
            }
            if(menuIdArray.length < 1){
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,this.baseRoleMenuService.createBaseRoleMenuDO(list.get(0)));
            }else{
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,this.baseRoleMenuService.createBatchBaseRoleMenuDO(list));
            }
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "修改角色菜单")
    @GetMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_update)
    public Envelop updateMenuForRole(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String id,
                                    @ApiParam(name = "newMenuId", value = "newMenuId", required = true) @RequestParam(value = "roleId", required = true) String newMenuId) {
        try {
            BaseRoleMenuDO baseEmployRoleDO = new BaseRoleMenuDO();
            baseEmployRoleDO.setId(id);
            baseEmployRoleDO.setMenuId(newMenuId);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.baseRoleMenuService.updateBaseEmployRoleDO(baseEmployRoleDO));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "查看角色菜单列表,不分页")
    @GetMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_getListNoPage)
    public Envelop findMenuListForRole(@ApiParam(name = "roleId", value = "roleId", required = true) @RequestParam(value = "roleId", required = true) String roleId) {
        try {
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.baseRoleMenuService.findAllByRoleId(roleId));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "删除角色菜单", notes = "删除角色菜单")
    @PostMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Envelop deleteMenuForRole(@ApiParam(name = "roleId", value = "", defaultValue = "") @RequestBody String roleId,
                                  @ApiParam(name = "menuIds", value = "", defaultValue = "") @RequestBody String menuIds){
        try{
            String[] menuIdArray = menuIds.split(",");
            if(menuIdArray.length < 1){
                this.baseRoleMenuService.deleteBaseRoleMenuDO(roleId,menuIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete,"删除角色单个菜单信息");
            }else{
                this.baseRoleMenuService.deleteBatchBaseRoleMenuDO(roleId,menuIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete,"删除角色多个菜单信息");
            }
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}
//package com.yihu.jw.business.user.contorller;
//
//import com.yihu.jw.base.user.BaseEmployRoleDO;
//import com.yihu.jw.base.user.BaseMenuDO;
//import com.yihu.jw.base.user.BaseRoleDO;
//import com.yihu.jw.base.user.BaseRoleMenuDO;
//import com.yihu.jw.business.user.service.BaseRoleMenuService;
//import com.yihu.jw.business.user.service.BaseRoleService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.restmodel.base.user.BaseEmployVO;
//import com.yihu.jw.restmodel.base.user.BaseRoleVO;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//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.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.text.ParseException;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by LiTaohong on 2017/11/28.
// */
//@RestController
//@RequestMapping(BaseUserRequestMapping.api_user_common)
//@Api(description = "基础角色")
//public class BaseRoleController extends EnvelopRestController {
//
//    @Autowired
//    private BaseRoleService baseRoleService;
//
//    @Autowired
//    private BaseRoleMenuService baseRoleMenuService;
//
//    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建角色", notes = "创建单个角色")
//    public Envelop createRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_create,baseRoleService.createBaseRole(baseRoleDO));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改角色", notes = "修改角色")
//    public Envelop updateBaseRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_update,baseRoleService.updateBaseRole(baseRoleDO));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_getById, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "查询单个角色", notes = "根据角色id查询角色信息")
//    public Envelop getOneRoleById(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findById(baseRoleDO.getId()));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_getOne, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "查询单个角色", notes = "根据平台和角色名称查询角色信息")
//    public Envelop getOneRoleBySaasIdAndName(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findBySaasIdAndName(baseRoleDO.getName(),baseRoleDO.getSaasId()));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_getlistNoPage, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "查询多个角色", notes = "根据平台id查询所有角色信息,不分页")
//    public Envelop getRoleListBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
//            return Envelop.getSuccessList(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findAllBySaasId(baseRoleDO.getSaasId()));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "根据指定条件查询所有角色列表,分页")
//    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getListPage)
//    public Envelop getRoleListPage(@ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,remark") @RequestParam(value = "fields", required = false) String fields,
//                                              @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
//                                              @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime") @RequestParam(value = "sorts", required = false) String sorts,
//                                              @ApiParam(name = "size", value = "分页大小", defaultValue = "15") @RequestParam(value = "size", required = false) int size,
//                                              @ApiParam(name = "page", value = "页码", defaultValue = "1") @RequestParam(value = "page", required = false) int page,
//                                              HttpServletRequest request, HttpServletResponse response) throws ParseException {
//        if (StringUtils.isBlank(filters)) {
//            return Envelop.getError(BaseUserRequestMapping.BaseRole.message_fail_params_not_present, ExceptionCode.common_error_params_code);
//        } else {
//            filters = "status<>-1;" + filters;
//        }
//        if (StringUtils.isBlank(sorts)) {
//            sorts = "-updateTime";
//        }
//
//        //得到list数据
//        List<BaseRoleVO> list = baseRoleService.search(fields, filters, sorts, page, size);
//
//        //获取总数
//        long count = baseRoleService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<BaseRoleVO> mFunctions = convertToModels(list, new ArrayList<>(list.size()), BaseRoleVO.class, fields);
//
//        return Envelop.getSuccessListWithPage(BaseUserRequestMapping.BaseRole.message_success_find, mFunctions, page, size, count);
//    }
//
//
//    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "删除角色", notes = "根据角色id删除角色")
//    public Envelop deleteRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
//            baseRoleService.deleteBaseRole(baseRoleDO);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_delete);
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_deleteBySaasId, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "批量删除角色", notes = "删除某一平台下所有角色信息")
//    public Envelop deleteRolesBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
//            baseRoleService.deleteBaseRolesBySaasId(baseRoleDO.getSaasId());
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_delete);
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "給角色添加菜单", notes = "給角色添加菜单")
//    @PostMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    public Envelop addMenuForRole(@ApiParam(name = "roleId", value = "", defaultValue = "") @RequestBody String roleId,
//                                  @ApiParam(name = "menuIds", value = "", defaultValue = "") @RequestBody String menuIds){
//        try{
//            String[] menuIdArray = menuIds.split(",");
//            List<BaseRoleMenuDO> list = new ArrayList<>();
//            for(String menuId:menuIdArray){
//                BaseRoleMenuDO baseRoleMenuDO = new BaseRoleMenuDO();
//                baseRoleMenuDO.setRoleId(roleId);
//                baseRoleMenuDO.setRoleId(menuId);
//            }
//            if(menuIdArray.length < 1){
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,this.baseRoleMenuService.createBaseRoleMenuDO(list.get(0)));
//            }else{
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,this.baseRoleMenuService.createBatchBaseRoleMenuDO(list));
//            }
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @ApiOperation(value = "修改角色菜单")
//    @GetMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_update)
//    public Envelop updateMenuForRole(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String id,
//                                    @ApiParam(name = "newMenuId", value = "newMenuId", required = true) @RequestParam(value = "roleId", required = true) String newMenuId) {
//        try {
//            BaseRoleMenuDO baseEmployRoleDO = new BaseRoleMenuDO();
//            baseEmployRoleDO.setId(id);
//            baseEmployRoleDO.setMenuId(newMenuId);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.baseRoleMenuService.updateBaseEmployRoleDO(baseEmployRoleDO));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "查看角色菜单列表,不分页")
//    @GetMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_getListNoPage)
//    public Envelop findMenuListForRole(@ApiParam(name = "roleId", value = "roleId", required = true) @RequestParam(value = "roleId", required = true) String roleId) {
//        try {
//            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.baseRoleMenuService.findAllByRoleId(roleId));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @ApiOperation(value = "删除角色菜单", notes = "删除角色菜单")
//    @PostMapping(value = BaseUserRequestMapping.BaseRoleMenu.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    public Envelop deleteMenuForRole(@ApiParam(name = "roleId", value = "", defaultValue = "") @RequestBody String roleId,
//                                  @ApiParam(name = "menuIds", value = "", defaultValue = "") @RequestBody String menuIds){
//        try{
//            String[] menuIdArray = menuIds.split(",");
//            if(menuIdArray.length < 1){
//                this.baseRoleMenuService.deleteBaseRoleMenuDO(roleId,menuIds);
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete,"删除角色单个菜单信息");
//            }else{
//                this.baseRoleMenuService.deleteBatchBaseRoleMenuDO(roleId,menuIds);
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete,"删除角色多个菜单信息");
//            }
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//}

+ 203 - 203
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployController.java

@ -1,203 +1,203 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.base.base.FunctionDO;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.business.user.service.EmployRoleService;
import com.yihu.jw.business.user.service.EmployService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.restmodel.base.base.FunctionVO;
import com.yihu.jw.restmodel.base.user.BaseEmployVO;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
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.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/5/11.
 */
@RestController
@RequestMapping(BaseUserRequestMapping.api_user_common)
@Api(description = "医生,行政人员等非患者用户(基础用户)")
public class EmployController extends EnvelopRestController {
    @Autowired
    private EmployService employService;
    @Autowired
    private EmployRoleService employRoleService;
    @PostMapping(value = BaseUserRequestMapping.BaseEmploy.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建用户", notes = "创建单个用户")
    public Envelop createBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_create,employService.createBaseEmployDO(baseEmployDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseEmploy.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改用户", notes = "修改用户")
    public Envelop updateBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_update,employService.updateBaseEmployDO(baseEmployDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据id查找用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getById)
    public Envelop getEmployeeById(@ApiParam(name = "id", value = "id", required = true) @RequestParam(value = "id", required = true) String id) {
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findById(id));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据saasId查找所有用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getListBySaasId)
    public Envelop getAllEmployeeBySaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
        try{
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findAllBySaasId(saasId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据手机号和saasId查找用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getByPhone)
    public Envelop getEmployeeByPhoneAndSaasId(@ApiParam(name = "phone", value = "phone", required = true) @RequestParam(value = "phone", required = true) String phone,
                                               @ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
        try {
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employService.findByPhoneAndSaasId(phone,saasId));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据name模糊查询某saasId平台下的所有用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getListByName)
    public Envelop getListByNameAndSaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId,
                                          @ApiParam(name = "name", value = "name", required = true) @RequestParam(value = "name", required = true) String name) {
        try{
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findAllByNameAndSaasId(name,saasId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据指定条件查询用户列表,分页")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getListNoPage)
    public Envelop getListPageByNameAndSaasId(@ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,sex,photo,skill,email,phone,family_tel,introduction,jxzc,lczc,xlzc,xzzc") @RequestParam(value = "fields", required = false) String fields,
                                              @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                                              @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime") @RequestParam(value = "sorts", required = false) String sorts,
                                              @ApiParam(name = "size", value = "分页大小", defaultValue = "15") @RequestParam(value = "size", required = false) int size,
                                              @ApiParam(name = "page", value = "页码", defaultValue = "1") @RequestParam(value = "page", required = false) int page,
                                              HttpServletRequest request, HttpServletResponse response) throws ParseException {
        if (StringUtils.isBlank(filters)) {
            return Envelop.getError(BaseUserRequestMapping.BaseEmploy.message_fail_params_not_present, ExceptionCode.common_error_params_code);
        } else {
            filters = "status<>-1;" + filters;
        }
        if (StringUtils.isBlank(sorts)) {
            sorts = "-updateTime";
        }
        //得到list数据
        List<BaseEmployVO> list = employService.search(fields, filters, sorts, page, size);
        //获取总数
        long count = employService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<BaseEmployVO> mFunctions = convertToModels(list, new ArrayList<>(list.size()), BaseEmployVO.class, fields);
        return Envelop.getSuccessListWithPage(BaseUserRequestMapping.BaseEmploy.message_success_find, mFunctions, page, size, count);
    }
    @ApiOperation(value = "给某一用户新增角色")
    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_create)
    public Envelop createEmployRoles(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId,
                                     @ApiParam(name = "roleIds", value = "roleIds", required = true) @RequestParam(value = "roleIds", required = true) String roleIds) {
        try {
            String[] roleIdArray = roleIds.split(",");
            List<BaseEmployRoleDO> list = new ArrayList<>();
            for (String roleId : roleIdArray) {
                BaseEmployRoleDO baseEmployRoleDO = new BaseEmployRoleDO();
                baseEmployRoleDO.setEmployId(employId);
                baseEmployRoleDO.setRoleId(roleId);
                list.add(baseEmployRoleDO);
            }
            if (roleIdArray.length < 1) {
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employRoleService.createBaseEmployRoleDO(list.get(0)));
            }else{
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employRoleService.createBatchBaseEmployRoleDO(list));
            }
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "修改用户角色")
    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_update)
    public Envelop updateEmployRole(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String id,
                                    @ApiParam(name = "roleId", value = "roleId", required = true) @RequestParam(value = "roleId", required = true) String newRoleId) {
        try {
            BaseEmployRoleDO baseEmployRoleDO = new BaseEmployRoleDO();
            baseEmployRoleDO.setId(id);
            baseEmployRoleDO.setRoleId(newRoleId);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.employRoleService.updateBaseEmployRoleDO(baseEmployRoleDO));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "查看用户角色列表,不分页")
    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_getListNoPage)
    public Envelop findEmployRoleList(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId) {
        try {
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.employRoleService.findAllByEmployId(employId));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "删除用户角色")
    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_delete)
    public Envelop deleteEmployRoles(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId,
                                     @ApiParam(name = "roleIds", value = "roleIds", required = true) @RequestParam(value = "roleIds", required = true) String roleIds) {
        try {
            String[] idArray = roleIds.split(",");
            if (idArray.length < 1) {
                this.employRoleService.deleteBaseEmployRoleDO(employId,roleIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete,"删除单个角色");
            }else{
                this.employRoleService.deleteBatchBaseEmployRoleDO(employId,roleIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, "删除多个角色");
            }
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}
//package com.yihu.jw.business.user.contorller;
//
//import com.yihu.jw.base.base.FunctionDO;
//import com.yihu.jw.base.user.BaseEmployDO;
//import com.yihu.jw.base.user.BaseEmployRoleDO;
//import com.yihu.jw.business.user.service.EmployRoleService;
//import com.yihu.jw.business.user.service.EmployService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.restmodel.base.base.FunctionVO;
//import com.yihu.jw.restmodel.base.user.BaseEmployVO;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.rm.base.BaseRequestMapping;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//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.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.text.ParseException;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by chenweida on 2017/5/11.
// */
//@RestController
//@RequestMapping(BaseUserRequestMapping.api_user_common)
//@Api(description = "医生,行政人员等非患者用户(基础用户)")
//public class EmployController extends EnvelopRestController {
//    @Autowired
//    private EmployService employService;
//
//    @Autowired
//    private EmployRoleService employRoleService;
//
//    @PostMapping(value = BaseUserRequestMapping.BaseEmploy.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建用户", notes = "创建单个用户")
//    public Envelop createBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_create,employService.createBaseEmployDO(baseEmployDO));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PostMapping(value = BaseUserRequestMapping.BaseEmploy.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改用户", notes = "修改用户")
//    public Envelop updateBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
//        try{
//            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_update,employService.updateBaseEmployDO(baseEmployDO));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "根据id查找用户")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getById)
//    public Envelop getEmployeeById(@ApiParam(name = "id", value = "id", required = true) @RequestParam(value = "id", required = true) String id) {
//        try{
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findById(id));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "根据saasId查找所有用户")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getListBySaasId)
//    public Envelop getAllEmployeeBySaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
//        try{
//            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findAllBySaasId(saasId));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @ApiOperation(value = "根据手机号和saasId查找用户")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getByPhone)
//    public Envelop getEmployeeByPhoneAndSaasId(@ApiParam(name = "phone", value = "phone", required = true) @RequestParam(value = "phone", required = true) String phone,
//                                               @ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
//        try {
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employService.findByPhoneAndSaasId(phone,saasId));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "根据name模糊查询某saasId平台下的所有用户")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getListByName)
//    public Envelop getListByNameAndSaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId,
//                                          @ApiParam(name = "name", value = "name", required = true) @RequestParam(value = "name", required = true) String name) {
//        try{
//            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findAllByNameAndSaasId(name,saasId));
//        } catch (ApiException e){
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "根据指定条件查询用户列表,分页")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getListNoPage)
//    public Envelop getListPageByNameAndSaasId(@ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,sex,photo,skill,email,phone,family_tel,introduction,jxzc,lczc,xlzc,xzzc") @RequestParam(value = "fields", required = false) String fields,
//                                              @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
//                                              @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime") @RequestParam(value = "sorts", required = false) String sorts,
//                                              @ApiParam(name = "size", value = "分页大小", defaultValue = "15") @RequestParam(value = "size", required = false) int size,
//                                              @ApiParam(name = "page", value = "页码", defaultValue = "1") @RequestParam(value = "page", required = false) int page,
//                                              HttpServletRequest request, HttpServletResponse response) throws ParseException {
//        if (StringUtils.isBlank(filters)) {
//            return Envelop.getError(BaseUserRequestMapping.BaseEmploy.message_fail_params_not_present, ExceptionCode.common_error_params_code);
//        } else {
//            filters = "status<>-1;" + filters;
//        }
//        if (StringUtils.isBlank(sorts)) {
//            sorts = "-updateTime";
//        }
//
//        //得到list数据
//        List<BaseEmployVO> list = employService.search(fields, filters, sorts, page, size);
//
//        //获取总数
//        long count = employService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<BaseEmployVO> mFunctions = convertToModels(list, new ArrayList<>(list.size()), BaseEmployVO.class, fields);
//
//        return Envelop.getSuccessListWithPage(BaseUserRequestMapping.BaseEmploy.message_success_find, mFunctions, page, size, count);
//    }
//
//
//    @ApiOperation(value = "给某一用户新增角色")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_create)
//    public Envelop createEmployRoles(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId,
//                                     @ApiParam(name = "roleIds", value = "roleIds", required = true) @RequestParam(value = "roleIds", required = true) String roleIds) {
//        try {
//            String[] roleIdArray = roleIds.split(",");
//            List<BaseEmployRoleDO> list = new ArrayList<>();
//            for (String roleId : roleIdArray) {
//                BaseEmployRoleDO baseEmployRoleDO = new BaseEmployRoleDO();
//                baseEmployRoleDO.setEmployId(employId);
//                baseEmployRoleDO.setRoleId(roleId);
//                list.add(baseEmployRoleDO);
//            }
//            if (roleIdArray.length < 1) {
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employRoleService.createBaseEmployRoleDO(list.get(0)));
//            }else{
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employRoleService.createBatchBaseEmployRoleDO(list));
//            }
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "修改用户角色")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_update)
//    public Envelop updateEmployRole(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String id,
//                                    @ApiParam(name = "roleId", value = "roleId", required = true) @RequestParam(value = "roleId", required = true) String newRoleId) {
//        try {
//            BaseEmployRoleDO baseEmployRoleDO = new BaseEmployRoleDO();
//            baseEmployRoleDO.setId(id);
//            baseEmployRoleDO.setRoleId(newRoleId);
//            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.employRoleService.updateBaseEmployRoleDO(baseEmployRoleDO));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "查看用户角色列表,不分页")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_getListNoPage)
//    public Envelop findEmployRoleList(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId) {
//        try {
//            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.employRoleService.findAllByEmployId(employId));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @ApiOperation(value = "删除用户角色")
//    @GetMapping(value = BaseUserRequestMapping.BaseEmployRole.api_delete)
//    public Envelop deleteEmployRoles(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId,
//                                     @ApiParam(name = "roleIds", value = "roleIds", required = true) @RequestParam(value = "roleIds", required = true) String roleIds) {
//        try {
//            String[] idArray = roleIds.split(",");
//            if (idArray.length < 1) {
//                this.employRoleService.deleteBaseEmployRoleDO(employId,roleIds);
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete,"删除单个角色");
//            }else{
//                this.employRoleService.deleteBatchBaseEmployRoleDO(employId,roleIds);
//                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, "删除多个角色");
//            }
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//}

+ 28 - 28
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/PatientController.java

@ -1,28 +1,28 @@
package com.yihu.jw.business.user.contorller;
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.cloud.sleuth.Tracer;
import org.springframework.web.bind.annotation.*;
/**
 * Created by chenweida on 2017/5/10.
 */
@RestController
@RequestMapping("/patient")
@Api(description = "患者")
public class PatientController {
    @Autowired
    private Tracer tracer;
    @ApiOperation(value = "根据code查找患者")
    @GetMapping(value = "findByCode")
    public String findByCode(
            @ApiParam(name = "code", value = "患者code", required = true)@RequestParam(value = "code", required = true) String code) {
      tracer.getCurrentSpan().logEvent("进入微服务查询患者");
       return "调用根据code查找患者";
    }
}
//package com.yihu.jw.business.user.contorller;
//
//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.cloud.sleuth.Tracer;
//import org.springframework.web.bind.annotation.*;
//
///**
// * Created by chenweida on 2017/5/10.
// */
//@RestController
//@RequestMapping("/patient")
//@Api(description = "患者")
//public class PatientController {
//    @Autowired
//    private Tracer tracer;
//
//
//    @ApiOperation(value = "根据code查找患者")
//    @GetMapping(value = "findByCode")
//    public String findByCode(
//            @ApiParam(name = "code", value = "患者code", required = true)@RequestParam(value = "code", required = true) String code) {
//      tracer.getCurrentSpan().logEvent("进入微服务查询患者");
//       return "调用根据code查找患者";
//    }
//}

+ 32 - 32
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseMenuDao.java

@ -1,32 +1,32 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseMenuDO;
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 LiTaohong on 2017/12/05.
 */
public interface BaseMenuDao extends PagingAndSortingRepository<BaseMenuDO, String>, JpaSpecificationExecutor<BaseMenuDO> {
    //角色与saasId为一对多关系
    @Query("from BaseMenuDO b where b.saasId = ?1")
    List<BaseMenuDO> findAllBySaasId(String saasId);
    @Query("from BaseMenuDO b where b.saasId = ?1 and b.name = ?2")
    BaseMenuDO findOneBySaasIdAndName(String saasId, String name);
    @Query("from BaseMenuDO b where b.name like %?1%")
    List<BaseMenuDO> findAllByName(String name);
    @Query("from BaseMenuDO b where b.saasId = ?1 and b.parentId = ?2")
    List<BaseMenuDO> getChildrenMenuList(String saasId,String parentId);
}
//package com.yihu.jw.business.user.dao;
//
//import com.yihu.jw.base.user.BaseMenuDO;
//import com.yihu.jw.base.user.BaseMenuDO;
//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 LiTaohong on 2017/12/05.
// */
//public interface BaseMenuDao extends PagingAndSortingRepository<BaseMenuDO, String>, JpaSpecificationExecutor<BaseMenuDO> {
//
//    //角色与saasId为一对多关系
//    @Query("from BaseMenuDO b where b.saasId = ?1")
//    List<BaseMenuDO> findAllBySaasId(String saasId);
//
//    @Query("from BaseMenuDO b where b.saasId = ?1 and b.name = ?2")
//    BaseMenuDO findOneBySaasIdAndName(String saasId, String name);
//
//    @Query("from BaseMenuDO b where b.name like %?1%")
//    List<BaseMenuDO> findAllByName(String name);
//
//    @Query("from BaseMenuDO b where b.saasId = ?1 and b.parentId = ?2")
//    List<BaseMenuDO> getChildrenMenuList(String saasId,String parentId);
//
//
//
//
//}

+ 28 - 28
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleDao.java

@ -1,28 +1,28 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseRoleDO;
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 LiTaohong on 2017/11/28.
 */
public interface BaseRoleDao extends PagingAndSortingRepository<BaseRoleDO, String>, JpaSpecificationExecutor<BaseRoleDO> {
    @Query("from BaseRoleDO b where b.id = ?1")
    BaseRoleDO findOneById(String id);
    //角色与saasId为一对多关系
    @Query("from BaseRoleDO b where b.saasId = ?1")
    List<BaseRoleDO> findAllBySaasId(String saasId);
    @Query("from BaseRoleDO b where b.saasId = ?1 and b.name = ?2")
    BaseRoleDO findOneBySaasIdAndName(String saasId,String name);
    @Query("from BaseRoleDO b where b.name like %?1%")
    List<BaseRoleDO> findAllByName(String name);
}
//package com.yihu.jw.business.user.dao;
//
//import com.yihu.jw.base.user.BaseRoleDO;
//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 LiTaohong on 2017/11/28.
// */
//public interface BaseRoleDao extends PagingAndSortingRepository<BaseRoleDO, String>, JpaSpecificationExecutor<BaseRoleDO> {
//
//
//    @Query("from BaseRoleDO b where b.id = ?1")
//    BaseRoleDO findOneById(String id);
//
//    //角色与saasId为一对多关系
//    @Query("from BaseRoleDO b where b.saasId = ?1")
//    List<BaseRoleDO> findAllBySaasId(String saasId);
//
//    @Query("from BaseRoleDO b where b.saasId = ?1 and b.name = ?2")
//    BaseRoleDO findOneBySaasIdAndName(String saasId,String name);
//
//    @Query("from BaseRoleDO b where b.name like %?1%")
//    List<BaseRoleDO> findAllByName(String name);
//}

+ 26 - 26
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleMenuDao.java

@ -1,26 +1,26 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.base.user.BaseRoleMenuDO;
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 LiTaohong on 2017/11/28.
 */
public interface BaseRoleMenuDao extends PagingAndSortingRepository<BaseRoleMenuDO, String>, JpaSpecificationExecutor<BaseRoleMenuDO> {
    @Query("from BaseRoleMenuDO ba where ba.roleId = ?1")
    List<BaseRoleMenuDO> findRoleMenuListByRoleId(String employId);
    @Query("delete from BaseRoleMenuDO ba where ba.roleId = ?1 and ba.menuId = ?2")
    int deleteOneByRoleIdAndMenuId(String roleId,String menuId);
    @Query("delete from BaseRoleMenuDO ba where ba.roleId = ?1 and ba.menuId in (?2)")
    int deleteManyByRoleIdAndMenuIds(String roleId,String menuIds);
}
//package com.yihu.jw.business.user.dao;
//
//import com.yihu.jw.base.user.BaseEmployRoleDO;
//import com.yihu.jw.base.user.BaseRoleDO;
//import com.yihu.jw.base.user.BaseRoleMenuDO;
//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 LiTaohong on 2017/11/28.
// */
//public interface BaseRoleMenuDao extends PagingAndSortingRepository<BaseRoleMenuDO, String>, JpaSpecificationExecutor<BaseRoleMenuDO> {
//
//
//    @Query("from BaseRoleMenuDO ba where ba.roleId = ?1")
//    List<BaseRoleMenuDO> findRoleMenuListByRoleId(String employId);
//
//    @Query("delete from BaseRoleMenuDO ba where ba.roleId = ?1 and ba.menuId = ?2")
//    int deleteOneByRoleIdAndMenuId(String roleId,String menuId);
//
//    @Query("delete from BaseRoleMenuDO ba where ba.roleId = ?1 and ba.menuId in (?2)")
//    int deleteManyByRoleIdAndMenuIds(String roleId,String menuIds);
//}

+ 24 - 24
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployRoleDao.java

@ -1,24 +1,24 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseRoleDO;
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 LiTaohong on 2017/11/28.
 */
public interface EmployRoleDao extends PagingAndSortingRepository<BaseEmployRoleDO, String>, JpaSpecificationExecutor<BaseEmployRoleDO> {
    @Query("from BaseEmployRoleDO ba where ba.employId = ?1")
    List<BaseEmployRoleDO> findRoleListByEmployId(String employId);
    @Query("delete from BaseEmployRoleDO ba where ba.employId = ?1 and ba.roleId = ?2")
    int deleteOneByEmployIdAndRoleId(String employId,String roleId);
    @Query("delete from BaseEmployRoleDO ba where ba.employId = ?1 and ba.roleId in (?2)")
    int deleteManyByEmployIdAndRoleIds(String employId,String roleIds);
}
//package com.yihu.jw.business.user.dao;
//
//import com.yihu.jw.base.user.BaseEmployRoleDO;
//import com.yihu.jw.base.user.BaseRoleDO;
//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 LiTaohong on 2017/11/28.
// */
//public interface EmployRoleDao extends PagingAndSortingRepository<BaseEmployRoleDO, String>, JpaSpecificationExecutor<BaseEmployRoleDO> {
//
//    @Query("from BaseEmployRoleDO ba where ba.employId = ?1")
//    List<BaseEmployRoleDO> findRoleListByEmployId(String employId);
//
//    @Query("delete from BaseEmployRoleDO ba where ba.employId = ?1 and ba.roleId = ?2")
//    int deleteOneByEmployIdAndRoleId(String employId,String roleId);
//
//    @Query("delete from BaseEmployRoleDO ba where ba.employId = ?1 and ba.roleId in (?2)")
//    int deleteManyByEmployIdAndRoleIds(String employId,String roleIds);
//}

+ 137 - 137
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseMenuService.java

@ -1,137 +1,137 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.business.user.dao.BaseMenuDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by LiTaohong on 2017/12/5.
 * 基础菜单功能
 */
@Service
public class BaseMenuService extends BaseJpaService<BaseMenuDO,BaseMenuDao>{
    @Autowired
    private BaseMenuDao baseMenuDao;
    /**
     * 创建菜单
     * @param baseMenuDO
     * @return
     */
    @Transactional
    public BaseMenuDO createBaseMenu(BaseMenuDO baseMenuDO){
        if (StringUtils.isEmpty(baseMenuDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseMenuDao.save(baseMenuDO);
    }
    /**
     * 更新菜单
     * @param baseMenuDO
     * @return
     */
    @Transactional
    public BaseMenuDO updateBaseMenuDO(BaseMenuDO baseMenuDO){
        if (StringUtils.isEmpty(baseMenuDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseMenuDao.save(baseMenuDO);
    }
    /**
     * 根据Id查询菜单
     * @param id
     * @return
     */
    public BaseMenuDO findById(String id){
        if (StringUtils.isEmpty(id)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
        BaseMenuDO baseRoleDO = this.baseMenuDao.findOne(id);
        if (null == baseRoleDO) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_no_exist,ExceptionCode.common_error_params_code);
        }
        return baseRoleDO;
    }
    /**
     * 查询某要saasId平台下的所有菜单
     * @param saasId
     * @return
     */
    public List<BaseMenuDO> findAllBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null,ExceptionCode.common_error_params_code);
        }
        List<BaseMenuDO> list = this.baseMenuDao.findAllBySaasId(saasId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 根据Id删除菜单
     * @param baseMenuDO
     */
    @Transactional
    public void deleteBaseMenu(BaseMenuDO baseMenuDO){
        if (StringUtils.isEmpty(baseMenuDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        baseMenuDO.setStatus(-1);
        this.baseMenuDao.save(baseMenuDO);
    }
    /**
     * 删除某一saasId相关的所有菜单
     * @param saasId
     */
    @Transactional
    public void deleteBaseMenusBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        List<BaseMenuDO> list = this.baseMenuDao.findAllBySaasId(saasId);
        for(BaseMenuDO baseMenuDO:list){
            baseMenuDO.setStatus(-1);
        }
        this.baseMenuDao.save(list);
    }
    /**
     * 获取某一平台下某一父级菜单的所有子菜单
     * @param saasId
     * @param parentId
     * @return
     */
    public List<BaseMenuDO> getChlidrenMenuList(String saasId,String parentId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_param_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(parentId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_param_parentId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseMenuDao.getChildrenMenuList(saasId,parentId);
    }
}
//package com.yihu.jw.business.user.service;
//
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.base.user.BaseMenuDO;
//import com.yihu.jw.base.user.BaseMenuDO;
//import com.yihu.jw.business.user.dao.BaseMenuDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//
//import java.util.List;
//
///**
// * Created by LiTaohong on 2017/12/5.
// * 基础菜单功能
// */
//@Service
//public class BaseMenuService extends BaseJpaService<BaseMenuDO,BaseMenuDao>{
//    @Autowired
//    private BaseMenuDao baseMenuDao;
//
//    /**
//     * 创建菜单
//     * @param baseMenuDO
//     * @return
//     */
//    @Transactional
//    public BaseMenuDO createBaseMenu(BaseMenuDO baseMenuDO){
//        if (StringUtils.isEmpty(baseMenuDO.getId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.baseMenuDao.save(baseMenuDO);
//    }
//
//    /**
//     * 更新菜单
//     * @param baseMenuDO
//     * @return
//     */
//    @Transactional
//    public BaseMenuDO updateBaseMenuDO(BaseMenuDO baseMenuDO){
//        if (StringUtils.isEmpty(baseMenuDO.getId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.baseMenuDao.save(baseMenuDO);
//    }
//
//    /**
//     * 根据Id查询菜单
//     * @param id
//     * @return
//     */
//    public BaseMenuDO findById(String id){
//        if (StringUtils.isEmpty(id)) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//        BaseMenuDO baseRoleDO = this.baseMenuDao.findOne(id);
//        if (null == baseRoleDO) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_no_exist,ExceptionCode.common_error_params_code);
//        }
//        return baseRoleDO;
//    }
//
//    /**
//     * 查询某要saasId平台下的所有菜单
//     * @param saasId
//     * @return
//     */
//    public List<BaseMenuDO> findAllBySaasId(String saasId){
//        if (StringUtils.isEmpty(saasId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null,ExceptionCode.common_error_params_code);
//        }
//        List<BaseMenuDO> list = this.baseMenuDao.findAllBySaasId(saasId);
//        if (null == list || list.size() == 0) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_no_exist,ExceptionCode.common_error_params_code);
//        }
//        return list;
//    }
//
//    /**
//     * 根据Id删除菜单
//     * @param baseMenuDO
//     */
//    @Transactional
//    public void deleteBaseMenu(BaseMenuDO baseMenuDO){
//        if (StringUtils.isEmpty(baseMenuDO.getId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
//        }
//        baseMenuDO.setStatus(-1);
//        this.baseMenuDao.save(baseMenuDO);
//    }
//
//    /**
//     * 删除某一saasId相关的所有菜单
//     * @param saasId
//     */
//    @Transactional
//    public void deleteBaseMenusBySaasId(String saasId){
//        if (StringUtils.isEmpty(saasId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
//        }
//        List<BaseMenuDO> list = this.baseMenuDao.findAllBySaasId(saasId);
//        for(BaseMenuDO baseMenuDO:list){
//            baseMenuDO.setStatus(-1);
//        }
//        this.baseMenuDao.save(list);
//    }
//
//    /**
//     * 获取某一平台下某一父级菜单的所有子菜单
//     * @param saasId
//     * @param parentId
//     * @return
//     */
//    public List<BaseMenuDO> getChlidrenMenuList(String saasId,String parentId){
//        if (StringUtils.isEmpty(saasId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_param_saasid_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(parentId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_param_parentId_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.baseMenuDao.getChildrenMenuList(saasId,parentId);
//    }
//}

+ 154 - 154
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleMenuService.java

@ -1,154 +1,154 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseRoleMenuDO;
import com.yihu.jw.business.user.dao.BaseMenuDao;
import com.yihu.jw.business.user.dao.BaseRoleMenuDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by LiTaohong on 2017/12/05.
 * 基础角色菜单功能
 */
@Service
public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleMenuDao> {
    @Autowired
    private BaseRoleMenuDao baseRoleMenuDao;
    @Autowired
    private BaseMenuDao baseMenuDao;
    /**
     * 新增角色菜单
     * @param baseRoleMenuDO
     * @return
     */
    @Transactional
    public BaseRoleMenuDO createBaseRoleMenuDO(BaseRoleMenuDO baseRoleMenuDO){
        if (StringUtils.isEmpty(baseRoleMenuDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseRoleMenuDao.save(baseRoleMenuDO);
    }
    /**
     * 批量新增角色菜单,一个角色拥有多个菜单的权限
     * @param list
     * @return
     */
    @Transactional
    public Iterable<BaseRoleMenuDO> createBatchBaseRoleMenuDO(List<BaseRoleMenuDO> list){
        return this.baseRoleMenuDao.save(list);
    }
    /**
     * 修改角色菜单信息
     * @param baseRoleMenuDO
     * @return
     */
    @Transactional
    public BaseRoleMenuDO updateBaseEmployRoleDO(BaseRoleMenuDO baseRoleMenuDO){
        BaseRoleMenuDO OldbaseRoleMenuDO = this.baseRoleMenuDao.findOne(baseRoleMenuDO.getId());
        if(null == OldbaseRoleMenuDO){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_baseRoleMenu_no_exist, ExceptionCode.common_error_params_code);
        }
        //菜单id一样,表示菜单没有变,则不修改
        if (baseRoleMenuDO.getMenuId().equals(OldbaseRoleMenuDO.getMenuId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_same_menuId, ExceptionCode.common_error_params_code);
        }
        baseRoleMenuDO.setRoleId(OldbaseRoleMenuDO.getRoleId());
        return this.baseRoleMenuDao.save(baseRoleMenuDO);
    }
    /**
     * 查询某一角色的菜单列表(角色与菜单为一对多关系)
     * @param roleId
     * @return
     */
    public List<BaseMenuDO> findAllByRoleId(String roleId){
        if (StringUtils.isEmpty(roleId)) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
        List<BaseRoleMenuDO> list = this.baseRoleMenuDao.findRoleMenuListByRoleId(roleId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_baseRoleMenu_no_exist,ExceptionCode.common_error_params_code);
        }
        List<String> ids = new ArrayList<>();
        for(BaseRoleMenuDO baseRoleMenuDO:list){
            ids.add(baseRoleMenuDO.getMenuId());
        }
        Iterable<String> iterable = (Iterable<String>)ids.iterator();
        List<BaseMenuDO> result = (List<BaseMenuDO>)baseMenuDao.findAll(iterable);
        return result;
    }
    /**
     * 根据id删除角色菜单
     * @param id
     * @return
     */
    @Transactional
    public void deleteBaseRoleMenuDO(String id){
        try{
            this.baseRoleMenuDao.delete(id);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
    /**
     * 根据roleId和menuId删除角色菜单
     * @param roleId
     * @param menuId
     * @return
     */
    @Transactional
    public void deleteBaseRoleMenuDO(String roleId,String menuId){
        try{
            this.baseRoleMenuDao.deleteOneByRoleIdAndMenuId(roleId,menuId);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
    /**
     * 根据roleId和menuId删除角色菜单
     * @param roleId
     * @param menuIds
     * @return
     */
    @Transactional
    public void deleteBatchBaseRoleMenuDO(String roleId,String menuIds){
        try{
            this.baseRoleMenuDao.deleteManyByRoleIdAndMenuIds(roleId,menuIds);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
}
//package com.yihu.jw.business.user.service;
//
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.base.user.BaseMenuDO;
//import com.yihu.jw.base.user.BaseRoleMenuDO;
//import com.yihu.jw.business.user.dao.BaseMenuDao;
//import com.yihu.jw.business.user.dao.BaseRoleMenuDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by LiTaohong on 2017/12/05.
// * 基础角色菜单功能
// */
//@Service
//public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleMenuDao> {
//
//    @Autowired
//    private BaseRoleMenuDao baseRoleMenuDao;
//
//    @Autowired
//    private BaseMenuDao baseMenuDao;
//
//    /**
//     * 新增角色菜单
//     * @param baseRoleMenuDO
//     * @return
//     */
//    @Transactional
//    public BaseRoleMenuDO createBaseRoleMenuDO(BaseRoleMenuDO baseRoleMenuDO){
//        if (StringUtils.isEmpty(baseRoleMenuDO.getRoleId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.baseRoleMenuDao.save(baseRoleMenuDO);
//    }
//
//    /**
//     * 批量新增角色菜单,一个角色拥有多个菜单的权限
//     * @param list
//     * @return
//     */
//    @Transactional
//    public Iterable<BaseRoleMenuDO> createBatchBaseRoleMenuDO(List<BaseRoleMenuDO> list){
//        return this.baseRoleMenuDao.save(list);
//    }
//
//    /**
//     * 修改角色菜单信息
//     * @param baseRoleMenuDO
//     * @return
//     */
//    @Transactional
//    public BaseRoleMenuDO updateBaseEmployRoleDO(BaseRoleMenuDO baseRoleMenuDO){
//        BaseRoleMenuDO OldbaseRoleMenuDO = this.baseRoleMenuDao.findOne(baseRoleMenuDO.getId());
//        if(null == OldbaseRoleMenuDO){
//            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_baseRoleMenu_no_exist, ExceptionCode.common_error_params_code);
//        }
//        //菜单id一样,表示菜单没有变,则不修改
//        if (baseRoleMenuDO.getMenuId().equals(OldbaseRoleMenuDO.getMenuId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_same_menuId, ExceptionCode.common_error_params_code);
//        }
//        baseRoleMenuDO.setRoleId(OldbaseRoleMenuDO.getRoleId());
//        return this.baseRoleMenuDao.save(baseRoleMenuDO);
//    }
//
//
//    /**
//     * 查询某一角色的菜单列表(角色与菜单为一对多关系)
//     * @param roleId
//     * @return
//     */
//    public List<BaseMenuDO> findAllByRoleId(String roleId){
//        if (StringUtils.isEmpty(roleId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
//        }
//        List<BaseRoleMenuDO> list = this.baseRoleMenuDao.findRoleMenuListByRoleId(roleId);
//        if (null == list || list.size() == 0) {
//            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_baseRoleMenu_no_exist,ExceptionCode.common_error_params_code);
//        }
//        List<String> ids = new ArrayList<>();
//        for(BaseRoleMenuDO baseRoleMenuDO:list){
//            ids.add(baseRoleMenuDO.getMenuId());
//        }
//        Iterable<String> iterable = (Iterable<String>)ids.iterator();
//        List<BaseMenuDO> result = (List<BaseMenuDO>)baseMenuDao.findAll(iterable);
//        return result;
//    }
//
//
//    /**
//     * 根据id删除角色菜单
//     * @param id
//     * @return
//     */
//    @Transactional
//    public void deleteBaseRoleMenuDO(String id){
//        try{
//            this.baseRoleMenuDao.delete(id);
//        }
//        catch (ApiException e){
//            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//
//    }
//
//    /**
//     * 根据roleId和menuId删除角色菜单
//     * @param roleId
//     * @param menuId
//     * @return
//     */
//    @Transactional
//    public void deleteBaseRoleMenuDO(String roleId,String menuId){
//        try{
//            this.baseRoleMenuDao.deleteOneByRoleIdAndMenuId(roleId,menuId);
//        }
//        catch (ApiException e){
//            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//    }
//
//    /**
//     * 根据roleId和menuId删除角色菜单
//     * @param roleId
//     * @param menuIds
//     * @return
//     */
//    @Transactional
//    public void deleteBatchBaseRoleMenuDO(String roleId,String menuIds){
//        try{
//            this.baseRoleMenuDao.deleteManyByRoleIdAndMenuIds(roleId,menuIds);
//        }
//        catch (ApiException e){
//            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//    }
//
//
//
//
//
//
//
//
//
//}

+ 174 - 174
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleService.java

@ -1,174 +1,174 @@
package com.yihu.jw.business.user.service;
import com.netflix.discovery.converters.Auto;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.dao.BaseRoleDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by LiTaohong on 2017/11/28.
 * 基础角色功能
 */
@Service
public class BaseRoleService extends BaseJpaService<BaseRoleDO,BaseRoleDao>{
    @Autowired
    private BaseRoleDao baseRoleDao;
    /**
     * 创建role
     * @param baseRoleDO
     * @return
     */
    @Transactional
    public BaseRoleDO createBaseRole(BaseRoleDO baseRoleDO){
        if (StringUtils.isEmpty(baseRoleDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseRoleDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseRoleDO.getName())) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_name_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseRoleDao.save(baseRoleDO);
    }
    /**
     * 更新role
     * @param baseRoleDO
     * @return
     */
    @Transactional
    public BaseRoleDO updateBaseRole(BaseRoleDO baseRoleDO){
        if (StringUtils.isEmpty(baseRoleDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseRoleDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseRoleDao.save(baseRoleDO);
    }
    /**
     * 根据roleId查询role
     * @param id
     * @return
     */
    public BaseRoleDO findById(String id){
        if (StringUtils.isEmpty(id)) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
        BaseRoleDO baseRoleDO = this.baseRoleDao.findOneById(id);
        if (null == baseRoleDO) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_no_exist,ExceptionCode.common_error_params_code);
        }
        return baseRoleDO;
    }
    /**
     * 查询某要saasId平台下的所有role
     * @param saasId
     * @return
     */
    public List<BaseRoleDO> findAllBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
        }
        List<BaseRoleDO> list = this.baseRoleDao.findAllBySaasId(saasId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 查找某一平台下某一个role
     * @param saasId
     * @param name
     * @return
     */
    public BaseRoleDO findBySaasIdAndName(String saasId,String name){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(name)) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_name_is_null,ExceptionCode.common_error_params_code);
        }
        BaseRoleDO baseRoleDO = this.baseRoleDao.findOneBySaasIdAndName(name,saasId);
        if (null == baseRoleDO) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_role_no_exist,ExceptionCode.common_error_params_code);
        }
        return baseRoleDO;
    }
    /**
     * 根据name查询所有的role,包括不同平台saasid的
     * @param name
     * @return
     */
    public List<BaseRoleDO> getRoleListByName(String name){
        if (StringUtils.isEmpty(name)) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_param_name_is_null,ExceptionCode.common_error_params_code);
        }
        List<BaseRoleDO> list = this.baseRoleDao.findAllByName(name);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_role_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 根据roleId删除role
     * @param baseRoleDO
     */
    @Transactional
    public void deleteBaseRole(BaseRoleDO baseRoleDO){
        if (StringUtils.isEmpty(baseRoleDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseRoleDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        baseRoleDO.setStatus(-1);
        this.baseRoleDao.save(baseRoleDO);
    }
    /**
     * 删除某一saasId相关的所有role
     * @param saasId
     */
    @Transactional
    public void deleteBaseRolesBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        List<BaseRoleDO> list = this.baseRoleDao.findAllBySaasId(saasId);
        for(BaseRoleDO baseRoleDO:list){
            baseRoleDO.setStatus(-1);
        }
        this.baseRoleDao.save(list);
    }
    /**
     * 根据saasId和name删除角色
     * @param saasId
     * @param name
     */
    @Transactional
    public void deleteBaseRoleByNameAndSaasId(String saasId,String name){
        BaseRoleDO baseRoleDO = this.findBySaasIdAndName(saasId,name);
        baseRoleDO.setStatus(-1);
        this.baseRoleDao.save(baseRoleDO);
    }
}
//package com.yihu.jw.business.user.service;
//
//import com.netflix.discovery.converters.Auto;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.base.user.BaseRoleDO;
//import com.yihu.jw.business.user.dao.BaseRoleDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//import net.bytebuddy.implementation.bytecode.Throw;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//
//import java.util.List;
//
///**
// * Created by LiTaohong on 2017/11/28.
// * 基础角色功能
// */
//@Service
//public class BaseRoleService extends BaseJpaService<BaseRoleDO,BaseRoleDao>{
//    @Autowired
//    private BaseRoleDao baseRoleDao;
//
//    /**
//     * 创建role
//     * @param baseRoleDO
//     * @return
//     */
//    @Transactional
//    public BaseRoleDO createBaseRole(BaseRoleDO baseRoleDO){
//        if (StringUtils.isEmpty(baseRoleDO.getId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseRoleDO.getSaasId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseRoleDO.getName())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_name_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.baseRoleDao.save(baseRoleDO);
//    }
//
//    /**
//     * 更新role
//     * @param baseRoleDO
//     * @return
//     */
//    @Transactional
//    public BaseRoleDO updateBaseRole(BaseRoleDO baseRoleDO){
//        if (StringUtils.isEmpty(baseRoleDO.getId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseRoleDO.getSaasId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.baseRoleDao.save(baseRoleDO);
//    }
//
//    /**
//     * 根据roleId查询role
//     * @param id
//     * @return
//     */
//    public BaseRoleDO findById(String id){
//        if (StringUtils.isEmpty(id)) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//        BaseRoleDO baseRoleDO = this.baseRoleDao.findOneById(id);
//        if (null == baseRoleDO) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_no_exist,ExceptionCode.common_error_params_code);
//        }
//        return baseRoleDO;
//    }
//
//    /**
//     * 查询某要saasId平台下的所有role
//     * @param saasId
//     * @return
//     */
//    public List<BaseRoleDO> findAllBySaasId(String saasId){
//        if (StringUtils.isEmpty(saasId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
//        }
//        List<BaseRoleDO> list = this.baseRoleDao.findAllBySaasId(saasId);
//        if (null == list || list.size() == 0) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_no_exist,ExceptionCode.common_error_params_code);
//        }
//        return list;
//    }
//
//    /**
//     * 查找某一平台下某一个role
//     * @param saasId
//     * @param name
//     * @return
//     */
//    public BaseRoleDO findBySaasIdAndName(String saasId,String name){
//        if (StringUtils.isEmpty(saasId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(name)) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_name_is_null,ExceptionCode.common_error_params_code);
//        }
//        BaseRoleDO baseRoleDO = this.baseRoleDao.findOneBySaasIdAndName(name,saasId);
//        if (null == baseRoleDO) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_role_no_exist,ExceptionCode.common_error_params_code);
//        }
//        return baseRoleDO;
//    }
//
//    /**
//     * 根据name查询所有的role,包括不同平台saasid的
//     * @param name
//     * @return
//     */
//    public List<BaseRoleDO> getRoleListByName(String name){
//        if (StringUtils.isEmpty(name)) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_param_name_is_null,ExceptionCode.common_error_params_code);
//        }
//        List<BaseRoleDO> list = this.baseRoleDao.findAllByName(name);
//        if (null == list || list.size() == 0) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_role_no_exist,ExceptionCode.common_error_params_code);
//        }
//        return list;
//    }
//
//
//    /**
//     * 根据roleId删除role
//     * @param baseRoleDO
//     */
//    @Transactional
//    public void deleteBaseRole(BaseRoleDO baseRoleDO){
//        if (StringUtils.isEmpty(baseRoleDO.getId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseRoleDO.getSaasId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
//        }
//        baseRoleDO.setStatus(-1);
//        this.baseRoleDao.save(baseRoleDO);
//    }
//
//    /**
//     * 删除某一saasId相关的所有role
//     * @param saasId
//     */
//    @Transactional
//    public void deleteBaseRolesBySaasId(String saasId){
//        if (StringUtils.isEmpty(saasId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseRole.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
//        }
//        List<BaseRoleDO> list = this.baseRoleDao.findAllBySaasId(saasId);
//        for(BaseRoleDO baseRoleDO:list){
//            baseRoleDO.setStatus(-1);
//        }
//        this.baseRoleDao.save(list);
//    }
//
//    /**
//     * 根据saasId和name删除角色
//     * @param saasId
//     * @param name
//     */
//    @Transactional
//    public void deleteBaseRoleByNameAndSaasId(String saasId,String name){
//        BaseRoleDO baseRoleDO = this.findBySaasIdAndName(saasId,name);
//        baseRoleDO.setStatus(-1);
//        this.baseRoleDao.save(baseRoleDO);
//    }
//}

+ 152 - 152
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployRoleService.java

@ -1,152 +1,152 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.dao.BaseRoleDao;
import com.yihu.jw.business.user.dao.EmployRoleDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/5/11.
 * 用户角色表功能
 */
@Service
public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRoleDao> {
    @Autowired
    private EmployRoleDao employRoleDao;
    @Autowired
    private BaseRoleDao baseRoleDao;
    /**
     * 新增用户角色
     * @param baseEmployRoleDO
     * @return
     */
    @Transactional
    public BaseEmployRoleDO createBaseEmployRoleDO(BaseEmployRoleDO baseEmployRoleDO){
        if (StringUtils.isEmpty(baseEmployRoleDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseEmployRoleDO.getEmployId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.employRoleDao.save(baseEmployRoleDO);
    }
    /**
     * 批量新增用户角色,一个用户可能有多个角色
     * @param list
     * @return
     */
    @Transactional
    public Iterable<BaseEmployRoleDO> createBatchBaseEmployRoleDO(List<BaseEmployRoleDO> list){
       return this.employRoleDao.save(list);
    }
    /**
     * 修改用户角色
     * @param baseEmployRoleDO
     * @return
     */
    @Transactional
    public BaseEmployRoleDO updateBaseEmployRoleDO(BaseEmployRoleDO baseEmployRoleDO){
        BaseEmployRoleDO OldbaseEmployRoleDO = this.employRoleDao.findOne(baseEmployRoleDO.getId());
        if(null == OldbaseEmployRoleDO){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employeeRole_no_exist, ExceptionCode.common_error_params_code);
        }
        if (baseEmployRoleDO.getRoleId().equals(OldbaseEmployRoleDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_same_roleId, ExceptionCode.common_error_params_code);
        }
        baseEmployRoleDO.setEmployId(OldbaseEmployRoleDO.getEmployId());
        return this.employRoleDao.save(baseEmployRoleDO);
    }
    /**
     * 查询某一用户的角色列表(用户与角色为一对多关系)
     * @param employId
     * @return
     */
    public List<BaseRoleDO> findAllByEmployId(String employId){
        if (StringUtils.isEmpty(employId)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employId_is_null, ExceptionCode.common_error_params_code);
        }
        List<BaseEmployRoleDO> list = this.employRoleDao.findRoleListByEmployId(employId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employeeRole_no_exist,ExceptionCode.common_error_params_code);
        }
        List ids = new ArrayList<>();
        for(BaseEmployRoleDO baseEmployRoleDO:list){
            ids.add(baseEmployRoleDO.getRoleId());
        }
        Iterable iterable = (Iterable)ids.iterator();
        List<BaseRoleDO> result = (List<BaseRoleDO>)baseRoleDao.findAll(iterable);
        return result;
    }
    /**
     * 根据Id删除用户角色
     * @param id
     * @return
     */
    @Transactional
    public void deleteBaseEmployRoleDO(String id){
        try{
            this.employRoleDao.delete(id);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
    /**
     * 根据用户Id和角色id删除用户角色
     * @param employId
     * @param roleIds
     * @return
     */
    @Transactional
    public void deleteBaseEmployRoleDO(String employId,String roleIds){
        try{
            this.employRoleDao.deleteOneByEmployIdAndRoleId(employId,roleIds);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
    /**
     * 批量删除用户角色
     * @param employId
     * @param roleIds
     * @return
     */
    @Transactional
    public void deleteBatchBaseEmployRoleDO(String employId,String roleIds){
        try{
            this.employRoleDao.deleteManyByEmployIdAndRoleIds(employId,roleIds);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
}
//package com.yihu.jw.business.user.service;
//
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.base.user.BaseEmployDO;
//import com.yihu.jw.base.user.BaseEmployRoleDO;
//import com.yihu.jw.base.user.BaseRoleDO;
//import com.yihu.jw.business.user.dao.BaseRoleDao;
//import com.yihu.jw.business.user.dao.EmployRoleDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.rm.base.BaseUserRequestMapping;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by chenweida on 2017/5/11.
// * 用户角色表功能
// */
//@Service
//public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRoleDao> {
//
//    @Autowired
//    private EmployRoleDao employRoleDao;
//
//    @Autowired
//    private BaseRoleDao baseRoleDao;
//
//    /**
//     * 新增用户角色
//     * @param baseEmployRoleDO
//     * @return
//     */
//    @Transactional
//    public BaseEmployRoleDO createBaseEmployRoleDO(BaseEmployRoleDO baseEmployRoleDO){
//        if (StringUtils.isEmpty(baseEmployRoleDO.getRoleId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(baseEmployRoleDO.getEmployId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employId_is_null, ExceptionCode.common_error_params_code);
//        }
//        return this.employRoleDao.save(baseEmployRoleDO);
//    }
//
//    /**
//     * 批量新增用户角色,一个用户可能有多个角色
//     * @param list
//     * @return
//     */
//    @Transactional
//    public Iterable<BaseEmployRoleDO> createBatchBaseEmployRoleDO(List<BaseEmployRoleDO> list){
//       return this.employRoleDao.save(list);
//    }
//
//    /**
//     * 修改用户角色
//     * @param baseEmployRoleDO
//     * @return
//     */
//    @Transactional
//    public BaseEmployRoleDO updateBaseEmployRoleDO(BaseEmployRoleDO baseEmployRoleDO){
//        BaseEmployRoleDO OldbaseEmployRoleDO = this.employRoleDao.findOne(baseEmployRoleDO.getId());
//        if(null == OldbaseEmployRoleDO){
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employeeRole_no_exist, ExceptionCode.common_error_params_code);
//        }
//        if (baseEmployRoleDO.getRoleId().equals(OldbaseEmployRoleDO.getRoleId())) {
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_same_roleId, ExceptionCode.common_error_params_code);
//        }
//        baseEmployRoleDO.setEmployId(OldbaseEmployRoleDO.getEmployId());
//        return this.employRoleDao.save(baseEmployRoleDO);
//    }
//
//
//    /**
//     * 查询某一用户的角色列表(用户与角色为一对多关系)
//     * @param employId
//     * @return
//     */
//    public List<BaseRoleDO> findAllByEmployId(String employId){
//        if (StringUtils.isEmpty(employId)) {
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employId_is_null, ExceptionCode.common_error_params_code);
//        }
//        List<BaseEmployRoleDO> list = this.employRoleDao.findRoleListByEmployId(employId);
//        if (null == list || list.size() == 0) {
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employeeRole_no_exist,ExceptionCode.common_error_params_code);
//        }
//        List ids = new ArrayList<>();
//        for(BaseEmployRoleDO baseEmployRoleDO:list){
//            ids.add(baseEmployRoleDO.getRoleId());
//        }
//        Iterable iterable = (Iterable)ids.iterator();
//        List<BaseRoleDO> result = (List<BaseRoleDO>)baseRoleDao.findAll(iterable);
//        return result;
//    }
//
//
//    /**
//     * 根据Id删除用户角色
//     * @param id
//     * @return
//     */
//    @Transactional
//    public void deleteBaseEmployRoleDO(String id){
//        try{
//            this.employRoleDao.delete(id);
//        }
//        catch (ApiException e){
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//
//    }
//
//    /**
//     * 根据用户Id和角色id删除用户角色
//     * @param employId
//     * @param roleIds
//     * @return
//     */
//    @Transactional
//    public void deleteBaseEmployRoleDO(String employId,String roleIds){
//        try{
//            this.employRoleDao.deleteOneByEmployIdAndRoleId(employId,roleIds);
//        }
//        catch (ApiException e){
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//
//    }
//
//    /**
//     * 批量删除用户角色
//     * @param employId
//     * @param roleIds
//     * @return
//     */
//    @Transactional
//    public void deleteBatchBaseEmployRoleDO(String employId,String roleIds){
//        try{
//            this.employRoleDao.deleteManyByEmployIdAndRoleIds(employId,roleIds);
//        }
//        catch (ApiException e){
//            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
//        }
//
//    }
//
//}

+ 7 - 3
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployService.java

@ -3,17 +3,21 @@ package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.dao.BaseRoleDao;
import com.yihu.jw.business.user.dao.EmployDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import javax.servlet.Servlet;
import java.util.List;
/**
@ -67,7 +71,7 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
     * @param id
     * @return
     */
    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
//    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
    public BaseEmployDO findById(String id){
        if (StringUtils.isEmpty(id)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null,ExceptionCode.common_error_params_code);
@ -86,7 +90,7 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
     * @param saasId
     * @return
     */
    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
//    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
    public BaseEmployDO findByPhoneAndSaasId(String phone,String saasId){
        if (StringUtils.isEmpty(phone)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null,ExceptionCode.common_error_params_code);

+ 125 - 125
svr/svr-base/src/main/java/com/yihu/jw/business/version/controller/UserVersionController.java

@ -1,125 +1,125 @@
package com.yihu.jw.business.version.controller;
import com.yihu.jw.base.version.BaseUserVersionDO;
import com.yihu.jw.business.version.service.BaseUserVersionService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseVersionRequestMapping;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.PathParam;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/11/10.
 */
@RestController
@RequestMapping(BaseVersionRequestMapping.api_common)
@Api(description = "灰度发布,用户版本信息")
public class UserVersionController extends EnvelopRestController {
    @Autowired
    private BaseUserVersionService baseEmployeeVersionService;
    @PostMapping(value = BaseVersionRequestMapping.UserVersion.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "给用户添加灰度发布版本信息", notes = "给用户添加灰度发布版本信息")
    public Envelop createUserVersion(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            BaseUserVersionDO baseUserVersion = toEntity(jsonData, BaseUserVersionDO.class);
            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_create, baseEmployeeVersionService.createUserVersion(baseUserVersion));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @DeleteMapping(value = BaseVersionRequestMapping.UserVersion.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "删除用户灰度发布版本信息", notes = "删除用户灰度发布版本信息")
    public Envelop deleteUsersVersion(
            @ApiParam(name = "ids", value = "ids")
            @RequestParam(value = "ids", required = true) String ids) {
        try {
            baseEmployeeVersionService.deleteUserVersion(ids);
            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_delete);
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @GetMapping(value = BaseVersionRequestMapping.UserVersion.api_getByUserId, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据用户和saadId获取用户的灰度发布版本信息", notes = "根据用户获取用户的灰度发布版本信息")
    public Envelop getUserVersionByUserId(
            @ApiParam(name = "userId", value = "userId")
            @PathParam(value = "userId") String userId) {
        try {
            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_find, baseEmployeeVersionService.getUserVersionByUserId(userId));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @GetMapping(value = BaseVersionRequestMapping.UserVersion.api_getById, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据ID获取用户的灰度发布版本信息", notes = "根据ID获取用户的灰度发布版本信息")
    public Envelop getUserVersion(
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id", required = true) String id) {
        try {
            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_find, baseEmployeeVersionService.getUserVersion(id));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @RequestMapping(value = BaseVersionRequestMapping.UserVersion.api_getList, method = RequestMethod.GET)
    @ApiOperation(value = "获取用户的灰度发布版本信息(分页)", notes = "根据用户获取用户的灰度发布版本信息")
    public Envelop getSmsGateways(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "code,name,saasId,parentCode,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            //code like 1,name大于aa ,code 等于1 , defaultValue = "code?1;name>aa;code=1"
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //得到list数据
        List<BaseUserVersionDO> list = baseEmployeeVersionService.search(fields, filters, sorts, page, size);
        //获取总数
        long count=baseEmployeeVersionService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<BaseUserVersionDO> baseUserVersions = convertToModels(list, new ArrayList<>(list.size()), BaseUserVersionDO.class, fields);
        return Envelop.getSuccessListWithPage(BaseVersionRequestMapping.UserVersion.message_success_find,baseUserVersions, page, size,count);
    }
    @GetMapping(value =BaseVersionRequestMapping.UserVersion.api_getListNoPage)
    @ApiOperation(value = "获取用户的灰度发布版本信息,不分页")
    public Envelop getAppsNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "code,name,saasId,parentCode,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        //得到list数据
        List<BaseUserVersionDO> list = baseEmployeeVersionService.search(fields,filters,sorts);
        //封装返回格式
        List<BaseUserVersionDO> baseUserVersions = convertToModels(list, new ArrayList<>(list.size()), BaseUserVersionDO.class, fields);
        return Envelop.getSuccessList(BaseVersionRequestMapping.UserVersion.message_success_find,baseUserVersions);
    }
}
//package com.yihu.jw.business.version.controller;
//
//import com.yihu.jw.base.version.BaseUserVersionDO;
//import com.yihu.jw.business.version.service.BaseUserVersionService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.rm.base.BaseVersionRequestMapping;
//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 javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.ws.rs.PathParam;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by chenweida on 2017/11/10.
// */
//@RestController
//@RequestMapping(BaseVersionRequestMapping.api_common)
//@Api(description = "灰度发布,用户版本信息")
//public class UserVersionController extends EnvelopRestController {
//    @Autowired
//    private BaseUserVersionService baseEmployeeVersionService;
//
//
//    @PostMapping(value = BaseVersionRequestMapping.UserVersion.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "给用户添加灰度发布版本信息", notes = "给用户添加灰度发布版本信息")
//    public Envelop createUserVersion(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            BaseUserVersionDO baseUserVersion = toEntity(jsonData, BaseUserVersionDO.class);
//            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_create, baseEmployeeVersionService.createUserVersion(baseUserVersion));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @DeleteMapping(value = BaseVersionRequestMapping.UserVersion.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "删除用户灰度发布版本信息", notes = "删除用户灰度发布版本信息")
//    public Envelop deleteUsersVersion(
//            @ApiParam(name = "ids", value = "ids")
//            @RequestParam(value = "ids", required = true) String ids) {
//        try {
//            baseEmployeeVersionService.deleteUserVersion(ids);
//            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_delete);
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = BaseVersionRequestMapping.UserVersion.api_getByUserId, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "根据用户和saadId获取用户的灰度发布版本信息", notes = "根据用户获取用户的灰度发布版本信息")
//    public Envelop getUserVersionByUserId(
//            @ApiParam(name = "userId", value = "userId")
//            @PathParam(value = "userId") String userId) {
//        try {
//            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_find, baseEmployeeVersionService.getUserVersionByUserId(userId));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//    @GetMapping(value = BaseVersionRequestMapping.UserVersion.api_getById, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "根据ID获取用户的灰度发布版本信息", notes = "根据ID获取用户的灰度发布版本信息")
//    public Envelop getUserVersion(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id) {
//        try {
//            return Envelop.getSuccess(BaseVersionRequestMapping.UserVersion.message_success_find, baseEmployeeVersionService.getUserVersion(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//    @RequestMapping(value = BaseVersionRequestMapping.UserVersion.api_getList, method = RequestMethod.GET)
//    @ApiOperation(value = "获取用户的灰度发布版本信息(分页)", notes = "根据用户获取用户的灰度发布版本信息")
//    public Envelop getSmsGateways(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "code,name,saasId,parentCode,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            //code like 1,name大于aa ,code 等于1 , defaultValue = "code?1;name>aa;code=1"
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        //得到list数据
//        List<BaseUserVersionDO> list = baseEmployeeVersionService.search(fields, filters, sorts, page, size);
//        //获取总数
//        long count=baseEmployeeVersionService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<BaseUserVersionDO> baseUserVersions = convertToModels(list, new ArrayList<>(list.size()), BaseUserVersionDO.class, fields);
//
//        return Envelop.getSuccessListWithPage(BaseVersionRequestMapping.UserVersion.message_success_find,baseUserVersions, page, size,count);
//    }
//
//
//    @GetMapping(value =BaseVersionRequestMapping.UserVersion.api_getListNoPage)
//    @ApiOperation(value = "获取用户的灰度发布版本信息,不分页")
//    public Envelop getAppsNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "code,name,saasId,parentCode,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<BaseUserVersionDO> list = baseEmployeeVersionService.search(fields,filters,sorts);
//        //封装返回格式
//        List<BaseUserVersionDO> baseUserVersions = convertToModels(list, new ArrayList<>(list.size()), BaseUserVersionDO.class, fields);
//        return Envelop.getSuccessList(BaseVersionRequestMapping.UserVersion.message_success_find,baseUserVersions);
//    }
//}

+ 14 - 14
svr/svr-base/src/main/java/com/yihu/jw/business/version/dao/BaseUserVersionDao.java

@ -1,14 +1,14 @@
package com.yihu.jw.business.version.dao;
import com.yihu.jw.base.version.BaseUserVersionDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/11/13.
 */
public interface BaseUserVersionDao extends PagingAndSortingRepository<BaseUserVersionDO, String>, JpaSpecificationExecutor<BaseUserVersionDO> {
    @Query("from BaseUserVersionDO where userId=?1")
    BaseUserVersionDO getUserVersionByUserId(String userId);
}
//package com.yihu.jw.business.version.dao;
//
//import com.yihu.jw.base.version.BaseUserVersionDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by chenweida on 2017/11/13.
// */
//public interface BaseUserVersionDao extends PagingAndSortingRepository<BaseUserVersionDO, String>, JpaSpecificationExecutor<BaseUserVersionDO> {
//    @Query("from BaseUserVersionDO where userId=?1")
//    BaseUserVersionDO getUserVersionByUserId(String userId);
//}

+ 41 - 41
svr/svr-base/src/main/java/com/yihu/jw/business/version/service/BaseUserVersionService.java

@ -1,41 +1,41 @@
package com.yihu.jw.business.version.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.version.BaseUserVersionDO;
import com.yihu.jw.business.sms.dao.SmsGatewayDao;
import com.yihu.jw.business.version.dao.BaseUserVersionDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
/**
 * Created by chenweida on 2017/11/10.
 */
@Service
public class BaseUserVersionService extends BaseJpaService<BaseUserVersionDO, BaseUserVersionDao> {
    @Autowired
    private BaseUserVersionDao baseUserVersionDao;
    @Transactional
    public BaseUserVersionDO createUserVersion(BaseUserVersionDO baseUserVersion) {
        return baseUserVersionDao.save(baseUserVersion);
    }
    @Transactional
    public void deleteUserVersion(String ids) {
        String[] idStr = ids.split(",");
        for (String id : idStr) {
            baseUserVersionDao.delete(id);
        }
    }
    public BaseUserVersionDO getUserVersionByUserId(String userId) {
        return baseUserVersionDao.getUserVersionByUserId(userId);
    }
    public BaseUserVersionDO getUserVersion(String id) {
        return baseUserVersionDao.findOne(id);
    }
}
//package com.yihu.jw.business.version.service;
//
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.base.version.BaseUserVersionDO;
//import com.yihu.jw.business.sms.dao.SmsGatewayDao;
//import com.yihu.jw.business.version.dao.BaseUserVersionDao;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.Arrays;
//
///**
// * Created by chenweida on 2017/11/10.
// */
//@Service
//public class BaseUserVersionService extends BaseJpaService<BaseUserVersionDO, BaseUserVersionDao> {
//    @Autowired
//    private BaseUserVersionDao baseUserVersionDao;
//
//    @Transactional
//    public BaseUserVersionDO createUserVersion(BaseUserVersionDO baseUserVersion) {
//        return baseUserVersionDao.save(baseUserVersion);
//    }
//
//    @Transactional
//    public void deleteUserVersion(String ids) {
//        String[] idStr = ids.split(",");
//        for (String id : idStr) {
//            baseUserVersionDao.delete(id);
//        }
//    }
//
//    public BaseUserVersionDO getUserVersionByUserId(String userId) {
//        return baseUserVersionDao.getUserVersionByUserId(userId);
//    }
//
//    public BaseUserVersionDO getUserVersion(String id) {
//        return baseUserVersionDao.findOne(id);
//    }
//}

+ 644 - 644
svr/svr-base/src/main/java/com/yihu/jw/business/wx/WechatResponse.java

@ -1,644 +1,644 @@
package com.yihu.jw.business.wx;
/**
 * Created by Administrator on 2017/5/27 0027.
 */
public class WechatResponse {
    /**
     * 微信返回值
     * 具体见   https://mp.weixin.qq.com/wiki
     *  -1       系统繁忙,此时请开发者稍候再试
     *  0        请求成功
     *  40001    获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口
     *  40002    不合法的凭证类型
     *  40003    不合法的OpenID,请开发者确认OpenID(该用户)是否已关注公众号,或是否是其他公众号的OpenID
     *  40004    不合法的媒体文件类型
     *  40005    不合法的文件类型
     *  40006    不合法的文件大小
     *  40007    不合法的媒体文件id
     *  40008    不合法的消息类型
     *  40009    不合法的图片文件大小
     *  40010    不合法的语音文件大小
     *  40011    不合法的视频文件大小
     *  40012    不合法的缩略图文件大小
     *  40013    不合法的AppID,请开发者检查AppID的正确性,避免异常字符,注意大小写
     *  40014    不合法的access_token,请开发者认真比对access_token的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口
     *  40015    不合法的菜单类型
     *  40016    不合法的按钮个数
     *  40017    不合法的按钮个数
     *  40018    不合法的按钮名字长度
     *  40019    不合法的按钮KEY长度
     *  40020    不合法的按钮URL长度
     *  40021    不合法的菜单版本号
     *  40022    不合法的子菜单级数
     *  40023    不合法的子菜单按钮个数
     *  40024    不合法的子菜单按钮类型
     *  40025    不合法的子菜单按钮名字长度
     *  40026    不合法的子菜单按钮KEY长度
     *  40027    不合法的子菜单按钮URL长度
     *  40028    不合法的自定义菜单使用用户
     *  40029    不合法的oauth_code
     *  40030    不合法的refresh_token
     *  40031    不合法的openid列表
     *  40032    不合法的openid列表长度
     *  40033    不合法的请求字符,不能包含\  uxxxx格式的字符
     *  40035    不合法的参数
     *  40038    不合法的请求格式
     *  40039    不合法的URL长度
     *  40050    不合法的分组id
     *  40051    分组名字不合法
     *  40060    删除单篇图文时,指定的 article_idx 不合法
     *  40117    分组名字不合法
     *  40118    media_id大小不合法
     *  40119    button类型错误
     *  40120    button类型错误
     *  40121    不合法的media_id类型
     *  40132    微信号不合法
     *  40137    不支持的图片格式
     *  40155    请勿添加其他公众号的主页链接
     *  41001    缺少access_token参数
     *  41002    缺少appid参数
     *  41003    缺少refresh_token参数
     *  41004    缺少secret参数
     *  41005    缺少多媒体文件数据
     *  41006    缺少media_id参数
     *  41007    缺少子菜单数据
     *  41008    缺少oauth code
     *  41009    缺少openid
     *  42001    access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明
     *  42002    refresh_token超时
     *  42003    oauth_code超时
     *  42007    用户修改微信密码,accesstoken和refreshtoken失效,需要重新授权
     *  43001    需要GET请求
     *  43002    需要POST请求
     *  43003    需要HTTPS请求
     *  43004    需要接收者关注
     *  43005    需要好友关系
     *  43019    需要将接收者从黑名单中移除
     *  44001    多媒体文件为空
     *  44002    POST的数据包为空
     *  44003    图文消息内容为空
     *  44004    文本消息内容为空
     *  45001    多媒体文件大小超过限制
     *  45002    消息内容超过限制
     *  45003    标题字段超过限制
     *  45004    描述字段超过限制
     *  45005    链接字段超过限制
     *  45006    图片链接字段超过限制
     *  45007    语音播放时间超过限制
     *  45008    图文消息超过限制
     *  45009    接口调用超过限制
     *  45010    创建菜单个数超过限制
     *  45011    API调用太频繁,请稍候再试
     *  45015    回复时间超过限制
     *  45016    系统分组,不允许修改
     *  45017    分组名字过长
     *  45018    分组数量超过上限
     *  45047    客服接口下行条数超过上限
     *  46001    不存在媒体数据
     *  46002    不存在的菜单版本
     *  46003    不存在的菜单数据
     *  46004    不存在的用户
     *  47001    解析JSON/XML内容错误
     *  48001    api功能未授权,请确认公众号已获得该接口,可以在公众平台官网-开发者中心页中查看接口权限
     *  48002    粉丝拒收消息(粉丝在公众号选项中,关闭了“接收消息”)
     *  48004    api接口被封禁,请登录mp.weixin.qq.com查看详情
     *  48005    api禁止删除被自动回复和自定义菜单引用的素材
     *  48006    api禁止清零调用次数,因为清零次数达到上限
     *  50001    用户未授权该api
     *  50002    用户受限,可能是违规后接口被封禁
     *  61451    参数错误(invalid parameter)
     *  61452    无效客服账号(invalid kf_account)
     *  61453    客服帐号已存在(kf_account exsited)
     *  61454    客服帐号名长度超过限制(仅允许10个英文字符,不包括@及@后的公众号的微信号)(invalid   kf_acount length)
     *  61455    客服帐号名包含非法字符(仅允许英文+数字)(illegal character in     kf_account)
     *  61456    客服帐号个数超过限制(10个客服账号)(kf_account count exceeded)
     *  61457    无效头像文件类型(invalid   file type)
     *  61450    系统错误(system error)
     *  61500    日期格式错误
     *  65301    不存在此menuid对应的个性化菜单
     *  65302    没有相应的用户
     *  65303    没有默认菜单,不能创建个性化菜单
     *  65304    MatchRule信息为空
     *  65305    个性化菜单数量受限
     *  65306    不支持个性化菜单的帐号
     *  65307    个性化菜单信息为空
     *  65308    包含没有响应类型的button
     *  65309    个性化菜单开关处于关闭状态
     *  65310    填写了省份或城市信息,国家信息不能为空
     *  65311    填写了城市信息,省份信息不能为空
     *  65312    不合法的国家信息
     *  65313    不合法的省份信息
     *  65314    不合法的城市信息
     *  65316    该公众号的菜单设置了过多的域名外跳(最多跳转到3个域名的链接)
     *  65317    不合法的URL
     *  9001001    POST数据参数不合法
     *  9001002    远端服务不可用
     *  9001003    Ticket不合法
     *  9001004    获取摇周边用户信息失败
     *  9001005    获取商户信息失败
     *  9001006    获取OpenID失败
     *  9001007    上传文件缺失
     *  9001008    上传素材的文件类型不合法
     *  9001009    上传素材的文件尺寸不合法
     *  9001010    上传失败
     *  9001020    帐号不合法
     *  9001021    已有设备激活率低于50%,不能新增设备
     *  9001022    设备申请数不合法,必须为大于0的数字
     *  9001023    已存在审核中的设备ID申请
     *  9001024    一次查询设备ID数量不能超过50
     *  9001025    设备ID不合法
     *  9001026    页面ID不合法
     *  9001027    页面参数不合法
     *  9001028    一次删除页面ID数量不能超过10
     *  9001029    页面已应用在设备中,请先解除应用关系再删除
     *  9001030    一次查询页面ID数量不能超过50
     *  9001031    时间区间不合法
     *  9001032    保存设备与页面的绑定关系参数错误
     *  9001033    门店ID不合法
     *  9001034    设备备注信息过长
     *  9001035    设备申请参数不合法
     *  9001036    查询起始值begin不合法
     */
    private Integer resultCode;
    /** 返回码对应信息 ***/
    private String msg;
    public Integer getResultCode() {
        return resultCode;
    }
    public void setResultCode(Integer resultCode) {
        this.resultCode = resultCode;
    }
    public WechatResponse(Integer resultCode) {
        this.resultCode = resultCode;
    }
    public String getMsg() {
        switch (resultCode) {
        case -1:
            msg="系统繁忙,此时请开发者稍候再试";
            break;
        case 0:
            msg="请求成功";
            break;
        case 40001:
            msg="获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口";
            break;
        case 40002:
            msg="不合法的凭证类型";
            break;
        case 40003:
            msg="不合法的OpenID,请开发者确认OpenID(该用户)是否已关注公众号,或是否是其他公众号的OpenID";
            break;
        case 40004:
            msg="不合法的媒体文件类型";
            break;
        case 40005:
            msg="不合法的文件类型";
            break;
        case 40006:
            msg="不合法的文件大小";
            break;
        case 40007:
            msg="不合法的媒体文件id";
            break;
        case 40008:
            msg="不合法的消息类型";
            break;
        case 40009:
            msg="不合法的图片文件大小";
            break;
        case 40010:
            msg="不合法的语音文件大小";
            break;
        case 40011:
            msg="不合法的视频文件大小";
            break;
        case 40012:
            msg="不合法的缩略图文件大小";
            break;
        case 40013:
            msg="不合法的AppID,请开发者检查AppID的正确性,避免异常字符,注意大小写";
            break;
        case 40014:
            msg="不合法的access_token,请开发者认真比对access_token的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口";
            break;
        case 40015:
            msg="不合法的菜单类型";
            break;
        case 40016:
            msg="不合法的按钮个数";
            break;
        case 40017:
            msg="不合法的按钮个数";
            break;
        case 40018:
            msg="不合法的按钮名字长度";
            break;
        case 40019:
            msg="不合法的按钮KEY长度";
            break;
        case 40020:
            msg="不合法的按钮URL长度";
            break;
        case 40021:
            msg="不合法的菜单版本号";
            break;
        case 40022:
            msg="不合法的子菜单级数";
            break;
        case 40023:
            msg="不合法的子菜单按钮个数";
            break;
        case 40024:
            msg="不合法的子菜单按钮类型";
            break;
        case 40025:
            msg="不合法的子菜单按钮名字长度";
            break;
        case 40026:
            msg="不合法的子菜单按钮KEY长度";
            break;
        case 40027:
            msg="不合法的子菜单按钮URL长度";
            break;
        case 40028:
            msg="不合法的自定义菜单使用用户";
            break;
        case 40029:
            msg="不合法的oauth_code";
            break;
        case 40030:
            msg="不合法的refresh_token";
            break;
        case 40031:
            msg="不合法的openid列表";
            break;
        case 40032:
            msg="不合法的openid列表长度";
            break;
        case 40033:
            msg="不合法的请求字符,不能包含\\uxxxx格式的字符";
            break;
        case 40035:
            msg="不合法的参数";
            break;
        case 40038:
            msg="不合法的请求格式";
            break;
        case 40039:
            msg="不合法的URL长度";
            break;
        case 40050:
            msg="不合法的分组id";
            break;
        case 40051:
            msg="分组名字不合法";
            break;
        case 40060:
            msg="删除单篇图文时,指定的 article_idx 不合法";
            break;
        case 40117:
            msg="分组名字不合法";
            break;
        case 40118:
            msg="media_id大小不合法";
            break;
        case 40119:
            msg="button类型错误";
            break;
        case 40120:
            msg="button类型错误";
            break;
        case 40121:
            msg="不合法的media_id类型";
            break;
        case 40132:
            msg="微信号不合法";
            break;
        case 40137:
            msg="不支持的图片格式";
            break;
        case 40155:
            msg="请勿添加其他公众号的主页链接";
            break;
        case 41001:
            msg="缺少access_token参数";
            break;
        case 41002:
            msg="缺少appid参数";
            break;
        case 41003:
            msg="缺少refresh_token参数";
            break;
        case 41004:
            msg="缺少secret参数";
            break;
        case 41005:
            msg="缺少多媒体文件数据";
            break;
        case 41006:
            msg="缺少media_id参数";
            break;
        case 41007:
            msg="缺少子菜单数据";
            break;
        case 41008:
            msg="缺少oauth code";
            break;
        case 41009:
            msg="缺少openid";
            break;
        case 42001:
            msg="access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明";
            break;
        case 42002:
            msg="refresh_token超时";
            break;
        case 42003:
            msg="oauth_code超时";
            break;
        case 42007:
            msg="用户修改微信密码,accesstoken和refreshtoken失效,需要重新授权";
            break;
        case 43001:
            msg="需要GET请求";
            break;
        case 43002:
            msg="需要POST请求";
            break;
        case 43003:
            msg="需要HTTPS请求";
            break;
        case 43004:
            msg="需要接收者关注";
            break;
        case 43005:
            msg="需要好友关系";
            break;
        case 43019:
            msg="需要将接收者从黑名单中移除";
            break;
        case 44001:
            msg="多媒体文件为空";
            break;
        case 44002:
            msg="POST的数据包为空";
            break;
        case 44003:
            msg="图文消息内容为空";
            break;
        case 44004:
            msg="文本消息内容为空";
            break;
        case 45001:
            msg="多媒体文件大小超过限制";
            break;
        case 45002:
            msg="消息内容超过限制";
            break;
        case 45003:
            msg="标题字段超过限制";
            break;
        case 45004:
            msg="描述字段超过限制";
            break;
        case 45005:
            msg="链接字段超过限制";
            break;
        case 45006:
            msg="图片链接字段超过限制";
            break;
        case 45007:
            msg="语音播放时间超过限制";
            break;
        case 45008:
            msg="图文消息超过限制";
            break;
        case 45009:
            msg="接口调用超过限制";
            break;
        case 45010:
            msg="创建菜单个数超过限制";
            break;
        case 45011:
            msg="API调用太频繁,请稍候再试";
            break;
        case 45015:
            msg="回复时间超过限制";
            break;
        case 45016:
            msg="系统分组,不允许修改";
            break;
        case 45017:
            msg="分组名字过长";
            break;
        case 45018:
            msg="分组数量超过上限";
            break;
        case 45047:
            msg="客服接口下行条数超过上限";
            break;
        case 46001:
            msg="不存在媒体数据";
            break;
        case 46002:
            msg="不存在的菜单版本";
            break;
        case 46003:
            msg="不存在的菜单数据";
            break;
        case 46004:
            msg="不存在的用户";
            break;
        case 47001:
            msg="解析JSON/XML内容错误";
            break;
        case 48001:
            msg="api功能未授权,请确认公众号已获得该接口,可以在公众平台官网-开发者中心页中查看接口权限";
            break;
        case 48002:
            msg="粉丝拒收消息(粉丝在公众号选项中,关闭了“接收消息”)";
            break;
        case 48004:
            msg="api接口被封禁,请登录mp.weixin.qq.com查看详情";
            break;
        case 48005:
            msg="api禁止删除被自动回复和自定义菜单引用的素材";
            break;
        case 48006:
            msg="api禁止清零调用次数,因为清零次数达到上限";
            break;
        case 50001:
            msg="用户未授权该api";
            break;
        case 50002:
            msg="用户受限,可能是违规后接口被封禁";
            break;
        case 61451:
            msg="参数错误(invalid parameter)";
            break;
        case 61452:
            msg="无效客服账号(invalid kf_account)";
            break;
        case 61453:
            msg="客服帐号已存在(kf_account exsited)";
            break;
        case 61454:
            msg="客服帐号名长度超过限制(仅允许10个英文字符,不包括@及@后的公众号的微信号)(invalid kf_acount length)";
            break;
        case 61455:
            msg="客服帐号名包含非法字符(仅允许英文+数字)(illegal character in kf_account)";
            break;
        case 61456:
            msg="客服帐号个数超过限制(10个客服账号)(kf_account count exceeded)";
            break;
        case 61457:
            msg="无效头像文件类型(invalid file type)";
            break;
        case 61450:
            msg="系统错误(system error)";
            break;
        case 61500:
            msg="日期格式错误";
            break;
        case 65301:
            msg="不存在此menuid对应的个性化菜单";
            break;
        case 65302:
            msg="没有相应的用户";
            break;
        case 65303:
            msg="没有默认菜单,不能创建个性化菜单";
            break;
        case 65304:
            msg="MatchRule信息为空";
            break;
        case 65305:
            msg="个性化菜单数量受限";
            break;
        case 65306:
            msg="不支持个性化菜单的帐号";
            break;
        case 65307:
            msg="个性化菜单信息为空";
            break;
        case 65308:
            msg="包含没有响应类型的button";
            break;
        case 65309:
            msg="个性化菜单开关处于关闭状态";
            break;
        case 65310:
            msg="填写了省份或城市信息,国家信息不能为空";
            break;
        case 65311:
            msg="填写了城市信息,省份信息不能为空";
            break;
        case 65312:
            msg="不合法的国家信息";
            break;
        case 65313:
            msg="不合法的省份信息";
            break;
        case 65314:
            msg="不合法的城市信息";
            break;
        case 65316:
            msg="该公众号的菜单设置了过多的域名外跳(最多跳转到3个域名的链接)";
            break;
        case 65317:
            msg="不合法的URL";
            break;
        case 9001001:
            msg="POST数据参数不合法";
            break;
        case 9001002:
            msg="远端服务不可用";
            break;
        case 9001003:
            msg="Ticket不合法";
            break;
        case 9001004:
            msg="获取摇周边用户信息失败";
            break;
        case 9001005:
            msg="获取商户信息失败";
            break;
        case 9001006:
            msg="获取OpenID失败";
            break;
        case 9001007:
            msg="上传文件缺失";
            break;
        case 9001008:
            msg="上传素材的文件类型不合法";
            break;
        case 9001009:
            msg="上传素材的文件尺寸不合法";
            break;
        case 9001010:
            msg="上传失败";
            break;
        case 9001020:
            msg="帐号不合法";
            break;
        case 9001021:
            msg="已有设备激活率低于50%,不能新增设备";
            break;
        case 9001022:
            msg="设备申请数不合法,必须为大于0的数字";
            break;
        case 9001023:
            msg="已存在审核中的设备ID申请";
            break;
        case 9001024:
            msg="一次查询设备ID数量不能超过50";
            break;
        case 9001025:
            msg="设备ID不合法";
            break;
        case 9001026:
            msg="页面ID不合法";
            break;
        case 9001027:
            msg="页面参数不合法";
            break;
        case 9001028:
            msg="一次删除页面ID数量不能超过10";
            break;
        case 9001029:
            msg="页面已应用在设备中,请先解除应用关系再删除";
            break;
        case 9001030:
            msg="一次查询页面ID数量不能超过50";
            break;
        case 9001031:
            msg="时间区间不合法";
            break;
        case 9001032:
            msg="保存设备与页面的绑定关系参数错误";
            break;
        case 9001033:
            msg="门店ID不合法";
            break;
        case 9001034:
            msg="设备备注信息过长";
            break;
        case 9001035:
            msg="设备申请参数不合法";
            break;
        case 9001036:
            msg="查询起始值begin不合法";
            break;
        default:
            msg = resultCode+":其他错误";
            break;
        }
        return msg;
    }
}
//package com.yihu.jw.business.wx;
//
///**
// * Created by Administrator on 2017/5/27 0027.
// */
//public class WechatResponse {
//    /**
//     * 微信返回值
//     * 具体见   https://mp.weixin.qq.com/wiki
//     *  -1       系统繁忙,此时请开发者稍候再试
//     *  0        请求成功
//     *  40001    获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口
//     *  40002    不合法的凭证类型
//     *  40003    不合法的OpenID,请开发者确认OpenID(该用户)是否已关注公众号,或是否是其他公众号的OpenID
//     *  40004    不合法的媒体文件类型
//     *  40005    不合法的文件类型
//     *  40006    不合法的文件大小
//     *  40007    不合法的媒体文件id
//     *  40008    不合法的消息类型
//     *  40009    不合法的图片文件大小
//     *  40010    不合法的语音文件大小
//     *  40011    不合法的视频文件大小
//     *  40012    不合法的缩略图文件大小
//     *  40013    不合法的AppID,请开发者检查AppID的正确性,避免异常字符,注意大小写
//     *  40014    不合法的access_token,请开发者认真比对access_token的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口
//     *  40015    不合法的菜单类型
//     *  40016    不合法的按钮个数
//     *  40017    不合法的按钮个数
//     *  40018    不合法的按钮名字长度
//     *  40019    不合法的按钮KEY长度
//     *  40020    不合法的按钮URL长度
//     *  40021    不合法的菜单版本号
//     *  40022    不合法的子菜单级数
//     *  40023    不合法的子菜单按钮个数
//     *  40024    不合法的子菜单按钮类型
//     *  40025    不合法的子菜单按钮名字长度
//     *  40026    不合法的子菜单按钮KEY长度
//     *  40027    不合法的子菜单按钮URL长度
//     *  40028    不合法的自定义菜单使用用户
//     *  40029    不合法的oauth_code
//     *  40030    不合法的refresh_token
//     *  40031    不合法的openid列表
//     *  40032    不合法的openid列表长度
//     *  40033    不合法的请求字符,不能包含\  uxxxx格式的字符
//     *  40035    不合法的参数
//     *  40038    不合法的请求格式
//     *  40039    不合法的URL长度
//     *  40050    不合法的分组id
//     *  40051    分组名字不合法
//     *  40060    删除单篇图文时,指定的 article_idx 不合法
//     *  40117    分组名字不合法
//     *  40118    media_id大小不合法
//     *  40119    button类型错误
//     *  40120    button类型错误
//     *  40121    不合法的media_id类型
//     *  40132    微信号不合法
//     *  40137    不支持的图片格式
//     *  40155    请勿添加其他公众号的主页链接
//     *  41001    缺少access_token参数
//     *  41002    缺少appid参数
//     *  41003    缺少refresh_token参数
//     *  41004    缺少secret参数
//     *  41005    缺少多媒体文件数据
//     *  41006    缺少media_id参数
//     *  41007    缺少子菜单数据
//     *  41008    缺少oauth code
//     *  41009    缺少openid
//     *  42001    access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明
//     *  42002    refresh_token超时
//     *  42003    oauth_code超时
//     *  42007    用户修改微信密码,accesstoken和refreshtoken失效,需要重新授权
//     *  43001    需要GET请求
//     *  43002    需要POST请求
//     *  43003    需要HTTPS请求
//     *  43004    需要接收者关注
//     *  43005    需要好友关系
//     *  43019    需要将接收者从黑名单中移除
//     *  44001    多媒体文件为空
//     *  44002    POST的数据包为空
//     *  44003    图文消息内容为空
//     *  44004    文本消息内容为空
//     *  45001    多媒体文件大小超过限制
//     *  45002    消息内容超过限制
//     *  45003    标题字段超过限制
//     *  45004    描述字段超过限制
//     *  45005    链接字段超过限制
//     *  45006    图片链接字段超过限制
//     *  45007    语音播放时间超过限制
//     *  45008    图文消息超过限制
//     *  45009    接口调用超过限制
//     *  45010    创建菜单个数超过限制
//     *  45011    API调用太频繁,请稍候再试
//     *  45015    回复时间超过限制
//     *  45016    系统分组,不允许修改
//     *  45017    分组名字过长
//     *  45018    分组数量超过上限
//     *  45047    客服接口下行条数超过上限
//     *  46001    不存在媒体数据
//     *  46002    不存在的菜单版本
//     *  46003    不存在的菜单数据
//     *  46004    不存在的用户
//     *  47001    解析JSON/XML内容错误
//     *  48001    api功能未授权,请确认公众号已获得该接口,可以在公众平台官网-开发者中心页中查看接口权限
//     *  48002    粉丝拒收消息(粉丝在公众号选项中,关闭了“接收消息”)
//     *  48004    api接口被封禁,请登录mp.weixin.qq.com查看详情
//     *  48005    api禁止删除被自动回复和自定义菜单引用的素材
//     *  48006    api禁止清零调用次数,因为清零次数达到上限
//     *  50001    用户未授权该api
//     *  50002    用户受限,可能是违规后接口被封禁
//     *  61451    参数错误(invalid parameter)
//     *  61452    无效客服账号(invalid kf_account)
//     *  61453    客服帐号已存在(kf_account exsited)
//     *  61454    客服帐号名长度超过限制(仅允许10个英文字符,不包括@及@后的公众号的微信号)(invalid   kf_acount length)
//     *  61455    客服帐号名包含非法字符(仅允许英文+数字)(illegal character in     kf_account)
//     *  61456    客服帐号个数超过限制(10个客服账号)(kf_account count exceeded)
//     *  61457    无效头像文件类型(invalid   file type)
//     *  61450    系统错误(system error)
//     *  61500    日期格式错误
//     *  65301    不存在此menuid对应的个性化菜单
//     *  65302    没有相应的用户
//     *  65303    没有默认菜单,不能创建个性化菜单
//     *  65304    MatchRule信息为空
//     *  65305    个性化菜单数量受限
//     *  65306    不支持个性化菜单的帐号
//     *  65307    个性化菜单信息为空
//     *  65308    包含没有响应类型的button
//     *  65309    个性化菜单开关处于关闭状态
//     *  65310    填写了省份或城市信息,国家信息不能为空
//     *  65311    填写了城市信息,省份信息不能为空
//     *  65312    不合法的国家信息
//     *  65313    不合法的省份信息
//     *  65314    不合法的城市信息
//     *  65316    该公众号的菜单设置了过多的域名外跳(最多跳转到3个域名的链接)
//     *  65317    不合法的URL
//     *  9001001    POST数据参数不合法
//     *  9001002    远端服务不可用
//     *  9001003    Ticket不合法
//     *  9001004    获取摇周边用户信息失败
//     *  9001005    获取商户信息失败
//     *  9001006    获取OpenID失败
//     *  9001007    上传文件缺失
//     *  9001008    上传素材的文件类型不合法
//     *  9001009    上传素材的文件尺寸不合法
//     *  9001010    上传失败
//     *  9001020    帐号不合法
//     *  9001021    已有设备激活率低于50%,不能新增设备
//     *  9001022    设备申请数不合法,必须为大于0的数字
//     *  9001023    已存在审核中的设备ID申请
//     *  9001024    一次查询设备ID数量不能超过50
//     *  9001025    设备ID不合法
//     *  9001026    页面ID不合法
//     *  9001027    页面参数不合法
//     *  9001028    一次删除页面ID数量不能超过10
//     *  9001029    页面已应用在设备中,请先解除应用关系再删除
//     *  9001030    一次查询页面ID数量不能超过50
//     *  9001031    时间区间不合法
//     *  9001032    保存设备与页面的绑定关系参数错误
//     *  9001033    门店ID不合法
//     *  9001034    设备备注信息过长
//     *  9001035    设备申请参数不合法
//     *  9001036    查询起始值begin不合法
//     */
//    private Integer resultCode;
//
//    /** 返回码对应信息 ***/
//    private String msg;
//
//    public Integer getResultCode() {
//        return resultCode;
//    }
//
//    public void setResultCode(Integer resultCode) {
//        this.resultCode = resultCode;
//    }
//
//    public WechatResponse(Integer resultCode) {
//        this.resultCode = resultCode;
//    }
//
//    public String getMsg() {
//        switch (resultCode) {
//        case -1:
//            msg="系统繁忙,此时请开发者稍候再试";
//            break;
//        case 0:
//            msg="请求成功";
//            break;
//        case 40001:
//            msg="获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口";
//            break;
//        case 40002:
//            msg="不合法的凭证类型";
//            break;
//        case 40003:
//            msg="不合法的OpenID,请开发者确认OpenID(该用户)是否已关注公众号,或是否是其他公众号的OpenID";
//            break;
//        case 40004:
//            msg="不合法的媒体文件类型";
//            break;
//        case 40005:
//            msg="不合法的文件类型";
//            break;
//        case 40006:
//            msg="不合法的文件大小";
//            break;
//        case 40007:
//            msg="不合法的媒体文件id";
//            break;
//        case 40008:
//            msg="不合法的消息类型";
//            break;
//        case 40009:
//            msg="不合法的图片文件大小";
//            break;
//        case 40010:
//            msg="不合法的语音文件大小";
//            break;
//        case 40011:
//            msg="不合法的视频文件大小";
//            break;
//        case 40012:
//            msg="不合法的缩略图文件大小";
//            break;
//        case 40013:
//            msg="不合法的AppID,请开发者检查AppID的正确性,避免异常字符,注意大小写";
//            break;
//        case 40014:
//            msg="不合法的access_token,请开发者认真比对access_token的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口";
//            break;
//        case 40015:
//            msg="不合法的菜单类型";
//            break;
//        case 40016:
//            msg="不合法的按钮个数";
//            break;
//        case 40017:
//            msg="不合法的按钮个数";
//            break;
//        case 40018:
//            msg="不合法的按钮名字长度";
//            break;
//        case 40019:
//            msg="不合法的按钮KEY长度";
//            break;
//        case 40020:
//            msg="不合法的按钮URL长度";
//            break;
//        case 40021:
//            msg="不合法的菜单版本号";
//            break;
//        case 40022:
//            msg="不合法的子菜单级数";
//            break;
//        case 40023:
//            msg="不合法的子菜单按钮个数";
//            break;
//        case 40024:
//            msg="不合法的子菜单按钮类型";
//            break;
//        case 40025:
//            msg="不合法的子菜单按钮名字长度";
//            break;
//        case 40026:
//            msg="不合法的子菜单按钮KEY长度";
//            break;
//        case 40027:
//            msg="不合法的子菜单按钮URL长度";
//            break;
//        case 40028:
//            msg="不合法的自定义菜单使用用户";
//            break;
//        case 40029:
//            msg="不合法的oauth_code";
//            break;
//        case 40030:
//            msg="不合法的refresh_token";
//            break;
//        case 40031:
//            msg="不合法的openid列表";
//            break;
//        case 40032:
//            msg="不合法的openid列表长度";
//            break;
//        case 40033:
//            msg="不合法的请求字符,不能包含\\uxxxx格式的字符";
//            break;
//        case 40035:
//            msg="不合法的参数";
//            break;
//        case 40038:
//            msg="不合法的请求格式";
//            break;
//        case 40039:
//            msg="不合法的URL长度";
//            break;
//        case 40050:
//            msg="不合法的分组id";
//            break;
//        case 40051:
//            msg="分组名字不合法";
//            break;
//        case 40060:
//            msg="删除单篇图文时,指定的 article_idx 不合法";
//            break;
//        case 40117:
//            msg="分组名字不合法";
//            break;
//        case 40118:
//            msg="media_id大小不合法";
//            break;
//        case 40119:
//            msg="button类型错误";
//            break;
//        case 40120:
//            msg="button类型错误";
//            break;
//        case 40121:
//            msg="不合法的media_id类型";
//            break;
//        case 40132:
//            msg="微信号不合法";
//            break;
//        case 40137:
//            msg="不支持的图片格式";
//            break;
//        case 40155:
//            msg="请勿添加其他公众号的主页链接";
//            break;
//        case 41001:
//            msg="缺少access_token参数";
//            break;
//        case 41002:
//            msg="缺少appid参数";
//            break;
//        case 41003:
//            msg="缺少refresh_token参数";
//            break;
//        case 41004:
//            msg="缺少secret参数";
//            break;
//        case 41005:
//            msg="缺少多媒体文件数据";
//            break;
//        case 41006:
//            msg="缺少media_id参数";
//            break;
//        case 41007:
//            msg="缺少子菜单数据";
//            break;
//        case 41008:
//            msg="缺少oauth code";
//            break;
//        case 41009:
//            msg="缺少openid";
//            break;
//        case 42001:
//            msg="access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明";
//            break;
//        case 42002:
//            msg="refresh_token超时";
//            break;
//        case 42003:
//            msg="oauth_code超时";
//            break;
//        case 42007:
//            msg="用户修改微信密码,accesstoken和refreshtoken失效,需要重新授权";
//            break;
//        case 43001:
//            msg="需要GET请求";
//            break;
//        case 43002:
//            msg="需要POST请求";
//            break;
//        case 43003:
//            msg="需要HTTPS请求";
//            break;
//        case 43004:
//            msg="需要接收者关注";
//            break;
//        case 43005:
//            msg="需要好友关系";
//            break;
//        case 43019:
//            msg="需要将接收者从黑名单中移除";
//            break;
//        case 44001:
//            msg="多媒体文件为空";
//            break;
//        case 44002:
//            msg="POST的数据包为空";
//            break;
//        case 44003:
//            msg="图文消息内容为空";
//            break;
//        case 44004:
//            msg="文本消息内容为空";
//            break;
//        case 45001:
//            msg="多媒体文件大小超过限制";
//            break;
//        case 45002:
//            msg="消息内容超过限制";
//            break;
//        case 45003:
//            msg="标题字段超过限制";
//            break;
//        case 45004:
//            msg="描述字段超过限制";
//            break;
//        case 45005:
//            msg="链接字段超过限制";
//            break;
//        case 45006:
//            msg="图片链接字段超过限制";
//            break;
//        case 45007:
//            msg="语音播放时间超过限制";
//            break;
//        case 45008:
//            msg="图文消息超过限制";
//            break;
//        case 45009:
//            msg="接口调用超过限制";
//            break;
//        case 45010:
//            msg="创建菜单个数超过限制";
//            break;
//        case 45011:
//            msg="API调用太频繁,请稍候再试";
//            break;
//        case 45015:
//            msg="回复时间超过限制";
//            break;
//        case 45016:
//            msg="系统分组,不允许修改";
//            break;
//        case 45017:
//            msg="分组名字过长";
//            break;
//        case 45018:
//            msg="分组数量超过上限";
//            break;
//        case 45047:
//            msg="客服接口下行条数超过上限";
//            break;
//        case 46001:
//            msg="不存在媒体数据";
//            break;
//        case 46002:
//            msg="不存在的菜单版本";
//            break;
//        case 46003:
//            msg="不存在的菜单数据";
//            break;
//        case 46004:
//            msg="不存在的用户";
//            break;
//        case 47001:
//            msg="解析JSON/XML内容错误";
//            break;
//        case 48001:
//            msg="api功能未授权,请确认公众号已获得该接口,可以在公众平台官网-开发者中心页中查看接口权限";
//            break;
//        case 48002:
//            msg="粉丝拒收消息(粉丝在公众号选项中,关闭了“接收消息”)";
//            break;
//        case 48004:
//            msg="api接口被封禁,请登录mp.weixin.qq.com查看详情";
//            break;
//        case 48005:
//            msg="api禁止删除被自动回复和自定义菜单引用的素材";
//            break;
//        case 48006:
//            msg="api禁止清零调用次数,因为清零次数达到上限";
//            break;
//        case 50001:
//            msg="用户未授权该api";
//            break;
//        case 50002:
//            msg="用户受限,可能是违规后接口被封禁";
//            break;
//        case 61451:
//            msg="参数错误(invalid parameter)";
//            break;
//        case 61452:
//            msg="无效客服账号(invalid kf_account)";
//            break;
//        case 61453:
//            msg="客服帐号已存在(kf_account exsited)";
//            break;
//        case 61454:
//            msg="客服帐号名长度超过限制(仅允许10个英文字符,不包括@及@后的公众号的微信号)(invalid kf_acount length)";
//            break;
//        case 61455:
//            msg="客服帐号名包含非法字符(仅允许英文+数字)(illegal character in kf_account)";
//            break;
//        case 61456:
//            msg="客服帐号个数超过限制(10个客服账号)(kf_account count exceeded)";
//            break;
//        case 61457:
//            msg="无效头像文件类型(invalid file type)";
//            break;
//        case 61450:
//            msg="系统错误(system error)";
//            break;
//        case 61500:
//            msg="日期格式错误";
//            break;
//        case 65301:
//            msg="不存在此menuid对应的个性化菜单";
//            break;
//        case 65302:
//            msg="没有相应的用户";
//            break;
//        case 65303:
//            msg="没有默认菜单,不能创建个性化菜单";
//            break;
//        case 65304:
//            msg="MatchRule信息为空";
//            break;
//        case 65305:
//            msg="个性化菜单数量受限";
//            break;
//        case 65306:
//            msg="不支持个性化菜单的帐号";
//            break;
//        case 65307:
//            msg="个性化菜单信息为空";
//            break;
//        case 65308:
//            msg="包含没有响应类型的button";
//            break;
//        case 65309:
//            msg="个性化菜单开关处于关闭状态";
//            break;
//        case 65310:
//            msg="填写了省份或城市信息,国家信息不能为空";
//            break;
//        case 65311:
//            msg="填写了城市信息,省份信息不能为空";
//            break;
//        case 65312:
//            msg="不合法的国家信息";
//            break;
//        case 65313:
//            msg="不合法的省份信息";
//            break;
//        case 65314:
//            msg="不合法的城市信息";
//            break;
//        case 65316:
//            msg="该公众号的菜单设置了过多的域名外跳(最多跳转到3个域名的链接)";
//            break;
//        case 65317:
//            msg="不合法的URL";
//            break;
//        case 9001001:
//            msg="POST数据参数不合法";
//            break;
//        case 9001002:
//            msg="远端服务不可用";
//            break;
//        case 9001003:
//            msg="Ticket不合法";
//            break;
//        case 9001004:
//            msg="获取摇周边用户信息失败";
//            break;
//        case 9001005:
//            msg="获取商户信息失败";
//            break;
//        case 9001006:
//            msg="获取OpenID失败";
//            break;
//        case 9001007:
//            msg="上传文件缺失";
//            break;
//        case 9001008:
//            msg="上传素材的文件类型不合法";
//            break;
//        case 9001009:
//            msg="上传素材的文件尺寸不合法";
//            break;
//        case 9001010:
//            msg="上传失败";
//            break;
//        case 9001020:
//            msg="帐号不合法";
//            break;
//        case 9001021:
//            msg="已有设备激活率低于50%,不能新增设备";
//            break;
//        case 9001022:
//            msg="设备申请数不合法,必须为大于0的数字";
//            break;
//        case 9001023:
//            msg="已存在审核中的设备ID申请";
//            break;
//        case 9001024:
//            msg="一次查询设备ID数量不能超过50";
//            break;
//        case 9001025:
//            msg="设备ID不合法";
//            break;
//        case 9001026:
//            msg="页面ID不合法";
//            break;
//        case 9001027:
//            msg="页面参数不合法";
//            break;
//        case 9001028:
//            msg="一次删除页面ID数量不能超过10";
//            break;
//        case 9001029:
//            msg="页面已应用在设备中,请先解除应用关系再删除";
//            break;
//        case 9001030:
//            msg="一次查询页面ID数量不能超过50";
//            break;
//        case 9001031:
//            msg="时间区间不合法";
//            break;
//        case 9001032:
//            msg="保存设备与页面的绑定关系参数错误";
//            break;
//        case 9001033:
//            msg="门店ID不合法";
//            break;
//        case 9001034:
//            msg="设备备注信息过长";
//            break;
//        case 9001035:
//            msg="设备申请参数不合法";
//            break;
//        case 9001036:
//            msg="查询起始值begin不合法";
//            break;
//        default:
//            msg = resultCode+":其他错误";
//            break;
//        }
//        return msg;
//    }
//}

+ 138 - 138
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WechatConfigController.java

@ -1,138 +1,138 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.base.wx.WxWechatDO;
import com.yihu.jw.business.wx.service.WechatService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.restmodel.base.wx.WxWechatVO;
import com.yihu.jw.rm.base.WechatRequestMapping;
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.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/5/11.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信相关操作", description = "微信相关操作")
public class WechatConfigController extends EnvelopRestController {
    @Autowired
    private WechatService wechatService;
    @PostMapping(value = WechatRequestMapping.WxConfig.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建微信配置", notes = "创建微信配置")
    public Envelop createWechat(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            WxWechatDO wechat = toEntity(jsonData, WxWechatDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_create, wechatService.createWechat(wechat));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PutMapping(value = WechatRequestMapping.WxConfig.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改微信配置", notes = "修改微信配置")
    public Envelop updateWechat(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            WxWechatDO wechat = toEntity(jsonData, WxWechatDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_update, wechatService.updateWxchat(wechat));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @DeleteMapping(value = WechatRequestMapping.WxConfig.api_delete)
    @ApiOperation(value = "删除微信配置", notes = "删除微信配置")
    public Envelop deleteWechat(
            @ApiParam(name = "ids", value = "ids")
            @RequestParam(value = "ids", required = true) String ids,
            @ApiParam(name = "userId", value = "userId")
            @RequestParam(value = "userId", required = true) String userId,
            @ApiParam(name = "userName", value = "userName")
            @RequestParam(value = "userName", required = true) String userName
            ) {
        try {
            wechatService.deleteWechat(ids,userId,userName);
            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_delete );
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @GetMapping(value = WechatRequestMapping.WxConfig.api_getById)
    @ApiOperation(value = "根据Id查找微信配置", notes = "根据code查找微信配置")
    public Envelop findById(
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id", required = true) String id
    ) {
        try {
            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_find, wechatService.findById(id));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @RequestMapping(value = WechatRequestMapping.WxConfig.api_getWechats, method = RequestMethod.GET)
    @ApiOperation(value = "获取微信配置列表(分页)")
    public Envelop getWechats(
            @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 = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if(StringUtils.isBlank(sorts)){
            sorts = "-updateTime";
        }
        //得到list数据
        List<WxWechatDO> list = wechatService.search(fields, filters, sorts, page, size);
        //获取总数
        long count=wechatService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<WxWechatVO> WxWechatVOs = convertToModels(list, new ArrayList<>(list.size()), WxWechatVO.class, fields);
        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxConfig.message_success_find_functions,WxWechatVOs, page, size,count);
    }
    @GetMapping(value = WechatRequestMapping.WxConfig.api_getWechatNoPage)
    @ApiOperation(value = "获取微信列表配置,不分页")
    public Envelop getWechatNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        //得到list数据
        List<WxWechatDO> list = wechatService.search(fields,filters,sorts);
        //封装返回格式
        List<WxWechatVO> WxWechatVOs = convertToModels(list, new ArrayList<>(list.size()), WxWechatVO.class, fields);
        return Envelop.getSuccessList(WechatRequestMapping.WxConfig.message_success_find_functions,WxWechatVOs);
    }
}
//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.service.WechatService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.restmodel.base.wx.WxWechatVO;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//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.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by chenweida on 2017/5/11.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信相关操作", description = "微信相关操作")
//public class WechatConfigController extends EnvelopRestController {
//    @Autowired
//    private WechatService wechatService;
//
//    @PostMapping(value = WechatRequestMapping.WxConfig.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信配置", notes = "创建微信配置")
//    public Envelop createWechat(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxWechatDO wechat = toEntity(jsonData, WxWechatDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_create, wechatService.createWechat(wechat));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PutMapping(value = WechatRequestMapping.WxConfig.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信配置", notes = "修改微信配置")
//    public Envelop updateWechat(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxWechatDO wechat = toEntity(jsonData, WxWechatDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_update, wechatService.updateWxchat(wechat));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @DeleteMapping(value = WechatRequestMapping.WxConfig.api_delete)
//    @ApiOperation(value = "删除微信配置", notes = "删除微信配置")
//    public Envelop deleteWechat(
//            @ApiParam(name = "ids", value = "ids")
//            @RequestParam(value = "ids", required = true) String ids,
//            @ApiParam(name = "userId", value = "userId")
//            @RequestParam(value = "userId", required = true) String userId,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//            ) {
//        try {
//            wechatService.deleteWechat(ids,userId,userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxConfig.api_getById)
//    @ApiOperation(value = "根据Id查找微信配置", notes = "根据code查找微信配置")
//    public Envelop findById(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_find, wechatService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxConfig.api_getWechats, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信配置列表(分页)")
//    public Envelop getWechats(
//            @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 = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//        //得到list数据
//        List<WxWechatDO> list = wechatService.search(fields, filters, sorts, page, size);
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> WxWechatVOs = convertToModels(list, new ArrayList<>(list.size()), WxWechatVO.class, fields);
//
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxConfig.message_success_find_functions,WxWechatVOs, page, size,count);
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxConfig.api_getWechatNoPage)
//    @ApiOperation(value = "获取微信列表配置,不分页")
//    public Envelop getWechatNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<WxWechatDO> list = wechatService.search(fields,filters,sorts);
//        //封装返回格式
//        List<WxWechatVO> WxWechatVOs = convertToModels(list, new ArrayList<>(list.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessList(WechatRequestMapping.WxConfig.message_success_find_functions,WxWechatVOs);
//    }
//
//}

+ 47 - 47
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxAccessTokenController.java

@ -1,47 +1,47 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.base.wx.WxAccessTokenDO;
import com.yihu.jw.business.wx.service.WxAccessTokenService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.WechatRequestMapping;
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;
/**
 * Created by cyx on 2017/5/11.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信token模块", description = "微信token模块接口管理")
public class WxAccessTokenController extends EnvelopRestController {
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    /**
     * 根据wechatCode获取WxAccessToken
     * @param wechatId
     * @return MWxAccessToken
     * @throws Exception
     */
    @GetMapping(value = WechatRequestMapping.WxAccessToken.api_get)
    @ApiOperation(value = "根据wechatId获取最新的WxAccessToken")
    public Envelop getWxAccessToken(
            @ApiParam(name = "wechatId", value = "wechatId")
            @RequestParam(value = "wechatId") String wechatId) {
        try {
            WxAccessTokenDO wxAccessToken = wxAccessTokenService.getWxAccessTokenById(wechatId);
            return Envelop.getSuccess(WechatRequestMapping.WxAccessToken.message_success_get, wxAccessToken);
        }catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}
//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.base.wx.WxAccessTokenDO;
//import com.yihu.jw.business.wx.service.WxAccessTokenService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//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;
//
///**
// * Created by cyx on 2017/5/11.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信token模块", description = "微信token模块接口管理")
//public class WxAccessTokenController extends EnvelopRestController {
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//    /**
//     * 根据wechatCode获取WxAccessToken
//     * @param wechatId
//     * @return MWxAccessToken
//     * @throws Exception
//     */
//    @GetMapping(value = WechatRequestMapping.WxAccessToken.api_get)
//    @ApiOperation(value = "根据wechatId获取最新的WxAccessToken")
//    public Envelop getWxAccessToken(
//            @ApiParam(name = "wechatId", value = "wechatId")
//            @RequestParam(value = "wechatId") String wechatId) {
//        try {
//            WxAccessTokenDO wxAccessToken = wxAccessTokenService.getWxAccessTokenById(wechatId);
//            return Envelop.getSuccess(WechatRequestMapping.WxAccessToken.message_success_get, wxAccessToken);
//        }catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//}

+ 164 - 164
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxGraphicMessageController.java

@ -1,164 +1,164 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.base.wx.WxGraphicMessageDO;
import com.yihu.jw.business.wx.service.WxGraphicMessageService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.restmodel.base.wx.WxGraphicMessageVO;
import com.yihu.jw.rm.base.WechatRequestMapping;
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.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
 *   2017/5/11.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信图文相关操作", description = "微信图文相关操作")
public class WxGraphicMessageController extends EnvelopRestController {
    @Autowired
    private WxGraphicMessageService wxGraphicMessageService;
    @PostMapping(value = WechatRequestMapping.WxGraphicMessage.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建微信图文消息", notes = "创建微信图文消息")
    public Envelop createWxGraphicMessage(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            WxGraphicMessageDO WxGraphicMessage = toEntity(jsonData, WxGraphicMessageDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_create, wxGraphicMessageService.createWxGraphicMessage(WxGraphicMessage));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PutMapping(value = WechatRequestMapping.WxGraphicMessage.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改微信图文消息", notes = "修改微信图文消息")
    public Envelop updateWxGraphicMessage(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            WxGraphicMessageDO WxGraphicMessage = toEntity(jsonData, WxGraphicMessageDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_update, wxGraphicMessageService.updateWxGraphicMessage(WxGraphicMessage));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @DeleteMapping(value = WechatRequestMapping.WxGraphicMessage.api_delete)
    @ApiOperation(value = "删除微信图文消息", notes = "删除微信图文消息")
    public Envelop deleteWxGraphicMessage(
            @ApiParam(name = "codes", value = "codes")
            @RequestParam(value = "codes", required = true) String codes,
            @ApiParam(name = "userCode", value = "userCode")
            @RequestParam(value = "userCode", required = true) String userCode,
            @ApiParam(name = "userName", value = "userName")
            @RequestParam(value = "userName", required = true) String userName
    ) {
        try {
            wxGraphicMessageService.deleteWxGraphicMessage(codes, userCode, userName);
            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_delete );
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_getById)
    @ApiOperation(value = "根据code查找微信图文消息", notes = "根据code查找微信图文消息")
    public Envelop findByCode(
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id", required = true) String id
    ) {
        try {
            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_find, wxGraphicMessageService.findById(id));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @RequestMapping(value = WechatRequestMapping.WxGraphicMessage.api_getWxGraphicMessages, method = RequestMethod.GET)
    @ApiOperation(value = "获取微信图文消息列表(分页)")
    public Envelop getWxGraphicMessages(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,description,url,pic_url,remark,status")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if(StringUtils.isBlank(sorts)){
            sorts = "-updateTime";
        }
        //得到list数据
        List<WxGraphicMessageDO> list = wxGraphicMessageService.search(fields, filters, sorts, page, size);
        //获取总数
        long count=wxGraphicMessageService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<WxGraphicMessageVO> WxGraphicMessageVOs = convertToModels(list, new ArrayList<>(list.size()), WxGraphicMessageVO.class, fields);
        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxGraphicMessage.message_success_find_functions,WxGraphicMessageVOs, page, size,count);
    }
    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_getWxGraphicMessageNoPage)
    @ApiOperation(value = "获取图文消息列表,不分页")
    public Envelop getWxGraphicMessageNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,description,url,pic_url,remark,status")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        //得到list数据
        List<WxGraphicMessageDO> list = wxGraphicMessageService.search(fields,filters,sorts);
        //封装返回格式
        List<WxGraphicMessageVO> WxGraphicMessageVOs = convertToModels(list, new ArrayList<>(list.size()), WxGraphicMessageVO.class, fields);
        return Envelop.getSuccessList(WechatRequestMapping.WxGraphicMessage.message_success_find_functions,WxGraphicMessageVOs);
    }
    //@GetMapping(value = WlyyContants.WxGraphicMessage.api_sendGraphicMessages)
    //@ApiOperation(value = "发送图文消息")
    //public Envelop sendGraphicMessages(
    //        @ApiParam(name = "codes", value = "根据code发送微信图文消息,多个code用,分割")
    //        @RequestParam(value = "codes", required = true) String codes,HttpServletRequest request) throws Exception {
    //    String messages = wxGraphicMessageService.sendGraphicMessages(codes, request);
    //    return Envelop.getSuccess("成功",messages);
    //}
    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_sendGraphicMessages)
    @ApiOperation(value = "发送图文消息")
    @ResponseBody
    public String sendGraphicMessages(
            @ApiParam(name = "ids", value = "根据code发送微信图文消息,多个code用,分割")
            @RequestParam(value = "ids", required = true) String ids,
            @ApiParam(name = "fromUserName", value = "用户openid")
            @RequestParam(value = "fromUserName", required = true) String fromUserName,
            @ApiParam(name = "toUserName", value = "公众号")
            @RequestParam(value = "toUserName", required = true) String toUserName
            ) throws Exception {
        String messages = wxGraphicMessageService.sendGraphicMessages(ids, fromUserName,toUserName);
        return messages;
    }
}
//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.base.wx.WxGraphicMessageDO;
//import com.yihu.jw.business.wx.service.WxGraphicMessageService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.restmodel.base.wx.WxGraphicMessageVO;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//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.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// *   2017/5/11.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信图文相关操作", description = "微信图文相关操作")
//public class WxGraphicMessageController extends EnvelopRestController {
//    @Autowired
//    private WxGraphicMessageService wxGraphicMessageService;
//
//    @PostMapping(value = WechatRequestMapping.WxGraphicMessage.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信图文消息", notes = "创建微信图文消息")
//    public Envelop createWxGraphicMessage(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxGraphicMessageDO WxGraphicMessage = toEntity(jsonData, WxGraphicMessageDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_create, wxGraphicMessageService.createWxGraphicMessage(WxGraphicMessage));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @PutMapping(value = WechatRequestMapping.WxGraphicMessage.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信图文消息", notes = "修改微信图文消息")
//    public Envelop updateWxGraphicMessage(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxGraphicMessageDO WxGraphicMessage = toEntity(jsonData, WxGraphicMessageDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_update, wxGraphicMessageService.updateWxGraphicMessage(WxGraphicMessage));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @DeleteMapping(value = WechatRequestMapping.WxGraphicMessage.api_delete)
//    @ApiOperation(value = "删除微信图文消息", notes = "删除微信图文消息")
//    public Envelop deleteWxGraphicMessage(
//            @ApiParam(name = "codes", value = "codes")
//            @RequestParam(value = "codes", required = true) String codes,
//            @ApiParam(name = "userCode", value = "userCode")
//            @RequestParam(value = "userCode", required = true) String userCode,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxGraphicMessageService.deleteWxGraphicMessage(codes, userCode, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_getById)
//    @ApiOperation(value = "根据code查找微信图文消息", notes = "根据code查找微信图文消息")
//    public Envelop findByCode(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_find, wxGraphicMessageService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxGraphicMessage.api_getWxGraphicMessages, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信图文消息列表(分页)")
//    public Envelop getWxGraphicMessages(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,description,url,pic_url,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//        //得到list数据
//        List<WxGraphicMessageDO> list = wxGraphicMessageService.search(fields, filters, sorts, page, size);
//        //获取总数
//        long count=wxGraphicMessageService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxGraphicMessageVO> WxGraphicMessageVOs = convertToModels(list, new ArrayList<>(list.size()), WxGraphicMessageVO.class, fields);
//
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxGraphicMessage.message_success_find_functions,WxGraphicMessageVOs, page, size,count);
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_getWxGraphicMessageNoPage)
//    @ApiOperation(value = "获取图文消息列表,不分页")
//    public Envelop getWxGraphicMessageNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,description,url,pic_url,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<WxGraphicMessageDO> list = wxGraphicMessageService.search(fields,filters,sorts);
//        //封装返回格式
//        List<WxGraphicMessageVO> WxGraphicMessageVOs = convertToModels(list, new ArrayList<>(list.size()), WxGraphicMessageVO.class, fields);
//        return Envelop.getSuccessList(WechatRequestMapping.WxGraphicMessage.message_success_find_functions,WxGraphicMessageVOs);
//    }
//
//    //@GetMapping(value = WlyyContants.WxGraphicMessage.api_sendGraphicMessages)
//    //@ApiOperation(value = "发送图文消息")
//    //public Envelop sendGraphicMessages(
//    //        @ApiParam(name = "codes", value = "根据code发送微信图文消息,多个code用,分割")
//    //        @RequestParam(value = "codes", required = true) String codes,HttpServletRequest request) throws Exception {
//    //    String messages = wxGraphicMessageService.sendGraphicMessages(codes, request);
//    //    return Envelop.getSuccess("成功",messages);
//    //}
//
//    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_sendGraphicMessages)
//    @ApiOperation(value = "发送图文消息")
//    @ResponseBody
//    public String sendGraphicMessages(
//            @ApiParam(name = "ids", value = "根据code发送微信图文消息,多个code用,分割")
//            @RequestParam(value = "ids", required = true) String ids,
//            @ApiParam(name = "fromUserName", value = "用户openid")
//            @RequestParam(value = "fromUserName", required = true) String fromUserName,
//            @ApiParam(name = "toUserName", value = "公众号")
//            @RequestParam(value = "toUserName", required = true) String toUserName
//            ) throws Exception {
//        String messages = wxGraphicMessageService.sendGraphicMessages(ids, fromUserName,toUserName);
//        return messages;
//    }
//
//
//}

+ 236 - 236
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxMenuController.java

@ -1,236 +1,236 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.base.wx.WxMenuDO;
import com.yihu.jw.base.wx.WxWechatDO;
import com.yihu.jw.business.wx.WechatResponse;
import com.yihu.jw.business.wx.service.WechatService;
import com.yihu.jw.business.wx.service.WxMenuService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.restmodel.base.wx.WxMenuVO;
import com.yihu.jw.restmodel.base.wx.WxWechatVO;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信菜单相关操作", description = "微信菜单相关操作")
public class WxMenuController extends EnvelopRestController {
    @Autowired
    private WxMenuService wxMenuService;
    @Autowired
    private WechatService wechatService;
    @PostMapping(value = WechatRequestMapping.WxMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "添加微信菜单", notes = "添加微信菜单")
    public Envelop createWxMenu(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            WxMenuDO wxMenu = toEntity(jsonData, WxMenuDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_create, wxMenuService.createWxMenu(wxMenu));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PutMapping(value = WechatRequestMapping.WxMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改微信菜单", notes = "修改微信菜单")
    public Envelop updateWxMenu(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            WxMenuDO wxMenu = toEntity(jsonData, WxMenuDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update, wxMenuService.updateWxMenu(wxMenu));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @DeleteMapping(value = WechatRequestMapping.WxMenu.api_delete)
    @ApiOperation(value = "删除微信菜单", notes = "删除微信菜单")
    public Envelop deleteWxMenu(
            @ApiParam(name = "ids", value = "ids")
            @RequestParam(value = "ids", required = true) String ids,
            @ApiParam(name = "userId", value = "userId")
            @RequestParam(value = "userId", required = true) String userId,
            @ApiParam(name = "userName", value = "userName")
            @RequestParam(value = "userName", required = true) String userName
    ) {
        try {
            wxMenuService.deleteWxMenu(ids, userId, userName);
            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_delete );
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @GetMapping(value = WechatRequestMapping.WxMenu.api_getById)
    @ApiOperation(value = "根据code查找微信菜单", notes = "根据code查找微信菜单")
    public Envelop findByCode(
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id", required = true) String id
    ) {
        try {
            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findById(id));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @RequestMapping(value = WechatRequestMapping.WxMenu.api_getWxMenus, method = RequestMethod.GET)
    @ApiOperation(value = "获取微信菜单列表(分页)")
    public Envelop getWxMenus(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if(StringUtils.isBlank(sorts)){
            sorts = "-updateTime";
        }
        //得到微信列表数据
        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
        for(WxWechatDO wechat:wechats){
            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechat.getId());
            if (parentMenus.size()>0){
                wechat.setState("closed");
            }else{
                wechat.setState("open");
            }
        }
        //获取总数
        long count=wechatService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
    }
    @GetMapping(value = WechatRequestMapping.WxMenu.api_getWxMenuNoPage)
    @ApiOperation(value = "获取微信菜单列表,不分页")
    public Envelop getWxMenuNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        if(filters!=null){
            filters = "supMenucode=0;"+filters;
        }else{
            filters = "supMenucode=0;";
        }
        //得到list数据
        List<WxMenuDO> list = wxMenuService.search(fields,filters,sorts);
        for(WxMenuDO wxMenu:list){
            List<WxMenuDO> childMenus = wxMenuService.findChildMenus(wxMenu.getId());
            wxMenu.setChildren(childMenus);
        }
        //封装返回格式
        List<WxMenuVO> WxMenuVOs = convertToModels(list, new ArrayList<>(list.size()), WxMenuVO.class, fields);
        Map<String, String> map = wechatService.getAllWechatConfig();
        for(WxMenuVO menu:WxMenuVOs){
            menu.setWechatName(map.get(menu.getWechatCode()));
        }
        return Envelop.getSuccessList(WechatRequestMapping.WxMenu.message_success_find_functions,WxMenuVOs);
    }
    /**
     * 创建微信公众号菜单
     *
     * @return
     */
    @ApiOperation(value = "创建微信公众号菜单", notes = "创建微信公众号菜单")
    @RequestMapping(value = WechatRequestMapping.WxMenu.api_createMenu ,method = RequestMethod.GET)
    public Envelop createWechatMenu(
            @ApiParam(name = "wechatId", value = "", defaultValue = "")
            @RequestParam(value = "wechatId", required = true)String wechatId){
        try{
            JSONObject result = wxMenuService.createWechatMenu(wechatId);
            String errcode = result.get("errcode").toString();
            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
            String msg = wechatResponse.getMsg();
            return Envelop.getSuccess("成功",msg);
        }catch (Exception e){
            return Envelop.getSuccess("创建失败",e );
        }
    }
    /**
     * 根据微信code查找父菜单
     * @param wechatId
     * @return
     */
    @GetMapping(value = WechatRequestMapping.WxMenu.api_getParentMenu)
    @ApiOperation(value = "根据微信code查找父菜单", notes = "根据微信code查找父菜单")
    public Envelop getParentMenu(
            @ApiParam(name = "wechatId", value = "wechatId")
            @PathVariable(value = "wechatId", required = true) String wechatId
    ) {
        try {
            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechatId);
            for(WxMenuDO parentMenu:parentMenus){
                List<WxMenuDO> childMenus = wxMenuService.findChildMenus(parentMenu.getId());
                if (childMenus.size()>0){
                    parentMenu.setState("closed");
                }else{
                    parentMenu.setState("open");
                }
            }
            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, parentMenus);
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    /**
     * 根据父级菜单code查找子菜单
     * @param parentCode
     * @return
     */
    @GetMapping(value = WechatRequestMapping.WxMenu.api_getChildMenus)
    @ApiOperation(value = "根据父级菜单code查找子菜单", notes = "根据父级菜单code查找子菜单")
    public Envelop getChildMenus(
            @ApiParam(name = "parentCode", value = "parentCode")
            @PathVariable(value = "parentCode", required = true) String parentCode
    ) {
        try {
            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findChildMenus(parentCode));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}
//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.base.wx.WxMenuDO;
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.WechatResponse;
//import com.yihu.jw.business.wx.service.WechatService;
//import com.yihu.jw.business.wx.service.WxMenuService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.restmodel.base.wx.WxMenuVO;
//import com.yihu.jw.restmodel.base.wx.WxWechatVO;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang.StringUtils;
//import org.json.JSONObject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信菜单相关操作", description = "微信菜单相关操作")
//public class WxMenuController extends EnvelopRestController {
//
//    @Autowired
//    private WxMenuService wxMenuService;
//
//    @Autowired
//    private WechatService wechatService;
//
//    @PostMapping(value = WechatRequestMapping.WxMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "添加微信菜单", notes = "添加微信菜单")
//    public Envelop createWxMenu(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxMenuDO wxMenu = toEntity(jsonData, WxMenuDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_create, wxMenuService.createWxMenu(wxMenu));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PutMapping(value = WechatRequestMapping.WxMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信菜单", notes = "修改微信菜单")
//    public Envelop updateWxMenu(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxMenuDO wxMenu = toEntity(jsonData, WxMenuDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update, wxMenuService.updateWxMenu(wxMenu));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @DeleteMapping(value = WechatRequestMapping.WxMenu.api_delete)
//    @ApiOperation(value = "删除微信菜单", notes = "删除微信菜单")
//    public Envelop deleteWxMenu(
//            @ApiParam(name = "ids", value = "ids")
//            @RequestParam(value = "ids", required = true) String ids,
//            @ApiParam(name = "userId", value = "userId")
//            @RequestParam(value = "userId", required = true) String userId,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxMenuService.deleteWxMenu(ids, userId, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getById)
//    @ApiOperation(value = "根据code查找微信菜单", notes = "根据code查找微信菜单")
//    public Envelop findByCode(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxMenu.api_getWxMenus, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信菜单列表(分页)")
//    public Envelop getWxMenus(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//
//        //得到微信列表数据
//        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
//        for(WxWechatDO wechat:wechats){
//            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechat.getId());
//            if (parentMenus.size()>0){
//                wechat.setState("closed");
//            }else{
//                wechat.setState("open");
//            }
//        }
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getWxMenuNoPage)
//    @ApiOperation(value = "获取微信菜单列表,不分页")
//    public Envelop getWxMenuNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        if(filters!=null){
//            filters = "supMenucode=0;"+filters;
//        }else{
//            filters = "supMenucode=0;";
//        }
//        //得到list数据
//        List<WxMenuDO> list = wxMenuService.search(fields,filters,sorts);
//        for(WxMenuDO wxMenu:list){
//            List<WxMenuDO> childMenus = wxMenuService.findChildMenus(wxMenu.getId());
//            wxMenu.setChildren(childMenus);
//        }
//        //封装返回格式
//        List<WxMenuVO> WxMenuVOs = convertToModels(list, new ArrayList<>(list.size()), WxMenuVO.class, fields);
//        Map<String, String> map = wechatService.getAllWechatConfig();
//        for(WxMenuVO menu:WxMenuVOs){
//            menu.setWechatName(map.get(menu.getWechatCode()));
//        }
//        return Envelop.getSuccessList(WechatRequestMapping.WxMenu.message_success_find_functions,WxMenuVOs);
//    }
//
//    /**
//     * 创建微信公众号菜单
//     *
//     * @return
//     */
//    @ApiOperation(value = "创建微信公众号菜单", notes = "创建微信公众号菜单")
//    @RequestMapping(value = WechatRequestMapping.WxMenu.api_createMenu ,method = RequestMethod.GET)
//    public Envelop createWechatMenu(
//            @ApiParam(name = "wechatId", value = "", defaultValue = "")
//            @RequestParam(value = "wechatId", required = true)String wechatId){
//        try{
//            JSONObject result = wxMenuService.createWechatMenu(wechatId);
//            String errcode = result.get("errcode").toString();
//            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
//            String msg = wechatResponse.getMsg();
//            return Envelop.getSuccess("成功",msg);
//        }catch (Exception e){
//            return Envelop.getSuccess("创建失败",e );
//        }
//    }
//
//    /**
//     * 根据微信code查找父菜单
//     * @param wechatId
//     * @return
//     */
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getParentMenu)
//    @ApiOperation(value = "根据微信code查找父菜单", notes = "根据微信code查找父菜单")
//    public Envelop getParentMenu(
//            @ApiParam(name = "wechatId", value = "wechatId")
//            @PathVariable(value = "wechatId", required = true) String wechatId
//    ) {
//        try {
//            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechatId);
//            for(WxMenuDO parentMenu:parentMenus){
//                List<WxMenuDO> childMenus = wxMenuService.findChildMenus(parentMenu.getId());
//                if (childMenus.size()>0){
//                    parentMenu.setState("closed");
//                }else{
//                    parentMenu.setState("open");
//                }
//            }
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, parentMenus);
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    /**
//     * 根据父级菜单code查找子菜单
//     * @param parentCode
//     * @return
//     */
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getChildMenus)
//    @ApiOperation(value = "根据父级菜单code查找子菜单", notes = "根据父级菜单code查找子菜单")
//    public Envelop getChildMenus(
//            @ApiParam(name = "parentCode", value = "parentCode")
//            @PathVariable(value = "parentCode", required = true) String parentCode
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findChildMenus(parentCode));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//}

+ 188 - 188
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxTemplateController.java

@ -1,188 +1,188 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.business.wx.WechatResponse;
import com.yihu.jw.base.wx.Miniprogram;
import com.yihu.jw.base.wx.WxTemplateDO;
import com.yihu.jw.base.wx.WxWechatDO;
import com.yihu.jw.business.wx.service.WechatService;
import com.yihu.jw.business.wx.service.WxTemplateService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.restmodel.base.wx.WxTemplateVO;
import com.yihu.jw.restmodel.base.wx.WxWechatVO;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信模版相关操作", description = "微信模版相关操作")
public class WxTemplateController extends EnvelopRestController {
    @Autowired
    private WxTemplateService wxTemplateService;
    @Autowired
    private WechatService wechatService;
    @PostMapping(value = WechatRequestMapping.WxTemplate.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建微信模版", notes = "创建微信模版")
    public Envelop createWxTemplate(
            @ApiParam(name = "json_data", value = "微信模版json字符串")
            @RequestBody String jsonData) {
        try {
            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_create, wxTemplateService.createWxTemplate(WxTemplate));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PutMapping(value = WechatRequestMapping.WxTemplate.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改微信模版", notes = "修改微信模版")
    public Envelop updateWxTemplate(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        try {
            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_update, wxTemplateService.updateWxTemplate(WxTemplate));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @DeleteMapping(value = WechatRequestMapping.WxTemplate.api_delete)
    @ApiOperation(value = "删除微信模版", notes = "删除微信模版")
    public Envelop deleteWxTemplate(
            @ApiParam(name = "codes", value = "codes")
            @RequestParam(value = "codes", required = true) String codes,
            @ApiParam(name = "userCode", value = "userCode")
            @RequestParam(value = "userCode", required = true) String userCode,
            @ApiParam(name = "userName", value = "userName")
            @RequestParam(value = "userName", required = true) String userName
    ) {
        try {
            wxTemplateService.deleteWxTemplate(codes, userCode, userName);
            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_delete );
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getById)
    @ApiOperation(value = "根据code查找微信模版", notes = "根据code查找微信模版")
    public Envelop findById(
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id", required = true) String id
    ) {
        try {
            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_find, wxTemplateService.findById(id));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @RequestMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplates, method = RequestMethod.GET)
    @ApiOperation(value = "获取微信模版列表(分页)")
    public Envelop getWechats(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if(StringUtils.isBlank(sorts)){
            sorts = "-updateTime";
        }
        //得到微信列表数据
        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
        for(WxWechatDO wechat:wechats){
            List<WxTemplateDO> wxTemplates = wxTemplateService.findByWxId(wechat.getId());
            if (wxTemplates.size()>0){
                wechat.setState("closed");
            }else{
                wechat.setState("open");
            }
        }
        //获取总数
        long count=wechatService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
    }
    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplatesNoPage)
    @ApiOperation(value = "获取微信模版列表(不分页)")
    public Envelop getList(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        //得到list数据
        List<WxTemplateDO> list = wxTemplateService.search(fields,filters,sorts);
        //封装返回格式
        List<WxTemplateVO> mWxTemplateVOs = convertToModels(list, new ArrayList<>(list.size()), WxTemplateVO.class, fields);
        return Envelop.getSuccessList(WechatRequestMapping.WxTemplate.message_success_find_functions,mWxTemplateVOs);
    }
    @GetMapping(value = WechatRequestMapping.WxTemplate.api_sendTemplateMessage)
    @ApiOperation(value = "发送微信模板消息")
    @ResponseBody
    public Envelop sendTemplateMessage(
            @ApiParam(name="openid",value="微信用户的openid")
            @RequestParam String openid,
            @ApiParam(name="templateCode",value = "模板code")
            @RequestParam String templateCode,
            @ApiParam(name="url",value="模板跳转链接")
            @RequestParam(required = false) String url,
            @ApiParam(name="appid",value="所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)")
            @RequestParam(required = false) String appid,
            @ApiParam(name="pagepath",value="所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)")
            @RequestParam(required = false) String pagepath,
            @ApiParam(name="data",value="json字符串")
            @RequestParam String data
    ){
        try {
            Miniprogram miniprogram = null;
            if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(pagepath)){
                miniprogram = new Miniprogram();
                miniprogram.setAppid(appid);
                miniprogram.setPagepath(pagepath);
            }
            JSONObject jsonObject = wxTemplateService.sendTemplateMessage(openid, templateCode, url, data, miniprogram);
            String errcode = jsonObject.get("errcode").toString();
            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
            String msg = wechatResponse.getMsg();
            return Envelop.getSuccess("成功",msg);
        }catch (Exception exception) {
            return Envelop.getSuccess("error", exception);
        }
    }
}
//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.business.wx.WechatResponse;
//import com.yihu.jw.base.wx.Miniprogram;
//import com.yihu.jw.base.wx.WxTemplateDO;
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.service.WechatService;
//import com.yihu.jw.business.wx.service.WxTemplateService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.restmodel.base.wx.WxTemplateVO;
//import com.yihu.jw.restmodel.base.wx.WxWechatVO;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang.StringUtils;
//import org.json.JSONObject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信模版相关操作", description = "微信模版相关操作")
//public class WxTemplateController extends EnvelopRestController {
//    @Autowired
//    private WxTemplateService wxTemplateService;
//
//    @Autowired
//    private WechatService wechatService;
//
//    @PostMapping(value = WechatRequestMapping.WxTemplate.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信模版", notes = "创建微信模版")
//    public Envelop createWxTemplate(
//            @ApiParam(name = "json_data", value = "微信模版json字符串")
//            @RequestBody String jsonData) {
//        try {
//            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_create, wxTemplateService.createWxTemplate(WxTemplate));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PutMapping(value = WechatRequestMapping.WxTemplate.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信模版", notes = "修改微信模版")
//    public Envelop updateWxTemplate(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_update, wxTemplateService.updateWxTemplate(WxTemplate));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @DeleteMapping(value = WechatRequestMapping.WxTemplate.api_delete)
//    @ApiOperation(value = "删除微信模版", notes = "删除微信模版")
//    public Envelop deleteWxTemplate(
//            @ApiParam(name = "codes", value = "codes")
//            @RequestParam(value = "codes", required = true) String codes,
//            @ApiParam(name = "userCode", value = "userCode")
//            @RequestParam(value = "userCode", required = true) String userCode,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxTemplateService.deleteWxTemplate(codes, userCode, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getById)
//    @ApiOperation(value = "根据code查找微信模版", notes = "根据code查找微信模版")
//    public Envelop findById(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_find, wxTemplateService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplates, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信模版列表(分页)")
//    public Envelop getWechats(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//
//        //得到微信列表数据
//        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
//        for(WxWechatDO wechat:wechats){
//            List<WxTemplateDO> wxTemplates = wxTemplateService.findByWxId(wechat.getId());
//            if (wxTemplates.size()>0){
//                wechat.setState("closed");
//            }else{
//                wechat.setState("open");
//            }
//        }
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
//
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplatesNoPage)
//    @ApiOperation(value = "获取微信模版列表(不分页)")
//    public Envelop getList(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<WxTemplateDO> list = wxTemplateService.search(fields,filters,sorts);
//        //封装返回格式
//        List<WxTemplateVO> mWxTemplateVOs = convertToModels(list, new ArrayList<>(list.size()), WxTemplateVO.class, fields);
//        return Envelop.getSuccessList(WechatRequestMapping.WxTemplate.message_success_find_functions,mWxTemplateVOs);
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_sendTemplateMessage)
//    @ApiOperation(value = "发送微信模板消息")
//    @ResponseBody
//    public Envelop sendTemplateMessage(
//            @ApiParam(name="openid",value="微信用户的openid")
//            @RequestParam String openid,
//            @ApiParam(name="templateCode",value = "模板code")
//            @RequestParam String templateCode,
//            @ApiParam(name="url",value="模板跳转链接")
//            @RequestParam(required = false) String url,
//            @ApiParam(name="appid",value="所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)")
//            @RequestParam(required = false) String appid,
//            @ApiParam(name="pagepath",value="所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)")
//            @RequestParam(required = false) String pagepath,
//            @ApiParam(name="data",value="json字符串")
//            @RequestParam String data
//    ){
//        try {
//            Miniprogram miniprogram = null;
//            if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(pagepath)){
//                miniprogram = new Miniprogram();
//                miniprogram.setAppid(appid);
//                miniprogram.setPagepath(pagepath);
//            }
//            JSONObject jsonObject = wxTemplateService.sendTemplateMessage(openid, templateCode, url, data, miniprogram);
//            String errcode = jsonObject.get("errcode").toString();
//            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
//            String msg = wechatResponse.getMsg();
//            return Envelop.getSuccess("成功",msg);
//        }catch (Exception exception) {
//            return Envelop.getSuccess("error", exception);
//        }
//    }
//}

+ 27 - 27
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WechatDao.java

@ -1,27 +1,27 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.base.wx.WxWechatDO;
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 WechatDao extends PagingAndSortingRepository<WxWechatDO, String>, JpaSpecificationExecutor<WxWechatDO> {
    @Query("from WxWechatDO w where w.appId = ?1 and w.status!=-1")
    WxWechatDO findByAppId(String appId);
    @Query("from WxWechatDO w where w.appId = ?1 and w.id!= ?2 and w.status!=-1")
    WxWechatDO findByAppIdExcludeId(String appId, String id);
    @Query("from WxWechatDO w where w.id = ?1 and w.status!=-1")
    WxWechatDO findById(String id);
    @Query("from WxWechatDO w where w.status!=-1")
    List<WxWechatDO> findAll();
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.base.wx.WxWechatDO;
//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 WechatDao extends PagingAndSortingRepository<WxWechatDO, String>, JpaSpecificationExecutor<WxWechatDO> {
//
//    @Query("from WxWechatDO w where w.appId = ?1 and w.status!=-1")
//    WxWechatDO findByAppId(String appId);
//
//
//    @Query("from WxWechatDO w where w.appId = ?1 and w.id!= ?2 and w.status!=-1")
//    WxWechatDO findByAppIdExcludeId(String appId, String id);
//
//    @Query("from WxWechatDO w where w.id = ?1 and w.status!=-1")
//    WxWechatDO findById(String id);
//
//    @Query("from WxWechatDO w where w.status!=-1")
//    List<WxWechatDO> findAll();
//}

+ 17 - 17
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxAccessTokenDao.java

@ -1,17 +1,17 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.base.wx.WxAccessTokenDO;
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/18 0018.
 */
public interface WxAccessTokenDao extends PagingAndSortingRepository<WxAccessTokenDO, String>, JpaSpecificationExecutor<WxAccessTokenDO> {
    @Query("from WxAccessTokenDO w where w.wechatId =?1 order by w.addTimestamp desc")
    List<WxAccessTokenDO> getWxAccessTokenById(String wechatId);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.base.wx.WxAccessTokenDO;
//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/18 0018.
// */
//public interface WxAccessTokenDao extends PagingAndSortingRepository<WxAccessTokenDO, String>, JpaSpecificationExecutor<WxAccessTokenDO> {
//
//    @Query("from WxAccessTokenDO w where w.wechatId =?1 order by w.addTimestamp desc")
//    List<WxAccessTokenDO> getWxAccessTokenById(String wechatId);
//}

+ 15 - 15
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxGraphicMessageDao.java

@ -1,15 +1,15 @@
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);
}
//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);
//}

+ 47 - 47
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxMenuDao.java

@ -1,47 +1,47 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.base.wx.WxMenuDO;
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/19 0019.
 */
public interface WxMenuDao  extends PagingAndSortingRepository<WxMenuDO, String>, JpaSpecificationExecutor<WxMenuDO> {
    @Query("from WxMenuDO m where m.id = ?1 and m.status = 1")
    WxMenuDO findById(String id);
    @Query("from WxMenuDO m where m.wechatId =?1 and m.status = 1 order  by m.supMenuid ,m.sort")
    List<WxMenuDO> findByWechatId(String wechatId);
    @Query("from WxMenuDO m where m.wechatId = ?1 and  m.supMenuid= ?2 and m.status =1 order by m.sort")
    List<WxMenuDO> findChildMenus(String wechatId, String supMenuid);
    @Query("from WxMenuDO m where  m.supMenuid= ?1 and m.status =1 order by m.sort")
    List<WxMenuDO> findChildMenus( String supMenuid);
    /**
     * 根据wechatId判断父菜单的sort是否重复
     * @param wechatId
     * @param sort
     */
    @Query("from WxMenuDO m where m.wechatId = ?1 and m.status =1 and m.sort =?2 and m.supMenuid ='0' and m.id != ?3")
    WxMenuDO findByWechatIdExcludeSortFromParent(String wechatId, Integer sort,String id);
    /**
     * 根据wechatId,supMenucode判断子菜单的sort是否重复
     * @param wechatId
     * @param sort
     */
    @Query("from WxMenuDO m where m.wechatId = ?1 and m.status =1 and m.sort =?2 and m.supMenuid =?3 and m.id != ?4")
    WxMenuDO findByWechatIdExcludeSortFromChild(String wechatId, Integer sort,String supMenuid,String id);
    @Query("from WxMenuDO m where m.wechatId =?1 and m.status = 1 and  m.supMenuid = '0' order by m.supMenuid ,m.sort")
    List<WxMenuDO> findParentMenuByWechatId(String wechatId);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.base.wx.WxMenuDO;
//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/19 0019.
// */
//public interface WxMenuDao  extends PagingAndSortingRepository<WxMenuDO, String>, JpaSpecificationExecutor<WxMenuDO> {
//
//
//    @Query("from WxMenuDO m where m.id = ?1 and m.status = 1")
//    WxMenuDO findById(String id);
//
//    @Query("from WxMenuDO m where m.wechatId =?1 and m.status = 1 order  by m.supMenuid ,m.sort")
//    List<WxMenuDO> findByWechatId(String wechatId);
//
//    @Query("from WxMenuDO m where m.wechatId = ?1 and  m.supMenuid= ?2 and m.status =1 order by m.sort")
//    List<WxMenuDO> findChildMenus(String wechatId, String supMenuid);
//
//    @Query("from WxMenuDO m where  m.supMenuid= ?1 and m.status =1 order by m.sort")
//    List<WxMenuDO> findChildMenus( String supMenuid);
//
//    /**
//     * 根据wechatId判断父菜单的sort是否重复
//     * @param wechatId
//     * @param sort
//     */
//    @Query("from WxMenuDO m where m.wechatId = ?1 and m.status =1 and m.sort =?2 and m.supMenuid ='0' and m.id != ?3")
//    WxMenuDO findByWechatIdExcludeSortFromParent(String wechatId, Integer sort,String id);
//
//    /**
//     * 根据wechatId,supMenucode判断子菜单的sort是否重复
//     * @param wechatId
//     * @param sort
//     */
//    @Query("from WxMenuDO m where m.wechatId = ?1 and m.status =1 and m.sort =?2 and m.supMenuid =?3 and m.id != ?4")
//    WxMenuDO findByWechatIdExcludeSortFromChild(String wechatId, Integer sort,String supMenuid,String id);
//
//    @Query("from WxMenuDO m where m.wechatId =?1 and m.status = 1 and  m.supMenuid = '0' order by m.supMenuid ,m.sort")
//    List<WxMenuDO> findParentMenuByWechatId(String wechatId);
//
//}

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

@ -1,21 +1,21 @@
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);
}
//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);
//}

+ 114 - 114
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatService.java

@ -1,114 +1,114 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.base.wx.WxWechatDO;
import com.yihu.jw.business.wx.dao.WechatDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.rm.base.WechatRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.Transient;
import java.util.*;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
@Service
public class WechatService extends BaseJpaService<WxWechatDO, WechatDao> {
    @Autowired
    private WechatDao wechatDao;
    @Transient
    public WxWechatDO createWechat(WxWechatDO wechat) {
        String code = UUID.randomUUID().toString().replaceAll("-", "");
        wechat.setId(code);
        if (StringUtils.isEmpty(wechat.getSaasId())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getStatus())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_status_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getType())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_type_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getName())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_name_is_null, ExceptionCode.common_error_params_code);
        }
        WxWechatDO wechatTem = wechatDao.findByAppId(wechat.getAppId());
        if (wechatTem != null) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_exist, ExceptionCode.common_error_params_code);
        }
        return wechatDao.save(wechat);
    }
    @Transient
    public WxWechatDO updateWxchat(WxWechatDO wechat) {
        if (StringUtils.isEmpty(wechat.getSaasId())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getStatus())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_status_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getType())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_type_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getName())) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_name_is_null, ExceptionCode.common_error_params_code);
        }
        WxWechatDO wechat1 = findById(wechat.getId());
        if (wechat1 == null) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
        }
        WxWechatDO wechatTem = wechatDao.findByAppIdExcludeId(wechat.getAppId(), wechat.getId());
        if (wechatTem != null) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_exist, ExceptionCode.common_error_params_code);
        }
        return wechatDao.save(wechat);
    }
    public WxWechatDO findById(String id) {
        return wechatDao.findById(id);
    }
    @Transient
    public void deleteWechat(String ids, String userId, String userName) {
        if (!StringUtils.isEmpty(ids)) {
            String[] codeArray = ids.split(",");
            for (String code : codeArray) {
                WxWechatDO wxWechat = wechatDao.findById(code);
                if (wxWechat == null) {
                    throw new ApiException(WechatRequestMapping.WxConfig.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
                }
                wxWechat.setStatus(-1);
                wxWechat.setUpdateUser(userId);
                wxWechat.setUpdateUserName(userName);
                wechatDao.save(wxWechat);
            }
        }
    }
    public List<WxWechatDO> findAll() {
        return wechatDao.findAll();
    }
    /**
     * key为code ,value为微信名字
     *
     * @return
     */
    public Map<String, String> getAllWechatConfig() {
        List<WxWechatDO> wechats = findAll();
        Map<String, String> map = new HashMap<>();
        if (null != wechats) {
            for (WxWechatDO wx : wechats) {
                map.put(wx.getId(), wx.getName());
            }
        }
        return map;
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.dao.WechatDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import javax.persistence.Transient;
//import java.util.*;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//@Service
//public class WechatService extends BaseJpaService<WxWechatDO, WechatDao> {
//
//    @Autowired
//    private WechatDao wechatDao;
//
//    @Transient
//    public WxWechatDO createWechat(WxWechatDO wechat) {
//        String code = UUID.randomUUID().toString().replaceAll("-", "");
//        wechat.setId(code);
//        if (StringUtils.isEmpty(wechat.getSaasId())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wechat.getStatus())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_status_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wechat.getType())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_type_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wechat.getName())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_name_is_null, ExceptionCode.common_error_params_code);
//        }
//        WxWechatDO wechatTem = wechatDao.findByAppId(wechat.getAppId());
//        if (wechatTem != null) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_exist, ExceptionCode.common_error_params_code);
//        }
//        return wechatDao.save(wechat);
//    }
//
//    @Transient
//    public WxWechatDO updateWxchat(WxWechatDO wechat) {
//        if (StringUtils.isEmpty(wechat.getSaasId())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wechat.getStatus())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_status_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wechat.getType())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_type_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wechat.getName())) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_name_is_null, ExceptionCode.common_error_params_code);
//        }
//        WxWechatDO wechat1 = findById(wechat.getId());
//        if (wechat1 == null) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        WxWechatDO wechatTem = wechatDao.findByAppIdExcludeId(wechat.getAppId(), wechat.getId());
//        if (wechatTem != null) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_exist, ExceptionCode.common_error_params_code);
//        }
//        return wechatDao.save(wechat);
//    }
//
//
//    public WxWechatDO findById(String id) {
//        return wechatDao.findById(id);
//    }
//
//    @Transient
//    public void deleteWechat(String ids, String userId, String userName) {
//        if (!StringUtils.isEmpty(ids)) {
//            String[] codeArray = ids.split(",");
//            for (String code : codeArray) {
//                WxWechatDO wxWechat = wechatDao.findById(code);
//                if (wxWechat == null) {
//                    throw new ApiException(WechatRequestMapping.WxConfig.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
//                }
//                wxWechat.setStatus(-1);
//                wxWechat.setUpdateUser(userId);
//                wxWechat.setUpdateUserName(userName);
//                wechatDao.save(wxWechat);
//            }
//        }
//    }
//
//    public List<WxWechatDO> findAll() {
//        return wechatDao.findAll();
//    }
//
//    /**
//     * key为code ,value为微信名字
//     *
//     * @return
//     */
//    public Map<String, String> getAllWechatConfig() {
//        List<WxWechatDO> wechats = findAll();
//        Map<String, String> map = new HashMap<>();
//        if (null != wechats) {
//            for (WxWechatDO wx : wechats) {
//                map.put(wx.getId(), wx.getName());
//            }
//        }
//        return map;
//    }
//}

+ 96 - 96
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxAccessTokenService.java

@ -1,96 +1,96 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.base.wx.WxAccessTokenDO;
import com.yihu.jw.base.wx.WxWechatDO;
import com.yihu.jw.business.wx.dao.WechatDao;
import com.yihu.jw.business.wx.dao.WxAccessTokenDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.jw.util.HttpUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * Created by Administrator on 2017/5/18 0018.
 */
@Service
public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAccessTokenDao> {
    private Logger logger= LoggerFactory.getLogger(WxAccessTokenService.class);
    @Autowired
    private WxAccessTokenDao wxAccessTokenDao;
    @Autowired
    private WechatDao wechatDao;
    /**
     * 根据wechatCode查找最新一条
     * @param wechatId
     * @return
     */
    public WxAccessTokenDO getWxAccessTokenById(String wechatId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findById(wechatId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wechatId);
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 1000)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String result = HttpUtil.sendGet(token_url, params);
            logger.info("--------------微信返回结果:"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wechatId);
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.base.wx.WxAccessTokenDO;
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.dao.WechatDao;
//import com.yihu.jw.business.wx.dao.WxAccessTokenDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.jw.util.HttpUtil;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import java.util.Date;
//import java.util.List;
//import java.util.UUID;
//
///**
// * Created by Administrator on 2017/5/18 0018.
// */
//@Service
//public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAccessTokenDao> {
//
//
//    private Logger logger= LoggerFactory.getLogger(WxAccessTokenService.class);
//
//    @Autowired
//    private WxAccessTokenDao wxAccessTokenDao;
//
//    @Autowired
//    private WechatDao wechatDao;
//
//    /**
//     * 根据wechatCode查找最新一条
//     * @param wechatId
//     * @return
//     */
//    public WxAccessTokenDO getWxAccessTokenById(String wechatId) {
//        try {
//            //根据wechatCode查找出appid和appSecret
//            WxWechatDO wxWechat = wechatDao.findById(wechatId);
//            if(wxWechat==null){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wechatId);
//            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
//                for (WxAccessTokenDO accessToken : wxAccessTokens) {
//                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 1000)) {
//                        return accessToken;
//                    } else {
//                        wxAccessTokenDao.delete(accessToken);
//                        break;
//                    }
//                }
//            }
//            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
//            String appId="";
//            String appSecret="";
//            appId = wxWechat.getAppId();
//            appSecret = wxWechat.getAppSecret();
//            if (StringUtils.isEmpty(appId)){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
//            }
//            if (StringUtils.isEmpty(appSecret)){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
//            }
//            String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
//            String result = HttpUtil.sendGet(token_url, params);
//            logger.info("--------------微信返回结果:"+result+"---------------");
//            JSONObject json = new JSONObject(result);
//            if (json.has("access_token")) {
//                String token = json.get("access_token").toString();
//                String expires_in = json.get("expires_in").toString();
//                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
//                newaccessToken.setAccessToken(token);
//                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
//                newaccessToken.setAddTimestamp(System.currentTimeMillis());
//                newaccessToken.setCzrq(new Date());
//                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
//                newaccessToken.setWechatId(wechatId);
//                wxAccessTokenDao.save(newaccessToken);
//                return newaccessToken;
//            } else {
//                return null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
//}

+ 177 - 177
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxGraphicMessageService.java

@ -1,177 +1,177 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.base.wx.WxGraphicMessageDO;
import com.yihu.jw.business.wx.dao.WxGraphicMessageDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.jw.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.Transient;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
@Service
public class WxGraphicMessageService extends BaseJpaService<WxGraphicMessageDO, WxGraphicMessageDao> {
    @Autowired
    private WxGraphicMessageDao wxGraphicMessageDao;
    @Transient
    public WxGraphicMessageDO createWxGraphicMessage(WxGraphicMessageDO wxGraphicMessage) {
        String code = UUID.randomUUID().toString().replaceAll("-", "");
        wxGraphicMessage.setId(code);
        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_status_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxGraphicMessage.getTitle())) {
            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_title_is_null, ExceptionCode.common_error_params_code);
        }
        WxGraphicMessageDO wxGraphicMessageTem = wxGraphicMessageDao.findById(wxGraphicMessage.getId());
        if (wxGraphicMessageTem != null) {
            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_id_exist, ExceptionCode.common_error_params_code);
        }
        return wxGraphicMessageDao.save(wxGraphicMessage);
    }
    @Transient
    public WxGraphicMessageDO updateWxGraphicMessage(WxGraphicMessageDO wxGraphicMessage) {
        if (StringUtils.isEmpty(wxGraphicMessage.getId())) {
            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_status_is_null, ExceptionCode.common_error_params_code);
        }
        //根据id查找
        WxGraphicMessageDO wxGraphicMessage1 = findById(wxGraphicMessage.getId());
        if(wxGraphicMessage1==null){
            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_wxGraphicMessage_is_no_exist, ExceptionCode.common_error_params_code);
        }
        return wxGraphicMessageDao.save(wxGraphicMessage);
    }
    public WxGraphicMessageDO findById(String id) {
      return wxGraphicMessageDao.findById(id);
    }
    @Transient
    public void deleteWxGraphicMessage(String codes, String userCode, String userName) {
        if(!StringUtils.isEmpty(codes)){
            String[] codeArray = codes.split(",");
            for(String code:codeArray){
                WxGraphicMessageDO wxGraphicMessage = findById(code);
                wxGraphicMessage.setStatus(-1);
                wxGraphicMessage.setUpdateUser(userCode);
                wxGraphicMessage.setUpdateUserName(userName);
                wxGraphicMessageDao.save(wxGraphicMessage);
            }
        }
    }
    private String replyNewsMessage(String toUser,String fromUser,List<Map<String,String>> articles) throws Exception {
        if(articles == null || articles.size() < 1){
            throw new Exception("图文信息不能为空!");
        }
        StringBuilder result = new StringBuilder();
        result.append("<xml>");
        result.append("<ToUserName>" + toUser + "</ToUserName>");
        result.append("<FromUserName>" + fromUser + "</FromUserName>");
        result.append("<CreateTime>" + new Date().getTime() + "</CreateTime>");
        result.append("<MsgType>news</MsgType>");
        result.append("<ArticleCount>" + articles.size() + "</ArticleCount>");
        result.append("<Articles>");
        for(Map<String,String>  article : articles){
            result.append("<item>");
            result.append("<Title>" +  article.get("Title") +"</Title>");
            result.append("<Description>" + article.get("Description") + "</Description>");
            result.append("<PicUrl>" + article.get("PicUrl") + "</PicUrl>");
            result.append("<Url>" + article.get("Url") + "</Url>");
            result.append("</item>");
        }
        result.append("</Articles>");
        result.append("</xml>");
        return result.toString();
    }
    /**
     * 发送图文消息
     * @param codes
     * @param request
     * @return
     */
    public String sendGraphicMessages(String codes, HttpServletRequest request) {
        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            //用户openid
            String fromUserName = requestMap.get("FromUserName");
            //微信公众号
            String toUserName = requestMap.get("ToUserName");
            // 图文信息
            List<Map<String,String>> articles =  new ArrayList<>();
            if(codes!=null){
                String[] codeArray = codes.split(",");
                for(String code: codeArray){
                    WxGraphicMessageDO graphicMessage = findById(code);
                    Map<String,String> article = new HashMap<>();
                    article.put("Url",graphicMessage.getUrl());
                    article.put("Title", graphicMessage.getTitle());
                    article.put("Description",graphicMessage.getDescription());
                    article.put("PicUrl",graphicMessage.getPicUrl());
                    articles.add(article);
                }
            }
            // 构建回复消息XML
            return replyNewsMessage(fromUserName, toUserName, articles);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
    /**
     * 发送图文消息
     * @param ids
     * @param fromUserName   用户的openId
     * @param toUserName
     * @return
     */
    public String sendGraphicMessages(String ids, String fromUserName,String toUserName) {
        try {
        // 图文信息
            List<Map<String,String>> articles =  new ArrayList<>();
            if(ids!=null){
                String[] codeArray = ids.split(",");
                for(String id: codeArray){
                    WxGraphicMessageDO graphicMessage = findById(id);
                    Map<String,String> article = new HashMap<>();
                    article.put("Url",graphicMessage.getUrl());
                    article.put("Title", graphicMessage.getTitle());
                    article.put("Description",graphicMessage.getDescription());
                    article.put("PicUrl",graphicMessage.getPicUrl());
                    articles.add(article);
                }
            }
            // 构建回复消息XML
            return replyNewsMessage(fromUserName, toUserName, articles);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.base.wx.WxGraphicMessageDO;
//import com.yihu.jw.business.wx.dao.WxGraphicMessageDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.jw.util.MessageUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import javax.persistence.Transient;
//import javax.servlet.http.HttpServletRequest;
//import java.util.*;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//@Service
//public class WxGraphicMessageService extends BaseJpaService<WxGraphicMessageDO, WxGraphicMessageDao> {
//
//    @Autowired
//    private WxGraphicMessageDao wxGraphicMessageDao;
//
//    @Transient
//    public WxGraphicMessageDO createWxGraphicMessage(WxGraphicMessageDO wxGraphicMessage) {
//        String code = UUID.randomUUID().toString().replaceAll("-", "");
//        wxGraphicMessage.setId(code);
//        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_status_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wxGraphicMessage.getTitle())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_title_is_null, ExceptionCode.common_error_params_code);
//        }
//        WxGraphicMessageDO wxGraphicMessageTem = wxGraphicMessageDao.findById(wxGraphicMessage.getId());
//        if (wxGraphicMessageTem != null) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_id_exist, ExceptionCode.common_error_params_code);
//        }
//        return wxGraphicMessageDao.save(wxGraphicMessage);
//    }
//
//    @Transient
//    public WxGraphicMessageDO updateWxGraphicMessage(WxGraphicMessageDO wxGraphicMessage) {
//        if (StringUtils.isEmpty(wxGraphicMessage.getId())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_status_is_null, ExceptionCode.common_error_params_code);
//        }
//
//        //根据id查找
//        WxGraphicMessageDO wxGraphicMessage1 = findById(wxGraphicMessage.getId());
//        if(wxGraphicMessage1==null){
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_wxGraphicMessage_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        return wxGraphicMessageDao.save(wxGraphicMessage);
//    }
//
//    public WxGraphicMessageDO findById(String id) {
//      return wxGraphicMessageDao.findById(id);
//    }
//
//    @Transient
//    public void deleteWxGraphicMessage(String codes, String userCode, String userName) {
//        if(!StringUtils.isEmpty(codes)){
//            String[] codeArray = codes.split(",");
//            for(String code:codeArray){
//                WxGraphicMessageDO wxGraphicMessage = findById(code);
//                wxGraphicMessage.setStatus(-1);
//                wxGraphicMessage.setUpdateUser(userCode);
//                wxGraphicMessage.setUpdateUserName(userName);
//                wxGraphicMessageDao.save(wxGraphicMessage);
//            }
//        }
//    }
//
//
//
//    private String replyNewsMessage(String toUser,String fromUser,List<Map<String,String>> articles) throws Exception {
//        if(articles == null || articles.size() < 1){
//            throw new Exception("图文信息不能为空!");
//        }
//
//        StringBuilder result = new StringBuilder();
//        result.append("<xml>");
//        result.append("<ToUserName>" + toUser + "</ToUserName>");
//        result.append("<FromUserName>" + fromUser + "</FromUserName>");
//        result.append("<CreateTime>" + new Date().getTime() + "</CreateTime>");
//        result.append("<MsgType>news</MsgType>");
//        result.append("<ArticleCount>" + articles.size() + "</ArticleCount>");
//        result.append("<Articles>");
//
//        for(Map<String,String>  article : articles){
//            result.append("<item>");
//            result.append("<Title>" +  article.get("Title") +"</Title>");
//            result.append("<Description>" + article.get("Description") + "</Description>");
//            result.append("<PicUrl>" + article.get("PicUrl") + "</PicUrl>");
//            result.append("<Url>" + article.get("Url") + "</Url>");
//            result.append("</item>");
//        }
//
//        result.append("</Articles>");
//        result.append("</xml>");
//
//        return result.toString();
//    }
//
//    /**
//     * 发送图文消息
//     * @param codes
//     * @param request
//     * @return
//     */
//    public String sendGraphicMessages(String codes, HttpServletRequest request) {
//        try {
//            // xml请求解析
//            Map<String, String> requestMap = MessageUtil.parseXml(request);
//            //用户openid
//            String fromUserName = requestMap.get("FromUserName");
//            //微信公众号
//            String toUserName = requestMap.get("ToUserName");
//            // 图文信息
//            List<Map<String,String>> articles =  new ArrayList<>();
//            if(codes!=null){
//                String[] codeArray = codes.split(",");
//                for(String code: codeArray){
//                    WxGraphicMessageDO graphicMessage = findById(code);
//                    Map<String,String> article = new HashMap<>();
//                    article.put("Url",graphicMessage.getUrl());
//                    article.put("Title", graphicMessage.getTitle());
//                    article.put("Description",graphicMessage.getDescription());
//                    article.put("PicUrl",graphicMessage.getPicUrl());
//                    articles.add(article);
//                }
//            }
//            // 构建回复消息XML
//            return replyNewsMessage(fromUserName, toUserName, articles);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 发送图文消息
//     * @param ids
//     * @param fromUserName   用户的openId
//     * @param toUserName
//     * @return
//     */
//    public String sendGraphicMessages(String ids, String fromUserName,String toUserName) {
//        try {
//        // 图文信息
//            List<Map<String,String>> articles =  new ArrayList<>();
//            if(ids!=null){
//                String[] codeArray = ids.split(",");
//                for(String id: codeArray){
//                    WxGraphicMessageDO graphicMessage = findById(id);
//                    Map<String,String> article = new HashMap<>();
//                    article.put("Url",graphicMessage.getUrl());
//                    article.put("Title", graphicMessage.getTitle());
//                    article.put("Description",graphicMessage.getDescription());
//                    article.put("PicUrl",graphicMessage.getPicUrl());
//                    articles.add(article);
//                }
//            }
//            // 构建回复消息XML
//            return replyNewsMessage(fromUserName, toUserName, articles);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
//    }
//
//}

+ 357 - 356
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxMenuService.java

@ -1,356 +1,357 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.base.wx.WxAccessTokenDO;
import com.yihu.jw.base.wx.WxMenuDO;
import com.yihu.jw.base.wx.WxWechatDO;
import com.yihu.jw.business.wx.dao.WxMenuDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.jw.util.HttpUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxMenuService extends BaseJpaService<WxMenuDO, WxMenuDao> {
    private Logger logger= LoggerFactory.getLogger(WxMenuService.class);
    @Autowired
    private WxMenuDao wxMenuDao;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    /**
     * 将菜单保存至数据库
     * @param wxMenu
     * @return
     */
    public WxMenuDO createWxMenu(WxMenuDO wxMenu) {
        String code = UUID.randomUUID().toString().replaceAll("-", "");
        wxMenu.setId(code);
        if(canSaveOrUpata(wxMenu)){
            return wxMenuDao.save(wxMenu);
        }
        return null;
    }
    @Transient
    public WxMenuDO updateWxMenu(WxMenuDO wxMenu) {
        if (StringUtils.isEmpty(wxMenu.getId())) {
            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if(canSaveOrUpata(wxMenu)){
            WxMenuDO wxMenu1 = findById(wxMenu.getId());
            if(wxMenu1==null){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_WxMenu_is_no_exist, ExceptionCode.common_error_params_code);
            }
            return wxMenuDao.save(wxMenu);
        }
        return null;
    }
    @Transient
    public void deleteWxMenu(String ids, String userId, String userName) {
        if(!StringUtils.isEmpty(ids)) {
            String[] codeArray = ids.split(",");
            for (String code : codeArray) {
                WxMenuDO wxMenu = wxMenuDao.findById(code);
                if (wxMenu == null) {
                    continue;
                }
                String supMenucode = wxMenu.getSupMenuid();
                if (StringUtils.isEmpty(supMenucode)) {//如果是空,则为父菜单
                    List<WxMenuDO> childMenus = findChildMenus(wxMenu.getWechatId(), wxMenu.getId());
                    if (childMenus != null) {
                        for (WxMenuDO wxmenu : childMenus) {
                            wxmenu.setStatus(-1);
                            wxmenu.setUpdateUser(userId);
                            wxmenu.setUpdateUserName(userName);
                            wxMenuDao.save(wxmenu);
                        }
                    }
                }
                wxMenu.setStatus(-1);
                wxMenu.setUpdateUser(userId);
                wxMenu.setUpdateUserName(userName);
                wxMenuDao.save(wxMenu);
            }
        }
    }
    @Transient
    public void delete(String codes,String userCode) {
        if(!StringUtils.isEmpty(codes)) {
            String[] codeArray = codes.split(",");
            for (String code : codeArray) {
                WxMenuDO wxMenu = wxMenuDao.findById(code);
                if (wxMenu == null) {
                    continue;
                }
                String supMenucode = wxMenu.getSupMenuid();
                if (StringUtils.isEmpty(supMenucode)) {//如果是空,则为父菜单
                    List<WxMenuDO> childMenus = findChildMenus(wxMenu.getWechatId(), wxMenu.getId());
                    if (childMenus != null) {
                        for (WxMenuDO wxmenu : childMenus) {
                            wxmenu.setStatus(-1);
                            wxmenu.setUpdateUser(userCode);
                            wxMenuDao.save(wxmenu);
                        }
                    }
                }
                wxMenu.setStatus(-1);
                wxMenu.setUpdateUser(userCode);
                wxMenuDao.save(wxMenu);
            }
        }
    }
    public WxMenuDO findById(String id) {
        return wxMenuDao.findById(id);
    }
    /**
     * 根据wechatCode查找所有父菜单
     * @param wechatCode
     * @return
     */
    public List<WxMenuDO> findParentMenuByWechatCode(String wechatCode){
        List<WxMenuDO> parentMenus = wxMenuDao.findParentMenuByWechatId(wechatCode);
        return parentMenus;
    }
    /**
     * 根据wechatCode在微信公众号创建菜单
     * @param wechatId
     * @return JSONObject
     */
    public JSONObject createWechatMenu(String wechatId) {
        WxWechatDO wechat = wechatService.findById(wechatId);
        if(wechat==null){
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
        }
        //首先根据wechatCode获取菜单,然后封装成json字符串
        List<WxMenuDO> menus = wxMenuDao.findByWechatId(wechatId);
        if(menus==null){
            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_WxMenu_is_no_exist, ExceptionCode.common_error_params_code);
        }
        String menuJsonString = getMenuToString(menus, wechatId);
        logger.info("-----------------微信菜单json字符串:"+ menuJsonString+"--------------------");
        WxAccessTokenDO wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenById(wechatId);
        String token = wxAccessTokenByCode.getAccessToken();
        // 请求微信接口创建菜单
        String url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;
        String jsonStr = HttpUtil.sendPost(url, menuJsonString);
        logger.info("------------------创建微信菜单,微信返回结果:"+jsonStr+"---------------------");
        JSONObject result = new JSONObject(jsonStr);
        return result;
    }
    private String getMenuToString(List<WxMenuDO> menus,String wechatCode){
        String menuJsonStr = "";
        List<WxMenuDO> parentMenus = new ArrayList<WxMenuDO>();//存储父菜单
        if(menus!=null){
            menuJsonStr = "{\"button\":[{";
            for(WxMenuDO wxMenu:menus){
                if(StringUtils.isEmpty(wxMenu.getSupMenuid())){//说明是父菜单
                    parentMenus.add(wxMenu);
                }
            }
        }
        int j = 0;
        for(WxMenuDO menu:parentMenus){//遍历父菜单
            if(j==0){
                j++;
            }else{
                menuJsonStr += ",{";
            }
            menuJsonStr = getString(menuJsonStr, menu);
            //查找是否有子菜单
            List<WxMenuDO> childMenus = findChildMenus(wechatCode, menu.getId());
            if(childMenus!=null){
                int i =0;
                menuJsonStr += ",\"sub_button\":[{";
                for(WxMenuDO childMenu:childMenus){
                    if(i==0){
                        i++;
                    }else{
                        menuJsonStr += ",{";
                    }
                    menuJsonStr = getString(menuJsonStr, childMenu);
                    menuJsonStr += "}";
                }
                menuJsonStr += "]}";
            }
        }
        menuJsonStr += "]}";
        return menuJsonStr;
    }
    private String getString(String menuJsonStr, WxMenuDO menu) {
        menuJsonStr += "\"name\":\""+ menu.getName()+"\"";
        if(!StringUtils.isEmpty(menu.getType())){
            menuJsonStr += ",\"type\":\"" + menu.getType()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getMenuKey())){
            menuJsonStr += ",\"key\":\"" + menu.getMenuKey()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getUrl())){
            menuJsonStr += ",\"url\":\"" + menu.getUrl()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getMediaId())){
            menuJsonStr += ",\"media_id\":\"" + menu.getMediaId()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getAppid())){
            menuJsonStr += ",\"appid\":\"" + menu.getAppid()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getPagepath())){
            menuJsonStr += ",\"pagepath\":\"" + menu.getPagepath()+"\"";
        }
        return menuJsonStr;
    }
    /**
     * 查找子菜单
     * @param wechatCode
     * @param sup_menucode
     * @return
     */
    public List<WxMenuDO> findChildMenus(String wechatCode,String sup_menucode ){
        return wxMenuDao.findChildMenus(wechatCode,sup_menucode);
    }
    public List<WxMenuDO> findChildMenus(String parentCode ){
        return wxMenuDao.findChildMenus(parentCode);
    }
    private boolean canSaveOrUpata(WxMenuDO wxMenu){
        String wechatCode = wxMenu.getWechatId();
        String supMenucode = wxMenu.getSupMenuid();
        if(StringUtils.isEmpty(wechatCode)){
            WxMenuDO parentMenuCode = findById(supMenucode);
            wechatCode = parentMenuCode.getWechatId();
            wxMenu.setWechatId(wechatCode);
        }
        String name = wxMenu.getName();
        if (StringUtils.isEmpty(name)) {
            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_name_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxMenu.getStatus())) {
            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_status_is_null, ExceptionCode.common_error_params_code);
        }
        if(StringUtils.isEmpty(wxMenu.getSort())){
            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_sort_is_null, ExceptionCode.common_error_params_code);
        }
        //根据wechatCode查找是否存在微信配置
        WxWechatDO wxWechat = wechatService.findById(wechatCode);
        if(wxWechat==null){
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
        }
        if (!"0".equals(supMenucode)) {//不为0,说明是子菜单,判断父菜单是否存在
            //说明是子菜单
            //判断父菜单是否存在
            WxMenuDO parentMenuCode = findById(supMenucode);
            if(parentMenuCode==null){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_supMenuId_is_no_exist, ExceptionCode.common_error_params_code);
            }
            //查询已经存在的子菜单条数
            List<WxMenuDO> childMenus = findChildMenus(wechatCode, supMenucode);
            if(childMenus.size()==5){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_childMenu_is_to_much, ExceptionCode.common_error_params_code);
            }
            if(name.getBytes().length>60){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_name_is_to_long, ExceptionCode.common_error_params_code);
            }
            if(StringUtils.isEmpty(wxMenu.getType())){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_type_is_null, ExceptionCode.common_error_params_code);
            }
        }else{
            //查找父菜单
            List<WxMenuDO> parentMenus = findParentMenuByWechatCode(wechatCode);
            if(parentMenus!=null){
                if(parentMenus.size()==3){
                    throw new ApiException(WechatRequestMapping.WxMenu.message_fail_parentMenu_is_to_much, ExceptionCode.common_error_params_code);
                }
            }
            //说明是父菜单
            if(name.getBytes().length>16){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_name_is_to_long, ExceptionCode.common_error_params_code);
            }
        }
        String type1=wxMenu.getType();
        if(type1==null){
            type1="";
        }
        String type = type1.toUpperCase();
        if("click".equals(type)){
            String key = wxMenu.getMenuKey();
            if(StringUtils.isEmpty(key)){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_key_is_null, ExceptionCode.common_error_params_code);
            }
            if(key.getBytes().length>128){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_key_is_toLong, ExceptionCode.common_error_params_code);
            }
        }
        String url = wxMenu.getUrl();
        if("view".equals(type)){
            if(StringUtils.isEmpty(url)){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_null, ExceptionCode.common_error_params_code);
            }
            if(url.getBytes().length>128){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_toLong, ExceptionCode.common_error_params_code);
            }
        }
        if("miniprogram".equals(type)){
            if(StringUtils.isEmpty(url)){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_null, ExceptionCode.common_error_params_code);
            }
            if(url.getBytes().length>128){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_toLong, ExceptionCode.common_error_params_code);
            }
            if(StringUtils.isEmpty(wxMenu.getAppid())){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_appid_is_null, ExceptionCode.common_error_params_code);
            }
            if(StringUtils.isEmpty(wxMenu.getPagepath())){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_pagepath_is_null, ExceptionCode.common_error_params_code);
            }
        }
        if("media_id".equals(type)||"view_limited".equals(type)){
            if(StringUtils.isEmpty(wxMenu.getMediaId())){
                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_mediaId_is_null, ExceptionCode.common_error_params_code);
            }
        }
        WxMenuDO wxMenuTemp = null;
        if(StringUtils.isEmpty(wxMenu.getSupMenuid())){//如果是空,则为父菜单
            //判断sort是否重复
            wxMenuTemp = wxMenuDao.findByWechatIdExcludeSortFromParent(wxMenu.getWechatId(), wxMenu.getSort(),wxMenu.getId());
        }else{//子菜单
            wxMenuTemp = wxMenuDao.findByWechatIdExcludeSortFromChild(wxMenu.getWechatId(), wxMenu.getSort(), wxMenu.getSupMenuid(), wxMenu.getId());
        }
        if(null!=wxMenuTemp){
            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_sort_is_repeat, ExceptionCode.common_error_params_code);
        }
        wxMenu.setUpdateTime(new Date());
        return true;
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.base.wx.WxAccessTokenDO;
//import com.yihu.jw.base.wx.WxMenuDO;
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.dao.WxMenuDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.jw.util.HttpUtil;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import javax.persistence.Transient;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import java.util.UUID;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@Service
//public class WxMenuService extends BaseJpaService<WxMenuDO, WxMenuDao> {
//
//    private Logger logger= LoggerFactory.getLogger(WxMenuService.class);
//
//    @Autowired
//    private WxMenuDao wxMenuDao;
//
//    @Autowired
//    private WechatService wechatService;
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//    /**
//     * 将菜单保存至数据库
//     * @param wxMenu
//     * @return
//     */
//    public WxMenuDO createWxMenu(WxMenuDO wxMenu) {
//        String code = UUID.randomUUID().toString().replaceAll("-", "");
//        wxMenu.setId(code);
//        if(canSaveOrUpata(wxMenu)){
//            return wxMenuDao.save(wxMenu);
//        }
//        return null;
//    }
//
//    @Transient
//    public WxMenuDO updateWxMenu(WxMenuDO wxMenu) {
//        if (StringUtils.isEmpty(wxMenu.getId())) {
//            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if(canSaveOrUpata(wxMenu)){
//            WxMenuDO wxMenu1 = findById(wxMenu.getId());
//            if(wxMenu1==null){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_WxMenu_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//            return wxMenuDao.save(wxMenu);
//        }
//        return null;
//    }
//
//    @Transient
//    public void deleteWxMenu(String ids, String userId, String userName) {
//        if(!StringUtils.isEmpty(ids)) {
//            String[] codeArray = ids.split(",");
//            for (String code : codeArray) {
//                WxMenuDO wxMenu = wxMenuDao.findById(code);
//                if (wxMenu == null) {
//                    continue;
//                }
//                String supMenucode = wxMenu.getSupMenuid();
//                if (StringUtils.isEmpty(supMenucode)) {//如果是空,则为父菜单
//                    List<WxMenuDO> childMenus = findChildMenus(wxMenu.getWechatId(), wxMenu.getId());
//                    if (childMenus != null) {
//                        for (WxMenuDO wxmenu : childMenus) {
//                            wxmenu.setStatus(-1);
//                            wxmenu.setUpdateUser(userId);
//                            wxmenu.setUpdateUserName(userName);
//                            wxMenuDao.save(wxmenu);
//                        }
//                    }
//                }
//                wxMenu.setStatus(-1);
//                wxMenu.setUpdateUser(userId);
//                wxMenu.setUpdateUserName(userName);
//                wxMenuDao.save(wxMenu);
//            }
//        }
//    }
//
//    @Transient
//    public void delete(String codes,String userCode) {
//        if(!StringUtils.isEmpty(codes)) {
//            String[] codeArray = codes.split(",");
//            for (String code : codeArray) {
//                WxMenuDO wxMenu = wxMenuDao.findById(code);
//                if (wxMenu == null) {
//                    continue;
//                }
//                String supMenucode = wxMenu.getSupMenuid();
//                if (StringUtils.isEmpty(supMenucode)) {//如果是空,则为父菜单
//                    List<WxMenuDO> childMenus = findChildMenus(wxMenu.getWechatId(), wxMenu.getId());
//                    if (childMenus != null) {
//                        for (WxMenuDO wxmenu : childMenus) {
//                            wxmenu.setStatus(-1);
//                            wxmenu.setUpdateUser(userCode);
//                            wxMenuDao.save(wxmenu);
//                        }
//                    }
//                }
//                wxMenu.setStatus(-1);
//                wxMenu.setUpdateUser(userCode);
//                wxMenuDao.save(wxMenu);
//            }
//        }
//    }
//
//    public WxMenuDO findById(String id) {
//        return wxMenuDao.findById(id);
//    }
//    /**
//     * 根据wechatCode查找所有父菜单
//     * @param wechatCode
//     * @return
//     */
//    public List<WxMenuDO> findParentMenuByWechatCode(String wechatCode){
//        List<WxMenuDO> parentMenus = wxMenuDao.findParentMenuByWechatId(wechatCode);
//        return parentMenus;
//    }
//
//    /**
//     * 根据wechatCode在微信公众号创建菜单
//     * @param wechatId
//     * @return JSONObject
//     */
//    public JSONObject createWechatMenu(String wechatId) throws JSONException {
//        WxWechatDO wechat = wechatService.findById(wechatId);
//        if(wechat==null){
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        //首先根据wechatCode获取菜单,然后封装成json字符串
//        List<WxMenuDO> menus = wxMenuDao.findByWechatId(wechatId);
//        if(menus==null){
//            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_WxMenu_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        String menuJsonString = getMenuToString(menus, wechatId);
//        logger.info("-----------------微信菜单json字符串:"+ menuJsonString+"--------------------");
//        WxAccessTokenDO wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenById(wechatId);
//        String token = wxAccessTokenByCode.getAccessToken();
//        // 请求微信接口创建菜单
//        String url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;
//        String jsonStr = HttpUtil.sendPost(url, menuJsonString);
//        logger.info("------------------创建微信菜单,微信返回结果:"+jsonStr+"---------------------");
//        JSONObject result = new JSONObject(jsonStr);
//        return result;
//    }
//
//    private String getMenuToString(List<WxMenuDO> menus,String wechatCode){
//        String menuJsonStr = "";
//        List<WxMenuDO> parentMenus = new ArrayList<WxMenuDO>();//存储父菜单
//        if(menus!=null){
//            menuJsonStr = "{\"button\":[{";
//            for(WxMenuDO wxMenu:menus){
//                if(StringUtils.isEmpty(wxMenu.getSupMenuid())){//说明是父菜单
//                    parentMenus.add(wxMenu);
//                }
//            }
//        }
//        int j = 0;
//        for(WxMenuDO menu:parentMenus){//遍历父菜单
//            if(j==0){
//                j++;
//            }else{
//                menuJsonStr += ",{";
//            }
//            menuJsonStr = getString(menuJsonStr, menu);
//            //查找是否有子菜单
//            List<WxMenuDO> childMenus = findChildMenus(wechatCode, menu.getId());
//            if(childMenus!=null){
//                int i =0;
//                menuJsonStr += ",\"sub_button\":[{";
//                for(WxMenuDO childMenu:childMenus){
//                    if(i==0){
//                        i++;
//                    }else{
//                        menuJsonStr += ",{";
//                    }
//                    menuJsonStr = getString(menuJsonStr, childMenu);
//                    menuJsonStr += "}";
//                }
//                menuJsonStr += "]}";
//            }
//        }
//        menuJsonStr += "]}";
//        return menuJsonStr;
//    }
//
//    private String getString(String menuJsonStr, WxMenuDO menu) {
//        menuJsonStr += "\"name\":\""+ menu.getName()+"\"";
//        if(!StringUtils.isEmpty(menu.getType())){
//            menuJsonStr += ",\"type\":\"" + menu.getType()+"\"";
//        }
//        if(!StringUtils.isEmpty(menu.getMenuKey())){
//            menuJsonStr += ",\"key\":\"" + menu.getMenuKey()+"\"";
//        }
//        if(!StringUtils.isEmpty(menu.getUrl())){
//            menuJsonStr += ",\"url\":\"" + menu.getUrl()+"\"";
//        }
//        if(!StringUtils.isEmpty(menu.getMediaId())){
//            menuJsonStr += ",\"media_id\":\"" + menu.getMediaId()+"\"";
//        }
//        if(!StringUtils.isEmpty(menu.getAppid())){
//            menuJsonStr += ",\"appid\":\"" + menu.getAppid()+"\"";
//        }
//        if(!StringUtils.isEmpty(menu.getPagepath())){
//            menuJsonStr += ",\"pagepath\":\"" + menu.getPagepath()+"\"";
//        }
//        return menuJsonStr;
//    }
//
//    /**
//     * 查找子菜单
//     * @param wechatCode
//     * @param sup_menucode
//     * @return
//     */
//    public List<WxMenuDO> findChildMenus(String wechatCode,String sup_menucode ){
//        return wxMenuDao.findChildMenus(wechatCode,sup_menucode);
//    }
//
//    public List<WxMenuDO> findChildMenus(String parentCode ){
//        return wxMenuDao.findChildMenus(parentCode);
//    }
//
//    private boolean canSaveOrUpata(WxMenuDO wxMenu){
//        String wechatCode = wxMenu.getWechatId();
//        String supMenucode = wxMenu.getSupMenuid();
//        if(StringUtils.isEmpty(wechatCode)){
//            WxMenuDO parentMenuCode = findById(supMenucode);
//            wechatCode = parentMenuCode.getWechatId();
//            wxMenu.setWechatId(wechatCode);
//        }
//        String name = wxMenu.getName();
//        if (StringUtils.isEmpty(name)) {
//            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_name_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wxMenu.getStatus())) {
//            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_status_is_null, ExceptionCode.common_error_params_code);
//        }
//        if(StringUtils.isEmpty(wxMenu.getSort())){
//            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_sort_is_null, ExceptionCode.common_error_params_code);
//        }
//        //根据wechatCode查找是否存在微信配置
//        WxWechatDO wxWechat = wechatService.findById(wechatCode);
//        if(wxWechat==null){
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        if (!"0".equals(supMenucode)) {//不为0,说明是子菜单,判断父菜单是否存在
//            //说明是子菜单
//            //判断父菜单是否存在
//            WxMenuDO parentMenuCode = findById(supMenucode);
//            if(parentMenuCode==null){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_supMenuId_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//
//            //查询已经存在的子菜单条数
//            List<WxMenuDO> childMenus = findChildMenus(wechatCode, supMenucode);
//            if(childMenus.size()==5){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_childMenu_is_to_much, ExceptionCode.common_error_params_code);
//            }
//            if(name.getBytes().length>60){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_name_is_to_long, ExceptionCode.common_error_params_code);
//            }
//            if(StringUtils.isEmpty(wxMenu.getType())){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_type_is_null, ExceptionCode.common_error_params_code);
//            }
//        }else{
//            //查找父菜单
//            List<WxMenuDO> parentMenus = findParentMenuByWechatCode(wechatCode);
//            if(parentMenus!=null){
//                if(parentMenus.size()==3){
//                    throw new ApiException(WechatRequestMapping.WxMenu.message_fail_parentMenu_is_to_much, ExceptionCode.common_error_params_code);
//                }
//            }
//
//            //说明是父菜单
//            if(name.getBytes().length>16){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_name_is_to_long, ExceptionCode.common_error_params_code);
//            }
//
//        }
//        String type1=wxMenu.getType();
//        if(type1==null){
//            type1="";
//        }
//        String type = type1.toUpperCase();
//        if("click".equals(type)){
//            String key = wxMenu.getMenuKey();
//            if(StringUtils.isEmpty(key)){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_key_is_null, ExceptionCode.common_error_params_code);
//            }
//            if(key.getBytes().length>128){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_key_is_toLong, ExceptionCode.common_error_params_code);
//            }
//        }
//        String url = wxMenu.getUrl();
//        if("view".equals(type)){
//            if(StringUtils.isEmpty(url)){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_null, ExceptionCode.common_error_params_code);
//            }
//            if(url.getBytes().length>128){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_toLong, ExceptionCode.common_error_params_code);
//            }
//        }
//        if("miniprogram".equals(type)){
//            if(StringUtils.isEmpty(url)){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_null, ExceptionCode.common_error_params_code);
//            }
//            if(url.getBytes().length>128){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_url_is_toLong, ExceptionCode.common_error_params_code);
//            }
//            if(StringUtils.isEmpty(wxMenu.getAppid())){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_appid_is_null, ExceptionCode.common_error_params_code);
//            }
//            if(StringUtils.isEmpty(wxMenu.getPagepath())){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_pagepath_is_null, ExceptionCode.common_error_params_code);
//            }
//        }
//        if("media_id".equals(type)||"view_limited".equals(type)){
//            if(StringUtils.isEmpty(wxMenu.getMediaId())){
//                throw new ApiException(WechatRequestMapping.WxMenu.message_fail_mediaId_is_null, ExceptionCode.common_error_params_code);
//            }
//        }
//        WxMenuDO wxMenuTemp = null;
//        if(StringUtils.isEmpty(wxMenu.getSupMenuid())){//如果是空,则为父菜单
//            //判断sort是否重复
//            wxMenuTemp = wxMenuDao.findByWechatIdExcludeSortFromParent(wxMenu.getWechatId(), wxMenu.getSort(),wxMenu.getId());
//        }else{//子菜单
//            wxMenuTemp = wxMenuDao.findByWechatIdExcludeSortFromChild(wxMenu.getWechatId(), wxMenu.getSort(), wxMenu.getSupMenuid(), wxMenu.getId());
//        }
//        if(null!=wxMenuTemp){
//            throw new ApiException(WechatRequestMapping.WxMenu.message_fail_sort_is_repeat, ExceptionCode.common_error_params_code);
//        }
//        wxMenu.setUpdateTime(new Date());
//        return true;
//    }
//}

+ 157 - 157
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxTemplateService.java

@ -1,157 +1,157 @@
package com.yihu.jw.business.wx.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.wx.*;
import com.yihu.jw.business.wx.dao.WxTemplateDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.jw.util.HttpUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxTemplateService extends BaseJpaService<WxTemplateDO, WxTemplateDao> {
    private Logger logger= LoggerFactory.getLogger(WxTemplateService.class);
    @Autowired
    private WxTemplateDao wxTemplateDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WechatService wechatService;
    public WxTemplateDO createWxTemplate(WxTemplateDO wxTemplate) {
        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
        }
        String content = wxTemplate.getContent().replace(" ","");
        if (StringUtils.isEmpty(content)) {
            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
        }
        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
        }
        return wxTemplateDao.save(wxTemplate);
    }
    public WxTemplateDO updateWxTemplate(WxTemplateDO wxTemplate) {
        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
        }
        String content = wxTemplate.getContent().replace(" ","");
        if (StringUtils.isEmpty(content)) {
            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
        }
        String id = wxTemplate.getId();
        if (StringUtils.isEmpty(id)) {
            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        WxTemplateDO wxTemplate1 = findById(id);
        if(wxTemplate1==null){
            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
        }
        wxTemplate.setCreateTime(wxTemplate1.getCreateTime());
        wxTemplate.setUpdateTime(new Date());
        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
        }
        return wxTemplateDao.save(wxTemplate);
    }
    public void deleteWxTemplate(String codes, String userCode, String userName) {
        if(!StringUtils.isEmpty(codes)) {
            String[] codeArray = codes.split(",");
            for (String code : codeArray) {
                WxTemplateDO wxTemplate = wxTemplateDao.findById(code);
                if (wxTemplate == null) {
                    throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
                }
                wxTemplate.setStatus(-1);
                wxTemplate.setUpdateUser(userCode);
                wxTemplate.setUpdateUserName(userName);
                wxTemplateDao.save(wxTemplate);
            }
        }
    }
    public WxTemplateDO findById(String id) {
        WxTemplateDO wxTemplate = wxTemplateDao.findById(id);
        return wxTemplate;
    }
    public JSONObject sendTemplateMessage(String openid, String templateId, String url, String data,Miniprogram miniprogram) {
        try {
            //首先根据wechatTemplate获取微信模版
            WxTemplateDO wxTemplate = findById(templateId);
            if(wxTemplate==null){
                throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
            }
            String wechatCode =  wxTemplate.getWechatId();
            String content = wxTemplate.getContent().replaceAll(" ", "");//{{result.DATA}}领奖金额:{{withdrawMoney.DATA}   }领奖  时间:{ {withdrawTime.DATA} }银行信息:{ {cardInfo.DATA} }到账时间:{{arrivedTime.DATA}}{{remark.DATA}}
            String[] contentArray = content.split("\\{\\{");
            //将result,withdrawMoney,withdrawTime,cardInfo,arrivedTime等字符串放入contentList中
            List<String> contentList = new ArrayList<>();
            for(int i=1;i<contentArray.length;i++){
                contentList.add(contentArray[i].substring(0,contentArray[i].indexOf(".")));
            }
            ObjectMapper mapper = new ObjectMapper();
            ////将data转为对象
            Map<String, WechatTemplateDataDO> dataMap = mapper.readValue(data, new TypeReference<LinkedHashMap<String, WechatTemplateDataDO>>() {});
            Map<String, WechatTemplateDataDO> newDataMap = new LinkedHashMap<String, WechatTemplateDataDO>();
            int j = 0;
            for (Map.Entry<String, WechatTemplateDataDO> entry : dataMap.entrySet()) {//(keyword1,WechatTemplateData)
                String key = entry.getKey();//keyword1   转为result
                newDataMap.put(contentList.get(j),entry.getValue());
                j++;
            }
            //将数据封装在WechatTemplate对象中
            WechatTemplateDO wechatTemplate = new WechatTemplateDO();
            wechatTemplate.setTouser(openid);
            wechatTemplate.setUrl(url);
            wechatTemplate.setTemplate_id(wxTemplate.getTemplateId());
            if(miniprogram!=null){
                wechatTemplate.setMiniprogram(miniprogram);
            }
            wechatTemplate.setData(newDataMap);
            String params = mapper.writeValueAsString(wechatTemplate);
            logger.info("----------------------模版消息json字符串:"+params+"------------------");
            WxAccessTokenDO wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenById(wechatCode);
            String token = wxAccessTokenByCode.getAccessToken();
            String token_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
            String result = HttpUtil.sendPost(token_url, params);
            logger.info("------------------------发送模板消息,微信返回结果:"+result+"-----------------------");
            JSONObject jsonResult = new JSONObject(result);
            return jsonResult;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonResult = new JSONObject(e);
            return jsonResult;
        }
    }
    public List<WxTemplateDO> findByWxId(String code) {
        return wxTemplateDao.findByWxId(code);
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.fasterxml.jackson.core.type.TypeReference;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.jw.base.wx.*;
//import com.yihu.jw.business.wx.dao.WxTemplateDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.jw.util.HttpUtil;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import java.util.*;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@Service
//public class WxTemplateService extends BaseJpaService<WxTemplateDO, WxTemplateDao> {
//
//    private Logger logger= LoggerFactory.getLogger(WxTemplateService.class);
//
//    @Autowired
//    private WxTemplateDao wxTemplateDao;
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//    @Autowired
//    private WechatService wechatService;
//
//    public WxTemplateDO createWxTemplate(WxTemplateDO wxTemplate) {
//        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
//        }
//        String content = wxTemplate.getContent().replace(" ","");
//        if (StringUtils.isEmpty(content)) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
//        }
//        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
//        }
//        return wxTemplateDao.save(wxTemplate);
//    }
//
//    public WxTemplateDO updateWxTemplate(WxTemplateDO wxTemplate) {
//        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
//        }
//        String content = wxTemplate.getContent().replace(" ","");
//        if (StringUtils.isEmpty(content)) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
//        }
//        String id = wxTemplate.getId();
//        if (StringUtils.isEmpty(id)) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        WxTemplateDO wxTemplate1 = findById(id);
//        if(wxTemplate1==null){
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        wxTemplate.setCreateTime(wxTemplate1.getCreateTime());
//        wxTemplate.setUpdateTime(new Date());
//        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
//        }
//        return wxTemplateDao.save(wxTemplate);
//    }
//
//    public void deleteWxTemplate(String codes, String userCode, String userName) {
//        if(!StringUtils.isEmpty(codes)) {
//            String[] codeArray = codes.split(",");
//            for (String code : codeArray) {
//                WxTemplateDO wxTemplate = wxTemplateDao.findById(code);
//                if (wxTemplate == null) {
//                    throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
//                }
//                wxTemplate.setStatus(-1);
//                wxTemplate.setUpdateUser(userCode);
//                wxTemplate.setUpdateUserName(userName);
//                wxTemplateDao.save(wxTemplate);
//            }
//        }
//    }
//
//
//    public WxTemplateDO findById(String id) {
//        WxTemplateDO wxTemplate = wxTemplateDao.findById(id);
//        return wxTemplate;
//    }
//
//    public JSONObject sendTemplateMessage(String openid, String templateId, String url, String data,Miniprogram miniprogram) {
//        try {
//            //首先根据wechatTemplate获取微信模版
//            WxTemplateDO wxTemplate = findById(templateId);
//            if(wxTemplate==null){
//                throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//            String wechatCode =  wxTemplate.getWechatId();
//            String content = wxTemplate.getContent().replaceAll(" ", "");//{{result.DATA}}领奖金额:{{withdrawMoney.DATA}   }领奖  时间:{ {withdrawTime.DATA} }银行信息:{ {cardInfo.DATA} }到账时间:{{arrivedTime.DATA}}{{remark.DATA}}
//            String[] contentArray = content.split("\\{\\{");
//
//            //将result,withdrawMoney,withdrawTime,cardInfo,arrivedTime等字符串放入contentList中
//            List<String> contentList = new ArrayList<>();
//            for(int i=1;i<contentArray.length;i++){
//                contentList.add(contentArray[i].substring(0,contentArray[i].indexOf(".")));
//            }
//
//            ObjectMapper mapper = new ObjectMapper();
//            ////将data转为对象
//            Map<String, WechatTemplateDataDO> dataMap = mapper.readValue(data, new TypeReference<LinkedHashMap<String, WechatTemplateDataDO>>() {});
//            Map<String, WechatTemplateDataDO> newDataMap = new LinkedHashMap<String, WechatTemplateDataDO>();
//            int j = 0;
//            for (Map.Entry<String, WechatTemplateDataDO> entry : dataMap.entrySet()) {//(keyword1,WechatTemplateData)
//                String key = entry.getKey();//keyword1   转为result
//                newDataMap.put(contentList.get(j),entry.getValue());
//                j++;
//            }
//
//            //将数据封装在WechatTemplate对象中
//            WechatTemplateDO wechatTemplate = new WechatTemplateDO();
//            wechatTemplate.setTouser(openid);
//            wechatTemplate.setUrl(url);
//            wechatTemplate.setTemplate_id(wxTemplate.getTemplateId());
//            if(miniprogram!=null){
//                wechatTemplate.setMiniprogram(miniprogram);
//            }
//            wechatTemplate.setData(newDataMap);
//
//            String params = mapper.writeValueAsString(wechatTemplate);
//            logger.info("----------------------模版消息json字符串:"+params+"------------------");
//
//            WxAccessTokenDO wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenById(wechatCode);
//            String token = wxAccessTokenByCode.getAccessToken();
//            String token_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
//            String result = HttpUtil.sendPost(token_url, params);
//            logger.info("------------------------发送模板消息,微信返回结果:"+result+"-----------------------");
//
//            JSONObject jsonResult = new JSONObject(result);
//            return jsonResult;
//        } catch (Exception e) {
//            e.printStackTrace();
//            JSONObject jsonResult = new JSONObject();
//            return jsonResult;
//        }
//    }
//
//    public List<WxTemplateDO> findByWxId(String code) {
//        return wxTemplateDao.findByWxId(code);
//    }
//}

+ 11 - 4
svr/svr-base/src/main/java/com/yihu/jw/config/jpa/HibernateProperties.java

@ -10,20 +10,27 @@ import java.util.Properties;
 * Created by chenweida on 2017/4/6.
 */
@Component
@RefreshScope
//@RefreshScope
public class HibernateProperties {
    @Value("${hibernate.dialect}")
    private String dialect;
    @Value("${hibernate.show_sql}")
    private String show_sql;
    @Value("${hibernate.ejb.naming_strategy}")
    private String naming_strategy;
//    @Value("${hibernate.ejb.naming_strategy}")
//    private String naming_strategy;
    @Value("${hibernate.physical_naming_strategy}")
    private String  physical_naming_strategy;
    @Value("${hibernate.implicit_naming_strategy}")
    private String implicit_naming_strategy;
    public  Properties hibProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect",dialect);
        properties.put("hibernate.show_sql", show_sql);
        properties.put("hibernate.ejb.naming_strategy", naming_strategy);
        properties.put("hibernate.physical_naming_strategy", physical_naming_strategy);
        properties.put("hibernate.implicit_naming_strategy", implicit_naming_strategy);
        return properties;
    }
}

+ 33 - 15
svr/svr-base/src/main/resources/application.yml

@ -1,33 +1,51 @@
##如果有配置服务的话,远程服务器和本地服务器配置不一致的情况下,优先远程的为主  git上 svr-base ->  git application ->本地 appliction ->本地 bootstarp
spring:
  application:
    name:  svr-base  #注册到发现服务的id 如果id一样 eurika会自动做负载
    name: svr-base  #注册到发现服务的id 如果id一样 eurika会自动做负载
#  jmx:
#    default-domain: svr-base
  jmx:
    default-domain: svr-base
    enabled: true
  data:
    elasticsearch: #ElasticsearchProperties
      cluster-name: jkzl #默认即为elasticsearch  集群名
      cluster-nodes: 172.19.103.45:9300,172.19.103.68:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
      local: false #是否本地连接
      properties: # Additional properties used to configure the client.
        enable: true
  # JEST (Elasticsearch HTTP client) (JestProperties)
  elasticsearch:
    jest:
      uris: http://172.19.103.45:9200,http://172.19.103.68:9200
#      uris: http://172.19.103.68:9200
      connection-timeout: 60000 # Connection timeout in milliseconds.
      multi-threaded: true
    elasticsearch:
      cluster-name: jkzl #es集群的名字
      cluster-nodes: 172.19.103.68:9300  #多个逗号分割
      cluster-nodes-jest: http://172.19.103.68:9200  #多个逗号分割
      repositories:
        enabled: false
      properties:
        client:
          transport:
            sniff: false #开启嗅探集群  用nginx代理一层过后会出现ip解析失败问题
management:
  security:
    enabled: false #关闭 refresh的权限认证
health:
  config:
    enabled: true
endpoints:
  info:
    enabled: true
---
spring:
  profiles: jwdev
jw:
  sms:
    url: 123
    code: 123
    name: 123
    password: 123
---
spring:
  profiles: jwtest

+ 9 - 2
svr/svr-base/src/main/resources/bootstrap.yml

@ -9,19 +9,26 @@ spring:
      discovery:
        enabled: true #使用发现服务
        service-id: svr-configurations ##配置服务的名字
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
    database: 0
---
spring:
  profiles: jwdev
  cloud:
    config:
      label: jwdev
##发现服务的地址
eureka:
  client:
    serviceUrl:
      #http://账号:密码@127.0.0.1:8761/eureka/
      defaultZone: http://jw:jkzl@172.19.103.33:8761//eureka/
#      defaultZone: http://jw:jkzl@127.0.0.1:8761//eureka/
#      defaultZone: http://jw:jkzl@172.19.103.33:8761//eureka/
      defaultZone: http://jw:jkzl@192.168.131.131:8761/eureka/
---
spring:

+ 11 - 6
web-gateway/pom.xml

@ -38,10 +38,11 @@
            <artifactId>common-swagger</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>com.yihu.base</groupId>-->
            <!--<artifactId>common-security</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>common-security-starter</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
@ -68,10 +69,10 @@
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
      <!--  <dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
@ -163,6 +164,10 @@
            <artifactId>jna</artifactId>
            <version>3.0.9</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
    </dependencies>
    <build>
        <finalName>webgate-way</finalName>

+ 3 - 1
web-gateway/src/main/java/com/yihu/jw/WebGateWayAppliaction.java

@ -13,7 +13,9 @@ import org.springframework.context.annotation.ComponentScan;
/**
 * Created by chenweida on 2017/5/10.
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@SpringBootApplication(
        exclude = {DataSourceAutoConfiguration.class,
                HibernateJpaAutoConfiguration.class})
//@SpringBootApplication
@EnableDiscoveryClient//服务注册到发现服务
@EnableHystrix //启动断路器

+ 2 - 2
web-gateway/src/main/java/com/yihu/jw/aspect/LogAspect.java

@ -38,8 +38,8 @@ public class LogAspect {
            tracer.getCurrentSpan().tag(GatewayContanrts.ZipkinElasticKey.gateway_input_params,new JSONObject(request.getParameterMap()).toString());
            o = point.proceed();
            //访问后日志
            String after = o==null?null:new JSONObject(o).toString();
            tracer.getCurrentSpan().tag(GatewayContanrts.ZipkinElasticKey.gateway_out_params,after);
//            String after = o==null?null:new JSONObject(o).toString();
//            tracer.getCurrentSpan().tag(GatewayContanrts.ZipkinElasticKey.gateway_out_params,after);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

+ 55 - 39
web-gateway/src/main/java/com/yihu/jw/config/security/ClientService.java

@ -1,40 +1,56 @@
//package com.yihu.jw.config.security;
//
//import com.yihu.base.security.rbas.ClientServiceProvider;
//import org.springframework.context.annotation.Primary;
//import org.springframework.security.oauth2.provider.ClientDetails;
//import org.springframework.security.oauth2.provider.ClientRegistrationException;
//import org.springframework.security.oauth2.provider.client.BaseClientDetails;
//import org.springframework.stereotype.Component;
//
//import java.util.HashSet;
//import java.util.Set;
//
///**
// * Created by chenweida on 2017/12/1.
// */
//@Component("baseClientDetailsService")
//@Primary
//public class ClientService implements ClientServiceProvider {
//
//    @Override
//    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
////        SaasDO saasDO = saasDao.findByAppId(clientId);
////        if (saasDO == null) {
////            throw new ClientRegistrationException("用户没有注册");
////        }
//        BaseClientDetails baseClientDetails = new BaseClientDetails();
//        baseClientDetails.setClientId("cwd");
//        baseClientDetails.setClientSecret("cwd");
//
//        Set<String> strings = new HashSet<>();
//        strings.add("password");
//        strings.add("custom_password");
//        strings.add("authorization_code");
//        strings.add("refresh_token");
//        baseClientDetails.setAuthorizedGrantTypes(strings);
//        return baseClientDetails;
package com.yihu.jw.config.security;
import com.yihu.base.security.rbas.ClientServiceProvider;
import com.yihu.jw.base.base.SaasDO;
import com.yihu.jw.fegin.base.base.SaasFeign;
import com.yihu.jw.restmodel.common.Envelop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
 * Created by chenweida on 2017/12/1.
 */
@Component("baseClientDetailsService")
@Primary
public class ClientService implements ClientServiceProvider {
    @Autowired
    private SaasFeign saasFeign;
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        Envelop envelop = saasFeign.findByCode(clientId);
        Map saasDO = (Map)envelop.getObj();
        if (saasDO.isEmpty()) {
            throw new ClientRegistrationException("该平台未注册");
        }
        BaseClientDetails baseClientDetails = new BaseClientDetails();
        baseClientDetails.setClientId(saasDO.get("id")+"");
        baseClientDetails.setClientSecret("");
        Set<String> strings = new HashSet<>();
        strings.add("password");
        strings.add("custom_password");
        strings.add("authorization_code");
        strings.add("refresh_token");
        baseClientDetails.setAuthorizedGrantTypes(strings);
        return baseClientDetails;
    }
//    public static void main(String[] args) {
//        byte[] a = Base64.encode("1:".getBytes());
//        String s = new String(a);
//        System.out.println(s);
//    }
//
//
//}
}

+ 49 - 48
web-gateway/src/main/java/com/yihu/jw/config/security/RbasService.java

@ -1,48 +1,49 @@
//package com.yihu.jw.config.security;
//
//import com.yihu.base.security.rbas.IRbasService;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.stereotype.Service;
//import org.springframework.util.AntPathMatcher;
//
//import javax.servlet.http.HttpServletRequest;
//import java.util.HashSet;
//import java.util.Set;
//
///**
// * Created by chenweida on 2017/12/5.
// * 判断用户是否有权限访问该路径
// */
//@Service("rbasService")
//public class RbasService implements IRbasService {
//
//    private AntPathMatcher antPathMatcher = new AntPathMatcher();
//
//
//    @Override
//    public Boolean hasPerssion(HttpServletRequest request, Authentication authentication) {
//        Object principal = authentication.getPrincipal();
//        boolean hasPerssion = false;
//        if (principal instanceof UserDetails) {
//            //获取用户名字
//            String username = ((UserDetails) principal).getUsername();
//
//
//            //获取用户全部权限
//            Set<String> uris = new HashSet<>();
//            for (String uri : uris) {
//                if (antPathMatcher.match(uri, request.getRequestURI())) {
//                    hasPerssion = true;
//                    break;
//                }
//            }
//        }
//        return true;
//        //  return hasPerssion;
//    }
//
//    public Boolean hello() {
//        return true;
//    }
//}
package com.yihu.jw.config.security;
import com.yihu.base.security.rbas.RbasServiceProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;
/**
 * Created by chenweida on 2017/12/5.
 * 判断用户是否有权限访问该请求路径
 */
@Service("rbasServiceProvider")
public class RbasService implements RbasServiceProvider {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Boolean hasPerssion(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPerssion = false;
        if (principal instanceof UserDetails) {
            //获取用户名字
            String username = ((UserDetails) principal).getUsername();
            String[] saasPhone = username.split(",");
            String saas = saasPhone[0];
            String phone = saasPhone[1];
            //从数据库获取用户全部权限
            Set<String> uris = new HashSet<>();
            for (String uri : uris) {
                if (antPathMatcher.match(uri, request.getRequestURI())) {
                    hasPerssion = true;
                    break;
                }
            }
            return hasPerssion;
        }else{
            return true;
        }
    }
}

+ 63 - 59
web-gateway/src/main/java/com/yihu/jw/config/security/UserService.java

@ -1,61 +1,65 @@
//package com.yihu.jw.config.security;
//
//
//import com.yihu.jw.fegin.base.user.EmployFeign;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.authority.AuthorityUtils;
//import org.springframework.security.core.userdetails.User;
//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.crypto.password.PasswordEncoder;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//
///**
// * Created by chenweida on 2017/11/29.
// * 处理用户校验
// */
//@Component
//public class UserService implements UserDetailsService {
//
//    @Autowired
//    private PasswordEncoder passwordEncoder;
package com.yihu.jw.config.security;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.fegin.base.user.EmployFeign;
import com.yihu.jw.restmodel.common.Envelop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
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.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
 * Created by chenweida on 2017/11/29.
 * 处理用户校验
 */
@Component
public class UserService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private EmployFeign employFeign;
//    @Autowired
//    private EmployFeign employFeign;
//
//    /**
//     * 我们只需要把用户返回给spring-security 密码框架自己帮我们校验
//     *
//     * @param userName
//     * @return
//     * @throws UsernameNotFoundException
//     */
//    @Override
//    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
//        if ("admin".equals(userName)) {
//            System.out.printf("password:" + passwordEncoder.encode("123456"));
//            return new User("admin",
//                    passwordEncoder.encode("123456"),
//                    true,
//                    true,
//                    true,
//                    true
//                    , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER") //权限
//            );
//        } else if ((!StringUtils.isEmpty(userName))&&userName.length() == 11) {
//            System.out.printf("password:" + passwordEncoder.encode("123456"));
//            return new User("admin",
//                    passwordEncoder.encode("123456"),
//                    true,
//                    true,
//                    true,
//                    true
//                    , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER") //权限
//            );
//        } else {
//            throw new UsernameNotFoundException("用户不存在");
//        }
//    }
//
//}
    /**
     * 我们只需要把用户返回给spring-security 密码框架自己帮我们校验
     *
     * @param saasPhone
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String saasPhone) throws UsernameNotFoundException {
        //saasPhone=saas+phone
        //根据userName获取账户信息(手机号码)
        String[] sp = saasPhone.split(",");
        String phone = sp[0];
        String saasId = sp[1];
        Envelop envelop = employFeign.getEmployeeByPhoneAndSaasId(phone,saasId);
        Map baseEmployDO =  (Map)envelop.getObj();
        if (!baseEmployDO.isEmpty()) {
            return new User(saasPhone,
                    passwordEncoder.encode(baseEmployDO.get("password")+""),
                    true,
                    true,
                    true,
                    true
                    , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER") //权限
            );
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }
}

+ 100 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/login/LoginContorller.java

@ -0,0 +1,100 @@
package com.yihu.jw.controller.base.login;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.sms.mobile.MobileCheck;
import com.yihu.base.security.sms.process.SmsValidateCodeProcessor;
import com.yihu.jw.common.base.base.BaseContants;
import com.yihu.jw.fegin.base.base.FunctionFeign;
import com.yihu.jw.fegin.base.login.LoginFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
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.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by 刘文彬 on 2018/4/20.
 */
@RestController
@RequestMapping(BaseLoginRequestMapping.api_gateway_common)
@Api(value = "登录模块", description = "登录模块")
public class LoginContorller {
    @Autowired
    private LoginFeign loginFeign;
    @Autowired
    private MobileCheck mobileCheck;
    @Autowired
    private SmsValidateCodeProcessor smsValidateCodeProcessor;
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_checkoutInfo, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "注册校验信息", notes = "注册校验姓名、身份证、医保卡号信息")
    public Envelop checkoutInfo(){
        return loginFeign.checkoutInfo();
    }
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_accountSub, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "注册账号", notes = "注册校验姓名、身份证、医保卡号信息")
    public Envelop register(
            @ApiParam(name = "mobilePhone", value = "电话号码(账号)", required = true) @RequestParam(value = "mobilePhone", required = true) String mobilePhone,
            @ApiParam(name = "saasId", value = "saasID", required = true) @RequestParam(value = "saasId", required = true) String saasId,
            @ApiParam(name = "type", value = "1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录", required = true) @RequestParam(value = "type", required = true) int type,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(value = "captcha", required = true) String captcha,
            @ApiParam(name = "name", value = "姓名", required = true) @RequestParam(value = "name", required = true) String name,
            @ApiParam(name = "password", value = "账户密码", required = true) @RequestParam(value = "password", required = true) String password,
            @ApiParam(name = "idcard", value = "身份证", required = true) @RequestParam(value = "idcard", required = true) String idcard,
            @ApiParam(name = "ssc", value = "医保卡号", required = true) @RequestParam(value = "ssc", required = true) String ssc) {
        return loginFeign.register(mobilePhone,saasId,type,captcha,name,password,idcard,ssc);
    }
    @PostMapping(BaseLoginRequestMapping.BaseLoginAccount.mobileSendSms)
    @ApiOperation(value = "发送短信登录的验证码", notes = "不走校验框架")
    public BaseEnvelop createCode(@ApiParam(name = "mobile", value = "手机号", required = true) @RequestParam(value = "mobile", required = true) String mobile,
                                  HttpServletRequest request, HttpServletResponse response) throws Exception{
        //验证手机号是否正确
        String[] mobileSaas = mobile.split(",");
        if (!mobileCheck.checkMobile(mobileSaas[0])) {
            return BaseEnvelop.getError("手机格式错误!");
        } else {
            //发送短信验证码并且保存到redis中
            smsValidateCodeProcessor.create(new ServletWebRequest(request, response));
            return BaseEnvelop.getSuccess("发送成功!");
        }
    }
    @PostMapping(BaseLoginRequestMapping.BaseLoginAccount.api_login)
    public Envelop login(@ApiParam(name = "mobilePhone", value = "电话号码(账号)", required = false) @RequestParam(value = "mobilePhone", required = false) String mobilePhone,
                       @ApiParam(name = "password", value = "password", required = false) @RequestParam(value = "password", required = false) String password,
                       @ApiParam(name = "saasId", value = "saasID", required = true) @RequestParam(value = "saasId", required = true) String saasId,
                       @ApiParam(name = "captcha", value = "短信验证码", required = false) @RequestParam(value = "captcha", required = false) String captcha){
        return loginFeign.login(mobilePhone,password,saasId,captcha);
    }
//    @PostMapping("/logout")
//    public Envelop logout(){
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Accept", "*/*");
//        headers.add("Cache-Control", "no-cache");
//        RestTemplate restTemplate = new RestTemplate();
//        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
//        //设置http请求实体
//        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
//        restTemplate.postForObject("http://localhost:8088/logout", requestEntity, String.class);
//        return new Envelop();
//    }
}

+ 40 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/login/RegisterSmsContorller.java

@ -0,0 +1,40 @@
package com.yihu.jw.controller.base.login;
import com.yihu.jw.common.base.base.BaseContants;
import com.yihu.jw.fegin.base.sms.RegisterSmsFeign;
import com.yihu.jw.fegin.common.security.LoginSmsFeign;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
/**
 * Created by 刘文彬 on 2018/4/24.
 */
@RestController
@RequestMapping(BaseLoginRequestMapping.api_common)
@Api(value = "注册发送短信验证码", description = "注册发送短信验证码")
public class RegisterSmsContorller {
    @Autowired
    private RegisterSmsFeign registerSmsFeign;
    @PostMapping(value = BaseSmsRequestMapping.Sms.api_sms_send, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码")
    BaseEnvelop send(@ApiParam(name = "mobile", value = "手机号码", required = true) @RequestParam(value = "mobile", required = true) String mobile,
                     @ApiParam(name = "type", value = "短信验证码类型", required = true) @RequestParam(value = "type", required = true) int type,
                     @ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) throws IOException{
        return registerSmsFeign.send(mobile,type,saasId);
    }
}

+ 134 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/security/TokenController.java

@ -0,0 +1,134 @@
package com.yihu.jw.controller.base.security;
import com.yihu.base.security.rbas.ClientServiceProvider;
import com.yihu.jw.fegin.base.user.EmployFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
import com.yihu.jw.rm.base.BaseSecurityRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
 * Created by 刘文彬 on 2018/5/4.
 */
@RestController
@RequestMapping(BaseLoginRequestMapping.api_gateway_common)
@Api(value = "权限token模块", description = "权限token模块")
public class TokenController {
    @Autowired
    private DefaultTokenServices defaultTokenServices;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private ClientServiceProvider clientDetailsService;
    @Autowired
    private EmployFeign employFeign;
    @PostMapping(BaseSecurityRequestMapping.BaseToken.api_update_token_expiration_time)
    @ApiOperation(value = "更新token过期时间", notes = "根据token更新token过期时间")
    public BaseEnvelop updateTokenExpiration(@ApiParam(name = "expiration", value = "token过期时间,格式:yyyy-mm-dd HH:mm:ss", required = true)
                     @RequestParam(value = "expiration", required = true) String expiration,
                     @ApiParam(name = "authHeaderValue", value = "登录的token", required = true)
                     @RequestParam(value = "authHeaderValue", required = true) String authHeaderValue){
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken)defaultTokenServices.readAccessToken(authHeaderValue);
        if(token!=null){
            token.setExpiration(DateUtil.strToDate(expiration));
            return BaseEnvelop.getSuccess("token 过期时间设置成功!");
        }
        return BaseEnvelop.getError("token 无效!");
    }
    @PostMapping(BaseSecurityRequestMapping.BaseToken.api_update_token_expiration_second)
    @ApiOperation(value = "延长token的过期时间", notes = "根据token延长token的过期时间")
    public BaseEnvelop updateTokenExpiration(@ApiParam(name = "seconds", value = "延长token过期时间分钟数", required = true)
                                             @RequestParam(value = "seconds", required = true) int seconds,
                                             @ApiParam(name = "authHeaderValue", value = "登录的token", required = true)
                                             @RequestParam(value = "authHeaderValue", required = true) String authHeaderValue){
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken)defaultTokenServices.readAccessToken(authHeaderValue);
        if(token!=null){
            token.setExpiration(new Date(System.currentTimeMillis() + (seconds * 1000L)));
            return BaseEnvelop.getSuccess("token 过期时间设置成功!");
        }
        return BaseEnvelop.getError("token 无效!");
    }
    @PostMapping(BaseSecurityRequestMapping.BaseToken.api_update_token_expiration)
    @ApiOperation(value = "设置token过期", notes = "设置token过期")
    public BaseEnvelop updateTokenExpiration2(HttpServletRequest request, HttpServletResponse response,
                                              @ApiParam(name = "authHeaderValue", value = "登录的token", required = true)
                                              @RequestParam(value = "authHeaderValue", required = true) String authHeaderValue){
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken)defaultTokenServices.readAccessToken(authHeaderValue);
        if(token!=null){
            token.setExpiration(new Date());
            return BaseEnvelop.getSuccess("token 过期时间设置成功!");
        }
        return BaseEnvelop.getError("token 无效!");
    }
    @PostMapping(BaseSecurityRequestMapping.BaseToken.api_update_token_expiration_second2)
    @ApiOperation(value = "设置token过期", notes = "设置token过期")
    public BaseEnvelop updateTokenExpiration3(HttpServletRequest request, HttpServletResponse response,
                                              @ApiParam(name = "mobileSaas", value = "mobile和saas组合,逗号分隔", required = true)
                                              @RequestParam(value = "mobileSaas", required = true) String mobileSaas){
        String[] sp = mobileSaas.split(",");
        String phone = sp[0];
        String saasId = sp[1];
        Envelop envelop = employFeign.getEmployeeByPhoneAndSaasId(phone,saasId);
        Map baseEmployDO =  (Map)envelop.getObj();
        if(baseEmployDO.isEmpty()){
            return BaseEnvelop.getError("该用户不存在!");
        }
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                mobileSaas, baseEmployDO.get("password"));
        // Allow subclasses to set the "details" property
        authRequest.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        Authentication authentication = authenticationManager.authenticate(authRequest);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(saasId);
        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, saasId, clientDetails.getScope(), "custom_password");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken)defaultTokenServices.getAccessToken(oAuth2Authentication);
        if(token!=null){
            token.setExpiration(new Date());
            return BaseEnvelop.getSuccess("token 过期时间设置成功!");
        }
        return BaseEnvelop.getError("token 无效!");
    }
}

+ 18 - 0
web-gateway/src/main/resources/application.yml

@ -11,6 +11,24 @@ spring:
      enabled: true
      max-file-size: 500MB
      max-request-size: 500MB
  data:
    elasticsearch: #ElasticsearchProperties
      cluster-name: jkzl #默认即为elasticsearch  集群名
      cluster-nodes: 172.19.103.45:9300,172.19.103.68:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
      local: false #是否本地连接
      properties: # Additional properties used to configure the client.
        enable: true
    # JEST (Elasticsearch HTTP client) (JestProperties)
  elasticsearch:
    jest:
      uris: http://172.19.103.45:9200,http://172.19.103.68:9200
#      uris: http://172.19.103.68:9200
      connection-timeout: 60000 # Connection timeout in milliseconds.
      multi-threaded: true
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
    database: 0
##开启feign断路器
feign:

+ 2 - 1
web-gateway/src/main/resources/bootstrap.yml

@ -20,7 +20,8 @@ eureka:
  client:
    serviceUrl:
      #http://账号:密码@127.0.0.1:8761/eureka/
      defaultZone: http://jw:jkzl@172.19.103.33:8761/eureka/
#      defaultZone: http://jw:jkzl@172.19.103.33:8761/eureka/
      defaultZone: http://jw:jkzl@127.0.0.1:8761/eureka/
---
spring: