Selaa lähdekoodia

1、收入填报时需要填到账时间;
2、累计欠费汇总时A项超额不能抵扣B项欠费;
3、超额完成收入需要汇总

yanliming 10 kuukautta sitten
vanhempi
commit
48d30e3571

+ 9 - 3
common/pom.xml

@@ -166,9 +166,15 @@
 
         <!--短信相关 start-->
         <dependency>
-            <groupId>com.taobao</groupId>
-            <artifactId>taobao-sdk-java</artifactId>
-            <version>1.0.0</version>
+            <groupId>com.aliyun</groupId>
+            <artifactId>aliyun-java-sdk-core</artifactId>
+            <version>4.5.0</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
+            <version>1.1.0</version>
         </dependency>
         <!--短信相关 end-->
 

+ 3 - 0
common/src/main/java/com/jpsoft/employment/modules/base/entity/TemplateInfo.java

@@ -60,5 +60,8 @@ public class TemplateInfo {
 	@ApiModelProperty(value = "所属年份")
 	private String year;
 
+	@ApiModelProperty(value = "创建人")
+	private String createByN;
+
 	
 		}

+ 22 - 12
common/src/main/java/com/jpsoft/employment/modules/base/service/impl/TemplateOptionServiceImpl.java

@@ -14,6 +14,8 @@ import com.jpsoft.employment.modules.base.dto.TemplateOptionDTO;
 import com.jpsoft.employment.modules.base.entity.FundIncomeInfo;
 import com.jpsoft.employment.modules.base.entity.TemplateInfo;
 import com.jpsoft.employment.modules.common.utils.StringUtils;
+import com.jpsoft.employment.modules.sys.dao.UserDAO;
+import com.jpsoft.employment.modules.sys.entity.User;
 import org.springframework.stereotype.Component;
 import org.springframework.transaction.annotation.Transactional;
 import com.jpsoft.employment.modules.base.dao.TemplateOptionDAO;
