Commit 0d060c9d authored by Administrator's avatar Administrator

Revert "Merge branch 'staging' into 'master'"

This reverts merge request !148
parent ff764b99
...@@ -103,12 +103,12 @@ ...@@ -103,12 +103,12 @@
<artifactId>alipay-sdk-java</artifactId> <artifactId>alipay-sdk-java</artifactId>
<version>3.7.110.ALL</version> <version>3.7.110.ALL</version>
</dependency> </dependency>
<!-- <dependency>--> <dependency>
<!-- <groupId>de.flapdoodle.embed</groupId>--> <groupId>de.flapdoodle.embed</groupId>
<!-- <artifactId>de.flapdoodle.embed.mongo</artifactId>--> <artifactId>de.flapdoodle.embed.mongo</artifactId>
<!-- <version>1.50.3</version>--> <version>1.50.3</version>
<!-- <scope>test</scope>--> <scope>test</scope>
<!-- </dependency>--> </dependency>
<dependency> <dependency>
<groupId>com.jayway.jsonpath</groupId> <groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId> <artifactId>json-path</artifactId>
......
...@@ -55,7 +55,7 @@ public class BrowserBackendApplication { ...@@ -55,7 +55,7 @@ public class BrowserBackendApplication {
@Bean @Bean
public TaskScheduler taskScheduler() { public TaskScheduler taskScheduler() {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10); scheduler.setPoolSize(5);
return scheduler; return scheduler;
} }
......
...@@ -30,9 +30,7 @@ import java.security.Principal; ...@@ -30,9 +30,7 @@ import java.security.Principal;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Date; import java.util.*;
import java.util.Enumeration;
import java.util.List;
@RestController @RestController
@RequestMapping("/user") @RequestMapping("/user")
...@@ -82,7 +80,11 @@ public class AccountController { ...@@ -82,7 +80,11 @@ public class AccountController {
resultDto.setStatus(0); resultDto.setStatus(0);
resultDto.setData(userDtos); resultDto.setData(userDtos);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -100,7 +102,11 @@ public class AccountController { ...@@ -100,7 +102,11 @@ public class AccountController {
resultDto.setStatus(0); resultDto.setStatus(0);
resultDto.setData(account1); resultDto.setData(account1);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -113,29 +119,32 @@ public class AccountController { ...@@ -113,29 +119,32 @@ public class AccountController {
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
logger.error("fail to send sms", e); logger.error("fail to send sms", e);
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
/**
* 用户注册
*/
@RequestMapping(path = "/signUp", method = RequestMethod.POST) @RequestMapping(path = "/signUp", method = RequestMethod.POST)
public ResultDto createNewAccount(@Valid @RequestBody User user) { public ResultDto createNewAccount(@Valid @RequestBody User user) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
try { try {
Account account = new Account(); Account account = new Account();
if (!StringUtils.isEmpty(user.getEmail())) { if (!StringUtils.isEmpty(user.getEmail()))
account = accountService.create(user); account = accountService.create(user);
} else { else
account = accountService.createWithSms(user); account = accountService.createWithSms(user);
}
resultDto.setStatus(0); resultDto.setStatus(0);
resultDto.setData(account); resultDto.setData(account);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -153,10 +162,7 @@ public class AccountController { ...@@ -153,10 +162,7 @@ public class AccountController {
emailService.sendHtmlMail("sales@cloudam.io", "客户联系:" + contactUs.getName(), sb.toString()); emailService.sendHtmlMail("sales@cloudam.io", "客户联系:" + contactUs.getName(), sb.toString());
} }
// 消费总览
/**
* 费用明细
*/
@RequestMapping(path = "/userbilling", method = RequestMethod.POST) @RequestMapping(path = "/userbilling", method = RequestMethod.POST)
public ResultDto getUserBills0(Principal principal, @RequestBody UserPrePaidBillingRequestDto userPrePaidBillingRequestDto) { public ResultDto getUserBills0(Principal principal, @RequestBody UserPrePaidBillingRequestDto userPrePaidBillingRequestDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
...@@ -164,7 +170,11 @@ public class AccountController { ...@@ -164,7 +170,11 @@ public class AccountController {
resultDto.setData(accountService.getUserPrePaidBills(principal.getName(), userPrePaidBillingRequestDto)); resultDto.setData(accountService.getUserPrePaidBills(principal.getName(), userPrePaidBillingRequestDto));
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -204,7 +214,11 @@ public class AccountController { ...@@ -204,7 +214,11 @@ public class AccountController {
accountService.resetPassword(principal.getName(), user); accountService.resetPassword(principal.getName(), user);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -221,30 +235,25 @@ public class AccountController { ...@@ -221,30 +235,25 @@ public class AccountController {
accountService.resetPasswordWithOtp(user); accountService.resetPasswordWithOtp(user);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
/**
* 使用微信进行账户充值
*/
@RequestMapping(path = "/0xwxpayputorder/{amount}", method = RequestMethod.GET) @RequestMapping(path = "/0xwxpayputorder/{amount}", method = RequestMethod.GET)
public UserPaymentDto wechatPayCallback(Principal principal, @PathVariable int amount) { public UserPaymentDto wechatPayCallback(Principal principal, @PathVariable int amount) {
return paymentService.wxPutPayOrder(principal.getName(), amount); return paymentService.wxPutPayOrder(principal.getName(), amount);
} }
/**
* 使用微信进行账户充值成功后,微信会调用该接口
*/
@RequestMapping(path = "/0xwxpaycallback/{tradno}", method = RequestMethod.GET) @RequestMapping(path = "/0xwxpaycallback/{tradno}", method = RequestMethod.GET)
public String wechatPayCallback(@PathVariable String tradno) { public String wechatPayCallback(@PathVariable String tradno) {
return paymentService.wechatPayCallback(tradno); return paymentService.wechatPayCallback(tradno);
} }
/**
* 使用微信进行账户充值成功后,微信会调用该接口
*/
@RequestMapping(path = "/0xwxcheckorderstatus/{tradno}/{chargeType}", method = RequestMethod.GET) @RequestMapping(path = "/0xwxcheckorderstatus/{tradno}/{chargeType}", method = RequestMethod.GET)
public UserPaymentDto wechatCheckOrderStatus(Principal principal, @PathVariable String tradno, @PathVariable int chargeType) { public UserPaymentDto wechatCheckOrderStatus(Principal principal, @PathVariable String tradno, @PathVariable int chargeType) {
return paymentService.wxCheckOrderStatus(tradno, chargeType); return paymentService.wxCheckOrderStatus(tradno, chargeType);
...@@ -255,28 +264,19 @@ public class AccountController { ...@@ -255,28 +264,19 @@ public class AccountController {
return paymentService.wxCheckOrderStatus(tradno, chargeType); return paymentService.wxCheckOrderStatus(tradno, chargeType);
} }
/**
* 使用 支付宝 充值 成功后回调
*/
@RequestMapping(path = "/0xalipaycallback/{tradno}", method = RequestMethod.GET) @RequestMapping(path = "/0xalipaycallback/{tradno}", method = RequestMethod.GET)
public void alipayPayCallback(@PathVariable String tradno) { public void alipayPayCallback(@PathVariable String tradno) {
paymentService.alipaCallback(tradno); paymentService.alipaCallback(tradno);
} }
/**
* 使用 支付宝 充值 成功后回调
*/
@RequestMapping(path = "/0xalicheckorderstatus/{tradno}/{chargeType}", method = RequestMethod.GET) @RequestMapping(path = "/0xalicheckorderstatus/{tradno}/{chargeType}", method = RequestMethod.GET)
public UserPaymentDto alipayCheckOrderStatus(Principal principal, @PathVariable(required = false) String tradno, @PathVariable int chargeType) { public UserPaymentDto alipayCheckOrderStatus(Principal principal, @PathVariable(required = false) String tradno, @PathVariable int chargeType) {
return paymentService.aliCheckOrderStatus(tradno, chargeType); return paymentService.aliCheckOrderStatus(tradno, chargeType);
} }
/**
* 使用 支付宝 充值
*/
@RequestMapping(path = "/0xalipay/{amount}", method = RequestMethod.GET) @RequestMapping(path = "/0xalipay/{amount}", method = RequestMethod.GET)
public void alipayPutOrder(HttpServletRequest request, HttpServletResponse response, @PathVariable int amount) throws Exception { public void alipayPutOrder(HttpServletRequest request, HttpServletResponse response, @PathVariable int amount) throws Exception {
String by = request.getParameter("by"); String by = request.getParameter("by");
String form = paymentService.alipayPutPayOrder(request.getUserPrincipal().getName(), amount, by); String form = paymentService.alipayPutPayOrder(request.getUserPrincipal().getName(), amount, by);
response.setContentType("text/html;charset=utf-8"); response.setContentType("text/html;charset=utf-8");
...@@ -428,7 +428,11 @@ public class AccountController { ...@@ -428,7 +428,11 @@ public class AccountController {
accountService.authorizeCompany(principal.getName(), companyAuthorizeDto); accountService.authorizeCompany(principal.getName(), companyAuthorizeDto);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -473,13 +477,12 @@ public class AccountController { ...@@ -473,13 +477,12 @@ public class AccountController {
else else
resultDto.setStatus(-1); resultDto.setStatus(-1);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
private void dealClientRequestException(ResultDto resultDto, ClientRequestException e) {
dealClientRequestException(resultDto, e);
}
} }
...@@ -67,14 +67,8 @@ public class Account { ...@@ -67,14 +67,8 @@ public class Account {
*/ */
private int permission = -1; private int permission = -1;
/**
* 注册成功后,当前用户的邀请码相关信息,用于邀请别人获取佣金
*/
private Promotion promotion; private Promotion promotion;
/**
* 注册时,其他用户给当前用户的邀请码
*/
private String promotionCode; private String promotionCode;
private String comment; private String comment;
......
package com.edgec.browserbackend.account.domain; package com.edgec.browserbackend.account.domain;
import lombok.Data;
@Data
public class IpChargeRequestDto { public class IpChargeRequestDto {
private int period; private int period;
private int amount; private int amount;
private String region; private String region;
private String unit = "month"; private String unit="month";
private String target; private String target;
//0 -- 充值, 1 -- newip, 2 --renew, 3 -- 退还 //0 -- 充值, 1 -- newip, 2 --renew, 3 -- 退还
...@@ -21,10 +18,83 @@ public class IpChargeRequestDto { ...@@ -21,10 +18,83 @@ public class IpChargeRequestDto {
private String services; private String services;
/** public String getServices() {
* 续费ip return services;
*/ }
private String chargeIp;
public void setServices(String services) {
this.services = services;
}
public String getTradeNo() {
return tradeNo;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
public float getDaysPerMonth() {
return daysPerMonth;
}
public void setDaysPerMonth(float daysPerMonth) {
this.daysPerMonth = daysPerMonth;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public int getChargeType() {
return chargeType;
}
public void setChargeType(int chargeType) {
this.chargeType = chargeType;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getPayMethod() {
return payMethod;
}
public void setPayMethod(int payMethod) {
this.payMethod = payMethod;
}
} }
package com.edgec.browserbackend.account.domain; package com.edgec.browserbackend.account.domain;
import lombok.Data;
@Data
public class IpChargeResultDto { public class IpChargeResultDto {
/**
* 充值状态
*/
private boolean success; private boolean success;
private int balance; private int balance;
/**
* 到账金额
*/
private int approvedAmount; private int approvedAmount;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getApprovedAmount() {
return approvedAmount;
}
public void setApprovedAmount(int approvedAmount) {
this.approvedAmount = approvedAmount;
}
} }
package com.edgec.browserbackend.account.domain; package com.edgec.browserbackend.account.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document(collection = "phoneotp") @Document(collection = "phoneotp")
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class Otp { public class Otp {
/**
* 手机号
*/
@Id @Id
private String phone; private String phone;
/**
* 发送给用户的短信验证码
*/
private String otp; private String otp;
/**
* 短信验证码的发送时间
*/
private long createdAt; private long createdAt;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getOtp() {
return otp;
}
public void setOtp(String otp) {
this.otp = otp;
}
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
} }
package com.edgec.browserbackend.account.domain; package com.edgec.browserbackend.account.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
/** /**
* @Desc * @Desc
* @Author jason * @Author jason
* @CreateTime 2020/3/12 3:14 下午 * @CreateTime 2020/3/12 3:14 下午
**/ **/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class Promotion { public class Promotion {
/**
* 邀请码(用户邀请好友使用本产品)
*/
private String code; private String code;
/** //邀请人数
* 邀请人数
*/
private int invitedUsers; private int invitedUsers;
//好友本月以前总消费
/**
* 好友本月以前总消费
*/
private int totalCommission; private int totalCommission;
//好友当月消费
/**
* 好友当月消费
*/
private int commission; private int commission;
//好友上月总消费
/**
* 好友上月总消费
*/
private int commissionLastMonth; private int commissionLastMonth;
//是否是本公司的销售
/**
* 是否是本公司的销售
*/
private boolean isSale; private boolean isSale;
//当月礼金
/**
* 当月礼金
*/
private double gift; private double gift;
//所有未提现金额
/**
* 所有未提现金额
*/
private double allGift; private double allGift;
//已提现金额
/**
* 已提现金额
*/
private double withdrawn; private double withdrawn;
public int getCommission() {
return commission;
}
public void setCommission(int commission) {
this.commission = commission;
}
public int getInvitedUsers() {
return invitedUsers;
}
public void setInvitedUsers(int invitedUsers) {
this.invitedUsers = invitedUsers;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public boolean isSale() {
return isSale;
}
public void setSale(boolean sale) {
isSale = sale;
}
public double getGift() {
return gift;
}
public void setGift(double gift) {
this.gift = gift;
}
public int getCommissionLastMonth() {
return commissionLastMonth;
}
public void setCommissionLastMonth(int commissionLastMonth) {
this.commissionLastMonth = commissionLastMonth;
}
public double getAllGift() {
return allGift;
}
public void setAllGift(double allGift) {
this.allGift = allGift;
}
public double getWithdrawn() {
return withdrawn;
}
public void setWithdrawn(double withdrawn) {
this.withdrawn = withdrawn;
}
public int getTotalCommission() {
return totalCommission;
}
public void setTotalCommission(int totalCommission) {
this.totalCommission = totalCommission;
}
} }
package com.edgec.browserbackend.account.domain; package com.edgec.browserbackend.account.domain;
import lombok.Data;
import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Email; import javax.validation.constraints.Email;
...@@ -8,16 +7,15 @@ import java.util.ArrayList; ...@@ -8,16 +7,15 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@Data
public class User { public class User {
@Length(min = 3, max = 20, message = "Name length should be between 3 - 20") @Length(min = 3, max = 20, message="Name length should be between 3 - 20")
private String username; private String username;
@Length(min = 6, max = 40, message = "Password length should be between 6 - 40") @Length(min = 6, max = 40, message="Password length should be between 6 - 40")
private String password; private String password;
@Email(message = "Invalid email address") @Email(message ="Invalid email address")
private String email; private String email;
private String phone; private String phone;
...@@ -30,12 +28,108 @@ public class User { ...@@ -30,12 +28,108 @@ public class User {
private String lockReason; private String lockReason;
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
private boolean allowedToCreateSubUser = true; private boolean allowedToCreateSubUser = true;
private int permission; private int permission;
private List<String> whiteList = new ArrayList<>(); private List<String> whiteList = new ArrayList<>();
private String verificationCode = UUID.randomUUID().toString(); private String verificationCode= UUID.randomUUID().toString();
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getVerificationCode() {
return verificationCode;
}
public void setVerificationCode(String verificationCode) {
this.verificationCode = verificationCode;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isAllowedToCreateSubUser() {
return allowedToCreateSubUser;
}
public void setAllowedToCreateSubUser(boolean allowedToCreateSubUser) {
allowedToCreateSubUser = allowedToCreateSubUser;
}
public int getPermission() {
return permission;
}
public void setPermission(int permission) {
this.permission = permission;
}
public String getLockReason() {
return lockReason;
}
public void setLockReason(String lockReason) {
this.lockReason = lockReason;
}
public List<String> getWhiteList() {
return whiteList;
}
public void setWhiteList(List<String> whiteList) {
this.whiteList = whiteList;
}
public String getPromotionCode() {
return promotionCode;
}
public void setPromotionCode(String promotionCode) {
this.promotionCode = promotionCode;
}
} }
...@@ -2,27 +2,41 @@ package com.edgec.browserbackend.account.domain; ...@@ -2,27 +2,41 @@ package com.edgec.browserbackend.account.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
@Getter
@Setter
@Document(collection = "userbalance") @Document(collection = "userbalance")
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class UserBalance { public class UserBalance {
/**
* 用户手机号
*/
@Id @Id
private String username; private String username;
/**
* 账户余额
*/
private float balanced; private float balanced;
private float used; private float used;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public float getBalanced() {
return balanced;
}
public void setBalanced(float balanced) {
this.balanced = balanced;
}
public float getUsed() {
return used;
}
public void setUsed(float used) {
this.used = used;
}
} }
...@@ -2,16 +2,12 @@ package com.edgec.browserbackend.account.domain; ...@@ -2,16 +2,12 @@ package com.edgec.browserbackend.account.domain;
import com.edgec.browserbackend.account.service.SmsUtils; import com.edgec.browserbackend.account.service.SmsUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@Getter
@Setter
@Document(collection = "userpayment") @Document(collection = "userpayment")
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class UserPayment { public class UserPayment {
...@@ -19,7 +15,7 @@ public class UserPayment { ...@@ -19,7 +15,7 @@ public class UserPayment {
@Id @Id
private String id; private String id;
private String tradeNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + SmsUtils.createRandom(true, 4); private String tradeNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+SmsUtils.createRandom(true, 4);
private String username; private String username;
...@@ -32,4 +28,69 @@ public class UserPayment { ...@@ -32,4 +28,69 @@ public class UserPayment {
private PaymentMethod paymentMethod; private PaymentMethod paymentMethod;
private String transId; private String transId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTradeNo() {
return tradeNo;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public boolean isSucceed() {
return succeed;
}
public void setSucceed(boolean succeed) {
this.succeed = succeed;
}
public Date getPaymentDate() {
return paymentDate;
}
public void setPaymentDate(Date paymentDate) {
this.paymentDate = paymentDate;
}
public PaymentMethod getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}
public String getTransId() {
return transId;
}
public void setTransId(String transId) {
this.transId = transId;
}
} }
package com.edgec.browserbackend.account.domain; package com.edgec.browserbackend.account.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter; import org.apache.commons.lang3.StringUtils;
import lombok.Setter;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex; import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
...@@ -10,8 +9,6 @@ import org.springframework.data.mongodb.core.mapping.Document; ...@@ -10,8 +9,6 @@ import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Getter
@Setter
@Document(collection = "userprepaidbilling") @Document(collection = "userprepaidbilling")
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
@CompoundIndex(name = "idx_username_timestamp", def = "{'username': 1, 'timestamp': 1}") @CompoundIndex(name = "idx_username_timestamp", def = "{'username': 1, 'timestamp': 1}")
...@@ -40,21 +37,13 @@ public class UserPrePaidBilling { ...@@ -40,21 +37,13 @@ public class UserPrePaidBilling {
private BillStatus status; private BillStatus status;
/** //0 -- 余额, 1 -- 支付宝, 2 -- 微信, 3 -- 银行转账
* 0 -- 余额, 1 -- 支付宝, 2 -- 微信, 3 -- 银行转账
*/
private int payMethod; private int payMethod;
private boolean isPrepaid; private boolean isPrepaid;
/**
* 本次消费金额
*/
private float total; private float total;
//0 -- 充值, 1 -- newip, 2 -- renew, 3 -- return, 4 -- 礼金提现
/**
* 0 -- 充值, 1 -- newip, 2 -- renew, 3 -- return, 4 -- 礼金提现
*/
private int chargeType; private int chargeType;
private String unit = "month"; private String unit = "month";
...@@ -63,15 +52,161 @@ public class UserPrePaidBilling { ...@@ -63,15 +52,161 @@ public class UserPrePaidBilling {
private float balanced; private float balanced;
/**
* 购买或者续费的ip 号
*/
private String chargeIp;
private List<DeductionRecord> deductionRecords = new ArrayList<>(); private List<DeductionRecord> deductionRecords = new ArrayList<>();
public float getRate() {
return rate;
}
public float getTotal() {
return total;
}
public void setRate(float rate) {
this.rate = rate;
}
public void setTotal(float total) {
this.total = total;
}
public int getChargeType() {
return chargeType;
}
public void setChargeType(int chargeType) {
this.chargeType = chargeType;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Services getServices() {
return services;
}
public void setServices(Services services) {
this.services = services;
}
public BillStatus getStatus() {
return status;
}
public void setStatus(BillStatus status) {
this.status = status;
}
public boolean isPrepaid() {
return isPrepaid;
}
public void setPrepaid(boolean prepaid) {
this.isPrepaid = prepaid;
}
public List<DeductionRecord> getDeductionRecords() {
return deductionRecords;
}
public void setDeductionRecords(List<DeductionRecord> deductionRecords) {
this.deductionRecords = deductionRecords;
}
public void addDeductionRecord(DeductionRecord record) { public void addDeductionRecord(DeductionRecord record) {
this.deductionRecords.add(record); this.deductionRecords.add(record);
} }
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getPayMethod() {
return payMethod;
}
public void setPayMethod(int payMethod) {
this.payMethod = payMethod;
}
public String getTradeNo() {
return tradeNo;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
public String getAdministrator() {
return administrator;
}
public void setAdministrator(String administrator) {
this.administrator = administrator;
}
public float getBalanced() {
return balanced;
}
public void setBalanced(float balanced) {
this.balanced = balanced;
}
} }
package com.edgec.browserbackend.account.dto; package com.edgec.browserbackend.account.dto;
import com.edgec.browserbackend.account.domain.Promotion; import com.edgec.browserbackend.account.domain.Promotion;
import com.edgec.browserbackend.account.domain.UserPrePaidBilling;
import org.springframework.data.domain.Page;
import java.util.List;
public class BillQueryResultDto { public class BillQueryResultDto {
double parentExpense; double parentExpense;
......
...@@ -59,6 +59,8 @@ public class AccountRepositoryCustomImpl implements AccountRepositoryCustom { ...@@ -59,6 +59,8 @@ public class AccountRepositoryCustomImpl implements AccountRepositoryCustom {
basicQuery.addCriteria(where("promotion.code").is(code).and("parent").exists(false)); basicQuery.addCriteria(where("promotion.code").is(code).and("parent").exists(false));
Account account = mongoTemplate.findOne(basicQuery, Account.class); Account account = mongoTemplate.findOne(basicQuery, Account.class);
if (account == null)
return null;
return account; return account;
} }
} }
...@@ -24,7 +24,10 @@ public class UserPaymentRepositoryCustomImpl implements UserPaymentRepositoryCus ...@@ -24,7 +24,10 @@ public class UserPaymentRepositoryCustomImpl implements UserPaymentRepositoryCus
update.set("succeed", result); update.set("succeed", result);
UpdateResult operation = mongoTemplate.updateFirst(basicQuery, update, UserPayment.class); UpdateResult operation = mongoTemplate.updateFirst(basicQuery, update, UserPayment.class);
return operation.getModifiedCount() >= 1; if (operation.getModifiedCount() < 1)
return false;
else
return true;
} }
} }
...@@ -366,6 +366,8 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -366,6 +366,8 @@ public class AdministratorServiceImpl implements AdministratorService {
@Override @Override
public void addPromotionCode(String username, String promotionCode) { public void addPromotionCode(String username, String promotionCode) {
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST)); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
account.setPromotionCode(promotionCode); account.setPromotionCode(promotionCode);
accountRepository.save(account); accountRepository.save(account);
} }
...@@ -495,6 +497,8 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -495,6 +497,8 @@ public class AdministratorServiceImpl implements AdministratorService {
@Override @Override
public void addUserWhiteList(String username, String website) { public void addUserWhiteList(String username, String website) {
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST)); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
account.getWhiteList().add(website); account.getWhiteList().add(website);
accountRepository.save(account); accountRepository.save(account);
} }
......
...@@ -37,20 +37,18 @@ public class EmailServiceImpl implements EmailService { ...@@ -37,20 +37,18 @@ public class EmailServiceImpl implements EmailService {
context.setVariable("code", code); context.setVariable("code", code);
context.setVariable("time", ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))); context.setVariable("time", ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")));
String emailContent = templateEngine.process("reset", context); String emailContent = templateEngine.process("reset", context);
sendHtmlMail(email, "Cloudam云端软件 | 密码重置", emailContent); sendHtmlMail(email,"Cloudam云端软件 | 密码重置",emailContent);
} }
@Override
public void sendEmailVerification(String username, String email, String code) { public void sendEmailVerification(String username, String email, String code) {
Context context = new Context(); Context context = new Context();
context.setVariable("id", username); context.setVariable("id", username);
context.setVariable("code", code); context.setVariable("code", code);
context.setVariable("time", ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))); context.setVariable("time", ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")));
String emailContent = templateEngine.process("verification", context); String emailContent = templateEngine.process("verification", context);
sendHtmlMail(email, "Cloudam云端软件 | 注册邮箱验证", emailContent); sendHtmlMail(email,"Cloudam云端软件 | 注册邮箱验证",emailContent);
} }
@Override
public void sendHtmlMail(String to, String subject, String content) { public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage(); MimeMessage message = mailSender.createMimeMessage();
try { try {
......
...@@ -30,13 +30,9 @@ public class UserLackMoneyServiceImpl implements UserLackMoneyService { ...@@ -30,13 +30,9 @@ public class UserLackMoneyServiceImpl implements UserLackMoneyService {
//用户名,欠费金额,账单Id,账单总数 //用户名,欠费金额,账单Id,账单总数
String username = billings.get(0).getUsername(); String username = billings.get(0).getUsername();
float totalUnpaid = billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID) float totalUnpaid = billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID)
.map( .map(x -> x.getTotal() - (x.getDeductionRecords() != null ? (x.getDeductionRecords().stream().collect(Collectors.summingDouble(
x -> x.getTotal() - ( DeductionRecord::getDeductionAmount
x.getDeductionRecords() != null ? (x.getDeductionRecords().stream().collect(Collectors.summingDouble(DeductionRecord::getDeductionAmount)).longValue()) : (0) )).longValue()) : (0))).collect(Collectors.summingDouble(Float::floatValue)).floatValue();
)
)
.collect(Collectors.summingDouble(Float::floatValue))
.floatValue();
List<String> ids = billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID).map(UserPrePaidBilling::getId).collect(Collectors.toList()); List<String> ids = billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID).map(UserPrePaidBilling::getId).collect(Collectors.toList());
int billsAmount = (int) billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID).count(); int billsAmount = (int) billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID).count();
......
...@@ -15,6 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -15,6 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Optional;
@Service @Service
public class UserServiceImpl implements UserService { public class UserServiceImpl implements UserService {
...@@ -94,11 +96,11 @@ public class UserServiceImpl implements UserService { ...@@ -94,11 +96,11 @@ public class UserServiceImpl implements UserService {
@Override @Override
public void create(User user) { public void create(User user) {
repository.findById(user.getUsername()).ifPresent(
it -> { Optional<User> existing = repository.findById(user.getUsername());
throw new ClientRequestException(AuthErrorCode.NAMEEXIST, "user already exists: " + it.getUsername()); existing.ifPresent(it -> {
} throw new ClientRequestException(AuthErrorCode.NAMEEXIST, "user already exists: " + it.getUsername());
); });
String hash = encoder.encode(user.getPassword()); String hash = encoder.encode(user.getPassword());
user.setPassword(hash); user.setPassword(hash);
......
...@@ -14,7 +14,6 @@ public enum BrowserErrorCode implements ErrorCode { ...@@ -14,7 +14,6 @@ public enum BrowserErrorCode implements ErrorCode {
IPNOTEXIST(BROWSER_BASE + 201, "The ip do not exist"), IPNOTEXIST(BROWSER_BASE + 201, "The ip do not exist"),
IPNOTBINDTOSHOP(BROWSER_BASE + 202, "The ip does not bind this shop."), IPNOTBINDTOSHOP(BROWSER_BASE + 202, "The ip does not bind this shop."),
USER_NOT_BIND_SHOP(BROWSER_BASE + 203, "The shop does not bind this user."),
GROUPNOTEXIST(BROWSER_BASE + 301, "The group does not exist"), GROUPNOTEXIST(BROWSER_BASE + 301, "The group does not exist"),
......
...@@ -22,9 +22,6 @@ public class GroupController { ...@@ -22,9 +22,6 @@ public class GroupController {
@Autowired @Autowired
private GroupService groupService; private GroupService groupService;
/**
* 添加分组
*/
@RequestMapping("/add") @RequestMapping("/add")
public ResultDto addGroup(Principal principal, @RequestBody GroupDto groupDto) { public ResultDto addGroup(Principal principal, @RequestBody GroupDto groupDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
...@@ -33,8 +30,12 @@ public class GroupController { ...@@ -33,8 +30,12 @@ public class GroupController {
groupDto1.setId(groupService.addGroup(principal.getName(), groupDto.getName())); groupDto1.setId(groupService.addGroup(principal.getName(), groupDto.getName()));
resultDto.setData(groupDto1); resultDto.setData(groupDto1);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { }catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -45,8 +46,12 @@ public class GroupController { ...@@ -45,8 +46,12 @@ public class GroupController {
try { try {
groupService.updateGroup(principal.getName(), group); groupService.updateGroup(principal.getName(), group);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { }catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -57,15 +62,16 @@ public class GroupController { ...@@ -57,15 +62,16 @@ public class GroupController {
try { try {
groupService.deleteGroup(principal.getName(), groupDto.getId()); groupService.deleteGroup(principal.getName(), groupDto.getId());
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { }catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
/**
* 分组列表
*/
@RequestMapping("/list") @RequestMapping("/list")
public ResultDto getGroupList(Principal principal) { public ResultDto getGroupList(Principal principal) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
...@@ -73,19 +79,14 @@ public class GroupController { ...@@ -73,19 +79,14 @@ public class GroupController {
List<GroupDto> groupDtos = groupService.getGroupList(principal.getName()); List<GroupDto> groupDtos = groupService.getGroupList(principal.getName());
resultDto.setData(groupDtos); resultDto.setData(groupDtos);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { }catch (ClientRequestException e) {
dealClientRequestException(resultDto, e); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
private void dealClientRequestException(ResultDto resultDto, ClientRequestException e) {
resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
}
} }
...@@ -138,9 +138,6 @@ public class ShopController { ...@@ -138,9 +138,6 @@ public class ShopController {
return resultDto; return resultDto;
} }
/**
* 店铺分配
*/
@RequestMapping(value = "/assign", method = RequestMethod.POST) @RequestMapping(value = "/assign", method = RequestMethod.POST)
public ResultDto assignShop(Principal principal, @RequestBody ShopRequestDto shopRequestDto) { public ResultDto assignShop(Principal principal, @RequestBody ShopRequestDto shopRequestDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
...@@ -153,9 +150,6 @@ public class ShopController { ...@@ -153,9 +150,6 @@ public class ShopController {
return resultDto; return resultDto;
} }
/**
* 获取带有 ip 资源信息的 shop
*/
@RequestMapping(value = "/list", method = RequestMethod.POST) @RequestMapping(value = "/list", method = RequestMethod.POST)
public ResultDto getShopList(Principal principal, @RequestBody ShopRequestDto shopRequestDto) { public ResultDto getShopList(Principal principal, @RequestBody ShopRequestDto shopRequestDto) {
logger.info("shop list params {}", JSONObject.toJSONString(shopRequestDto)); logger.info("shop list params {}", JSONObject.toJSONString(shopRequestDto));
...@@ -171,9 +165,6 @@ public class ShopController { ...@@ -171,9 +165,6 @@ public class ShopController {
return resultDto; return resultDto;
} }
/**
* 获取当前登录用户已经绑定了当前商铺的 所有子用户名
*/
@RequestMapping(value = "/subusers", method = RequestMethod.POST) @RequestMapping(value = "/subusers", method = RequestMethod.POST)
public ResultDto getShopSubUsers(Principal principal, @RequestBody ShopRequestDto shopRequestDto) { public ResultDto getShopSubUsers(Principal principal, @RequestBody ShopRequestDto shopRequestDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
...@@ -200,9 +191,6 @@ public class ShopController { ...@@ -200,9 +191,6 @@ public class ShopController {
return resultDto; return resultDto;
} }
/**
* 查询店铺信息
*/
@RequestMapping(value = "/query", method = RequestMethod.POST) @RequestMapping(value = "/query", method = RequestMethod.POST)
public ResultDto queryShop(Principal principal, @RequestBody ShopRequestDto shopRequestDto) { public ResultDto queryShop(Principal principal, @RequestBody ShopRequestDto shopRequestDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
...@@ -216,22 +204,6 @@ public class ShopController { ...@@ -216,22 +204,6 @@ public class ShopController {
return resultDto; return resultDto;
} }
/**
* 恢复部分缺失数据,仅仅调用一次就好了
*/
@GetMapping(value = "/deal_dirtydata")
public ResultDto dealDirtydata() {
Integer num = shopService.dealDirtyData();
ResultDto resultDto = new ResultDto();
resultDto.setStatus(0);
resultDto.setData("修复脏数据" + num + "条");
return resultDto;
}
private void dealClientRequestException(ResultDto resultDto, ClientRequestException e) { private void dealClientRequestException(ResultDto resultDto, ClientRequestException e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
......
...@@ -21,129 +21,42 @@ public class IpResource implements Serializable { ...@@ -21,129 +21,42 @@ public class IpResource implements Serializable {
@Id @Id
private String id; private String id;
/**
* ip 地址
*/
private String addr; private String addr;
/**
* ip 类型,默认是 ip代理 模式
*/
private IpType ipType = IpType.VENDOR; private IpType ipType = IpType.VENDOR;
/**
* ip 的具体代理使用
*/
private Vendor vendor; private Vendor vendor;
private String vendorCn; private String vendorCn;
/**
* ip 地域
*/
private String region; private String region;
private String regionCn; private String regionCn;
//0:正常, 1:已过期, 2:即将过期, 3:正在分配, 4:未使用, 5:已失效, 6:未分配, 7:未缴费, 8:分配成功
/**
* ip 的状态
* 0:正常, 1:已过期, 2:即将过期, 3:正在分配, 4:未使用, 5:已失效, 6:未分配, 7:未缴费, 8:分配成功
*/
private int status; private int status;
/**
* ip 端口号
*/
private List<String> port; private List<String> port;
/**
* ip的购买时间点
*/
private long purchasedTime; private long purchasedTime;
/**
* ip的过期的时间点
*/
private long validTime; private long validTime;
private String details; private String details;
/**
* ip的绑定历史
*/
private List<BindHistory> bindHistory = new ArrayList<>(); private List<BindHistory> bindHistory = new ArrayList<>();
/**
* ip的状态
* 当 ip 资源过期的时候,系统不会直接删除 ip 资源,而是将 isDeleted 设置为 true
* 过期7天后再删除这个ip资源
*/
private boolean isDeleted; private boolean isDeleted;
/**
* 如果 使用的 ip 资源 是在我们系统申请的,则默认为 fangguanlianbrowser
*/
private String username; private String username;
/**
* ip 资源的购买者(拥有者)
*/
private String owner; private String owner;
private String userParent; private String userParent;
/**
* ip访问协议
*/
private List<String> protocol; private List<String> protocol;
private String password; private String password;
private double price; private double price;
/** private boolean specialLine; //是否使用专线
* 是否使用专线 private boolean usingSpecialLine; //是否正在使用专线
*/ //专线数据
private boolean specialLine; private String proxyUsername; //专线的代理用户名
private String proxyPassword; //专线的代理密码
/**
* 是否正在使用专线
*/
private boolean usingSpecialLine;
/**
* 专线的代理用户名
*/
private String proxyUsername;
/**
* 专线的代理密码
*/
private String proxyPassword;
/**
* ip 资源绑定的 商铺号
*/
private String shopId; private String shopId;
private List<String> shopIds = new ArrayList<>(); private List<String> shopIds = new ArrayList<>();
/**
* 绑定状态
*/
private boolean bind; private boolean bind;
private boolean isLocked; private boolean isLocked;
private long lockTimestamp; private long lockTimestamp;
private long healthLockTimestamp; private long healthLockTimestamp;
/**
* 购买方式(按月、按周)
*/
private String unit; private String unit;
/**
* 购买数量
* 例如 购买了 2 个月 的 ip资源,则
* period:2
* unit:month
*/
private int period; private int period;
@Override @Override
......
...@@ -14,5 +14,5 @@ public enum IpType { ...@@ -14,5 +14,5 @@ public enum IpType {
/** /**
* 自有ip,即该ip不是从我们系统购买的 * 自有ip,即该ip不是从我们系统购买的
*/ */
OWN OWN;
} }
...@@ -4,44 +4,14 @@ import java.util.ArrayList; ...@@ -4,44 +4,14 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class IpBuyResultDto { public class IpBuyResultDto {
private String errorCode = ""; private String errorCode="";
private String requestid = ""; private String requestid ="";
private int balance = 0; private int balance = 0;
private List<IPData> iplist = new ArrayList<>(); private List<IPData> iplist = new ArrayList<>();
public static class IPData {
private String ip;
private String validTill;
public IPData(String ip, String validTill) {
this.ip = ip;
this.validTill = validTill;
}
public IPData() {
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getValidTill() {
return validTill;
}
public void setValidTill(String validTill) {
this.validTill = validTill;
}
}
public String getErrorCode() { public String getErrorCode() {
return errorCode; return errorCode;
} }
...@@ -73,4 +43,34 @@ public class IpBuyResultDto { ...@@ -73,4 +43,34 @@ public class IpBuyResultDto {
public void setIplist(List<IPData> iplist) { public void setIplist(List<IPData> iplist) {
this.iplist = iplist; this.iplist = iplist;
} }
public static class IPData {
private String ip;
private String validTill;
public IPData(String ip, String validTill) {
this.ip = ip;
this.validTill = validTill;
}
public IPData() {
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getValidTill() {
return validTill;
}
public void setValidTill(String validTill) {
this.validTill = validTill;
}
}
} }
package com.edgec.browserbackend.browser.dto; package com.edgec.browserbackend.browser.dto;
import lombok.Data; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Data
public class IpOperationResultDto { public class IpOperationResultDto {
List<String> successList; List<String> successList = new ArrayList<>();
List<String> failList; List<String> failList = new ArrayList<>();
public List<String> getSuccessList() {
return successList;
}
public void setSuccessList(List<String> successList) {
this.successList = successList;
}
public List<String> getFailList() {
return failList;
}
public void setFailList(List<String> failList) {
this.failList = failList;
}
} }
...@@ -10,58 +10,27 @@ import java.util.List; ...@@ -10,58 +10,27 @@ import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class IpResourceRequestDto { public class IpResourceRequestDto {
private String name; private String name;
/**
* ip 所在地域(英文)
*/
private String region; private String region;
/**
* ip 所在地域(中文)
*/
private String regionCn; private String regionCn;
private String vendor="aliyun";
/**
* ip 厂商
*/
private String vendor = "aliyun";
private String logintype = "password"; private String logintype = "password";
private String shopId; private String shopId;
/** //0 -- 余额, 1 -- 支付宝, 2 -- 微信
* 0:余额, 1:支付宝, 2:微信
*/
private int payMethod = 0; private int payMethod = 0;
@Max(12) @Max(12)
@Min(1) @Min(1)
private int period = 1; private int period = 1;
private String unit="month";
/**
* 例如 period :2,unit = month
* 代表:购买 ip 2 个 月
*/
private String unit = "month";
/**
* 购买的ip数量(用户可以一次购买多个ip)
*/
private int amount = 1; private int amount = 1;
private boolean autorenew = false; private boolean autorenew = false;
private int ipkeptperiod = 7; private int ipkeptperiod = 7;
private String startscript = ""; private String startscript = "";
/**
* ip 是否需要使用专线
*/
private boolean specialLine; private boolean specialLine;
//自有IP需要传proxy的账号
/**
* 自有IP需要传proxy的账号
*/
private String username; private String username;
private String password; private String password;
private String instanceSpecKey; private String instanceSpecKey;
...@@ -75,7 +44,6 @@ public class IpResourceRequestDto { ...@@ -75,7 +44,6 @@ public class IpResourceRequestDto {
private List<String> ipId = new ArrayList<>(); private List<String> ipId = new ArrayList<>();
public String getName() { public String getName() {
return name; return name;
} }
......
...@@ -4,12 +4,36 @@ import java.util.ArrayList; ...@@ -4,12 +4,36 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class RenewIpResultDto { public class RenewIpResultDto {
private String errorCode = ""; private String errorCode="";
private int balance = 0; private int balance = 0;
private List<IpBuyResultDto.IPData> iplist = new ArrayList<>(); private List<IpBuyResultDto.IPData> iplist = new ArrayList<>();
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public List<IpBuyResultDto.IPData> getIplist() {
return iplist;
}
public void setIplist(List<IpBuyResultDto.IPData> iplist) {
this.iplist = iplist;
}
public static class IPData { public static class IPData {
private String ip; private String ip;
private String validTill; private String validTill;
...@@ -20,6 +44,7 @@ public class RenewIpResultDto { ...@@ -20,6 +44,7 @@ public class RenewIpResultDto {
} }
public IPData() { public IPData() {
} }
public String getIp() { public String getIp() {
...@@ -39,28 +64,4 @@ public class RenewIpResultDto { ...@@ -39,28 +64,4 @@ public class RenewIpResultDto {
} }
} }
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public List<IpBuyResultDto.IPData> getIplist() {
return iplist;
}
public void setIplist(List<IpBuyResultDto.IPData> iplist) {
this.iplist = iplist;
}
} }
\ No newline at end of file
...@@ -35,7 +35,10 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -35,7 +35,10 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
update.set("isLocked", true).set("lockTimestamp", Instant.now().toEpochMilli()); update.set("isLocked", true).set("lockTimestamp", Instant.now().toEpochMilli());
UpdateResult result = mongoTemplate.updateFirst(basicQuery, update, IpResource.class); UpdateResult result = mongoTemplate.updateFirst(basicQuery, update, IpResource.class);
return result.getModifiedCount() >= 1; if (result.getModifiedCount() < 1)
return false;
else
return true;
} }
@Override @Override
......
...@@ -9,12 +9,7 @@ import java.util.List; ...@@ -9,12 +9,7 @@ import java.util.List;
public interface ShopRepository extends MongoRepository<Shop, String> { public interface ShopRepository extends MongoRepository<Shop, String> {
Page<Shop> findByShopIdInAndShopAccountLikeOrderByCreateTimeDesc(List<String> shopIds, String shopAccount, Pageable pageable); Page<Shop> findByShopIdInAndShopAccountLikeOrderByCreateTimeDesc(List<String> shopIds, String shopAccount, Pageable pageable);
Page<Shop> findByShopIdInAndShopNameLikeOrderByCreateTimeDesc(List<String> shopIds, String shopName, Pageable pageable); Page<Shop> findByShopIdInAndShopNameLikeOrderByCreateTimeDesc(List<String> shopIds, String shopName, Pageable pageable);
Page<Shop> findByShopIdInOrderByCreateTimeDesc(List<String> shopIds, Pageable pageable); Page<Shop> findByShopIdInOrderByCreateTimeDesc(List<String> shopIds, Pageable pageable);
List<Shop> findByShopIdIn(List<String> shopIds); List<Shop> findByShopIdIn(List<String> shopIds);
List<Shop> findByOwnerIn(List<String> owners);
} }
...@@ -35,26 +35,20 @@ public class GroupServiceImpl implements GroupService { ...@@ -35,26 +35,20 @@ public class GroupServiceImpl implements GroupService {
@Override @Override
public String addGroup(String username, String groupName) { public String addGroup(String username, String groupName) {
// 1. 校验传参 if (StringUtils.isBlank(username) || StringUtils.isBlank(groupName))
if (StringUtils.isBlank(username) || StringUtils.isBlank(groupName)) {
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
}
// 2. 获取account信息并校验account
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST)); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account.getGroupCount() >= 100) { if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (account.getGroupCount() >= 100)
throw new ClientRequestException(AccountErrorCode.GROUPMAX); throw new ClientRequestException(AccountErrorCode.GROUPMAX);
}
Group group = new Group(); Group group = new Group();
group.setOwner(username); group.setOwner(username);
group.setName(groupName); group.setName(groupName);
String id; String id;
try { try {
// 3. 保存 group信息
Group group1 = groupRepository.save(group); Group group1 = groupRepository.save(group);
//可以优化
// 4. 更新 account 的 分组数
account.setGroupCount(account.getGroupCount() + 1); account.setGroupCount(account.getGroupCount() + 1);
accountRepository.save(account); accountRepository.save(account);
id = group1.getId(); id = group1.getId();
...@@ -86,6 +80,8 @@ public class GroupServiceImpl implements GroupService { ...@@ -86,6 +80,8 @@ public class GroupServiceImpl implements GroupService {
if (StringUtils.isBlank(username) || StringUtils.isBlank(groupId)) if (StringUtils.isBlank(username) || StringUtils.isBlank(groupId))
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST)); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
try { try {
userShopRepository.updateGroupId(groupId, null); userShopRepository.updateGroupId(groupId, null);
groupRepository.deleteById(groupId); groupRepository.deleteById(groupId);
...@@ -100,17 +96,20 @@ public class GroupServiceImpl implements GroupService { ...@@ -100,17 +96,20 @@ public class GroupServiceImpl implements GroupService {
@Override @Override
public List<GroupDto> getGroupList(String username) { public List<GroupDto> getGroupList(String username) {
if (StringUtils.isBlank(username)) { if (StringUtils.isBlank(username))
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
List<GroupDto> groupDtos = new ArrayList<>();
List<Group> groups = groupRepository.findByOwner(username); List<Group> groups = groupRepository.findByOwner(username);
if (groups == null)
groups.forEach( return new ArrayList<>();
x -> groupDtos.add(new GroupDto(x.getId(), x.getName(), x.getDetails())) List<GroupDto> groupDtos = new ArrayList<>();
); try {
groups.stream().forEach(x -> {
groupDtos.add(new GroupDto(x.getId(), x.getName(), x.getDetails()));
});
} catch (Exception e) {
logger.error("fail to delete group", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
}
return groupDtos; return groupDtos;
} }
} }
package com.edgec.browserbackend.browser.service; package com.edgec.browserbackend.browser.service;
import com.edgec.browserbackend.browser.domain.Shop;
import com.edgec.browserbackend.browser.domain.ShopSummary; import com.edgec.browserbackend.browser.domain.ShopSummary;
import com.edgec.browserbackend.browser.dto.ShopFilterDto; import com.edgec.browserbackend.browser.dto.*;
import com.edgec.browserbackend.browser.dto.ShopPageResultDto;
import com.edgec.browserbackend.browser.dto.ShopResultDto;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.IOException;
...@@ -32,6 +31,4 @@ public interface ShopService { ...@@ -32,6 +31,4 @@ public interface ShopService {
List<String> getShopUsers(String username, String shopId); List<String> getShopUsers(String username, String shopId);
List<String> getBatchShopUsers(String username, List<String> shopIds); List<String> getBatchShopUsers(String username, List<String> shopIds);
Integer dealDirtyData();
} }
...@@ -101,15 +101,12 @@ public class BrowserTask { ...@@ -101,15 +101,12 @@ public class BrowserTask {
} }
/**
* 购买ip的定时任务,每分钟一次
*/
@Scheduled(cron = "0 0/1 * * * ?") @Scheduled(cron = "0 0/1 * * * ?")
public void buyIpTasks() { public void buyIpTasks() {
String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL; String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
long time = Instant.now().minusSeconds(300).toEpochMilli(); long time = Instant.now().minusSeconds(300).toEpochMilli();
List<IpResource> ipResources = ipResourceRepository.sampleTasks(6, time); List<IpResource> ipResources = ipResourceRepository.sampleTasks(6, time);
log.info("buyIpTasks sample {} tasks", ipResources.size()); log.error("buyIpTasks sample {} tasks", ipResources.size());
List<CompletableFuture> futureList = new ArrayList<>(); List<CompletableFuture> futureList = new ArrayList<>();
for (IpResource ipResource : ipResources) { for (IpResource ipResource : ipResources) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
...@@ -142,21 +139,22 @@ public class BrowserTask { ...@@ -142,21 +139,22 @@ public class BrowserTask {
} }
if (ipBuyResultDto != null && ipBuyResultDto.getIplist() != null && ipBuyResultDto.getIplist().size() >= 1) { if (ipBuyResultDto != null && ipBuyResultDto.getIplist() != null && ipBuyResultDto.getIplist().size() >= 1) {
AtomicInteger index = new AtomicInteger(); AtomicInteger index = new AtomicInteger();
ipBuyResultDto.getIplist().forEach( ipBuyResultDto.getIplist().forEach(x -> {
x -> { if (ipResource != null) {
ipResource.setAddr(x.getIp()); ipResource.setAddr(x.getIp());
ipResource.setStatus(3); ipResource.setStatus(3);
ipResource.setValidTime(Instant.parse(x.getValidTill()).toEpochMilli()); ipResource.setValidTime(Instant.parse(x.getValidTill()).toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion()) && region.contains(ipResource.getRegion())) { if (StringUtils.isNotBlank(ipResource.getRegion()) && region.contains(ipResource.getRegion())) {
ipResource.setProxyUsername(ipResource.getAddr()); ipResource.setProxyUsername(ipResource.getAddr());
ipResource.setProxyPassword(genRandom(3, 12)); ipResource.setProxyPassword(genRandom(3, 12));
ipResource.setSpecialLine(true); ipResource.setSpecialLine(true);
}
ipResourceRepository.save(ipResource);
index.getAndIncrement();
} }
); ipResourceRepository.save(ipResource);
} else {
log.error("no ipResource");
}
index.getAndIncrement();
});
result = true; result = true;
} }
} catch (Exception e) { } catch (Exception e) {
......
...@@ -32,34 +32,25 @@ public class PaymentTask { ...@@ -32,34 +32,25 @@ public class PaymentTask {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Date date_5min = new Date(now - 5 * 60 * 1000); Date date_5min = new Date(now - 5 * 60 * 1000);
Date date_10min = new Date(now - 10 * 60 * 1000); Date date_10min = new Date(now - 10 * 60 * 1000);
// 查找 5-10 分钟内 支付状态为 false 的订单
List<UserPayment> unfinishedPayments = userPaymentRepository.findAllByPaymentDateBetweenAndSucceed( List<UserPayment> unfinishedPayments = userPaymentRepository.findAllByPaymentDateBetweenAndSucceed(
ZonedDateTime.ofInstant(date_10min.toInstant(), ZoneId.systemDefault()), ZonedDateTime.ofInstant(date_10min.toInstant(), ZoneId.systemDefault())
ZonedDateTime.ofInstant(date_5min.toInstant(), ZoneId.systemDefault()), , ZonedDateTime.ofInstant(date_5min.toInstant(), ZoneId.systemDefault()), false);
false);
if (unfinishedPayments != null && !unfinishedPayments.isEmpty()) { if (unfinishedPayments != null && unfinishedPayments.size() > 0) {
unfinishedPayments.forEach(
payment -> {
PaymentMethod paymentMethod = payment.getPaymentMethod();
try {
/*
* 自动调用 微信或者支付宝的支付接口来确认 支付状态
* chargeType 取值范围为 0-4
* 此处设置为 100 仅仅只是为了避免 wxCheckOrderStatus() 方法中 chargeType == 0 相关代码块
*/
if (PaymentMethod.WECHAT.equals(paymentMethod)) {
paymentService.wxCheckOrderStatus(payment.getTradeNo(), 100);
}
if (PaymentMethod.ALIPAY.equals(paymentMethod)) { unfinishedPayments.stream().forEach(payment -> {
paymentService.aliCheckOrderStatus(payment.getTradeNo(), 100); PaymentMethod paymentMethod = payment.getPaymentMethod();
}
} catch (Exception e) { try {
log.error("checkPayments", e); if (PaymentMethod.WECHAT.equals(paymentMethod)) {
} paymentService.wxCheckOrderStatus(payment.getTradeNo());
} else if (PaymentMethod.ALIPAY.equals(paymentMethod)) {
paymentService.aliCheckOrderStatus(payment.getTradeNo());
} }
); } catch (Exception e) {
log.error("checkPayments", e);
}
});
} }
} }
} }
\ No newline at end of file
...@@ -12,7 +12,9 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -12,7 +12,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.YearMonth; import java.time.YearMonth;
import java.time.ZoneOffset;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
...@@ -27,48 +29,35 @@ public class PromotionTask { ...@@ -27,48 +29,35 @@ public class PromotionTask {
@Autowired @Autowired
private UserPrePaidBillingRepository userPrePaidBillingRepository; private UserPrePaidBillingRepository userPrePaidBillingRepository;
//临时修改为7月2号的11点执行执行一次
@SchedulerLock(name = "countGift", lockAtLeastForString = "PT1H", lockAtMostForString = "PT2H") @SchedulerLock(name = "countGift", lockAtLeastForString = "PT1H", lockAtMostForString = "PT2H")
//@Scheduled(cron = "0 0 1 1 * ?") @Scheduled(cron = "0 0 1 1 * ?")
@Scheduled(cron = "0 0 3 2 * ?")
public void countGift() { public void countGift() {
log.info("Start scheduled task:Scheduled.countGift...");
List<Account> accounts = accountRepository.findByParentIsNull(); List<Account> accounts = accountRepository.findByParentIsNull();
for (Account account : accounts) { for (Account account : accounts) {
// 1. 获取当前账户的邀请码信息
String code = account.getPromotion().getCode(); String code = account.getPromotion().getCode();
// 2. 获取被当前账户邀请的所有账户
List<Account> promotes = accountRepository.findByPromotionCodeAndParentIsNull(code); List<Account> promotes = accountRepository.findByPromotionCodeAndParentIsNull(code);
double totalCommission = 0; double totalCommission = 0;
double secondCommission = 0; double secondCommission = 0;
// 3. 计算所有被当前账户邀请的账户上个月的消费信息,以及如果当前账户是销售账户则还需要计算销售账户的下下级账户的上个月消费信息
for (Account promote : promotes) { for (Account promote : promotes) {
// 3.1 获取被邀请的用户上个月的消费信息,todo 感觉这个地方最好加上支付状态 List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn(promote.getName(),
List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn( YearMonth.now().minusMonths(1).getYear(),
promote.getName(), YearMonth.now().minusMonths(1).getYear(), YearMonth.now().minusMonths(1).getMonthValue(), Arrays.asList(1, 2, 3) YearMonth.now().minusMonths(1).getMonthValue(), Arrays.asList(1,2,3));
);
// 3.2. 计算被邀请的用户上个月的总消费金额
totalCommission += userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); totalCommission += userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
// 3.3. 如果当前账户是本公司销售,则计算下下级用户(例如:销售人员A 邀请了 用户B,用户B 邀请了 其他用户,其他用户就是A的下下级用户)上个月总消费金额
if (account.getPromotion().isSale() && promote.getParent() == null) { if (account.getPromotion().isSale() && promote.getParent() == null) {
// 获取下下级账户
List<Account> secondPromotes = accountRepository.findByPromotionCodeAndParentIsNull(promote.getPromotion().getCode()); List<Account> secondPromotes = accountRepository.findByPromotionCodeAndParentIsNull(promote.getPromotion().getCode());
if (secondPromotes != null && !secondPromotes.isEmpty()) { if (secondPromotes != null && secondPromotes.size() > 0) {
for (Account secondPromote : secondPromotes) { for (Account secondPromote : secondPromotes) {
List<UserPrePaidBilling> userPrePaidBillings1 = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn( List<UserPrePaidBilling> userPrePaidBillings1 = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn(secondPromote.getName(),
secondPromote.getName(), YearMonth.now().minusMonths(1).getYear(), YearMonth.now().minusMonths(1).getMonthValue(), Arrays.asList(1, 2, 3) YearMonth.now().minusMonths(1).getYear(),
); YearMonth.now().minusMonths(1).getMonthValue(), Arrays.asList(1,2,3));
secondCommission += userPrePaidBillings1.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); secondCommission += userPrePaidBillings1.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
} }
} }
} }
} }
// 4. 封装当前账户的返佣相关信息(总消费、上月消费、上月礼金、总共未提现礼金)并保存
Promotion promotion = account.getPromotion(); Promotion promotion = account.getPromotion();
promotion.setTotalCommission((int) (promotion.getTotalCommission() + totalCommission)); promotion.setTotalCommission((int)(promotion.getTotalCommission() + totalCommission));
promotion.setCommissionLastMonth((int) totalCommission); promotion.setCommissionLastMonth((int)totalCommission);
promotion.setGift(totalCommission * 0.08); promotion.setGift(totalCommission * 0.08);
if (account.getPromotion().isSale()) { if (account.getPromotion().isSale()) {
promotion.setGift(totalCommission * 0.1 + secondCommission * 0.02); promotion.setGift(totalCommission * 0.1 + secondCommission * 0.02);
...@@ -76,52 +65,41 @@ public class PromotionTask { ...@@ -76,52 +65,41 @@ public class PromotionTask {
promotion.setAllGift(promotion.getAllGift() + promotion.getGift()); promotion.setAllGift(promotion.getAllGift() + promotion.getGift());
accountRepository.save(account); accountRepository.save(account);
} }
log.info("End scheduled task:Scheduled.countGift...");
} }
//临时修改为7月2号的12点执行执行一次
@SchedulerLock(name = "countCommission", lockAtLeastForString = "PT1H", lockAtMostForString = "PT2H") @SchedulerLock(name = "countCommission", lockAtLeastForString = "PT1H", lockAtMostForString = "PT2H")
//@Scheduled(cron = "0 0 1 * * ?") @Scheduled(cron = "0 0 1 * * ?")
@Scheduled(cron = "0 0 4 2 * ?")
public void countCommission() { public void countCommission() {
log.info("Start scheduled task:Scheduled.countCommission...");
List<Account> accounts = accountRepository.findByParentIsNull(); List<Account> accounts = accountRepository.findByParentIsNull();
for (Account account : accounts) { for (Account account : accounts) {
// 1. 获取被当前账户邀请的所有账户
String code = account.getPromotion().getCode(); String code = account.getPromotion().getCode();
List<Account> promotes = accountRepository.findByPromotionCodeAndParentIsNull(code); List<Account> promotes = accountRepository.findByPromotionCodeAndParentIsNull(code);
double totalCommission = 0; double totalCommission = 0;
double secondCommission = 0; double secondCommission = 0;
// 2. 计算所有被当前账户邀请的账户当月当前的消费信息,以及如果当前账户是销售账户则还需要计算销售账户的下下级账户的当月当前消费信息
for (Account promote : promotes) { for (Account promote : promotes) {
List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn( List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn(promote.getName(),
promote.getName(), YearMonth.now().getYear(), YearMonth.now().getMonthValue(), Arrays.asList(1, 2, 3) YearMonth.now().getYear(),
); YearMonth.now().getMonthValue(), Arrays.asList(1,2,3));
totalCommission += userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); totalCommission += userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
if (account.getPromotion().isSale() && promote.getParent() == null) { if (account.getPromotion().isSale() && promote.getParent() == null) {
List<Account> secondPromotes = accountRepository.findByPromotionCodeAndParentIsNull(promote.getPromotion().getCode()); List<Account> secondPromotes = accountRepository.findByPromotionCodeAndParentIsNull(promote.getPromotion().getCode());
if (secondPromotes != null && secondPromotes.size() > 0) { if (secondPromotes != null && secondPromotes.size() > 0) {
for (Account secondPromote : secondPromotes) { for (Account secondPromote : secondPromotes) {
List<UserPrePaidBilling> userPrePaidBillings1 = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn( List<UserPrePaidBilling> userPrePaidBillings1 = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn(secondPromote.getName(),
secondPromote.getName(), YearMonth.now().getYear(), YearMonth.now().getMonthValue(), Arrays.asList(1, 2, 3) YearMonth.now().getYear(),
); YearMonth.now().getMonthValue(), Arrays.asList(1,2,3));
secondCommission += userPrePaidBillings1.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); secondCommission += userPrePaidBillings1.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
} }
} }
} }
} }
// 3. 封装当前账户的返佣相关信息(当月当前的消费、当月当前的返佣)并保存
Promotion promotion = account.getPromotion(); Promotion promotion = account.getPromotion();
promotion.setCommission((int) totalCommission); promotion.setCommission((int)totalCommission);
promotion.setGift(totalCommission * 0.08); promotion.setGift(totalCommission * 0.08);
if (account.getPromotion().isSale()) { if (account.getPromotion().isSale()) {
promotion.setGift(totalCommission * 0.1 + secondCommission * 0.02); promotion.setGift(totalCommission * 0.1 + secondCommission * 0.02);
} }
accountRepository.save(account); accountRepository.save(account);
} }
log.info("End scheduled task:Scheduled.countCommission...");
} }
} }
...@@ -56,8 +56,8 @@ public class Trans { ...@@ -56,8 +56,8 @@ public class Trans {
* @param args * @param args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
String url = "https://china-merchant.wish.com/login"; String url = "http://free.ipwhois.io/json/";
Trans trans = new Trans("8.210.96.188", "WC5w4M5jkdz1aA1"); Trans trans = new Trans("112.74.47.217", 20001, "fangguanlianbrowser", "5D753F36QKqIaA1");
String rs = trans.get(url); String rs = trans.get(url);
System.out.println(rs); System.out.println(rs);
} }
......
...@@ -18,12 +18,10 @@ public class FGLWxConfig extends WXPayConfig { ...@@ -18,12 +18,10 @@ public class FGLWxConfig extends WXPayConfig {
return "acdkgjef237ckgSriEICRe2408sdjEDC"; return "acdkgjef237ckgSriEICRe2408sdjEDC";
} }
@Override
public int getHttpConnectTimeoutMs() { public int getHttpConnectTimeoutMs() {
return 8000; return 8000;
} }
@Override
public int getHttpReadTimeoutMs() { public int getHttpReadTimeoutMs() {
return 10000; return 10000;
} }
...@@ -37,12 +35,10 @@ public class FGLWxConfig extends WXPayConfig { ...@@ -37,12 +35,10 @@ public class FGLWxConfig extends WXPayConfig {
public IWXPayDomain getWXPayDomain() { public IWXPayDomain getWXPayDomain() {
IWXPayDomain iwxPayDomain = new IWXPayDomain() { IWXPayDomain iwxPayDomain = new IWXPayDomain() {
@Override
public void report(String domain, long elapsedTimeMillis, Exception ex) { public void report(String domain, long elapsedTimeMillis, Exception ex) {
} }
@Override
public DomainInfo getDomain(WXPayConfig config) { public DomainInfo getDomain(WXPayConfig config) {
return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API, true); return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API, true);
} }
......
package com.edgec.browserbackend; package com.edgec.browserbackend;
import com.edgec.browserbackend.account.domain.Account;
import com.edgec.browserbackend.account.repository.AccountRepository;
import com.edgec.browserbackend.account.repository.UserPaymentRepository;
import com.edgec.browserbackend.account.repository.UserPrePaidBillingRepository;
import com.edgec.browserbackend.browser.repository.IpOptionsRepository;
import com.edgec.browserbackend.browser.repository.IpResourceRepository;
import com.edgec.browserbackend.browser.repository.ShopRepository;
import com.edgec.browserbackend.browser.repository.UserShopRepository;
import com.edgec.browserbackend.browser.service.IpResourceService;
import com.edgec.browserbackend.browser.service.ShopService;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
@SpringBootTest @SpringBootTest
class BrowserBackendApplicationTests { class BrowserBackendApplicationTests {
@Autowired
ShopService shopService;
@Autowired
MongoTemplate mongoTemplate;
@Autowired
private UserShopRepository userShopRepository;
@Autowired
IpResourceRepository ipResourceRepository;
@Autowired
ShopRepository shopRepository;
@Autowired
AccountRepository accountRepository;
@Autowired
IpOptionsRepository ipOptionsRepository;
@Autowired
IpResourceService ipResourceService;
@Autowired
UserPaymentRepository userPaymentRepository;
@Autowired
UserPrePaidBillingRepository userPrePaidBillingRepository;
@Test @Test
void contextLoads() { void contextLoads() {
} }
@Test
public void testShopList() throws Exception {
/*List<Account> all = accountRepository.findAll();
List<Account> parents = all.stream().filter(x -> StringUtils.isEmpty(x.getParent())).collect(Collectors.toList());
// 移除 父账户,剩下的都是子账户了
all.removeAll(parents);
// 父账户, 子账户列表
Map<Account, List<Account>> map = new HashMap<>();
for (Account account : parents) {
List<Account> list = new ArrayList<>();
for (Account child : all) {
if (child.getParent().equals(account.getName())) {
list.add(child);
}
}
if (list.size() != 0) {
map.put(account, list);
}
}
Iterator<Map.Entry<Account, List<Account>>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Account, List<Account>> entry = entries.next();
List<Account> children = entry.getValue();
// 查找子类所拥有的店铺
List<Shop> childrenShop = shopRepository.findByOwnerIn(children.stream().map(Account::getName).collect(Collectors.toList()));
if (childrenShop.size() == 0) {
continue;
}
List<String> ids = childrenShop.stream().map(x -> x.getShopId()).collect(Collectors.toList());
// 查出来 父账户已有的 usershop信息
List<UserShop> parentUserShops = userShopRepository.findByUsernameAndShopIdIn(entry.getKey().getName(), ids);
List<String> parentShopIds = parentUserShops.stream().map(x -> x.getShopId()).collect(Collectors.toList());
// 剩下的就是 父账户的 usershop 缺失的信息
ids.removeAll(parentShopIds);
List<UserShop> userShops = new ArrayList<>();
for (String id : ids) {
UserShop userShop = new UserShop();
userShop.setShopId(id);
userShop.setUsername(entry.getKey().getName());
userShop.setGroupId("-1");
userShops.add(userShop);
}
if (userShops.size() != 0) {
// 将父账户缺失的 usershop 信息补充完整
List<UserShop> userShops1 = userShopRepository.saveAll(userShops);
}
}
//shopService.getShopUsers("18622987110", "5e82dbd407f16f1c782b9f1e");
/*IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted("5e82e3d407f16f1c782b9f26", false);
IpResourceDto ipResourceDto = new IpResourceDto(ipResource, null, false);
IpResourceDto ipResourceDto1 = new IpResourceDto(ipResource, null, false, null);
System.out.println(ipResourceDto.equals(ipResourceDto1));
Map<String, List<String>> priceList = ipOptionsRepository.findAll().get(0).getIpPlatForm();
System.out.println(priceList);
String json = "{\"addr\":[\"8.210.63.174\"],\"ipId\":[],\"period\":1,\"unit\":\"month\",\"payMethod\":0}";
IpResourceRequestDto ipResourceRequestDto = JSON.parseObject(json, IpResourceRequestDto.class);
String username = "15919921106";
try {
ipResourceService.renewIp(username, ipResourceRequestDto);
} catch (Exception e) {
e.printStackTrace();
}
UserPayment byTradeNo = userPaymentRepository.findByTradeNo("202003141459128356");
if (byTradeNo.getPaymentMethod().equals(PaymentMethod.ALIPAY)) {
System.out.println("hhhh");
}
if (byTradeNo.getPaymentMethod().equals(PaymentMethod.WECHAT)) {
System.out.println("wwww");
}
// 输入json 字符串的快捷方式 alt + enter、alt+enter
String json = "{\"region\":\"us\",\"regionCn\":\"美国随机\",\"vendor\":\"aliyun\",\"period\":1,\"unit\":\"week\",\"amount\":2,\"price\":24,\"payMethod\":0}";
IpResourceRequestDto ipResourceRequestDto = JSON.parseObject(json, IpResourceRequestDto.class);
String username = "15919921106";
List<String> ipResourceDto = ipResourceService.buyIp(username, ipResourceRequestDto);
System.out.println(ipResourceDto);
Optional<Shop> shop = shopRepository.findById("5efbfec70718e43054d65168");
String shopCookie = shop.get().getShopCookie();
List<Account> accounts = accountRepository.findByParentIsNull();
for (Account account : accounts) {
if (account.getName().equals("17665464606")) {
// 1. 获取当前账户的邀请码信息
String code = account.getPromotion().getCode();
// 2. 获取被当前账户邀请的所有账户
List<Account> promotes = accountRepository.findByPromotionCodeAndParentIsNull(code);
double totalCommission = 0;
double secondCommission = 0;
// 3. 计算所有被当前账户邀请的账户上个月的消费信息,以及如果当前账户是销售账户则还需要计算销售账户的下下级账户的上个月消费信息
for (Account promote : promotes) {
// 3.1 获取被邀请的用户上个月的消费信息,todo 感觉这个地方最好加上支付状态
List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn(
promote.getName(), YearMonth.now().minusMonths(1).getYear(), YearMonth.now().minusMonths(1).getMonthValue(), Arrays.asList(1, 2, 3)
);
// 3.2. 计算被邀请的用户上个月的总消费金额
totalCommission += userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
// 3.3. 如果当前账户是本公司销售,则计算下下级用户(例如:销售人员A 邀请了 用户B,用户B 邀请了 其他用户,其他用户就是A的下下级用户)上个月总消费金额
if (account.getPromotion().isSale() && promote.getParent() == null) {
// 获取下下级账户
List<Account> secondPromotes = accountRepository.findByPromotionCodeAndParentIsNull(promote.getPromotion().getCode());
if (secondPromotes != null && !secondPromotes.isEmpty()) {
for (Account secondPromote : secondPromotes) {
List<UserPrePaidBilling> userPrePaidBillings1 = userPrePaidBillingRepository.findByAdministratorAndYearAndMonthAndPayMethodIn(
secondPromote.getName(), YearMonth.now().minusMonths(1).getYear(), YearMonth.now().minusMonths(1).getMonthValue(), Arrays.asList(1, 2, 3)
);
secondCommission += userPrePaidBillings1.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
}
}
}
}
// 4. 封装当前账户的返佣相关信息(总消费、上月消费、当月礼金、总共未体现礼金)并保存
Promotion promotion = account.getPromotion();
promotion.setTotalCommission((int) (promotion.getTotalCommission() + totalCommission));
promotion.setCommissionLastMonth((int) totalCommission);
promotion.setGift(totalCommission * 0.08);
if (account.getPromotion().isSale()) {
promotion.setGift(totalCommission * 0.1 + secondCommission * 0.02);
}
promotion.setAllGift(promotion.getAllGift() + promotion.getGift());
System.out.println(111);
}
}*/
Account account = new Account();
account.setName("110110110");
account.setPhoneNumber("110110110");
accountRepository.save(account);
Account byName = accountRepository.findByName("110110110").get();
byName.setParent("110");
accountRepository.save(byName);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment