Commit fc8e8d2f authored by xuxin's avatar xuxin

代码调优及bug修复

parent 1803862e
package com.edgec.browserbackend.account.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@NoArgsConstructor
@Getter
@Setter
@Document(collection = "accounts")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Account {
/**
* 账户id
*/
@Id
private String name;
/**
* 父账户
*/
private String parent;
//子用户使用
/**
* 子用户使用的密码
*/
private String password;
private Date lastSeen;
......@@ -44,6 +58,13 @@ public class Account {
private boolean allowedToCreateSubUser = false;
/**
* 操作与权重
* <p>
* 下载 cookie:1
* 上传 cookie:2
* 店铺管理(增删改店铺、绑定与解绑ip):4
*/
private int permission = -1;
private Promotion promotion;
......@@ -64,24 +85,8 @@ public class Account {
private List<String> queryIpUrlList = new ArrayList<>();
public Date getSignupDate() {
return signupDate;
}
public void setSignupDate(Date signupDate) {
this.signupDate = signupDate;
}
public boolean isPrePaid() {
return isPrePaid;
}
public void setPrePaid(boolean prePaid) {
isPrePaid = prePaid;
}
public Account() {
}
@Length(min = 0, max = 20000)
private String note;
public Account(AccountDto account) {
this.setName(account.getName());
......@@ -94,191 +99,5 @@ public class Account {
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;
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.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
......@@ -9,11 +8,12 @@ import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Repository
public interface AccountRepository extends MongoRepository<Account, String>, AccountRepositoryCustom {
Account findByName(String name);
Optional<Account> findByName(String name);
Account findByEmail(String email);
......@@ -37,6 +37,7 @@ public interface AccountRepository extends MongoRepository<Account, String>, Acc
Page<Account> findAllBySignupDateBetweenAndParentIsNullAndAuthorized(Pageable pageable, Date startDate, Date endDate, int authorized);
@Override
Page<Account> findAll(Pageable pageable);
List<Account> findByNameIn(List<String> names);
......
......@@ -4,21 +4,18 @@ import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
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.repository.*;
import com.edgec.browserbackend.account.service.AccountService;
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.UserPrePaidBillingService;
import com.edgec.browserbackend.alipay.AlipayConfig;
import com.edgec.browserbackend.alipay.CloudamAlipayConfig;
import com.edgec.browserbackend.alipay.VpsAlipayConfig;
......@@ -32,10 +29,8 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import javax.swing.text.Document;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.YearMonth;
......@@ -176,12 +171,12 @@ public class PaymentServiceImpl implements PaymentService {
if (chargeType == 0) {
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)
bill.setAdministrator(account.getParent());
else
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.setAmount(0);
bill.setUnit(null);
......@@ -308,12 +303,12 @@ public class PaymentServiceImpl implements PaymentService {
if (chargeType == 0) {
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)
bill.setAdministrator(account.getParent());
else
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.setAmount(0);
bill.setUnit(null);
......@@ -365,7 +360,7 @@ public class PaymentServiceImpl implements PaymentService {
public String alipayPutPayOrder(String username, int amount, String by) {
Account byName = accountService.findByName(username);
if (byName == null )
if (byName == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + username);
if (byName.getPermission() < 4)
throw new ClientRequestException(AccountErrorCode.NOPERMISSION, "account does not have permission: " + username);
......@@ -483,12 +478,12 @@ public class PaymentServiceImpl implements PaymentService {
UserBalance userBalance = userBalanceRepository.findById(username).orElse(null);
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)
bill.setAdministrator(account.getParent());
else
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.setAmount(0);
bill.setUnit(null);
......@@ -645,7 +640,7 @@ public class PaymentServiceImpl implements PaymentService {
if (response == null)
throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
if(response.isSuccess()){
if (response.isSuccess()) {
internalOrder.setSucceed(true);
userWithdrawRepository.save(internalOrder);
......@@ -654,7 +649,7 @@ public class PaymentServiceImpl implements PaymentService {
bill.setAdministrator(byName.getParent());
else
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.setAmount(0);
bill.setUnit(null);
......@@ -675,7 +670,7 @@ public class PaymentServiceImpl implements PaymentService {
userPrePaidBillingRepository.save(bill);
return true;
}else{
} else {
byName.getPromotion().setAllGift(byName.getPromotion().getAllGift() + amount);
byName.getPromotion().setWithdrawn(byName.getPromotion().getWithdrawn() - amount);
accountRepository.save(byName);
......
......@@ -2,9 +2,11 @@ package com.edgec.browserbackend.account.service.impl;
import com.alibaba.fastjson.JSONObject;
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.UserLackMoneyRepository;
import com.edgec.browserbackend.account.service.UserLackMoneyService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -28,9 +30,9 @@ public class UserLackMoneyServiceImpl implements UserLackMoneyService {
//用户名,欠费金额,账单Id,账单总数
String username = billings.get(0).getUsername();
float totalUnpaid = billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID)
.map(x -> x.getTotal() - (x.getDeductionRecords() != null ? (x.getDeductionRecords().stream().collect(Collectors.summingDouble(
DeductionRecord::getDeductionAmount
)).longValue()) : (0))).collect(Collectors.summingDouble(Float::floatValue)).floatValue();
.map(x -> x.getTotal() - (x.getDeductionRecords() != null ? (x.getDeductionRecords().stream().collect(Collectors.summingDouble(
DeductionRecord::getDeductionAmount
)).longValue()) : (0))).collect(Collectors.summingDouble(Float::floatValue)).floatValue();
List<String> ids = billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID).map(UserPrePaidBilling::getId).collect(Collectors.toList());
int billsAmount = (int) billings.stream().filter(x -> x.getStatus() == BillStatus.UNPAID).count();
......@@ -45,7 +47,7 @@ public class UserLackMoneyServiceImpl implements UserLackMoneyService {
//发送短信提醒
if (totalUnpaid > 0 && ifMessageRemind) {
Account account = repository.findByName(username);
Account account = repository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
String telephone = account.getPhoneNumber();
JSONObject param = new JSONObject();
param.put("billsamount", billsAmount);
......
......@@ -34,7 +34,7 @@ public class ShopController {
@Autowired
private IpAndShopService ipAndShopService;
@RequestMapping(value = "/add", method = RequestMethod.POST)
@PostMapping("/add")
public ResultDto addShop(Principal principal, @RequestBody ShopResultDto shopResultDto) {
ResultDto resultDto = new ResultDto();
try {
......@@ -48,7 +48,7 @@ public class ShopController {
return resultDto;
}
@RequestMapping(value = "/multiadd", method = RequestMethod.POST)
@PostMapping("/multiadd")
public ResultDto addShops(Principal principal, @RequestParam("file") MultipartFile file) {
ResultDto resultDto = new ResultDto();
String name = file.getOriginalFilename();
......@@ -123,6 +123,9 @@ public class ShopController {
return resultDto;
}
/**
* 移动店铺 到 分组
*/
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
public ResultDto transferShop(Principal principal, @RequestBody ShopRequestDto shopRequestDto) {
ResultDto resultDto = new ResultDto();
......
......@@ -7,6 +7,10 @@ import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* @author cloudam
* 这是一个中间表,关联 user 、shop、 group 表
*/
@Getter
@Setter
@NoArgsConstructor
......
package com.edgec.browserbackend.browser.dto;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
@Getter
@Setter
public class IpFilterDto {
String region;
String addr;
String vendor;
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
public boolean isEmpty() {
boolean flag = false;
if (StringUtils.isEmpty(region) && StringUtils.isEmpty(addr) && StringUtils.isEmpty(vendor)) {
flag = true;
}
return flag;
}
}
package com.edgec.browserbackend.browser.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageInfo {
int currentPage;
int totalPages;
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;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ShopFilterDto {
private String shopName;
......@@ -9,35 +14,11 @@ public class ShopFilterDto {
private String shopAccount;
private int bindIp;
public String getShopAccount() {
return shopAccount;
}
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;
public boolean isEmpty() {
boolean flag = false;
if (StringUtils.isEmpty(shopName) && StringUtils.isEmpty(IpRegion) && StringUtils.isEmpty(shopAccount)) {
flag = true;
}
return flag;
}
}
package com.edgec.browserbackend.browser.dto;
import lombok.Data;
@Data
public class ShopStringResultDto {
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
......@@ -113,10 +113,10 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
}
@Override
public boolean deleteShopId(String ipId, String shopId, BindHistory bindHistory) {
public boolean deleteShopId(String id, String shopId, BindHistory bindHistory) {
Document doc = new Document();
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.pull("shopIds", shopId).push("bindhistory", bindHistory);
UpdateResult result = mongoTemplate.updateFirst(basicQuery, update, IpResource.class);
......@@ -163,18 +163,23 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
UnwindOperation unwind = Aggregation.unwind("shopIds");
MatchOperation matchshopId = Aggregation.match(where("shopIds").in(shopIds));
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()) {
return new ArrayList<>();
}
HashMap<String, IpResource> ipResourceHashMap = new HashMap<>();
ipResourceUnwindResultDtos.forEach(x -> {
if (ipResourceHashMap.containsKey(x.getId())) {
ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId());
} else {
ipResourceHashMap.put(x.getId(), x.toResource());
}
});
ipResourceUnwindResultDtos.forEach(
x -> {
if (ipResourceHashMap.containsKey(x.getId())) {
ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId());
} else {
ipResourceHashMap.put(x.getId(), x.toResource());
}
}
);
List<IpResource> result = new ArrayList<>();
Set<Map.Entry<String, IpResource>> entry = ipResourceHashMap.entrySet();
for (Map.Entry<String, IpResource> e : entry) {
......
......@@ -37,7 +37,7 @@ public class GroupServiceImpl implements GroupService {
public String addGroup(String username, String groupName) {
if (StringUtils.isBlank(username) || StringUtils.isBlank(groupName))
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
Account account = accountRepository.findByName(username);
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (account.getGroupCount() >= 100)
......@@ -79,14 +79,14 @@ public class GroupServiceImpl implements GroupService {
public void deleteGroup(String username, String groupId) {
if (StringUtils.isBlank(username) || StringUtils.isBlank(groupId))
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
Account account = accountRepository.findByName(username);
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
try {
userShopRepository.updateGroupId(groupId, null);
groupRepository.deleteById(groupId);
//可以优化
account.setGroupCount(account.getGroupCount()-1);
account.setGroupCount(account.getGroupCount() - 1);
accountRepository.save(account);
} catch (Exception e) {
logger.error("fail to delete group", e.getMessage());
......@@ -106,7 +106,7 @@ public class GroupServiceImpl implements GroupService {
groups.stream().forEach(x -> {
groupDtos.add(new GroupDto(x.getId(), x.getName(), x.getDetails()));
});
} catch (Exception e){
} catch (Exception e) {
logger.error("fail to delete group", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
}
......
......@@ -44,10 +44,7 @@ public class IpAndShopServiceImpl implements IpAndShopService {
@Override
public void bindShop(String username, ShopRequestDto shopRequestDto) {
// 1. 根据id 来获取账户
Account account = accountRepository.findByName(username);
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
String shopId = shopRequestDto.getShopId();
// 2.获取当前账户下指定的商铺
......@@ -62,10 +59,10 @@ public class IpAndShopServiceImpl implements IpAndShopService {
IpResource ipResource = null;
if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) {
ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false);
} else if (StringUtils.isNotBlank(shopRequestDto.getIpId())) {
}
if (StringUtils.isNotBlank(shopRequestDto.getIpId())) {
ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false);
}
if (ipResource == null) {
throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST);
}
......@@ -87,40 +84,56 @@ public class IpAndShopServiceImpl implements IpAndShopService {
@Override
public void unBindShop(String username, ShopRequestDto shopRequestDto) {
String shopId = null;
if (StringUtils.isNotBlank(shopRequestDto.getShopId()))
shopId = shopRequestDto.getShopId();
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) {
// 1. 检查当前账户是否存在,是否具备操作权限
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account.getPermission() < 4) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
}
Shop shop = shopRepository.findById(shopId).orElse(null);
if (shop == null)
String shopId = shopRequestDto.getShopId();
// 2. 查找当前用户是否已经绑定商铺 以及 关联商铺的绑定 (一个商铺可以被多个用户持有)
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
if (userShop == null) {
throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST);
}
// 3. 查找商铺信息
Shop shop = shopRepository.findById(shopId).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST));
// 4. 查找当前商铺绑定的 ip 资源是否存在
IpResource ipResource = null;
if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) {
ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false);
} else if (StringUtils.isNotBlank(shopRequestDto.getIpId())) {
}
if (StringUtils.isNotBlank(shopRequestDto.getIpId())) {
ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false);
}
if (ipResource == null)
if (ipResource == null) {
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);
}
// 封装 ip 资源绑定的历史信息
BindHistory bindHistory = new BindHistory();
bindHistory.setIp(ipResource.getAddr());
bindHistory.setPlatform(shop.getShopPlatform());
bindHistory.setShopName(shop.getShopName());
bindHistory.setUnbindTime(ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
try {
BindHistory bindHistory = new BindHistory();
bindHistory.setIp(ipResource.getAddr());
bindHistory.setPlatform(shop.getShopPlatform());
bindHistory.setShopName(shop.getShopName());
bindHistory.setUnbindTime(ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// 6. IP资源解除绑定的店铺并更新ip资源的绑定历史
ipResourceRepository.deleteShopId(ipResource.getId(), shopId, bindHistory);
// 7. 更新 ip 资源的绑定状态为 未绑定
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);
}
} catch (Exception e) {
logger.error("fail to unbind", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
......@@ -132,10 +145,8 @@ public class IpAndShopServiceImpl implements IpAndShopService {
List<String> shopIds = null;
if (shopRequestDto.getShopIds() != null && shopRequestDto.getShopIds().size() > 0)
shopIds = shopRequestDto.getShopIds();
Account account = accountRepository.findByName(username);
if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
IpResource ipResource = null;
if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) {
ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false);
......
......@@ -2,9 +2,11 @@ package com.edgec.browserbackend.browser.task;
import com.alibaba.fastjson.JSONObject;
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.browser.domain.IpResource;
import com.edgec.browserbackend.browser.repository.IpResourceRepository;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.SmsUtils;
import net.javacrumbs.shedlock.core.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -56,7 +58,7 @@ public class ExpireSoonWarn {
}
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();
param.put("day", day);
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