@@ -35,6 +37,9 @@ public class TemplateOptionServiceImpl implements TemplateOptionService {
     @Resource(name = "templateInfoDAO")
     private TemplateInfoDAO templateInfoDAO;
 
+    @Resource(name = "userDAO")
+    private UserDAO userDAO;
+
     @Override
     public TemplateOption get(String id) {
         // TODO Auto-generated method stub
@@ -137,6 +142,8 @@ public class TemplateOptionServiceImpl implements TemplateOptionService {
         String templateId = dto.getTemplateId();
         Date now = new Date();
 
+        User user = userDAO.get(subject);
+
         int affectCount = 0;
 
         List<TemplateOption> curList = templateOptionDAO.findByTemplateId(templateId);
@@ -157,20 +164,23 @@ public class TemplateOptionServiceImpl implements TemplateOptionService {
             templateOption.setCreateBy(subject);
             templateOption.setDelFlag(false);
 
-
-            if (templateOption.getDepartmentIdArr() != null && templateOption.getDepartmentIdArr().length > 0) {
-                String[] arr = templateOption.getDepartmentIdArr();
-                String departmentId = "";
-                for (String departId : arr) {
-                    departmentId += departId + ",";
-                }
-
-                if (StringUtils.isNotEmpty(departmentId)) {
-                    departmentId = departmentId.substring(0, departmentId.lastIndexOf(","));
-                    templateOption.setDepartmentIds(departmentId);
-                }
+            if(StringUtils.isNotEmpty(user.getDepartmentId())){
+                templateOption.setDepartmentIds(user.getDepartmentId());
             }
 
+//            if (templateOption.getDepartmentIdArr() != null && templateOption.getDepartmentIdArr().length > 0) {
+//                String[] arr = templateOption.getDepartmentIdArr();
+//                String departmentId = "";
+//                for (String departId : arr) {
+//                    departmentId += departId + ",";
+//                }
+//
+//                if (StringUtils.isNotEmpty(departmentId)) {
+//                    departmentId = departmentId.substring(0, departmentId.lastIndexOf(","));
+//                    templateOption.setDepartmentIds(departmentId);
+//                }
+//            }
+
             if (templateOption.getIncomeTimeRangeArr() != null && templateOption.getIncomeTimeRangeArr().length > 0) {
                 String[] arr = templateOption.getIncomeTimeRangeArr();
 

+ 5 - 0
common/src/main/java/com/jpsoft/employment/modules/common/service/SmsService.java

@@ -0,0 +1,5 @@
+package com.jpsoft.employment.modules.common.service;
+
+public interface SmsService {
+    boolean sendVerificationCode(String phoneNumber, String code);
+}

+ 38 - 0
common/src/main/java/com/jpsoft/employment/modules/common/service/impl/SmsServiceImpl.java

@@ -0,0 +1,38 @@
+package com.jpsoft.employment.modules.common.service.impl;
+
+import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
+import com.jpsoft.employment.modules.common.service.SmsService;
+import com.jpsoft.employment.modules.common.utils.AliyunSmsConfig;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+
+@Service
+@Slf4j
+public class SmsServiceImpl implements SmsService {
+
+    @Resource
+    private AliyunSmsConfig aliyunSmsConfig;
+
+
+    @Override
+    public boolean sendVerificationCode(String phoneNumber, String code) {
+        try {
+            // aliyun 短信测试控制台地址  https://dysms.console.aliyun.com/quickstart?spm=5176.25163407.domtextsigncreate-index-1ec3c_58c50_0.1.3ac1bb6eYTArb1
+            // 因为是测试,这个地址先绑定测试机号码,选择专用测试模版 然后点击 下方调用api发送消息  就能看到 signName, templateCode,templateParam 这4个参数
+            // 如果是正式环境 需要先审核资质,审核模板,然后添加签名,审核完成之后,就能看到所需要的参数(这里我自己为了方便就不去做资质审核了)
+            SendSmsResponse response = aliyunSmsConfig.sendSms(
+                    phoneNumber,
+                    "十八匠", // 阿里云短信签名
+                    "SMS_478595063", // 阿里云短信模板代码
+                    "{\"code\":\"" + code + "\"}" // 模板参数
+            );
+            log.info(response.getCode());
+            return "OK".equals(response.getCode());
+        } catch (Exception e) {
+            e.printStackTrace();
+            return false;
+        }
+    }
+}

+ 40 - 0
common/src/main/java/com/jpsoft/employment/modules/common/utils/AliyunSmsConfig.java

@@ -0,0 +1,40 @@
+package com.jpsoft.employment.modules.common.utils;
+
+
+import com.aliyuncs.DefaultAcsClient;
+import com.aliyuncs.IAcsClient;
+import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
+import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
+import com.aliyuncs.profile.DefaultProfile;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class AliyunSmsConfig {
+    @Value("${aliyun.accessKeyId}")
+    private String accessKeyId;
+
+    @Value("${aliyun.accessKeySecret}")
+    private String accessKeySecret;
+
+    @Value("${aliyun.regionId}")
+    private String regionId;
+
+    @Bean
+    public IAcsClient acsClient() {
+        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
+        return new DefaultAcsClient(profile);
+    }
+
+    public SendSmsResponse sendSms(String phoneNumber, String signName, String templateCode, String templateParam) throws Exception {
+        IAcsClient client = acsClient();
+        SendSmsRequest request = new SendSmsRequest();
+        request.setPhoneNumbers(phoneNumber);
+        request.setSignName(signName);
+        request.setTemplateCode(templateCode);
+        request.setTemplateParam(templateParam);
+
+        return client.getAcsResponse(request);
+    }
+}

+ 40 - 157
common/src/main/java/com/jpsoft/employment/modules/common/utils/SMSUtil.java

@@ -1,166 +1,49 @@
 package com.jpsoft.employment.modules.common.utils;
 
-import com.jpsoft.employment.modules.common.dto.MessageResult;
-import com.taobao.api.ApiException;
-import com.taobao.api.DefaultTaobaoClient;
-import com.taobao.api.TaobaoClient;
-import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
-import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
-import net.sf.json.JSONException;
-import net.sf.json.JSONObject;
 
 import java.util.Random;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
 
 
 public class SMSUtil {
-
-	public final static String REG_TEMPLATE_CODE = "SMS_49390047";
-	public static final String NUMBERCHAR = "0123456789";
-
-	private final static String APP_KEY = "24698874";
-	private final static String APP_SECRET = "5f5b21d1dc93e124aa803f95d71c00b8";
-	private final static String APP_URL = "https://eco.taobao.com/router/rest";
-	private final static String SIGN_NAME = "小鹏管家"; //校信达
-	private final static String SMS_TYPE = "normal";
-
-	/**
-	 *
-	 * @param phones 手机号,多个以英文逗号","隔开
-	 * @param smsTemplateCode 短信模版ID
-	 * @param jsonStr 短信模板变量,传参规则{"key":"value"},key的名字须和申请模板中的变量名一致,多个变量之间以逗号隔开。示例:针对模板“验证码${code},您正在进行${product}身份验证,打死不要告诉别人哦!”,传参时需传入{"code":"1234","product":"alidayu"}
-	 * @return
-	 */
-	public static MessageResult send(String phones, String smsTemplateCode, String jsonStr){
-
-		boolean success = true;
-		String msg = "发送成功";
-
-		TaobaoClient client = new DefaultTaobaoClient(APP_URL, APP_KEY, APP_SECRET);
-		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
-		req.setSmsType(SMS_TYPE);
-		req.setSmsFreeSignName(SIGN_NAME);
-		if(jsonStr != null){
-			req.setSmsParamString(jsonStr);
-		}
-		req.setRecNum(phones);
-		req.setSmsTemplateCode(smsTemplateCode);
-		AlibabaAliqinFcSmsNumSendResponse rsp;
-		try {
-			rsp = client.execute(req);
-
-			JSONObject ret = JSONObject.fromObject(rsp.getBody());
-
-			System.out.println("ret>>>>" + ret);
-
-			if(ret.containsKey("error_response")){
-				success = false;
-				msg = ret.getJSONObject("error_response").getString("sub_msg");
-			}else if(ret.containsKey("alibaba_aliqin_fc_sms_num_send_response")){
-
-				JSONObject result = ret.getJSONObject("alibaba_aliqin_fc_sms_num_send_response").getJSONObject("result");
-
-				if(!result.getBoolean("success")){
-					msg = result.getString("msg");
-				}
-			}else{
-				success = false;
-				msg = ret.toString();
-			}
-		} catch (ApiException e) {
-			success = false;
-			msg = e.getErrMsg();
-		} catch (JSONException ex) {
-			success = false;
-			msg = ex.getMessage();
-		}
-
-		MessageResult retMessage = new MessageResult();
-
-		retMessage.setMessage(msg);
-		retMessage.setResult(success);
-
-		return retMessage;
-	}
-
-	/**
-	 *
-	 * @param phones 手机号,多个以英文逗号","隔开
-	 * @param signName 签名:目前仅支持"荆鹏云平台","速乐购"两种签名
-	 * @param smsTemplateCode 短信模版ID
-	 * @param json 短信模板变量,传参规则{"key":"value"},key的名字须和申请模板中的变量名一致,多个变量之间以逗号隔开。示例:针对模板“验证码${code},您正在进行${product}身份验证,打死不要告诉别人哦!”,传参时需传入{"code":"1234","product":"alidayu"}
-	 * @return
-	 */
-	public static MessageResult send(String phones, String signName, String smsTemplateCode, JSONObject json) throws Exception{
-
-		boolean success = true;
-		String msg = "发送成功";
-
-		TaobaoClient client = new DefaultTaobaoClient(APP_URL, APP_KEY, APP_SECRET);
-		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
-		req.setSmsType(SMS_TYPE);
-		req.setSmsFreeSignName(signName);
-		if(json != null){
-			req.setSmsParamString(json.toString());
-		}
-		req.setRecNum(phones);
-		req.setSmsTemplateCode(smsTemplateCode);
-		AlibabaAliqinFcSmsNumSendResponse rsp;
-		try {
-			rsp = client.execute(req);
-
-			JSONObject ret = JSONObject.fromObject(rsp.getBody());
-
-			System.out.println("ret>>>>" + ret);
-
-			if(ret.containsKey("error_response")){
-				success = false;
-				throw new Exception(ret.getJSONObject("error_response").getString("sub_msg"));
-			//	msg = ret.getJSONObject("error_response").getString("sub_msg");
-			}else if(ret.containsKey("alibaba_aliqin_fc_sms_num_send_response")){
-
-				JSONObject result = ret.getJSONObject("alibaba_aliqin_fc_sms_num_send_response").getJSONObject("result");
-
-				if(!result.getBoolean("success")){
-					msg = result.getString("msg");
-				}
-			}else{
-				success = false;
-				throw new Exception(ret.toString());
-		//		msg = ret.toString();
-			}
-		} catch (ApiException e) {
-			success = false;
-			throw new Exception(e.getErrMsg());
-		//	msg = e.getErrMsg();
-		} catch (JSONException ex) {
-			success = false;
-			msg = ex.getMessage();
-			throw new Exception(ex.getMessage());
-		}
-
-		MessageResult retMessage = new MessageResult();
-
-		retMessage.setMessage(msg);
-		retMessage.setResult(success);
-
-		return retMessage;
-	}
-
-
-
-	public static String generateNumberString(int length) {
-		StringBuffer sb = new StringBuffer();
-		Random random = new Random();
-		for (int i = 0; i < length; i++) {
-			sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
-		}
-		return sb.toString();
-	}
-
-//	public static void main(String[] args) {
-//		JSONObject verifyCodeJSON = new JSONObject();
-//		verifyCodeJSON.put("code", "66666");
+    private final static String APP_KEY = "LTAI5tS5VM3ewtNgMBugXRVu";
+    private final static String APP_SECRET = "GSEiVLd4nj6CN7KahXX6FOl1N8PNpw";
+    private final static String SIGN_NAME = "十八匠";
+    private final static String templateCode = "SMS_478595063";
+
+
+    /**
+     * 生成验证码
+     *
+     * @return
+     */
+    public static String getCaptcha() {
+        String str = "0,1,2,3,4,5,6,7,8,9";
+        String str2[] = str.split(",");// 将字符串以,分割
+        Random rand = new Random();// 创建Random类的对象rand
+        int index = 0;
+        String randStr = "";// 创建内容为空字符串对象randStr
+        randStr = "";// 清空字符串对象randStr中的值
+        for (int i = 0; i < 6; ++i) {
+            index = rand.nextInt(str2.length - 1);// 在0到str2.length-1生成一个伪随机数赋值给index
+            randStr += str2[index];// 将对应索引的数组与randStr的变量值相连接
+        }
+        return randStr;
+    }
+
+    public static void main(String[] args) {
+
+//        try {
+//            String phone = "15207211859";
+//            String code = getCaptcha();
 //
-//		SMSUtil.send("13437120102", "SMS_49390047", verifyCodeJSON.toString());
-//	}
+//            // 发送短信验证码
+//            sendSms(phone, code);
+//        } catch (ExecutionException e) {
+//            e.printStackTrace();
+//        } catch (InterruptedException e) {
+//            e.printStackTrace();
+//        }
+    }
 }

+ 9 - 0
common/src/main/java/com/jpsoft/employment/modules/sys/entity/User.java

@@ -25,6 +25,7 @@ public class User {
 	private String companyId;
 	private String companyName;
 	private String departmentId;
+	private String phone;
 
 
 	@ApiModelProperty(value = "头像")
@@ -225,4 +226,12 @@ public class User {
 	public void setDepartmentId(String departmentId) {
 		this.departmentId = departmentId;
 	}
+
+	public String getPhone() {
+		return phone;
+	}
+
+	public void setPhone(String phone) {
+		this.phone = phone;
+	}
 }

+ 2 - 3
common/src/main/resources/mapper/base/FundIncomeInfo.xml

@@ -243,7 +243,7 @@
 	</select>
 	<select id="findBudgetRevenue" resultType="java.util.Map">
 		<![CDATA[
-			select cur_budget_revenue-sum(cur_month_received) as 'accAmount' from base_fund_income_info
+			select cur_budget_revenue-sum(IFNULL(cur_month_received,0)) as 'accAmount' from base_fund_income_info
 		]]>
 		<where>
 			del_flag=false and is_sum=FALSE
@@ -256,8 +256,7 @@
 					and template_id=#{templateId}
 				]]>
 		</where>
-		GROUP BY template_option_id
-		order by create_time
+		GROUP BY template_option_id,cur_budget_revenue
 	</select>
 	<select id="search" parameterType="hashmap" resultMap="FundIncomeInfoMap">
 		<![CDATA[

+ 3 - 0
common/src/main/resources/mapper/base/TemplateInfo.xml

@@ -119,6 +119,9 @@
 			<if test="searchParams.year != null">
 				and year_ = #{searchParams.year}
 			</if>
+			<if test="searchParams.createBy != null">
+				and create_by = #{searchParams.createBy}
+			</if>
 		</where>
 		<foreach item="sort" collection="sortList"  open="order by" separator=",">
 	        ${sort.name} ${sort.order}

+ 6 - 2
common/src/main/resources/mapper/sys/User.xml

@@ -18,7 +18,7 @@
         <result property="companyName" column="company_name"/>
         <result property="photo" column="photo_"/>
         <result property="departmentId" column="department_id"/>
-
+        <result property="phone" column="phone_"/>
     </resultMap>
 
     <resultMap id="UserVOMap" type="com.jpsoft.employment.modules.sys.entity.UserVO" extends="UserMap">
@@ -36,7 +36,7 @@
         <![CDATA[
 		insert into sys_user
 	    (id_,user_name,password_,real_name,create_time,update_time,
-	    del_flag,create_by,update_by,open_id,company_id,photo_,department_id)
+	    del_flag,create_by,update_by,open_id,company_id,photo_,department_id,phone_)
 		values
 		(
             #{id,jdbcType=VARCHAR}
@@ -52,6 +52,7 @@
             ,#{companyId,jdbcType=VARCHAR}
             ,#{photo,jdbcType=VARCHAR}
             ,#{departmentId,jdbcType=VARCHAR}
+            ,#{phone,jdbcType=VARCHAR}
 		)
 	]]>
     </insert>
@@ -97,6 +98,9 @@
             <if test="departmentId!=null">
                 department_id=#{departmentId,jdbcType=VARCHAR},
             </if>
+            <if test="phone!=null">
+                phone_=#{phone,jdbcType=VARCHAR},
+            </if>
         </set>
         where id_=#{id}
     </update>

+ 1 - 1
web/src/main/java/com/jpsoft/employment/config/WebMvcConfig.java

@@ -72,7 +72,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
 				.excludePathPatterns("/mobile/training/trainingDetail")
 				.excludePathPatterns("/wechat/decryptData")
 				.excludePathPatterns("/mobile/user/saveLoginRecord")
-
+				.excludePathPatterns("/generateCaptCha")
 		;
 
 

+ 18 - 6
web/src/main/java/com/jpsoft/employment/modules/base/controller/FundIncomeInfoController.java

@@ -1086,15 +1086,17 @@ public class FundIncomeInfoController {
                 BigDecimal accumulatedArrears1 = BigDecimal.ZERO;
 
                 for (Map<String, BigDecimal> mapItem : accListMap) {
-                    BigDecimal accAmount = mapItem.get("accAmount");
+                    if (mapItem != null && mapItem.get("accAmount") != null) {
+                        BigDecimal accAmount = mapItem.get("accAmount");
 
-                    accumulatedArrears1 = accumulatedArrears1.add(accAmount);
+                        accumulatedArrears1 = accumulatedArrears1.add(accAmount);
 
-                    if (accAmount.compareTo(BigDecimal.ZERO) < 0) {
-                        accAmount = BigDecimal.ZERO;
-                    }
+                        if (accAmount.compareTo(BigDecimal.ZERO) < 0) {
+                            accAmount = BigDecimal.ZERO;
+                        }
 
-                    accumulatedArrears = accumulatedArrears.add(accAmount);
+                        accumulatedArrears = accumulatedArrears.add(accAmount);
+                    }
 
                 }
 
@@ -1132,6 +1134,16 @@ public class FundIncomeInfoController {
 
                 BigDecimal curMonthReceived = fundIncomeInfoService.sumByTemplateOptionId(item.getId(), startDate, endDate);
 
+                FundIncomeInfo fundIncomeInfo = fundIncomeInfoService.findOneByTemplateOptionId(item.getId(), startDate, endDate);
+
+
+                //责任人
+                String chargePerson = "";
+                if (fundIncomeInfo != null) {
+                    chargePerson = fundIncomeInfo.getChargePerson();
+                }
+                map.put("chargePerson", chargePerson);
+
                 //本月到账
                 map.put("curMonthReceived", curMonthReceived);
 

+ 20 - 0
web/src/main/java/com/jpsoft/employment/modules/base/controller/TemplateInfoController.java

@@ -6,6 +6,8 @@ import com.jpsoft.employment.modules.common.dto.MessageResult;
 import com.jpsoft.employment.modules.base.entity.TemplateInfo;
 import com.jpsoft.employment.modules.base.service.TemplateInfoService;
 import com.jpsoft.employment.modules.common.utils.PojoUtils;
+import com.jpsoft.employment.modules.sys.entity.User;
+import com.jpsoft.employment.modules.sys.service.UserService;
 import io.swagger.annotations.ApiOperation;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
@@ -24,6 +26,9 @@ public class TemplateInfoController {
 
     @Autowired
     private TemplateInfoService templateInfoService;
+
+    @Autowired
+    private UserService userService;
 	
 	
 	@ApiOperation(value="创建空记录")
@@ -207,10 +212,18 @@ public class TemplateInfoController {
         //当前用户ID
         System.out.println(subject);
 
+        User user = userService.get(subject);
+
+
+
         MessageResult<Map> msgResult = new MessageResult<>();
 
         Map<String,Object> searchParams = new HashMap<>();
 
+        if(!userService.hasRole(user.getId(),"SYSADMIN")&&!userService.hasRole(user.getId(),"ADMIN")) {
+            searchParams.put("createBy",user.getId());
+        }
+
         List<Sort> sortList = new ArrayList<>();
         sortList.add(new Sort("create_time","desc"));
 
@@ -225,6 +238,13 @@ public class TemplateInfoController {
 
         Page<TemplateInfo> page = templateInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
 
+        for (TemplateInfo templateInfo:page) {
+            User user1 = userService.get(templateInfo.getCreateBy());
+            if(user1!=null){
+                templateInfo.setCreateByN(user1.getRealName());
+            }
+        }
+
 
         msgResult.setResult(true);
         msgResult.setData(PojoUtils.pageWrapper(page));

+ 105 - 31
web/src/main/java/com/jpsoft/employment/modules/common/controller/JwtsUserController.java

@@ -1,9 +1,12 @@
 package com.jpsoft.employment.modules.common.controller;
 
 
+import com.github.pagehelper.util.StringUtil;
 import com.jpsoft.employment.modules.common.dto.MessageResult;
+import com.jpsoft.employment.modules.common.service.SmsService;
 import com.jpsoft.employment.modules.common.utils.DES3;
 import com.jpsoft.employment.modules.common.utils.JwtUtil;
+import com.jpsoft.employment.modules.common.utils.SMSUtil;
 import com.jpsoft.employment.modules.sys.entity.User;
 import com.jpsoft.employment.modules.sys.service.UserService;
 import io.swagger.annotations.ApiImplicitParam;
@@ -15,11 +18,13 @@ import org.apache.commons.lang3.StringUtils;
 import org.joda.time.DateTime;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.core.ValueOperations;
 import org.springframework.web.bind.annotation.*;
 import springfox.documentation.annotations.ApiIgnore;
 
 import javax.servlet.http.HttpSession;
+import java.util.HashMap;
 import java.util.concurrent.TimeUnit;
 
 @Slf4j
@@ -32,38 +37,46 @@ public class JwtsUserController {
     private UserService userService;
 
     @Autowired
-    private ValueOperations<String,Object> valueOperations;
+    private SmsService smsService;
+
+    @Autowired
+    private RedisTemplate<String, String> redisTemplate;
+
+    @Autowired
+    private ValueOperations<String, Object> valueOperations;
+
+    private HashMap<String, Long> captchaStore = new HashMap<>();
 
     /**
      * 接收扫码登录回调
+     *
      * @param eventKey
      * @param openId
      * @return 返回值会在微信中显示
      */
     @ApiOperation(value = "接收扫码登录回调")
-    @PostMapping(value="/qrcode/scanLogin")
+    @PostMapping(value = "/qrcode/scanLogin")
     @ResponseBody
-    public MessageResult<String> scanLogin(String eventKey, String openId){
+    public MessageResult<String> scanLogin(String eventKey, String openId) {
         MessageResult<String> messageResult = new MessageResult<>();
         log.warn(openId + "请求登录!");
         String result;
 
         User user = userService.findByOpenId(openId);
 
-        if(user!=null) {
+        if (user != null) {
             String[] arr = eventKey.split(",");
             String randNum = arr[1];
 
             long expireSeconds = 3000; //5分钟
 
             //生成token
-            String token = JwtUtil.createToken(jwtSecret,user.getId(), DateTime.now().plusHours(6).toDate());
+            String token = JwtUtil.createToken(jwtSecret, user.getId(), DateTime.now().plusHours(6).toDate());
 
             valueOperations.set("scan_qrcode_login_" + randNum, token, expireSeconds, TimeUnit.SECONDS);
             messageResult.setMessage("扫码登录成功!");
             messageResult.setResult(true);
-        }
-        else{
+        } else {
             messageResult.setMessage("当前用户未绑定微信!");
             messageResult.setResult(false);
         }
@@ -72,24 +85,22 @@ public class JwtsUserController {
     }
 
     @PostMapping("/qrcode/queryScanResult")
-    @ApiOperation(value="查询扫码结果")
-    public MessageResult<String> queryScanResult(String rnd){
+    @ApiOperation(value = "查询扫码结果")
+    public MessageResult<String> queryScanResult(String rnd) {
         MessageResult<String> messageResult = new MessageResult<>();
 
         try {
-            String data = (String)valueOperations.get("scan_qrcode_login_" + rnd);
+            String data = (String) valueOperations.get("scan_qrcode_login_" + rnd);
 
-            if(StringUtils.isNotEmpty(data)) {
+            if (StringUtils.isNotEmpty(data)) {
                 messageResult.setData(data);
                 messageResult.setResult(true);
-            }
-            else{
+            } else {
                 messageResult.setResult(false);
                 messageResult.setMessage("暂无扫码结果");
             }
-        }
-        catch (Exception ex){
-            log.error(ex.getMessage(),ex);
+        } catch (Exception ex) {
+            log.error(ex.getMessage(), ex);
 
             messageResult.setResult(false);
             messageResult.setMessage(ex.getMessage());
@@ -98,39 +109,53 @@ public class JwtsUserController {
         return messageResult;
     }
 
+
     @PostMapping("/login")
-    @ApiOperation(value="登录获取token,在swagger ui中获取token时将写入session,调用其它接口时不用再设置header")
+    @ApiOperation(value = "登录获取token,在swagger ui中获取token时将写入session,调用其它接口时不用再设置header")
     @ApiImplicitParams({
-            @ApiImplicitParam(name="userName", paramType="query", required=true, value="用户名"),
-            @ApiImplicitParam(name="password", paramType="query", required=true, value="密码")
+            @ApiImplicitParam(name = "userName", paramType = "query", required = true, value = "用户名"),
+            @ApiImplicitParam(name = "password", paramType = "query", required = true, value = "密码"),
+            @ApiImplicitParam(name = "captCha", paramType = "query", required = true, value = "验证码")
     })
-    public MessageResult<String> login(String userName, String password, @ApiIgnore HttpSession session){
+    public MessageResult<String> login(String userName, String password, String captCha, @ApiIgnore HttpSession session) {
         MessageResult<String> messageResult = new MessageResult<>();
 
         try {
+
             User user = userService.findByUserName(userName);
 
             DES3 des3 = new DES3();
 
-            String passwordEnc = des3.encrypt(jwtSecret,password);
+            String passwordEnc = des3.encrypt(jwtSecret, password);
 
-            if(user!=null && passwordEnc.equals(user.getPassword())){
+            //验证码
+            Boolean isCodePass = isCaptchaValid(captCha);
+
+            if (!isCodePass) {
+                messageResult.setResult(false);
+                messageResult.setMessage("验证码不正确或已过期!");
+                return messageResult;
+            }
+
+            if (user != null && passwordEnc.equals(user.getPassword())) {
 
                 //生成token
-                String token = JwtUtil.createToken(jwtSecret,user.getId(),DateTime.now().plusHours(6).toDate());
+                String token = JwtUtil.createToken(jwtSecret, user.getId(), DateTime.now().plusHours(6).toDate());
 
-                session.setAttribute("token",token);
+                session.setAttribute("token", token);
 
                 messageResult.setResult(true);
                 messageResult.setData(token);
-            }
-            else{
+
+                //登录成功,清理使用过的验证码
+                captchaStore.remove(captCha);
+
+            } else {
                 messageResult.setResult(false);
                 messageResult.setMessage("用户不存在或密码错误!");
             }
 
-        }
-        catch(Exception ex){
+        } catch (Exception ex) {
             messageResult.setResult(false);
             messageResult.setMessage(ex.getMessage());
         }
@@ -139,7 +164,7 @@ public class JwtsUserController {
     }
 
     @GetMapping("/userInfo")
-    public MessageResult<User> userInfo(@RequestAttribute String subject){
+    public MessageResult<User> userInfo(@RequestAttribute String subject) {
         MessageResult<User> messageResult = new MessageResult<>();
 
         try {
@@ -147,12 +172,61 @@ public class JwtsUserController {
 
             messageResult.setResult(true);
             messageResult.setData(user);
-        }
-        catch(Exception ex){
+        } catch (Exception ex) {
             messageResult.setResult(false);
             messageResult.setMessage(ex.getMessage());
         }
 
         return messageResult;
     }
+
+
+    @PostMapping("/generateCaptCha")
+    @ApiOperation(value = "生成验证码")
+    public MessageResult<String> generateCaptCha(String phoneNumber) {
+        MessageResult<String> messageResult = new MessageResult<>();
+
+        String captCha = SMSUtil.getCaptcha();
+
+        User user = userService.findByUserName(phoneNumber);
+
+        if (user == null) {
+            messageResult.setResult(false);
+            messageResult.setMessage("用户不存在!");
+        }
+        else{
+            String phone = user.getPhone();
+            if(StringUtil.isNotEmpty(phone)){
+                // 将验证码发送给用户
+                //boolean success = smsService.sendVerificationCode(phone, captCha);
+                captchaStore.put(captCha, System.currentTimeMillis());
+                messageResult.setResult(true);
+                messageResult.setData(captCha);
+            }
+            else{
+                messageResult.setResult(false);
+                messageResult.setMessage("此用户名绑定的手机号码不正确或未绑定手机号码!");
+            }
+        }
+
+        return messageResult;
+    }
+
+    public boolean isCaptchaValid(String captCha) {
+        Long generatedTime = captchaStore.get(captCha);
+        long currentTime = System.currentTimeMillis();
+
+        if (generatedTime != null && (currentTime - generatedTime) <= TimeUnit.MINUTES.toMillis(5)) {
+            return true;
+        }
+        return false;
+    }
+
+    public void verifyCaptcha(String captCha) {
+        if (isCaptchaValid(captCha)) {
+            System.out.print("验证码通过");
+        } else {
+            System.out.print("验证码无效或已过期");
+        }
+    }
 }

+ 7 - 0
web/src/main/resources/application.yml

@@ -140,3 +140,10 @@ oss:
 #  urlPrefix: http://rccs.oss-cn-hangzhou.aliyuncs.com
   urlPrefix: http://oss.jzrccs.com
   objectPre: enterprise
+
+
+
+aliyun:
+  accessKeyId: LTAI5tS5VM3ewtNgMBugXRVu
+  accessKeySecret: GSEiVLd4nj6CN7KahXX6FOl1N8PNpw
+  regionId: cn-hangzhou

+ 39 - 0
web/src/test/java/com/jpsoft/employment/SendSmsTest.java

@@ -0,0 +1,39 @@
+package com.jpsoft.employment;
+
+import com.jpsoft.employment.modules.common.service.SmsService;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.util.concurrent.TimeUnit;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class SendSmsTest {
+
+    @Autowired
+    private SmsService smsService;
+
+    @Autowired
+    private RedisTemplate<String, String> redisTemplate;
+
+    @Test
+    public void sendCode() {
+        String phoneNumber = "15207211859";
+        // 生成随机验证码
+        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
+
+        // 将验证码发送给用户
+        boolean success = smsService.sendVerificationCode(phoneNumber, code);
+
+        if (success) {
+            // 你可以将验证码存储在Redis中,并设置过期时间
+            redisTemplate.opsForValue().set("SMS_" + phoneNumber, code, 5, TimeUnit.MINUTES);
+
+        }
+    }
+
+}