Commit fc8e8d2f authored by xuxin's avatar xuxin

代码调优及bug修复

parent 1803862e
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.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Length;
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.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@NoArgsConstructor
@Getter
@Setter
@Document(collection = "accounts") @Document(collection = "accounts")
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class Account { public class Account {
/**
* 账户id
*/
@Id @Id
private String name; private String name;
/**
* 父账户
*/
private String parent; private String parent;
//子用户使用
/**
* 子用户使用的密码
*/
private String password; private String password;
private Date lastSeen; private Date lastSeen;
...@@ -44,6 +58,13 @@ public class Account { ...@@ -44,6 +58,13 @@ public class Account {
private boolean allowedToCreateSubUser = false; private boolean allowedToCreateSubUser = false;
/**
* 操作与权重
* <p>
* 下载 cookie:1
* 上传 cookie:2
* 店铺管理(增删改店铺、绑定与解绑ip):4
*/
private int permission = -1; private int permission = -1;
private Promotion promotion; private Promotion promotion;
...@@ -64,24 +85,8 @@ public class Account { ...@@ -64,24 +85,8 @@ public class Account {
private List<String> queryIpUrlList = new ArrayList<>(); private List<String> queryIpUrlList = new ArrayList<>();
public Date getSignupDate() { @Length(min = 0, max = 20000)
return signupDate; private String note;
}
public void setSignupDate(Date signupDate) {
this.signupDate = signupDate;
}
public boolean isPrePaid() {
return isPrePaid;
}
public void setPrePaid(boolean prePaid) {
isPrePaid = prePaid;
}
public Account() {
}
public Account(AccountDto account) { public Account(AccountDto account) {
this.setName(account.getName()); this.setName(account.getName());
...@@ -94,191 +99,5 @@ public class Account { ...@@ -94,191 +99,5 @@ public class Account {
this.setWhiteList(account.getWhiteList()); this.setWhiteList(account.getWhiteList());
} }
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Length(min = 0, max = 20000)
private String note;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastSeen() {
return lastSeen;
}
public void setLastSeen(Date lastSeen) {
this.lastSeen = lastSeen;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public boolean isAllowedToCreateSubUser() {
return allowedToCreateSubUser;
}
public void setAllowedToCreateSubUser(boolean allowedToCreateSubUser) {
this.allowedToCreateSubUser = allowedToCreateSubUser;
}
public String getLockReason() {
return lockReason;
}
public void setLockReason(String lockReason) {
this.lockReason = lockReason;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getPermission() {
return permission;
}
public void setPermission(int permission) {
this.permission = permission;
}
public List<String> getWhiteList() {
return whiteList;
}
public void setWhiteList(List<String> whiteList) {
this.whiteList = whiteList;
}
public int getChildCount() {
return childCount;
}
public void setChildCount(int childCount) {
this.childCount = childCount;
}
public int getGroupCount() {
return groupCount;
}
public void setGroupCount(int groupCount) {
this.groupCount = groupCount;
}
public int getShopCount() {
return shopCount;
}
public void setShopCount(int shopCount) {
this.shopCount = shopCount;
}
public Promotion getPromotion() {
return promotion;
}
public void setPromotion(Promotion promotion) {
this.promotion = promotion;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public List<String> getQueryIpUrlList() {
return queryIpUrlList;
}
public void setQueryIpUrlList(List<String> queryIpUrlList) {
this.queryIpUrlList = queryIpUrlList;
}
public int getAuthorized() {
return authorized;
}
public void setAuthorized(int authorized) {
this.authorized = authorized;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPromotionCode() {
return promotionCode;
}
public void setPromotionCode(String promotionCode) {
this.promotionCode = promotionCode;
}
} }
package com.edgec.browserbackend.account.repository; package com.edgec.browserbackend.account.repository;
import com.edgec.browserbackend.account.domain.Account; import com.edgec.browserbackend.account.domain.Account;
import com.edgec.browserbackend.browser.dto.PageInfo;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.MongoRepository;
...@@ -9,11 +8,12 @@ import org.springframework.stereotype.Repository; ...@@ -9,11 +8,12 @@ import org.springframework.stereotype.Repository;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Optional;
@Repository @Repository
public interface AccountRepository extends MongoRepository<Account, String>, AccountRepositoryCustom { public interface AccountRepository extends MongoRepository<Account, String>, AccountRepositoryCustom {
Account findByName(String name); Optional<Account> findByName(String name);
Account findByEmail(String email); Account findByEmail(String email);
...@@ -37,6 +37,7 @@ public interface AccountRepository extends MongoRepository<Account, String>, Acc ...@@ -37,6 +37,7 @@ public interface AccountRepository extends MongoRepository<Account, String>, Acc
Page<Account> findAllBySignupDateBetweenAndParentIsNullAndAuthorized(Pageable pageable, Date startDate, Date endDate, int authorized); Page<Account> findAllBySignupDateBetweenAndParentIsNullAndAuthorized(Pageable pageable, Date startDate, Date endDate, int authorized);
@Override
Page<Account> findAll(Pageable pageable); Page<Account> findAll(Pageable pageable);
List<Account> findByNameIn(List<String> names); List<Account> findByNameIn(List<String> names);
......
...@@ -62,7 +62,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -62,7 +62,7 @@ public class AccountServiceImpl implements AccountService {
private PreOrderRepository preOrderRepository; private PreOrderRepository preOrderRepository;
@Autowired @Autowired
private AccountRepository repository; private AccountRepository accountRepository;
@Autowired @Autowired
private EmailService emailService; private EmailService emailService;
...@@ -116,7 +116,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -116,7 +116,7 @@ public class AccountServiceImpl implements AccountService {
list.addUserBill(userBilling); list.addUserBill(userBilling);
result.add(list); result.add(list);
List<Account> children = repository.findByParent(name); List<Account> children = accountRepository.findByParent(name);
if (children != null && children.size() > 0) { if (children != null && children.size() > 0) {
List<String> collect = children.stream().map(x -> x.getName()).collect(Collectors.toList()); List<String> collect = children.stream().map(x -> x.getName()).collect(Collectors.toList());
List<UserBilling> childrenBills = billingRepository.findByUsernameInAndYearAndMonthOrderByYearDescMonthDesc(collect, userBilling.getYear(), userBilling.getMonth()); List<UserBilling> childrenBills = billingRepository.findByUsernameInAndYearAndMonthOrderByYearDescMonthDesc(collect, userBilling.getYear(), userBilling.getMonth());
...@@ -147,9 +147,8 @@ public class AccountServiceImpl implements AccountService { ...@@ -147,9 +147,8 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public PrePaidBillingPageResultDto getUserPrePaidBills(String name, UserPrePaidBillingRequestDto userPrePaidBillingRequestDto) { public PrePaidBillingPageResultDto getUserPrePaidBills(String name, UserPrePaidBillingRequestDto userPrePaidBillingRequestDto) {
Account account = repository.findByName(name); Account account = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (userPrePaidBillingRequestDto.getAmount() > 100) if (userPrePaidBillingRequestDto.getAmount() > 100)
userPrePaidBillingRequestDto.setAmount(100); userPrePaidBillingRequestDto.setAmount(100);
...@@ -191,7 +190,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -191,7 +190,7 @@ public class AccountServiceImpl implements AccountService {
charge.setApprovedAmount(0); charge.setApprovedAmount(0);
charge.setSuccess(true); charge.setSuccess(true);
Account account = repository.findByName(name); Account account = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account != null) { if (account != null) {
UserBalance userBalance = userBalanceRepository.findById(name).orElse(null); UserBalance userBalance = userBalanceRepository.findById(name).orElse(null);
if (userBalance == null) { if (userBalance == null) {
...@@ -260,7 +259,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -260,7 +259,7 @@ public class AccountServiceImpl implements AccountService {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
precharge.setApprovedAmount(0); precharge.setApprovedAmount(0);
precharge.setSuccess(false); precharge.setSuccess(false);
Account account = repository.findByName(name); Account account = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account != null) { if (account != null) {
UserBalance userBalance = userBalanceRepository.findById(name).orElse(null); UserBalance userBalance = userBalanceRepository.findById(name).orElse(null);
float balance = 0; float balance = 0;
...@@ -285,7 +284,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -285,7 +284,7 @@ public class AccountServiceImpl implements AccountService {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
precharge.setApprovedAmount(0); precharge.setApprovedAmount(0);
precharge.setSuccess(false); precharge.setSuccess(false);
Account account = repository.findByName(name); Account account = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account != null) { if (account != null) {
UserBalance userBalance = userBalanceRepository.findById(name).orElse(null); UserBalance userBalance = userBalanceRepository.findById(name).orElse(null);
float balance = 0; float balance = 0;
...@@ -309,10 +308,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -309,10 +308,7 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public Account findByName(String accountName) { public Account findByName(String accountName) {
Assert.hasLength(accountName); Assert.hasLength(accountName);
Account account = repository.findByName(accountName); Account account = accountRepository.findByName(accountName).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
return null;
}
if (StringUtils.isEmpty(account.getParent())) { if (StringUtils.isEmpty(account.getParent())) {
account.setPermission(15); account.setPermission(15);
account.setAllowedToCreateSubUser(true); account.setAllowedToCreateSubUser(true);
...@@ -341,7 +337,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -341,7 +337,7 @@ public class AccountServiceImpl implements AccountService {
current.setAllowedToCreateSubUser(true); current.setAllowedToCreateSubUser(true);
} }
List<Account> child = repository.findByParent(name); List<Account> child = accountRepository.findByParent(name);
if (child != null && child.size() > 0) { if (child != null && child.size() > 0) {
List<AccountDto> childDto = child.stream().map(item -> new AccountDto(item)).collect(Collectors.toList()); List<AccountDto> childDto = child.stream().map(item -> new AccountDto(item)).collect(Collectors.toList());
current.setChild(childDto); current.setChild(childDto);
...@@ -367,9 +363,9 @@ public class AccountServiceImpl implements AccountService { ...@@ -367,9 +363,9 @@ public class AccountServiceImpl implements AccountService {
current.setWhiteList(whiteList); current.setWhiteList(whiteList);
if (account.getPromotion() != null) { if (account.getPromotion() != null) {
int invitedUsers = repository.countByPromotionCodeAndParentIsNull(account.getPromotion().getCode()); int invitedUsers = accountRepository.countByPromotionCodeAndParentIsNull(account.getPromotion().getCode());
String code = account.getPromotion().getCode(); String code = account.getPromotion().getCode();
List<Account> promotes = repository.findByPromotionCodeAndParentIsNull(code); List<Account> promotes = accountRepository.findByPromotionCodeAndParentIsNull(code);
double totalCommission = 0; double totalCommission = 0;
totalCommission = 0; totalCommission = 0;
for (Account promote : promotes) { for (Account promote : promotes) {
...@@ -381,7 +377,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -381,7 +377,7 @@ public class AccountServiceImpl implements AccountService {
account.getPromotion().setCommission((int) totalCommission); account.getPromotion().setCommission((int) totalCommission);
account.getPromotion().setInvitedUsers(invitedUsers); account.getPromotion().setInvitedUsers(invitedUsers);
repository.save(account); accountRepository.save(account);
} }
resultDto.setStatus(0); resultDto.setStatus(0);
...@@ -402,7 +398,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -402,7 +398,7 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public void deleteByName(String name) { public void deleteByName(String name) {
userService.deleteUser(name); userService.deleteUser(name);
repository.deleteById(name); accountRepository.deleteById(name);
} }
/** /**
...@@ -416,34 +412,34 @@ public class AccountServiceImpl implements AccountService { ...@@ -416,34 +412,34 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public void deleteSub(String parent, String child) { public void deleteSub(String parent, String child) {
Assert.hasText(parent); Assert.hasText(parent);
Account childAccount = repository.findByName(child); Account childAccount = accountRepository.findByName(child).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (childAccount == null || !parent.equals(childAccount.getParent())) { if (!parent.equals(childAccount.getParent())) {
throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request"); throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request");
} }
userService.deleteUser(child); userService.deleteUser(child);
repository.delete(childAccount); accountRepository.delete(childAccount);
Account parentAccount = repository.findByName(parent); Account parentAccount = accountRepository.findByName(parent).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
parentAccount.setChildCount(parentAccount.getChildCount() - 1); parentAccount.setChildCount(parentAccount.getChildCount() - 1);
repository.save(parentAccount); accountRepository.save(parentAccount);
} }
@Override @Override
public Account createWithSms(User user) { public Account createWithSms(User user) {
Account existing = repository.findByName(user.getUsername()); Account existing = accountRepository.findByName(user.getUsername()).orElse(null);
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername()); throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername());
existing = repository.findByPhoneNumber(user.getUsername()); existing = accountRepository.findByPhoneNumber(user.getUsername());
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername()); throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername());
existing = repository.findByPhoneNumber(user.getPhone()); existing = accountRepository.findByPhoneNumber(user.getPhone());
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getPhone()); throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getPhone());
existing = repository.findByName(user.getPhone()); existing = accountRepository.findByName(user.getPhone()).orElse(null);
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getPhone()); throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getPhone());
...@@ -469,17 +465,17 @@ public class AccountServiceImpl implements AccountService { ...@@ -469,17 +465,17 @@ public class AccountServiceImpl implements AccountService {
account.setPromotionCode(user.getPromotionCode()); account.setPromotionCode(user.getPromotionCode());
} }
Account inviter = repository.findByPromotion(user.getPromotionCode()); Account inviter = accountRepository.findByPromotion(user.getPromotionCode());
if (inviter != null) { if (inviter != null) {
inviter.getPromotion().setInvitedUsers(inviter.getPromotion().getInvitedUsers() + 1); inviter.getPromotion().setInvitedUsers(inviter.getPromotion().getInvitedUsers() + 1);
repository.save(inviter); accountRepository.save(inviter);
} }
Account pExisting = null; Account pExisting = null;
String random = null; String random = null;
do { do {
random = String.valueOf((int) ((Math.random() * 9 + 1) * 100000)); random = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
pExisting = repository.findByPromotion(random); pExisting = accountRepository.findByPromotion(random);
} while (pExisting != null); } while (pExisting != null);
Promotion promotion = new Promotion(); Promotion promotion = new Promotion();
...@@ -497,7 +493,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -497,7 +493,7 @@ public class AccountServiceImpl implements AccountService {
user.setEnabled(true); user.setEnabled(true);
userService.create(new com.edgec.browserbackend.auth.domain.User(user)); userService.create(new com.edgec.browserbackend.auth.domain.User(user));
repository.save(account); accountRepository.save(account);
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("newuser", account.getName()); param.put("newuser", account.getName());
...@@ -520,15 +516,15 @@ public class AccountServiceImpl implements AccountService { ...@@ -520,15 +516,15 @@ public class AccountServiceImpl implements AccountService {
public Account create(User user, String parentName) { public Account create(User user, String parentName) {
Account existing = repository.findByName(user.getUsername()); Account existing = accountRepository.findByName(user.getUsername()).orElse(null);
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername()); throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername());
existing = repository.findByPhoneNumber(user.getUsername()); existing = accountRepository.findByPhoneNumber(user.getUsername());
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername()); throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getUsername());
existing = repository.findByEmail(user.getEmail()); existing = accountRepository.findByEmail(user.getEmail());
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.EMAILEXIST, "email already exists: " + user.getEmail()); throw new ClientRequestException(AccountErrorCode.EMAILEXIST, "email already exists: " + user.getEmail());
user.setEnabled(false); user.setEnabled(false);
...@@ -550,7 +546,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -550,7 +546,7 @@ public class AccountServiceImpl implements AccountService {
emailService.sendEmailVerification(user.getUsername(), user.getEmail(), user.getVerificationCode()); emailService.sendEmailVerification(user.getUsername(), user.getEmail(), user.getVerificationCode());
userService.create(new com.edgec.browserbackend.auth.domain.User(user)); userService.create(new com.edgec.browserbackend.auth.domain.User(user));
repository.save(account); accountRepository.save(account);
log.info("new account has been created: " + account.getName()); log.info("new account has been created: " + account.getName());
...@@ -579,7 +575,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -579,7 +575,7 @@ public class AccountServiceImpl implements AccountService {
if (level == -1) { if (level == -1) {
//find its parent. //find its parent.
String parent = repository.findByName(name).getParent(); String parent = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST)).getParent();
if (StringUtils.isEmpty(parent)) if (StringUtils.isEmpty(parent))
return Arrays.asList(); return Arrays.asList();
...@@ -588,7 +584,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -588,7 +584,7 @@ public class AccountServiceImpl implements AccountService {
return Arrays.asList(dto); return Arrays.asList(dto);
} }
List<Account> accounts = repository.findByParent(name); List<Account> accounts = accountRepository.findByParent(name);
if (accounts == null || accounts.size() <= 0) if (accounts == null || accounts.size() <= 0)
return new ArrayList<>(); return new ArrayList<>();
...@@ -617,7 +613,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -617,7 +613,7 @@ public class AccountServiceImpl implements AccountService {
if (amount > 100) if (amount > 100)
amount = 100; amount = 100;
Pageable pageable = PageRequest.of(page, amount); Pageable pageable = PageRequest.of(page, amount);
Page<Account> accounts = repository.findByParent(name, pageable); Page<Account> accounts = accountRepository.findByParent(name, pageable);
SubUserPageResultDto subUserPageResultDto = new SubUserPageResultDto(); SubUserPageResultDto subUserPageResultDto = new SubUserPageResultDto();
if (accounts == null || accounts.getNumberOfElements() <= 0) if (accounts == null || accounts.getNumberOfElements() <= 0)
...@@ -639,7 +635,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -639,7 +635,7 @@ public class AccountServiceImpl implements AccountService {
} }
public Account createSub(String name, AccountDto user) { public Account createSub(String name, AccountDto user) {
Account existing = repository.findByName(name); Account existing = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (existing == null) if (existing == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + name); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + name);
if (!existing.isAllowedToCreateSubUser() && !StringUtils.isEmpty(existing.getParent())) if (!existing.isAllowedToCreateSubUser() && !StringUtils.isEmpty(existing.getParent()))
...@@ -649,23 +645,23 @@ public class AccountServiceImpl implements AccountService { ...@@ -649,23 +645,23 @@ public class AccountServiceImpl implements AccountService {
throw new ClientRequestException(AccountErrorCode.CHILDMAX, "account cannot have more children"); throw new ClientRequestException(AccountErrorCode.CHILDMAX, "account cannot have more children");
} }
existing = repository.findByName(user.getName()); existing = accountRepository.findByName(user.getName()).orElse(null);
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getName()); throw new ClientRequestException(AccountErrorCode.NAMEEXIST, "account already exists: " + user.getName());
if (!StringUtils.isEmpty(user.getEmail())) { if (!StringUtils.isEmpty(user.getEmail())) {
existing = repository.findByEmail(user.getEmail()); existing = accountRepository.findByEmail(user.getEmail());
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.EMAILEXIST, "email already exists: " + user.getEmail()); throw new ClientRequestException(AccountErrorCode.EMAILEXIST, "email already exists: " + user.getEmail());
} }
if (!StringUtils.isEmpty(user.getPhoneNumber())) { if (!StringUtils.isEmpty(user.getPhoneNumber())) {
existing = repository.findByPhoneNumber(user.getPhoneNumber()); existing = accountRepository.findByPhoneNumber(user.getPhoneNumber());
if (existing != null) if (existing != null)
throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getEmail()); throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getEmail());
} }
existing = repository.findByPhoneNumber(user.getName()); existing = accountRepository.findByPhoneNumber(user.getName());
if (existing != null) { if (existing != null) {
throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getEmail()); throw new ClientRequestException(AccountErrorCode.PHONEEXIST, "phone number already exists: " + user.getEmail());
} }
...@@ -687,7 +683,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -687,7 +683,7 @@ public class AccountServiceImpl implements AccountService {
account.setPhoneNumber(user.getPhoneNumber()); account.setPhoneNumber(user.getPhoneNumber());
account.setEmail(user.getEmail()); account.setEmail(user.getEmail());
account.setParent(name); account.setParent(name);
repository.save(account); accountRepository.save(account);
// emailService.sendEmailVerification(user.getUsername(), user.getEmail(), user.getVerificationCode()); // emailService.sendEmailVerification(user.getUsername(), user.getEmail(), user.getVerificationCode());
...@@ -707,7 +703,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -707,7 +703,7 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public void createSubUsers(String name, SubUsersRequestDto subUsersRequestDto) { public void createSubUsers(String name, SubUsersRequestDto subUsersRequestDto) {
Account existing = repository.findByName(name); Account existing = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (existing == null) if (existing == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + name); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + name);
if (!existing.isAllowedToCreateSubUser() && !StringUtils.isEmpty(existing.getParent())) if (!existing.isAllowedToCreateSubUser() && !StringUtils.isEmpty(existing.getParent()))
...@@ -730,7 +726,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -730,7 +726,7 @@ public class AccountServiceImpl implements AccountService {
else else
user.setName(existing.getName() + i); user.setName(existing.getName() + i);
Account child = repository.findByName(user.getName()); Account child = accountRepository.findByName(user.getName()).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (child != null) { if (child != null) {
time++; time++;
continue; continue;
...@@ -769,7 +765,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -769,7 +765,7 @@ public class AccountServiceImpl implements AccountService {
account.setWhiteList(whiteList); account.setWhiteList(whiteList);
String newpassword = Aes.aesEncrypt(password); String newpassword = Aes.aesEncrypt(password);
account.setPassword(newpassword); account.setPassword(newpassword);
repository.save(account); accountRepository.save(account);
// emailService.sendEmailVerification(user.getUsername(), user.getEmail(), user.getVerificationCode()); // emailService.sendEmailVerification(user.getUsername(), user.getEmail(), user.getVerificationCode());
log.info("new account has been created: " + account.getName()); log.info("new account has been created: " + account.getName());
...@@ -777,13 +773,13 @@ public class AccountServiceImpl implements AccountService { ...@@ -777,13 +773,13 @@ public class AccountServiceImpl implements AccountService {
} }
existing.setChildCount(count); existing.setChildCount(count);
repository.save(existing); accountRepository.save(existing);
} }
public Account saveSub(String name, AccountDto user) { public Account saveSub(String name, AccountDto user) {
Account childAccount = repository.findByName(user.getName()); Account childAccount = accountRepository.findByName(user.getName()).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (childAccount == null || !name.equals(childAccount.getParent())) { if (!name.equals(childAccount.getParent())) {
throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request"); throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request");
} }
childAccount.setAllowedToCreateSubUser(user.isAllowedToCreateSubUser()); childAccount.setAllowedToCreateSubUser(user.isAllowedToCreateSubUser());
...@@ -795,15 +791,15 @@ public class AccountServiceImpl implements AccountService { ...@@ -795,15 +791,15 @@ public class AccountServiceImpl implements AccountService {
if (user.getWhiteList() != null && user.getWhiteList().size() > 0) if (user.getWhiteList() != null && user.getWhiteList().size() > 0)
whiteList.addAll(user.getWhiteList()); whiteList.addAll(user.getWhiteList());
childAccount.setWhiteList(whiteList); childAccount.setWhiteList(whiteList);
repository.save(childAccount); accountRepository.save(childAccount);
return childAccount; return childAccount;
} }
@Override @Override
public void saveSubUsers(String name, SubUsersRequestDto subUsersRequestDto) { public void saveSubUsers(String name, SubUsersRequestDto subUsersRequestDto) {
for (String username : subUsersRequestDto.getUsernames()) { for (String username : subUsersRequestDto.getUsernames()) {
Account childAccount = repository.findByName(username); Account childAccount = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (childAccount == null || !name.equals(childAccount.getParent())) { if (!name.equals(childAccount.getParent())) {
throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request"); throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request");
} }
...@@ -828,7 +824,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -828,7 +824,7 @@ public class AccountServiceImpl implements AccountService {
childAccount.setWhiteList(whiteList); childAccount.setWhiteList(whiteList);
if (org.apache.commons.lang3.StringUtils.isNotBlank(subUsersRequestDto.getPassword())) if (org.apache.commons.lang3.StringUtils.isNotBlank(subUsersRequestDto.getPassword()))
childAccount.setPassword(subUsersRequestDto.getPassword()); childAccount.setPassword(subUsersRequestDto.getPassword());
repository.save(childAccount); accountRepository.save(childAccount);
} }
} }
...@@ -839,9 +835,8 @@ public class AccountServiceImpl implements AccountService { ...@@ -839,9 +835,8 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public Account saveChanges(String name, Account update) { public Account saveChanges(String name, Account update) {
Account account = repository.findByName(name); Account account = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "can't find account with name " + name));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "can't find account with name " + name);
String preEmail = account.getEmail(); String preEmail = account.getEmail();
if (update.getNote() != null) if (update.getNote() != null)
account.setNote(update.getNote()); account.setNote(update.getNote());
...@@ -871,7 +866,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -871,7 +866,7 @@ public class AccountServiceImpl implements AccountService {
log.debug("account {} changes has been saved", name); log.debug("account {} changes has been saved", name);
if (!org.apache.commons.lang3.StringUtils.equalsIgnoreCase(preEmail, update.getEmail())) { if (!org.apache.commons.lang3.StringUtils.equalsIgnoreCase(preEmail, update.getEmail())) {
Account account1 = repository.findByEmail(update.getEmail()); Account account1 = accountRepository.findByEmail(update.getEmail());
if (account1 != null) { if (account1 != null) {
throw new ClientRequestException(AccountErrorCode.EMAILEXIST); throw new ClientRequestException(AccountErrorCode.EMAILEXIST);
} }
...@@ -880,20 +875,19 @@ public class AccountServiceImpl implements AccountService { ...@@ -880,20 +875,19 @@ public class AccountServiceImpl implements AccountService {
newuser.setEmail(update.getEmail()); newuser.setEmail(update.getEmail());
userService.updateUser(name, new com.edgec.browserbackend.auth.domain.User(newuser)); userService.updateUser(name, new com.edgec.browserbackend.auth.domain.User(newuser));
} }
repository.save(account); accountRepository.save(account);
return account; return account;
} }
@Override @Override
public void resetPassword(String username, UserDto user) { public void resetPassword(String username, UserDto user) {
if (user == null) if (user == null) {
throw new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name or mail: " + user); throw new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name or mail: " + user);
Account account = repository.findByName(user.getUsername());
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name: " + user);
} }
Account account = accountRepository.findByName(user.getUsername()).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name: " + user));
User newuser = new User(); User newuser = new User();
newuser.setUsername(account.getName()); newuser.setUsername(account.getName());
String code = UUID.randomUUID().toString() + System.currentTimeMillis(); String code = UUID.randomUUID().toString() + System.currentTimeMillis();
...@@ -906,13 +900,15 @@ public class AccountServiceImpl implements AccountService { ...@@ -906,13 +900,15 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public UserDto determUsernameOrEmail(String text) { public UserDto determUsernameOrEmail(String text) {
if (StringUtils.isEmpty(text)) if (StringUtils.isEmpty(text)) {
throw new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name or mail: " + text);
Account account = repository.findByEmail(text);
if (account == null)
account = repository.findByName(text);
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name or mail: " + text); throw new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name or mail: " + text);
}
Account account = accountRepository.findByEmail(text);
if (account == null) {
account = accountRepository.findByName(text).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMEOREMAILNOTEXIST, "Can't find user with name or mail: " + text));
}
UserDto user = new UserDto(); UserDto user = new UserDto();
user.setEmail(account.getEmail()); user.setEmail(account.getEmail());
user.setUsername(account.getName()); user.setUsername(account.getName());
...@@ -931,7 +927,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -931,7 +927,7 @@ public class AccountServiceImpl implements AccountService {
throw new ClientRequestException(AccountErrorCode.OTPWRONG, AccountErrorCode.OTPWRONG.getReason()); throw new ClientRequestException(AccountErrorCode.OTPWRONG, AccountErrorCode.OTPWRONG.getReason());
} }
Account account = repository.findById(user.getUsername()).orElse(null); Account account = accountRepository.findById(user.getUsername()).orElse(null);
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.PHONENOTEXIST, "Can't find account with phone " + user.getPhone()); throw new ClientRequestException(AccountErrorCode.PHONENOTEXIST, "Can't find account with phone " + user.getPhone());
...@@ -963,7 +959,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -963,7 +959,7 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public AccountDto getAccountByCellphone(String cellphone) { public AccountDto getAccountByCellphone(String cellphone) {
Account account = repository.findByPhoneNumber(cellphone); Account account = accountRepository.findByPhoneNumber(cellphone);
if (account == null) { if (account == null) {
return null; return null;
} }
...@@ -1022,7 +1018,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -1022,7 +1018,7 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public Page<Account> listAccountBySingupDate(Pageable pageable, Date beginDate, Date endDate) { public Page<Account> listAccountBySingupDate(Pageable pageable, Date beginDate, Date endDate) {
return repository.findAllBySignupDateBetween(pageable, beginDate, endDate); return accountRepository.findAllBySignupDateBetween(pageable, beginDate, endDate);
} }
@Override @Override
...@@ -1070,9 +1066,9 @@ public class AccountServiceImpl implements AccountService { ...@@ -1070,9 +1066,9 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public void updateUserToken(String username, String token) { public void updateUserToken(String username, String token) {
Account byName = repository.findByName(username); Account byName = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
byName.setToken(token); byName.setToken(token);
repository.save(byName); accountRepository.save(byName);
} }
@Override @Override
...@@ -1087,9 +1083,8 @@ public class AccountServiceImpl implements AccountService { ...@@ -1087,9 +1083,8 @@ public class AccountServiceImpl implements AccountService {
throw new ClientRequestException(BrowserErrorCode.COMPANYAUTHORIZEEXIST); throw new ClientRequestException(BrowserErrorCode.COMPANYAUTHORIZEEXIST);
} }
try { try {
Account account = repository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
companyLicenseId = companyAuthorizeRepository.saveFile(companyAuthorizeDto.getCompanyLicense(), "companyLicense-" + username); companyLicenseId = companyAuthorizeRepository.saveFile(companyAuthorizeDto.getCompanyLicense(), "companyLicense-" + username);
coporationLicenseFront = companyAuthorizeRepository.saveFile(companyAuthorizeDto.getCoporationLicense_front(), "coporationLicense-front-" + username); coporationLicenseFront = companyAuthorizeRepository.saveFile(companyAuthorizeDto.getCoporationLicense_front(), "coporationLicense-front-" + username);
...@@ -1111,7 +1106,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -1111,7 +1106,7 @@ public class AccountServiceImpl implements AccountService {
} }
companyAuthorizeRepository.save(companyAuthorize); companyAuthorizeRepository.save(companyAuthorize);
account.setAuthorized(1); account.setAuthorized(1);
repository.save(account); accountRepository.save(account);
} catch (Exception e) { } catch (Exception e) {
if (agencyBack != null) if (agencyBack != null)
companyAuthorizeRepository.deleteFile(agencyBack); companyAuthorizeRepository.deleteFile(agencyBack);
...@@ -1172,18 +1167,17 @@ public class AccountServiceImpl implements AccountService { ...@@ -1172,18 +1167,17 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public boolean setAuthorize(String username, boolean isAgree) { public boolean setAuthorize(String username, boolean isAgree) {
try { try {
Account account = repository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (isAgree) { if (isAgree) {
account.setAuthorized(2); account.setAuthorized(2);
CompanyAuthorize companyAuthorize = companyAuthorizeRepository.findByUsername(username); CompanyAuthorize companyAuthorize = companyAuthorizeRepository.findByUsername(username);
account.setCompanyName(companyAuthorize.getCompanyName()); account.setCompanyName(companyAuthorize.getCompanyName());
repository.save(account); accountRepository.save(account);
} else { } else {
account.setAuthorized(3); account.setAuthorized(3);
account.setCompanyName(null); account.setCompanyName(null);
repository.save(account); accountRepository.save(account);
CompanyAuthorize companyAuthorize = companyAuthorizeRepository.findByUsername(username); CompanyAuthorize companyAuthorize = companyAuthorizeRepository.findByUsername(username);
if (companyAuthorize != null) { if (companyAuthorize != null) {
......
...@@ -75,8 +75,8 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -75,8 +75,8 @@ public class AdministratorServiceImpl implements AdministratorService {
@Override @Override
public Administrator createAdministrator(Administrator administrator) { public Administrator createAdministrator(Administrator administrator) {
Administrator administrator1 = new Administrator(); Administrator administrator1 = new Administrator();
if(StringUtils.isEmpty(administrator.getName())){ if (StringUtils.isEmpty(administrator.getName())) {
throw new ClientRequestException(AccountErrorCode.NAMEEMPTY, "userName connot be empty " ); throw new ClientRequestException(AccountErrorCode.NAMEEMPTY, "userName connot be empty ");
} }
administrator1.setName(administrator.getName()); administrator1.setName(administrator.getName());
...@@ -100,9 +100,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -100,9 +100,7 @@ public class AdministratorServiceImpl implements AdministratorService {
@Override @Override
public Account getAccountByName(String name) { public Account getAccountByName(String name) {
Account account = accountRepository.findByName(name); Account account = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "Username does not exist: " + name));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "Username does not exist: " + name);
return account; return account;
} }
...@@ -125,10 +123,8 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -125,10 +123,8 @@ public class AdministratorServiceImpl implements AdministratorService {
@Override @Override
public BillQueryResultDto getUserBillingByName(String name) { public BillQueryResultDto getUserBillingByName(String name) {
Account account = accountRepository.findByName(name); Account account = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByUsernameAndPayMethodIn(name, Arrays.asList(1, 2));
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByUsernameAndPayMethodIn(name, Arrays.asList(1,2));
double parentexpense = 0; double parentexpense = 0;
if (userPrePaidBillings != null) if (userPrePaidBillings != null)
parentexpense = userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); parentexpense = userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
...@@ -154,7 +150,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -154,7 +150,7 @@ public class AdministratorServiceImpl implements AdministratorService {
List<Account> children = accountRepository.findByParent(account.getName()); List<Account> children = accountRepository.findByParent(account.getName());
if (children != null && children.size() > 0) { if (children != null && children.size() > 0) {
for (Account child : children) { for (Account child : children) {
List<UserPrePaidBilling> userPrePaidBillings_child = userPrePaidBillingRepository.findByUsernameAndPayMethodIn(child.getName(), Arrays.asList(1,2)); List<UserPrePaidBilling> userPrePaidBillings_child = userPrePaidBillingRepository.findByUsernameAndPayMethodIn(child.getName(), Arrays.asList(1, 2));
if (userPrePaidBillings_child != null) if (userPrePaidBillings_child != null)
childexpense += userPrePaidBillings_child.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); childexpense += userPrePaidBillings_child.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
UserBalance userBalance_child = userBalanceRepository.findById(child.getName()).orElse(null); UserBalance userBalance_child = userBalanceRepository.findById(child.getName()).orElse(null);
...@@ -194,29 +190,27 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -194,29 +190,27 @@ public class AdministratorServiceImpl implements AdministratorService {
} }
@Override @Override
public Account unLockLockedAccount(String name,Account account) { public Account unLockLockedAccount(String name, Account account) {
Account newAccount = accountRepository.findByName(name); Account newAccount = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (newAccount == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "Username does not exist: " + name);
User newUser = new User(); User newUser = new User();
newUser.setUsername(name); newUser.setUsername(name);
userService.unlock(new com.edgec.browserbackend.auth.domain.User(newUser),"unlock"); userService.unlock(new com.edgec.browserbackend.auth.domain.User(newUser), "unlock");
return newAccount; return newAccount;
} }
@Override @Override
public Account lockAbnormalAccount(String name, Account account) { public Account lockAbnormalAccount(String name, Account account) {
Account abnormalAccount = accountRepository.findByName(name); Account abnormalAccount = accountRepository.findByName(name).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (abnormalAccount == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "Username does not exist: " + name);
abnormalAccount.setLockReason(account.getLockReason()); abnormalAccount.setLockReason(account.getLockReason());
User abnormalUser = new User(); User abnormalUser = new User();
abnormalUser.setUsername(name); abnormalUser.setUsername(name);
userService.lock(new com.edgec.browserbackend.auth.domain.User(abnormalUser),"lock"); userService.lock(new com.edgec.browserbackend.auth.domain.User(abnormalUser), "lock");
accountRepository.save(abnormalAccount); accountRepository.save(abnormalAccount);
...@@ -237,7 +231,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -237,7 +231,7 @@ public class AdministratorServiceImpl implements AdministratorService {
} }
@Override @Override
public Page<Account> searchCreateAccountBetween(Pageable pageable, String strDate1, String strDate2, int isAuthorized ) { public Page<Account> searchCreateAccountBetween(Pageable pageable, String strDate1, String strDate2, int isAuthorized) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Page<Account> accounts = null; Page<Account> accounts = null;
try { try {
...@@ -247,14 +241,15 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -247,14 +241,15 @@ public class AdministratorServiceImpl implements AdministratorService {
accounts = accountRepository.findAllBySignupDateBetweenAndParentIsNull(pageable, dateTime1, dateTime2); accounts = accountRepository.findAllBySignupDateBetweenAndParentIsNull(pageable, dateTime1, dateTime2);
else else
accounts = accountRepository.findAllBySignupDateBetweenAndParentIsNullAndAuthorized(pageable, dateTime1, dateTime2, isAuthorized); accounts = accountRepository.findAllBySignupDateBetweenAndParentIsNullAndAuthorized(pageable, dateTime1, dateTime2, isAuthorized);
}catch (ParseException e){ } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} }
return accounts; return accounts;
} }
@Override @Override
public void deleteAdministrator( String name) { public void deleteAdministrator(String name) {
Administrator administrator = administratorRepository.findByName(name); Administrator administrator = administratorRepository.findByName(name);
if (administrator == null) { if (administrator == null) {
throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request"); throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request");
...@@ -294,7 +289,8 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -294,7 +289,8 @@ public class AdministratorServiceImpl implements AdministratorService {
companyEarningsDto.setTotalBillingCost(userPrePaidBilling.getTotal()); companyEarningsDto.setTotalBillingCost(userPrePaidBilling.getTotal());
companyEarningsDto.setPayStatus(userPrePaidBilling.getStatus()); companyEarningsDto.setPayStatus(userPrePaidBilling.getStatus());
Account account = accountRepository.findByName(userPrePaidBilling.getUsername()); Account account = accountRepository.findByName(userPrePaidBilling.getUsername())
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
companyEarningsDto.setCompanyShouldEarning(userPrePaidBilling.getTotal()); companyEarningsDto.setCompanyShouldEarning(userPrePaidBilling.getTotal());
...@@ -340,7 +336,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -340,7 +336,7 @@ public class AdministratorServiceImpl implements AdministratorService {
@Override @Override
public boolean userbillingTransfer() { public boolean userbillingTransfer() {
List<UserBilling> userBillings = userBillingRepository.findByUsername("51tou"); List<UserBilling> userBillings = userBillingRepository.findByUsername("51tou");
userBillings.forEach(x ->{ userBillings.forEach(x -> {
generateUserPrePaidBillingByUserBilling(x); generateUserPrePaidBillingByUserBilling(x);
}); });
return true; return true;
...@@ -369,7 +365,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -369,7 +365,7 @@ 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); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
account.setPromotionCode(promotionCode); account.setPromotionCode(promotionCode);
...@@ -414,7 +410,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -414,7 +410,7 @@ public class AdministratorServiceImpl implements AdministratorService {
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
Account account = null; Account account = null;
if (!StringUtils.isBlank(username)) if (!StringUtils.isBlank(username))
account = accountRepository.findByName(username); account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
else account = accountRepository.findByPromotion(promotionCode); else account = accountRepository.findByPromotion(promotionCode);
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
...@@ -444,11 +440,11 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -444,11 +440,11 @@ public class AdministratorServiceImpl implements AdministratorService {
if (accounts != null && accounts.size() > 0) { if (accounts != null && accounts.size() > 0) {
accounts.forEach(x -> { accounts.forEach(x -> {
promotion.setInvitedUsers(promotion.getInvitedUsers() + 1); promotion.setInvitedUsers(promotion.getInvitedUsers() + 1);
List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByAdministratorAndPayMethodInAndTimestampBetween(x.getName(), Arrays.asList(1,2,3), dateTime1.getTime(), dateTime2.getTime()); List<UserPrePaidBilling> userPrePaidBillings = userPrePaidBillingRepository.findByAdministratorAndPayMethodInAndTimestampBetween(x.getName(), Arrays.asList(1, 2, 3), dateTime1.getTime(), dateTime2.getTime());
double totalCommission = 0; double totalCommission = 0;
if (userPrePaidBillings != null && userPrePaidBillings.size() > 0) if (userPrePaidBillings != null && userPrePaidBillings.size() > 0)
totalCommission = userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); totalCommission = userPrePaidBillings.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
promotion.setTotalCommission(promotion.getTotalCommission() + (int)totalCommission); promotion.setTotalCommission(promotion.getTotalCommission() + (int) totalCommission);
promotion.setCommission(promotion.getCommission() + x.getPromotion().getCommission()); promotion.setCommission(promotion.getCommission() + x.getPromotion().getCommission());
double secondCommission = 0; double secondCommission = 0;
ipCount.addAndGet(ipResourceRepository.countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(x.getName(), false, Instant.now().toEpochMilli())); ipCount.addAndGet(ipResourceRepository.countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(x.getName(), false, Instant.now().toEpochMilli()));
...@@ -467,7 +463,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -467,7 +463,7 @@ public class AdministratorServiceImpl implements AdministratorService {
ipCount.addAndGet(ipResourceRepository.countAllByOwnerInAndIsDeletedAndValidTimeGreaterThan(secondChildren.stream().map(Account::getName).collect(Collectors.toList()), false, Instant.now().toEpochMilli())); ipCount.addAndGet(ipResourceRepository.countAllByOwnerInAndIsDeletedAndValidTimeGreaterThan(secondChildren.stream().map(Account::getName).collect(Collectors.toList()), false, Instant.now().toEpochMilli()));
} }
} }
List<UserPrePaidBilling> userPrePaidBillings1 = userPrePaidBillingRepository.findByAdministratorAndPayMethodInAndTimestampBetween(secondPromote.getName(), Arrays.asList(1,2,3), dateTime1.getTime(), dateTime2.getTime()); List<UserPrePaidBilling> userPrePaidBillings1 = userPrePaidBillingRepository.findByAdministratorAndPayMethodInAndTimestampBetween(secondPromote.getName(), Arrays.asList(1, 2, 3), dateTime1.getTime(), dateTime2.getTime());
if (userPrePaidBillings1 != null && userPrePaidBillings1.size() > 0) if (userPrePaidBillings1 != null && userPrePaidBillings1.size() > 0)
secondCommission += userPrePaidBillings1.stream().mapToDouble(UserPrePaidBilling::getTotal).sum(); secondCommission += userPrePaidBillings1.stream().mapToDouble(UserPrePaidBilling::getTotal).sum();
} }
...@@ -500,7 +496,7 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -500,7 +496,7 @@ 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); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
account.getWhiteList().add(website); account.getWhiteList().add(website);
...@@ -529,7 +525,9 @@ public class AdministratorServiceImpl implements AdministratorService { ...@@ -529,7 +525,9 @@ public class AdministratorServiceImpl implements AdministratorService {
if (userBalanceList != null && userBalanceList.size() > 0) { if (userBalanceList != null && userBalanceList.size() > 0) {
userBalanceList.forEach(x -> { userBalanceList.forEach(x -> {
UserUsedDto userUsedDto = new UserUsedDto(); UserUsedDto userUsedDto = new UserUsedDto();
Account account = accountRepository.findByName(x.getUsername()); Account account = accountRepository.findByName(x.getUsername())
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
userUsedDto.setPromotionCode(account.getPromotionCode()); userUsedDto.setPromotionCode(account.getPromotionCode());
userUsedDto.setUserBalance(x); userUsedDto.setUserBalance(x);
userUsedDtos.add(userUsedDto); userUsedDtos.add(userUsedDto);
......
...@@ -4,21 +4,18 @@ import com.alibaba.fastjson.JSONObject; ...@@ -4,21 +4,18 @@ import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient; import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient; import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest; import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradePagePayRequest; import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest; import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse; import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradePagePayResponse; import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse; import com.alipay.api.response.AlipayTradeQueryResponse;
import com.edgec.browserbackend.account.controller.AccountController;
import com.edgec.browserbackend.account.domain.*;
import com.edgec.browserbackend.account.exception.AccountErrorCode; import com.edgec.browserbackend.account.exception.AccountErrorCode;
import com.edgec.browserbackend.account.repository.*; import com.edgec.browserbackend.account.repository.*;
import com.edgec.browserbackend.account.service.AccountService; import com.edgec.browserbackend.account.service.AccountService;
import com.edgec.browserbackend.account.service.PaymentService; import com.edgec.browserbackend.account.service.PaymentService;
import com.edgec.browserbackend.account.controller.AccountController;
import com.edgec.browserbackend.account.domain.*;
import com.edgec.browserbackend.account.service.SmsUtils; import com.edgec.browserbackend.account.service.SmsUtils;
import com.edgec.browserbackend.account.service.UserPrePaidBillingService;
import com.edgec.browserbackend.alipay.AlipayConfig; import com.edgec.browserbackend.alipay.AlipayConfig;
import com.edgec.browserbackend.alipay.CloudamAlipayConfig; import com.edgec.browserbackend.alipay.CloudamAlipayConfig;
import com.edgec.browserbackend.alipay.VpsAlipayConfig; import com.edgec.browserbackend.alipay.VpsAlipayConfig;
...@@ -32,10 +29,8 @@ import org.apache.commons.lang3.StringUtils; ...@@ -32,10 +29,8 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.swing.text.Document;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.Instant; import java.time.Instant;
import java.time.YearMonth; import java.time.YearMonth;
...@@ -176,12 +171,12 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -176,12 +171,12 @@ public class PaymentServiceImpl implements PaymentService {
if (chargeType == 0) { if (chargeType == 0) {
UserPrePaidBilling bill = new UserPrePaidBilling(); UserPrePaidBilling bill = new UserPrePaidBilling();
Account account = accountRepository.findByName(byTradeNo.getUsername()); Account account = accountRepository.findByName(byTradeNo.getUsername()).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account != null && account.getParent() != null) if (account != null && account.getParent() != null)
bill.setAdministrator(account.getParent()); bill.setAdministrator(account.getParent());
else else
bill.setAdministrator(account.getName()); bill.setAdministrator(account.getName());
bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ SmsUtils.createRandom(true, 4)); bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + SmsUtils.createRandom(true, 4));
bill.setChargeType(0); bill.setChargeType(0);
bill.setAmount(0); bill.setAmount(0);
bill.setUnit(null); bill.setUnit(null);
...@@ -308,12 +303,12 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -308,12 +303,12 @@ public class PaymentServiceImpl implements PaymentService {
if (chargeType == 0) { if (chargeType == 0) {
UserPrePaidBilling bill = new UserPrePaidBilling(); UserPrePaidBilling bill = new UserPrePaidBilling();
Account account = accountRepository.findByName(byTradeNo.getUsername()); Account account = accountRepository.findByName(byTradeNo.getUsername()).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account != null && account.getParent() != null) if (account != null && account.getParent() != null)
bill.setAdministrator(account.getParent()); bill.setAdministrator(account.getParent());
else else
bill.setAdministrator(account.getName()); bill.setAdministrator(account.getName());
bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ SmsUtils.createRandom(true, 4)); bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + SmsUtils.createRandom(true, 4));
bill.setChargeType(0); bill.setChargeType(0);
bill.setAmount(0); bill.setAmount(0);
bill.setUnit(null); bill.setUnit(null);
...@@ -365,7 +360,7 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -365,7 +360,7 @@ public class PaymentServiceImpl implements PaymentService {
public String alipayPutPayOrder(String username, int amount, String by) { public String alipayPutPayOrder(String username, int amount, String by) {
Account byName = accountService.findByName(username); Account byName = accountService.findByName(username);
if (byName == null ) if (byName == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + username); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + username);
if (byName.getPermission() < 4) if (byName.getPermission() < 4)
throw new ClientRequestException(AccountErrorCode.NOPERMISSION, "account does not have permission: " + username); throw new ClientRequestException(AccountErrorCode.NOPERMISSION, "account does not have permission: " + username);
...@@ -483,12 +478,12 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -483,12 +478,12 @@ public class PaymentServiceImpl implements PaymentService {
UserBalance userBalance = userBalanceRepository.findById(username).orElse(null); UserBalance userBalance = userBalanceRepository.findById(username).orElse(null);
UserPrePaidBilling bill = new UserPrePaidBilling(); UserPrePaidBilling bill = new UserPrePaidBilling();
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account != null && account.getParent() != null) if (account != null && account.getParent() != null)
bill.setAdministrator(account.getParent()); bill.setAdministrator(account.getParent());
else else
bill.setAdministrator(account.getName()); bill.setAdministrator(account.getName());
bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ SmsUtils.createRandom(true, 4)); bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + SmsUtils.createRandom(true, 4));
bill.setChargeType(0); bill.setChargeType(0);
bill.setAmount(0); bill.setAmount(0);
bill.setUnit(null); bill.setUnit(null);
...@@ -645,7 +640,7 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -645,7 +640,7 @@ public class PaymentServiceImpl implements PaymentService {
if (response == null) if (response == null)
throw new ClientRequestException(BrowserErrorCode.UNKNOWN); throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
if(response.isSuccess()){ if (response.isSuccess()) {
internalOrder.setSucceed(true); internalOrder.setSucceed(true);
userWithdrawRepository.save(internalOrder); userWithdrawRepository.save(internalOrder);
...@@ -654,7 +649,7 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -654,7 +649,7 @@ public class PaymentServiceImpl implements PaymentService {
bill.setAdministrator(byName.getParent()); bill.setAdministrator(byName.getParent());
else else
bill.setAdministrator(byName.getName()); bill.setAdministrator(byName.getName());
bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ SmsUtils.createRandom(true, 4)); bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + SmsUtils.createRandom(true, 4));
bill.setChargeType(4); bill.setChargeType(4);
bill.setAmount(0); bill.setAmount(0);
bill.setUnit(null); bill.setUnit(null);
...@@ -675,7 +670,7 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -675,7 +670,7 @@ public class PaymentServiceImpl implements PaymentService {
userPrePaidBillingRepository.save(bill); userPrePaidBillingRepository.save(bill);
return true; return true;
}else{ } else {
byName.getPromotion().setAllGift(byName.getPromotion().getAllGift() + amount); byName.getPromotion().setAllGift(byName.getPromotion().getAllGift() + amount);
byName.getPromotion().setWithdrawn(byName.getPromotion().getWithdrawn() - amount); byName.getPromotion().setWithdrawn(byName.getPromotion().getWithdrawn() - amount);
accountRepository.save(byName); accountRepository.save(byName);
......
...@@ -2,9 +2,11 @@ package com.edgec.browserbackend.account.service.impl; ...@@ -2,9 +2,11 @@ package com.edgec.browserbackend.account.service.impl;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.edgec.browserbackend.account.domain.*; import com.edgec.browserbackend.account.domain.*;
import com.edgec.browserbackend.account.exception.AccountErrorCode;
import com.edgec.browserbackend.account.repository.AccountRepository; import com.edgec.browserbackend.account.repository.AccountRepository;
import com.edgec.browserbackend.account.repository.UserLackMoneyRepository; import com.edgec.browserbackend.account.repository.UserLackMoneyRepository;
import com.edgec.browserbackend.account.service.UserLackMoneyService; import com.edgec.browserbackend.account.service.UserLackMoneyService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.SmsUtils; import com.edgec.browserbackend.common.commons.utils.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -45,7 +47,7 @@ public class UserLackMoneyServiceImpl implements UserLackMoneyService { ...@@ -45,7 +47,7 @@ public class UserLackMoneyServiceImpl implements UserLackMoneyService {
//发送短信提醒 //发送短信提醒
if (totalUnpaid > 0 && ifMessageRemind) { if (totalUnpaid > 0 && ifMessageRemind) {
Account account = repository.findByName(username); Account account = repository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
String telephone = account.getPhoneNumber(); String telephone = account.getPhoneNumber();
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("billsamount", billsAmount); param.put("billsamount", billsAmount);
......
...@@ -34,7 +34,7 @@ public class ShopController { ...@@ -34,7 +34,7 @@ public class ShopController {
@Autowired @Autowired
private IpAndShopService ipAndShopService; private IpAndShopService ipAndShopService;
@RequestMapping(value = "/add", method = RequestMethod.POST) @PostMapping("/add")
public ResultDto addShop(Principal principal, @RequestBody ShopResultDto shopResultDto) { public ResultDto addShop(Principal principal, @RequestBody ShopResultDto shopResultDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
try { try {
...@@ -48,7 +48,7 @@ public class ShopController { ...@@ -48,7 +48,7 @@ public class ShopController {
return resultDto; return resultDto;
} }
@RequestMapping(value = "/multiadd", method = RequestMethod.POST) @PostMapping("/multiadd")
public ResultDto addShops(Principal principal, @RequestParam("file") MultipartFile file) { public ResultDto addShops(Principal principal, @RequestParam("file") MultipartFile file) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
String name = file.getOriginalFilename(); String name = file.getOriginalFilename();
...@@ -123,6 +123,9 @@ public class ShopController { ...@@ -123,6 +123,9 @@ public class ShopController {
return resultDto; return resultDto;
} }
/**
* 移动店铺 到 分组
*/
@RequestMapping(value = "/transfer", method = RequestMethod.POST) @RequestMapping(value = "/transfer", method = RequestMethod.POST)
public ResultDto transferShop(Principal principal, @RequestBody ShopRequestDto shopRequestDto) { public ResultDto transferShop(Principal principal, @RequestBody ShopRequestDto shopRequestDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
......
...@@ -7,6 +7,10 @@ import lombok.Setter; ...@@ -7,6 +7,10 @@ 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;
/**
* @author cloudam
* 这是一个中间表,关联 user 、shop、 group 表
*/
@Getter @Getter
@Setter @Setter
@NoArgsConstructor @NoArgsConstructor
......
package com.edgec.browserbackend.browser.dto; package com.edgec.browserbackend.browser.dto;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
@Getter
@Setter
public class IpFilterDto { public class IpFilterDto {
String region; String region;
String addr; String addr;
String vendor; String vendor;
public String getAddr() { public boolean isEmpty() {
return addr; boolean flag = false;
} if (StringUtils.isEmpty(region) && StringUtils.isEmpty(addr) && StringUtils.isEmpty(vendor)) {
flag = true;
public void setAddr(String addr) {
this.addr = addr;
}
public String getRegion() {
return region;
} }
return flag;
public void setRegion(String region) {
this.region = region;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
} }
} }
package com.edgec.browserbackend.browser.dto; package com.edgec.browserbackend.browser.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageInfo { public class PageInfo {
int currentPage; int currentPage;
int totalPages; int totalPages;
int totalItems; int totalItems;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPage) {
this.totalPages = totalPage;
}
public int getTotalItems() {
return totalItems;
}
public void setTotalItems(int totalItems) {
this.totalItems = totalItems;
}
} }
package com.edgec.browserbackend.browser.dto; package com.edgec.browserbackend.browser.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class ShopFilterDto { public class ShopFilterDto {
private String shopName; private String shopName;
...@@ -9,35 +14,11 @@ public class ShopFilterDto { ...@@ -9,35 +14,11 @@ public class ShopFilterDto {
private String shopAccount; private String shopAccount;
private int bindIp; private int bindIp;
public String getShopAccount() { public boolean isEmpty() {
return shopAccount; boolean flag = false;
if (StringUtils.isEmpty(shopName) && StringUtils.isEmpty(IpRegion) && StringUtils.isEmpty(shopAccount)) {
flag = true;
} }
return flag;
public void setShopAccount(String shopAccount) {
this.shopAccount = shopAccount;
}
public String getIpRegion() {
return IpRegion;
}
public void setIpRegion(String ipRegion) {
IpRegion = ipRegion;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public int getBindIp() {
return bindIp;
}
public void setBindIp(int bindIp) {
this.bindIp = bindIp;
} }
} }
package com.edgec.browserbackend.browser.dto; package com.edgec.browserbackend.browser.dto;
import lombok.Data;
@Data
public class ShopStringResultDto { public class ShopStringResultDto {
String id; String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
} }
...@@ -113,10 +113,10 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -113,10 +113,10 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
} }
@Override @Override
public boolean deleteShopId(String ipId, String shopId, BindHistory bindHistory) { public boolean deleteShopId(String id, String shopId, BindHistory bindHistory) {
Document doc = new Document(); Document doc = new Document();
BasicQuery basicQuery = new BasicQuery(doc); BasicQuery basicQuery = new BasicQuery(doc);
basicQuery.addCriteria(where("id").is(ipId).and("isDeleted").is(false)); basicQuery.addCriteria(where("id").is(id).and("isDeleted").is(false));
Update update = new Update(); Update update = new Update();
update.pull("shopIds", shopId).push("bindhistory", bindHistory); update.pull("shopIds", shopId).push("bindhistory", bindHistory);
UpdateResult result = mongoTemplate.updateFirst(basicQuery, update, IpResource.class); UpdateResult result = mongoTemplate.updateFirst(basicQuery, update, IpResource.class);
...@@ -163,18 +163,23 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -163,18 +163,23 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
UnwindOperation unwind = Aggregation.unwind("shopIds"); UnwindOperation unwind = Aggregation.unwind("shopIds");
MatchOperation matchshopId = Aggregation.match(where("shopIds").in(shopIds)); MatchOperation matchshopId = Aggregation.match(where("shopIds").in(shopIds));
List<IpResourceUnwindResultDto> ipResourceUnwindResultDtos = mongoTemplate.aggregate( List<IpResourceUnwindResultDto> ipResourceUnwindResultDtos = mongoTemplate.aggregate(
Aggregation.newAggregation(matchOperation, unwind, matchshopId), IpResource.class, IpResourceUnwindResultDto.class).getMappedResults(); Aggregation.newAggregation(matchOperation, unwind, matchshopId), IpResource.class, IpResourceUnwindResultDto.class
).getMappedResults();
if (ipResourceUnwindResultDtos.isEmpty()) { if (ipResourceUnwindResultDtos.isEmpty()) {
return new ArrayList<>(); return new ArrayList<>();
} }
HashMap<String, IpResource> ipResourceHashMap = new HashMap<>(); HashMap<String, IpResource> ipResourceHashMap = new HashMap<>();
ipResourceUnwindResultDtos.forEach(x -> { ipResourceUnwindResultDtos.forEach(
x -> {
if (ipResourceHashMap.containsKey(x.getId())) { if (ipResourceHashMap.containsKey(x.getId())) {
ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId()); ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId());
} else { } else {
ipResourceHashMap.put(x.getId(), x.toResource()); ipResourceHashMap.put(x.getId(), x.toResource());
} }
}); }
);
List<IpResource> result = new ArrayList<>(); List<IpResource> result = new ArrayList<>();
Set<Map.Entry<String, IpResource>> entry = ipResourceHashMap.entrySet(); Set<Map.Entry<String, IpResource>> entry = ipResourceHashMap.entrySet();
for (Map.Entry<String, IpResource> e : entry) { for (Map.Entry<String, IpResource> e : entry) {
......
...@@ -37,7 +37,7 @@ public class GroupServiceImpl implements GroupService { ...@@ -37,7 +37,7 @@ public class GroupServiceImpl implements GroupService {
public String addGroup(String username, String groupName) { public String addGroup(String username, String groupName) {
if (StringUtils.isBlank(username) || StringUtils.isBlank(groupName)) if (StringUtils.isBlank(username) || StringUtils.isBlank(groupName))
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (account.getGroupCount() >= 100) if (account.getGroupCount() >= 100)
...@@ -79,14 +79,14 @@ public class GroupServiceImpl implements GroupService { ...@@ -79,14 +79,14 @@ public class GroupServiceImpl implements GroupService {
public void deleteGroup(String username, String groupId) { public void deleteGroup(String username, String groupId) {
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); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
try { try {
userShopRepository.updateGroupId(groupId, null); userShopRepository.updateGroupId(groupId, null);
groupRepository.deleteById(groupId); groupRepository.deleteById(groupId);
//可以优化 //可以优化
account.setGroupCount(account.getGroupCount()-1); account.setGroupCount(account.getGroupCount() - 1);
accountRepository.save(account); accountRepository.save(account);
} catch (Exception e) { } catch (Exception e) {
logger.error("fail to delete group", e.getMessage()); logger.error("fail to delete group", e.getMessage());
...@@ -106,7 +106,7 @@ public class GroupServiceImpl implements GroupService { ...@@ -106,7 +106,7 @@ public class GroupServiceImpl implements GroupService {
groups.stream().forEach(x -> { groups.stream().forEach(x -> {
groupDtos.add(new GroupDto(x.getId(), x.getName(), x.getDetails())); groupDtos.add(new GroupDto(x.getId(), x.getName(), x.getDetails()));
}); });
} catch (Exception e){ } catch (Exception e) {
logger.error("fail to delete group", e.getMessage()); logger.error("fail to delete group", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.UNKNOWN); throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
} }
......
...@@ -44,10 +44,7 @@ public class IpAndShopServiceImpl implements IpAndShopService { ...@@ -44,10 +44,7 @@ public class IpAndShopServiceImpl implements IpAndShopService {
@Override @Override
public void bindShop(String username, ShopRequestDto shopRequestDto) { public void bindShop(String username, ShopRequestDto shopRequestDto) {
// 1. 根据id 来获取账户 // 1. 根据id 来获取账户
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
String shopId = shopRequestDto.getShopId(); String shopId = shopRequestDto.getShopId();
// 2.获取当前账户下指定的商铺 // 2.获取当前账户下指定的商铺
...@@ -62,10 +59,10 @@ public class IpAndShopServiceImpl implements IpAndShopService { ...@@ -62,10 +59,10 @@ public class IpAndShopServiceImpl implements IpAndShopService {
IpResource ipResource = null; IpResource ipResource = null;
if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) { if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) {
ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false); ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false);
} else if (StringUtils.isNotBlank(shopRequestDto.getIpId())) { }
if (StringUtils.isNotBlank(shopRequestDto.getIpId())) {
ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false); ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false);
} }
if (ipResource == null) { if (ipResource == null) {
throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST);
} }
...@@ -87,40 +84,56 @@ public class IpAndShopServiceImpl implements IpAndShopService { ...@@ -87,40 +84,56 @@ public class IpAndShopServiceImpl implements IpAndShopService {
@Override @Override
public void unBindShop(String username, ShopRequestDto shopRequestDto) { public void unBindShop(String username, ShopRequestDto shopRequestDto) {
String shopId = null; // 1. 检查当前账户是否存在,是否具备操作权限
if (StringUtils.isNotBlank(shopRequestDto.getShopId())) Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
shopId = shopRequestDto.getShopId(); if (account.getPermission() < 4) {
Account account = accountRepository.findByName(username);
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
if (account.getPermission() < 4 || userShop == null) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
Shop shop = shopRepository.findById(shopId).orElse(null); String shopId = shopRequestDto.getShopId();
if (shop == null)
// 2. 查找当前用户是否已经绑定商铺 以及 关联商铺的绑定 (一个商铺可以被多个用户持有)
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
if (userShop == null) {
throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST);
}
// 3. 查找商铺信息
Shop shop = shopRepository.findById(shopId).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST));
// 4. 查找当前商铺绑定的 ip 资源是否存在
IpResource ipResource = null; IpResource ipResource = null;
if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) { if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) {
ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false); ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false);
} else if (StringUtils.isNotBlank(shopRequestDto.getIpId())) { }
if (StringUtils.isNotBlank(shopRequestDto.getIpId())) {
ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false); ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false);
} }
if (ipResource == null) if (ipResource == null) {
throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST);
if (ipResource.getShopIds() == null && !ipResource.getShopIds().contains(shop.getShopId())) }
// 5. 若存在,ip资源是否绑定了该店铺(一个ip资源可以被多个店铺绑定)
if (ipResource.getShopIds() == null && !ipResource.getShopIds().contains(shop.getShopId())) {
throw new ClientRequestException(BrowserErrorCode.IPNOTBINDTOSHOP); throw new ClientRequestException(BrowserErrorCode.IPNOTBINDTOSHOP);
try { }
// 封装 ip 资源绑定的历史信息
BindHistory bindHistory = new BindHistory(); BindHistory bindHistory = new BindHistory();
bindHistory.setIp(ipResource.getAddr()); bindHistory.setIp(ipResource.getAddr());
bindHistory.setPlatform(shop.getShopPlatform()); bindHistory.setPlatform(shop.getShopPlatform());
bindHistory.setShopName(shop.getShopName()); bindHistory.setShopName(shop.getShopName());
bindHistory.setUnbindTime(ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); bindHistory.setUnbindTime(ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
try {
// 6. IP资源解除绑定的店铺并更新ip资源的绑定历史
ipResourceRepository.deleteShopId(ipResource.getId(), shopId, bindHistory); ipResourceRepository.deleteShopId(ipResource.getId(), shopId, bindHistory);
// 7. 更新 ip 资源的绑定状态为 未绑定
IpResource newIp = ipResourceRepository.findById(ipResource.getId()).orElse(null); IpResource newIp = ipResourceRepository.findById(ipResource.getId()).orElse(null);
if (newIp.getShopIds() == null || newIp.getShopIds().size() == 0) if (newIp.getShopIds() == null || !newIp.getShopIds().contains(shopId)) {
ipResourceRepository.updateBind(ipResource.getId(), false); ipResourceRepository.updateBind(ipResource.getId(), false);
}
} catch (Exception e) { } catch (Exception e) {
logger.error("fail to unbind", e.getMessage()); logger.error("fail to unbind", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.UNKNOWN); throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
...@@ -132,10 +145,8 @@ public class IpAndShopServiceImpl implements IpAndShopService { ...@@ -132,10 +145,8 @@ public class IpAndShopServiceImpl implements IpAndShopService {
List<String> shopIds = null; List<String> shopIds = null;
if (shopRequestDto.getShopIds() != null && shopRequestDto.getShopIds().size() > 0) if (shopRequestDto.getShopIds() != null && shopRequestDto.getShopIds().size() > 0)
shopIds = shopRequestDto.getShopIds(); shopIds = shopRequestDto.getShopIds();
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
IpResource ipResource = null; IpResource ipResource = null;
if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) { if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) {
ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false); ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false);
......
...@@ -157,7 +157,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -157,7 +157,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public List<String> buyIp(String username, IpResourceRequestDto ipResourceRequestDto) throws Exception { public List<String> buyIp(String username, IpResourceRequestDto ipResourceRequestDto) throws Exception {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (account.getPermission() < 4) if (account.getPermission() < 4)
...@@ -291,7 +291,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -291,7 +291,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public IpOperationResultDto renewIp(String username, IpResourceRequestDto ipResourceRequestDto) { public IpOperationResultDto renewIp(String username, IpResourceRequestDto ipResourceRequestDto) {
String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL; String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
...@@ -410,10 +410,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -410,10 +410,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public IpOperationResultDto deleteIp(String username, IpResourceRequestDto ipResourceRequestDto) { public IpOperationResultDto deleteIp(String username, IpResourceRequestDto ipResourceRequestDto) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL; String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
...@@ -521,10 +518,8 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -521,10 +518,8 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public IpPageResultDto getIpList(String username, int groupType, int page, int amount, IpFilterDto ipFilterDto) { public IpPageResultDto getIpList(String username, int groupType, int page, int amount, IpFilterDto ipFilterDto) {
// 获取当前用户的账户 // 获取当前用户的账户
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
List<IpResource> ipResources = new ArrayList<>(); List<IpResource> ipResources = new ArrayList<>();
List<IpResource> notUsed = new ArrayList<>(); List<IpResource> notUsed = new ArrayList<>();
...@@ -535,7 +530,6 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -535,7 +530,6 @@ public class IpResourceServiceImpl implements IpResourceService {
ipResources.addAll(notUsed); ipResources.addAll(notUsed);
} }
List<IpResourceDto> ipResourceDtos = new ArrayList<>();
// 去掉重复 ip // 去掉重复 ip
List<String> allIpIds = ipResources.stream().distinct().map(IpResource::getId).collect(Collectors.toList()); List<String> allIpIds = ipResources.stream().distinct().map(IpResource::getId).collect(Collectors.toList());
...@@ -543,17 +537,9 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -543,17 +537,9 @@ public class IpResourceServiceImpl implements IpResourceService {
// 根据过滤条件来分页获取 ip 资源 // 根据过滤条件来分页获取 ip 资源
amount = amount > 100 ? 100 : amount; amount = amount > 100 ? 100 : amount;
Pageable pageable = PageRequest.of(page, amount); Pageable pageable = PageRequest.of(page, amount);
Page<IpResource> ipResources1 = null; Page<IpResource> ipResources1 = getIpResourcesByFilter(ipFilterDto, allIpIds, pageable);
if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getRegion())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndRegionCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getRegion(), pageable);
} else if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getAddr())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndAddrLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getAddr(), pageable);
} else if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getVendor())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndVendorCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getVendor(), pageable);
} else {
ipResources1 = ipResourceRepository.findByIdInAndIsDeletedOrderByPurchasedTimeDesc(allIpIds, false, pageable);
}
List<IpResourceDto> ipResourceDtos = new ArrayList<>();
if (ipResources1 != null) { if (ipResources1 != null) {
ipResources1.getContent().forEach( ipResources1.getContent().forEach(
x -> { x -> {
...@@ -598,7 +584,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -598,7 +584,7 @@ public class IpResourceServiceImpl implements IpResourceService {
} }
// 2. 如果 ip 资源的 status 为 6(未分配) 或者 ( ip资源为专线 且 purchasedTime(购买IP的时间) 在 14 分钟内) // 2. 如果 ip 资源的 status 为 6(未分配) 或者 ( ip资源为专线 且 purchasedTime(购买IP的时间) 在 14 分钟内)
if (x.getStatus() == 6 || (x.isSpecialLine() && x.getPurchasedTime() > (Instant.now().minusSeconds(12 * 60).toEpochMilli()))) { if (x.getStatus() == 6 || (x.isSpecialLine() && x.getPurchasedTime() > (Instant.now().minusSeconds(14 * 60).toEpochMilli()))) {
x.setStatus(3); x.setStatus(3);
} }
...@@ -615,15 +601,13 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -615,15 +601,13 @@ public class IpResourceServiceImpl implements IpResourceService {
); );
} }
// 将当前页的数据封装到 Page 中 // 将当前页的数据封装到 ipPageResultDto 中
Page<IpResourceDto> ipResourceDtoPage = new PageImpl<>(ipResourceDtos, pageable, allIpIds.size());
IpPageResultDto ipPageResultDto = new IpPageResultDto(); IpPageResultDto ipPageResultDto = new IpPageResultDto();
Page<IpResourceDto> ipResourceDtoPage = new PageImpl<>(ipResourceDtos, pageable, allIpIds.size());
ipPageResultDto.setIpList(ipResourceDtoPage.getContent()); ipPageResultDto.setIpList(ipResourceDtoPage.getContent());
PageInfo pageInfo = new PageInfo(); PageInfo pageInfo = new PageInfo(ipResourceDtoPage.getPageable().getPageNumber(), ipResourceDtoPage.getTotalPages(), allIpIds.size());
pageInfo.setCurrentPage(ipResourceDtoPage.getPageable().getPageNumber());
pageInfo.setTotalPages(ipResourceDtoPage.getTotalPages());
pageInfo.setTotalItems(allIpIds.size());
ipPageResultDto.setIpPage(pageInfo); ipPageResultDto.setIpPage(pageInfo);
return ipPageResultDto; return ipPageResultDto;
} }
...@@ -658,10 +642,8 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -658,10 +642,8 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public IpSummary getIpSummary(String username) { public IpSummary getIpSummary(String username) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
IpSummary ipSummary = new IpSummary(); IpSummary ipSummary = new IpSummary();
List<String> shopIds = userShopRepository.findByUsername(username).stream().map(x -> x.getShopId()).collect(Collectors.toList()); List<String> shopIds = userShopRepository.findByUsername(username).stream().map(x -> x.getShopId()).collect(Collectors.toList());
...@@ -680,13 +662,10 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -680,13 +662,10 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public void updateIp(String username, IpResourceUpdateDto ipResourceUpdateDto) { public void updateIp(String username, IpResourceUpdateDto ipResourceUpdateDto) {
// 1. 根据id 来获取账户 // 1. 根据id 来获取账户
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
/// 这个地方本来是8,现在由于更新ip失败,改为和绑定店铺时一样的 4 // 只有管理员可以 更新 ip,管理员的权限是 8
if (account.getPermission() < 4) { if (account.getPermission() < 8) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
...@@ -705,7 +684,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -705,7 +684,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public boolean queryIpExist(String username, IpResourceUpdateDto ipResourceUpdateDto) { public boolean queryIpExist(String username, IpResourceUpdateDto ipResourceUpdateDto) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
IpResource ipResource = ipResourceRepository.findByAddrAndIsDeleted(ipResourceUpdateDto.getAddr(), false); IpResource ipResource = ipResourceRepository.findByAddrAndIsDeleted(ipResourceUpdateDto.getAddr(), false);
...@@ -717,7 +696,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -717,7 +696,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public IpResourceDto queryIp(String username, IpResourceRequestDto ipResourceRequestDto) { public IpResourceDto queryIp(String username, IpResourceRequestDto ipResourceRequestDto) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
IpResource ipResource = null; IpResource ipResource = null;
...@@ -855,16 +834,18 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -855,16 +834,18 @@ public class IpResourceServiceImpl implements IpResourceService {
break; break;
case 3: case 3:
ipResources = ipResourceRepository.findShopIdInListAndStatus(shopIds, false, 1); ipResources = ipResourceRepository.findShopIdInListAndStatus(shopIds, false, 1);
if (!isParent) if (!isParent) {
notUsed = ipResourceRepository.findByOwnerAndStatusAndIsDeletedAndBind(username, 1, false, false); notUsed = ipResourceRepository.findByOwnerAndStatusAndIsDeletedAndBind(username, 1, false, false);
else } else {
notUsed = ipResourceRepository.findByOwnerInAndStatusAndIsDeletedAndBind(accountNameList, 1, false, false); notUsed = ipResourceRepository.findByOwnerInAndStatusAndIsDeletedAndBind(accountNameList, 1, false, false);
}
break; break;
case 4: case 4:
if (!isParent) if (!isParent) {
notUsed = ipResourceRepository.findByOwnerAndStatusIsNotInAndIsDeletedAndBind(username, Arrays.asList(3, 5, 6), false, false); notUsed = ipResourceRepository.findByOwnerAndStatusIsNotInAndIsDeletedAndBind(username, Arrays.asList(3, 5, 6), false, false);
else } else {
notUsed = ipResourceRepository.findByOwnerInAndStatusIsNotInAndIsDeletedAndBind(accountNameList, Arrays.asList(3, 5, 6), false, false); notUsed = ipResourceRepository.findByOwnerInAndStatusIsNotInAndIsDeletedAndBind(accountNameList, Arrays.asList(3, 5, 6), false, false);
}
break; break;
case 5: case 5:
// 已分配 // 已分配
...@@ -897,4 +878,21 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -897,4 +878,21 @@ public class IpResourceServiceImpl implements IpResourceService {
} }
return shopDtos; return shopDtos;
} }
private Page<IpResource> getIpResourcesByFilter(IpFilterDto ipFilterDto, List<String> allIpIds, Pageable pageable) {
Page<IpResource> ipResources1 = null;
if (StringUtils.isNotBlank(ipFilterDto.getRegion())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndRegionCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getRegion(), pageable);
}
if (StringUtils.isNotBlank(ipFilterDto.getAddr())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndAddrLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getAddr(), pageable);
}
if (StringUtils.isNotBlank(ipFilterDto.getVendor())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndVendorCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getVendor(), pageable);
}
if (ipFilterDto.isEmpty()) {
ipResources1 = ipResourceRepository.findByIdInAndIsDeletedOrderByPurchasedTimeDesc(allIpIds, false, pageable);
}
return ipResources1;
}
} }
...@@ -12,7 +12,6 @@ import com.edgec.browserbackend.browser.service.IpResourceService; ...@@ -12,7 +12,6 @@ import com.edgec.browserbackend.browser.service.IpResourceService;
import com.edgec.browserbackend.browser.service.ShopService; import com.edgec.browserbackend.browser.service.ShopService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException; import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.utils.FileUtil; import com.edgec.browserbackend.common.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -22,6 +21,7 @@ import org.springframework.data.domain.PageRequest; ...@@ -22,6 +21,7 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.IOException;
...@@ -63,112 +63,112 @@ public class ShopServiceImpl implements ShopService { ...@@ -63,112 +63,112 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public String addShop(String username, ShopResultDto shopResultDto) { public String addShop(String username, ShopResultDto shopResultDto) {
Account account = accountRepository.findByName(username); // 1. 对商铺的分组信息校验
String id = null; if (shopResultDto.getGroup() == null) {
if (account == null) { throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); }
if (shopResultDto.getGroup() != null) {
Group group = groupRepository.findById(shopResultDto.getGroup())
.orElseThrow(() -> new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST));
} }
// 2. 对当前用户的 account 信息进行校验
Account account = accountRepository.findByName(username)
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account.getPermission() < 4) { if (account.getPermission() < 4) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
if (account.getShopCount() >= 10000) { if (account.getShopCount() >= 10000) {
throw new ClientRequestException(AccountErrorCode.SHOPMAX); throw new ClientRequestException(AccountErrorCode.SHOPMAX);
} }
UserShop us = null;
if (shopResultDto.getShopId() != null)
us = userShopRepository.findByUsernameAndShopId(username, shopResultDto.getShopId());
if (shopResultDto.getGroup() == null)
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
Group group = groupRepository.findById(shopResultDto.getGroup()).orElse(null);
if (group == null) {
throw new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST);
}
try { try {
shopResultDto.setOwner(username); // 3. 将新增的 shop 信息保存并返回 id
Shop shop = new Shop(); String id = getShopId(username, shopResultDto);
shop.of(shopResultDto);
shop.setCreateTime(Instant.now().toEpochMilli()); // 4. 封装 usershop 并保存到 usershop 表
id = shopRepository.save(shop).getShopId();
UserShop userShop = new UserShop(); UserShop userShop = new UserShop();
userShop.setUsername(username);
userShop.setShopId(id); userShop.setShopId(id);
if (shopResultDto.getGroup() != null && us == null) { userShop.setUsername(username);
userShop.setGroupId(shopResultDto.getGroup()); userShop.setGroupId(shopResultDto.getGroup());
}
userShopRepository.save(userShop); userShopRepository.save(userShop);
if (StringUtils.isNotBlank(account.getParent())) {
// 5. 如果当前用户有父账户,则也封装usershop并保存到 usershop 表,区别是 username 与 groupId,同时更新 父账户的商铺数
if (!StringUtils.isEmpty(account.getParent())) {
UserShop userShop1 = new UserShop(); UserShop userShop1 = new UserShop();
userShop1.setUsername(account.getParent());
userShop1.setShopId(id); userShop1.setShopId(id);
userShop1.setUsername(account.getParent());
userShop1.setGroupId("-1"); userShop1.setGroupId("-1");
userShopRepository.save(userShop1); userShopRepository.save(userShop1);
Account parentAccount = accountRepository.findByName(account.getParent())
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
account.setShopCount(parentAccount.getShopCount() + 1);
accountRepository.save(parentAccount);
} }
//可以优化
// 6. 更新当前 account 的商铺数
account.setShopCount(account.getShopCount() + 1); account.setShopCount(account.getShopCount() + 1);
accountRepository.save(account); accountRepository.save(account);
// 7. 返回新增商铺的 id
return id;
} catch (Exception e) { } catch (Exception e) {
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
} }
return id;
} }
@Override @Override
public List<String> addShops(String username, MultipartFile file) throws IOException { public List<String> addShops(String username, MultipartFile file) throws IOException {
List<String> ids = new ArrayList<>(); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
List<List<Object>> list = FileUtil.readExcel(file.getInputStream());
Account account = accountRepository.findByName(username);
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
if (account.getPermission() < 4) { if (account.getPermission() < 4) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
if (account.getShopCount() >= 10000) { if (account.getShopCount() >= 10000) {
throw new ClientRequestException(AccountErrorCode.SHOPMAX); throw new ClientRequestException(AccountErrorCode.SHOPMAX);
} }
List<String> ids = new ArrayList<>();
List<List<Object>> list = FileUtil.readExcel(file.getInputStream());
for (List<Object> l : list) { for (List<Object> l : list) {
ShopResultDto shopResultDto = new ShopResultDto(); ShopResultDto shopResultDto = new ShopResultDto();
shopResultDto.setOwner(username); shopResultDto.setOwner(username);
shopResultDto.setShopName(l.get(0).toString()); shopResultDto.setShopName(l.get(0).toString());
shopResultDto.setShopPlatform(l.get(1).toString()); shopResultDto.setShopPlatform(l.get(1).toString());
shopResultDto.setGroup("-1"); if (!StringUtils.isEmpty(l.get(2).toString())) {
if (StringUtils.isNotBlank(l.get(2).toString()))
shopResultDto.setShopAccount(l.get(2).toString()); shopResultDto.setShopAccount(l.get(2).toString());
if (StringUtils.isNotBlank(l.get(3).toString())) }
if (!StringUtils.isEmpty(l.get(3).toString())) {
shopResultDto.setShopPassword(l.get(3).toString()); shopResultDto.setShopPassword(l.get(3).toString());
String id = null;
UserShop us = null;
if (shopResultDto.getShopId() != null)
us = userShopRepository.findByUsernameAndShopId(username, shopResultDto.getShopId());
if (shopResultDto.getGroup() == null)
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
Group group = groupRepository.findById(shopResultDto.getGroup()).orElse(null);
if (group == null) {
throw new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST);
} }
// 批量导入店铺时,默认不分组
shopResultDto.setGroup("-1");
try { try {
shopResultDto.setOwner(username); String id = getShopId(username, shopResultDto);
Shop shop = new Shop();
shop.of(shopResultDto);
shop.setCreateTime(Instant.now().toEpochMilli());
id = shopRepository.save(shop).getShopId();
UserShop userShop = new UserShop(); UserShop userShop = new UserShop();
userShop.setUsername(username);
userShop.setShopId(id); userShop.setShopId(id);
if (shopResultDto.getGroup() != null && us == null) {
userShop.setGroupId(shopResultDto.getGroup()); userShop.setGroupId(shopResultDto.getGroup());
} userShop.setUsername(username);
userShopRepository.save(userShop); userShopRepository.save(userShop);
if (StringUtils.isNotBlank(account.getParent())) {
if (!StringUtils.isEmpty(account.getParent())) {
UserShop userShop1 = new UserShop(); UserShop userShop1 = new UserShop();
userShop1.setUsername(account.getParent());
userShop1.setShopId(id); userShop1.setShopId(id);
userShop1.setGroupId("-1"); userShop1.setGroupId("-1");
userShop1.setUsername(account.getParent());
userShopRepository.save(userShop1); userShopRepository.save(userShop1);
Account parentAccount = accountRepository.findByName(account.getParent())
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
account.setShopCount(parentAccount.getShopCount() + 1);
accountRepository.save(parentAccount);
} }
//可以优化
account.setShopCount(account.getShopCount() + 1); account.setShopCount(account.getShopCount() + 1);
accountRepository.save(account); accountRepository.save(account);
ids.add(id); ids.add(id);
} catch (Exception e) { } catch (Exception e) {
logger.error("fail to add shops", e.getMessage()); logger.error("fail to add shops", e.getMessage());
...@@ -180,22 +180,27 @@ public class ShopServiceImpl implements ShopService { ...@@ -180,22 +180,27 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public String updateShop(String username, ShopResultDto shopResultDto) { public String updateShop(String username, ShopResultDto shopResultDto) {
Account account = accountRepository.findByName(username); // 1.校验参数、account 、权限
if (account == null) { if (StringUtils.isEmpty(shopResultDto.getShopId())) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
if (shopResultDto == null || StringUtils.isBlank(shopResultDto.getShopId())) {
throw new ClientRequestException(AccountErrorCode.OTHERS); throw new ClientRequestException(AccountErrorCode.OTHERS);
} }
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopResultDto.getShopId()); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account.getPermission() < 4 || userShop == null) { if (account.getPermission() < 4) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
Shop shop_old = shopRepository.findById(shopResultDto.getShopId()).orElseGet(null);
if (shop_old == null) // 2.查询当前店铺是否已经绑定当前用户
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopResultDto.getShopId());
if (userShop == null) {
throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST);
try { }
// 3. 获取旧的店铺信息,并封装新的数据
Shop shop_old = shopRepository.findById(shopResultDto.getShopId()).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST));
shop_old = shop_old.of(shopResultDto); shop_old = shop_old.of(shopResultDto);
try {
// 4. 更新店铺信息
shopRepository.save(shop_old); shopRepository.save(shop_old);
} catch (Exception e) { } catch (Exception e) {
logger.error("fail to update", e.getMessage()); logger.error("fail to update", e.getMessage());
...@@ -206,49 +211,60 @@ public class ShopServiceImpl implements ShopService { ...@@ -206,49 +211,60 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public void deleteShop(String username, String shopId) { public void deleteShop(String username, String shopId) {
Account account = accountRepository.findByName(username); // 1. 校验参数、account 、权限、店铺是否已经和用户绑定
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
if (shopId == null) { if (shopId == null) {
throw new ClientRequestException(AccountErrorCode.OTHERS); throw new ClientRequestException(AccountErrorCode.OTHERS);
} }
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account.getPermission() < 4 || userShop == null) { if (account.getPermission() < 4) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
Shop shop = shopRepository.findById(shopId).orElse(null); UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
if (shop == null) if (userShop == null) {
throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST);
}
// 2. 获取店铺信息
Shop shop = shopRepository.findById(shopId).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST));
// 3. 如果当前店铺已经绑定 未被删除的 ip 资源,则让IP资源先解绑店铺
IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(shop.getShopId(), false); IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(shop.getShopId(), false);
if (ipResource != null) { if (ipResource != null) {
ShopRequestDto shopRequestDto = new ShopRequestDto(); ShopRequestDto shopRequestDto = new ShopRequestDto();
shopRequestDto.setIpId(ipResource.getId());
shopRequestDto.setShopId(shopId); shopRequestDto.setShopId(shopId);
shopRequestDto.setIpId(ipResource.getId());
ipAndShopService.unBindShop(username, shopRequestDto); ipAndShopService.unBindShop(username, shopRequestDto);
} }
// 4. 删除当前店铺关联的所有的 usershop信息
boolean result = userShopRepository.deleteByShopId(shopId); boolean result = userShopRepository.deleteByShopId(shopId);
if (result) { if (result) {
// 5. 删除当前店铺,并更新 account信息 todo
shopRepository.deleteById(shopId); shopRepository.deleteById(shopId);
account.setShopCount(account.getShopCount() - 1);
accountRepository.save(account); // 6. 更新 和店铺关联的所有的 account 的信息
} else throw new ClientRequestException(AccountErrorCode.NOPERMISSION); List<UserShop> userShops = userShopRepository.findByShopId(shopId);
List<Account> accountList = accountRepository.findByNameIn(userShops.stream().map(UserShop::getUsername).collect(Collectors.toList()));
for (Account a : accountList) {
a.setShopCount(account.getShopCount() - 1);
accountRepository.save(a);
}
} else {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
}
} }
@Override @Override
public void transferShop(String username, String shopId, String groupId) { public void transferShop(String username, String shopId, String groupId) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId); UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
Group group = groupRepository.findById(groupId).orElse(null); Group group = groupRepository.findById(groupId).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST));
if (userShop == null || (!group.getId().equals("-1") && group.getOwner() != null && !group.getOwner().equals(username))) { if (userShop == null || (!group.getId().equals("-1") && group.getOwner() != null && !group.getOwner().equals(username))) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
Shop shop = shopRepository.findById(shopId).orElse(null); Shop shop = shopRepository.findById(shopId).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST));
if (shop == null)
throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST);
try { try {
userShop.setGroupId(groupId); userShop.setGroupId(groupId);
userShopRepository.save(userShop); userShopRepository.save(userShop);
...@@ -261,10 +277,8 @@ public class ShopServiceImpl implements ShopService { ...@@ -261,10 +277,8 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public void assignShops(String username, List<String> shopIds, List<String> users) { public void assignShops(String username, List<String> shopIds, List<String> users) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
List<UserShop> userShops = userShopRepository.findByUsernameAndShopIdIn(username, shopIds); List<UserShop> userShops = userShopRepository.findByUsernameAndShopIdIn(username, shopIds);
if (account.getPermission() < 8 || userShops == null || userShops.size() < 1) { if (account.getPermission() < 8 || userShops == null || userShops.size() < 1) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
...@@ -315,10 +329,8 @@ public class ShopServiceImpl implements ShopService { ...@@ -315,10 +329,8 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public ShopResultDto queryShop(String username, String shopId) { public ShopResultDto queryShop(String username, String shopId) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId); UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
if (userShop == null) { if (userShop == null) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
...@@ -342,23 +354,21 @@ public class ShopServiceImpl implements ShopService { ...@@ -342,23 +354,21 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public ShopPageResultDto getShopList(String username, String groupId, int pageNum, int amount, ShopFilterDto shopFilterDto) { public ShopPageResultDto getShopList(String username, String groupId, int pageNum, int amount, ShopFilterDto shopFilterDto) {
Account account = accountRepository.findByName(username); // 当前登录用户的账户是否存在
if (account == null) { Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
// 当前查询的分组信息是否正确
Group group = null; Group group = null;
if (groupId != null) { if (groupId != null) {
group = groupRepository.findById(groupId).orElse(null); group = groupRepository.findById(groupId).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST));
}
if (group == null) {
throw new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST);
}
if (group.getOwner() != null && !group.getOwner().equals(username)) { if (group.getOwner() != null && !group.getOwner().equals(username)) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
}
// 根据 groupId 与 username 来查询 shopIds (如果当前用户是父账户,则查询结果包含子账户的shopId)
// 根据 groupId 与 username 来查询 shopIds
List<String> allIds = null; List<String> allIds = null;
if ("-1".equals(groupId)) { if ("-1".equals(groupId)) {
allIds = userShopRepository.findByUsername(username).stream() allIds = userShopRepository.findByUsername(username).stream()
...@@ -372,10 +382,16 @@ public class ShopServiceImpl implements ShopService { ...@@ -372,10 +382,16 @@ public class ShopServiceImpl implements ShopService {
List<String> shopIds = null; List<String> shopIds = null;
if (shopFilterDto.getBindIp() == 0) { if (shopFilterDto.getBindIp() == 0) {
shopIds = allIds; shopIds = allIds;
// 这个地方有点奇怪,为啥不去 userShop 中找,而是在 ipresource 中找? 可以查看下删除绑定状态的逻辑
} else if (shopFilterDto.getBindIp() == 1) { } else if (shopFilterDto.getBindIp() == 1) {
// ip资源已经分配了 的店铺
shopIds = ipResourceRepository.findShopIdInList(allIds, false).stream() shopIds = ipResourceRepository.findShopIdInList(allIds, false).stream()
.flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList()); .flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
// 这个地方的其他情况是指什么情况
} else { } else {
// 店铺绑定的 ip 资源被删除的 店铺
for (String id : allIds) { for (String id : allIds) {
IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false); IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false);
if (ipResource == null) { if (ipResource == null) {
...@@ -386,19 +402,8 @@ public class ShopServiceImpl implements ShopService { ...@@ -386,19 +402,8 @@ public class ShopServiceImpl implements ShopService {
amount = amount > 100 ? 100 : amount; amount = amount > 100 ? 100 : amount;
Pageable pageable = PageRequest.of(pageNum, amount); Pageable pageable = PageRequest.of(pageNum, amount);
Page<Shop> shops;
// 根据商铺ids 与 过滤条件 得到商铺 // 根据商铺ids 与 过滤条件 得到商铺
if (StringUtils.isNotBlank(shopFilterDto.getIpRegion())) { Page<Shop> shops = getShopsByFilter(shopFilterDto, shopIds, pageable);
List<String> filter = ipResourceRepository.findShopIdInListAndRegionLike(shopIds, false, shopFilterDto.getIpRegion())
.stream().flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(filter, pageable);
} else if (StringUtils.isNotBlank(shopFilterDto.getShopAccount())) {
shops = shopRepository.findByShopIdInAndShopAccountLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopAccount(), pageable);
} else if (StringUtils.isNotBlank(shopFilterDto.getShopName())) {
shops = shopRepository.findByShopIdInAndShopNameLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopName(), pageable);
} else {
shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(shopIds, pageable);
}
ShopPageResultDto<ShopResultDto> shopPageResultDto = new ShopPageResultDto<>(); ShopPageResultDto<ShopResultDto> shopPageResultDto = new ShopPageResultDto<>();
if (shops != null && shops.getNumberOfElements() >= 1) { if (shops != null && shops.getNumberOfElements() >= 1) {
...@@ -407,7 +412,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -407,7 +412,7 @@ public class ShopServiceImpl implements ShopService {
x -> { x -> {
IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(x.getShopId(), false); IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(x.getShopId(), false);
// 如果 ip资源非空 且 addr 也非空 // 如果 ip资源非空 且 addr 也非空
if (ipResource != null && StringUtils.isNotBlank(ipResource.getAddr())) { if (ipResource != null && !StringUtils.isEmpty(ipResource.getAddr())) {
// 1. ip资源在未来七天内到期 且 ip 资源的状态不是 3(正在分配)、5(已失效)、6(未分配),则将 ip 资源设置为 2(即将过期) // 1. ip资源在未来七天内到期 且 ip 资源的状态不是 3(正在分配)、5(已失效)、6(未分配),则将 ip 资源设置为 2(即将过期)
if (ipResource.getValidTime() <= Instant.now().plusSeconds(60 * 60 * 24 * 7).toEpochMilli() && ipResource.getValidTime() > Instant.now().toEpochMilli()) { if (ipResource.getValidTime() <= Instant.now().plusSeconds(60 * 60 * 24 * 7).toEpochMilli() && ipResource.getValidTime() > Instant.now().toEpochMilli()) {
if (ipResource.getStatus() != 5 && ipResource.getStatus() != 3 && ipResource.getStatus() != 6) { if (ipResource.getStatus() != 5 && ipResource.getStatus() != 3 && ipResource.getStatus() != 6) {
...@@ -460,37 +465,17 @@ public class ShopServiceImpl implements ShopService { ...@@ -460,37 +465,17 @@ public class ShopServiceImpl implements ShopService {
Page<ShopResultDto> shopDtoPage = new PageImpl<>(shopResultDtos, pageable, shopIds.size()); Page<ShopResultDto> shopDtoPage = new PageImpl<>(shopResultDtos, pageable, shopIds.size());
shopPageResultDto.setShopList(shopDtoPage.getContent()); shopPageResultDto.setShopList(shopDtoPage.getContent());
PageInfo pageInfo = new PageInfo(); PageInfo pageInfo = new PageInfo(shopDtoPage.getPageable().getPageNumber(), shopDtoPage.getTotalPages(), shopIds.size());
pageInfo.setCurrentPage(shopDtoPage.getPageable().getPageNumber());
pageInfo.setTotalPages(shopDtoPage.getTotalPages());
pageInfo.setTotalItems(shopIds.size());
shopPageResultDto.setShopPage(pageInfo); shopPageResultDto.setShopPage(pageInfo);
} }
return shopPageResultDto; return shopPageResultDto;
} }
private ShopResultDto getShopResultDto(String username, Shop x, IpResource ipResource) {
if (ipResource == null) {
ipResource = new IpResource();
}
String group1 = userShopRepository.findByUsernameAndShopId(username, x.getShopId()).getGroupId();
ShopResultDto shopResultDto = null;
if (ipResource.isSpecialLine()) {
SpecialLine specialLine = specialLineRepository.findAll().get(0);
shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false, specialLine));
} else {
shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false));
}
return shopResultDto;
}
@Override @Override
public ShopSummary getShopSummary(String username) { public ShopSummary getShopSummary(String username) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
ShopSummary shopSummary = new ShopSummary(); ShopSummary shopSummary = new ShopSummary();
List<String> allShopIds = userShopRepository.findByUsername(username).stream() List<String> allShopIds = userShopRepository.findByUsername(username).stream()
...@@ -520,7 +505,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -520,7 +505,7 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public List<String> getShopUsers(String username, String shopId) { public List<String> getShopUsers(String username, String shopId) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (account.getParent() != null) if (account.getParent() != null)
...@@ -531,7 +516,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -531,7 +516,7 @@ public class ShopServiceImpl implements ShopService {
@Override @Override
public List<String> getBatchShopUsers(String username, List<String> shopIds) { public List<String> getBatchShopUsers(String username, List<String> shopIds) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (account.getParent() != null) if (account.getParent() != null)
...@@ -560,4 +545,48 @@ public class ShopServiceImpl implements ShopService { ...@@ -560,4 +545,48 @@ public class ShopServiceImpl implements ShopService {
} }
return shopUsers; return shopUsers;
} }
private String getShopId(String username, ShopResultDto shopResultDto) {
Shop shop = new Shop();
shopResultDto.setOwner(username);
shop.of(shopResultDto);
shop.setCreateTime(Instant.now().toEpochMilli());
String id = shopRepository.save(shop).getShopId();
return id;
}
private Page<Shop> getShopsByFilter(ShopFilterDto shopFilterDto, List<String> shopIds, Pageable pageable) {
Page<Shop> shops = null;
if (!StringUtils.isEmpty(shopFilterDto.getIpRegion())) {
List<String> filter = ipResourceRepository.findShopIdInListAndRegionLike(shopIds, false, shopFilterDto.getIpRegion())
.stream().flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(filter, pageable);
}
if (!StringUtils.isEmpty(shopFilterDto.getShopAccount())) {
shops = shopRepository.findByShopIdInAndShopAccountLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopAccount(), pageable);
}
if (!StringUtils.isEmpty(shopFilterDto.getShopName())) {
shops = shopRepository.findByShopIdInAndShopNameLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopName(), pageable);
}
if (shopFilterDto.isEmpty()) {
shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(shopIds, pageable);
}
return shops;
}
private ShopResultDto getShopResultDto(String username, Shop x, IpResource ipResource) {
if (ipResource == null) {
ipResource = new IpResource();
}
String group1 = userShopRepository.findByUsernameAndShopId(username, x.getShopId()).getGroupId();
ShopResultDto shopResultDto = null;
if (ipResource.isSpecialLine()) {
SpecialLine specialLine = specialLineRepository.findAll().get(0);
shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false, specialLine));
} else {
shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false));
}
return shopResultDto;
}
} }
...@@ -2,9 +2,11 @@ package com.edgec.browserbackend.browser.task; ...@@ -2,9 +2,11 @@ package com.edgec.browserbackend.browser.task;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.edgec.browserbackend.account.domain.Account; import com.edgec.browserbackend.account.domain.Account;
import com.edgec.browserbackend.account.exception.AccountErrorCode;
import com.edgec.browserbackend.account.repository.AccountRepository; import com.edgec.browserbackend.account.repository.AccountRepository;
import com.edgec.browserbackend.browser.domain.IpResource; import com.edgec.browserbackend.browser.domain.IpResource;
import com.edgec.browserbackend.browser.repository.IpResourceRepository; import com.edgec.browserbackend.browser.repository.IpResourceRepository;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.SmsUtils; import com.edgec.browserbackend.common.commons.utils.SmsUtils;
import net.javacrumbs.shedlock.core.SchedulerLock; import net.javacrumbs.shedlock.core.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -56,7 +58,7 @@ public class ExpireSoonWarn { ...@@ -56,7 +58,7 @@ public class ExpireSoonWarn {
} }
private void sendToAccount(String username, int day, int amount, List<String> ips) { private void sendToAccount(String username, int day, int amount, List<String> ips) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("day", day); param.put("day", day);
param.put("amount", amount); param.put("amount", amount);
......
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