Commit 20a0c831 authored by huangjiamin's avatar huangjiamin

【Shop模块】处理UA BUG:选择UA后依然出现随机UA的BUG,并重构addShop部分代码

parent df6eef1c
......@@ -2,7 +2,6 @@ package com.edgec.browserbackend.browser.controller;
import com.alibaba.fastjson.JSONObject;
import com.edgec.browserbackend.account.dto.ResultDto;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.browser.dto.ShopPageResultDto;
import com.edgec.browserbackend.browser.dto.ShopRequestDto;
import com.edgec.browserbackend.browser.dto.ShopResultDto;
......@@ -10,74 +9,83 @@ import com.edgec.browserbackend.browser.dto.ShopStringResultDto;
import com.edgec.browserbackend.browser.service.IpAndShopService;
import com.edgec.browserbackend.browser.service.ShopService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
/**
* 商铺操作
*/
@RequestMapping("/shop")
@RestController
public class ShopController {
private final Logger log = LoggerFactory.getLogger(ShopController.class);
private ShopService shopService;
private IpAndShopService ipAndShopService;
@Autowired
private ShopService shopService;
public void setShopService(ShopService shopService) {
this.shopService = shopService;
}
@Autowired
private IpAndShopService ipAndShopService;
public void setIpAndShopService(IpAndShopService ipAndShopService) {
this.ipAndShopService = ipAndShopService;
}
private final Logger log = LoggerFactory.getLogger(ShopController.class);
/**
* 新增店铺操作
*
* @param principal principal
* @param shopResultDto shopResultDto
* @return resultDto
*/
@PostMapping("/add")
public ResultDto addShop(Principal principal, @RequestBody ShopResultDto shopResultDto) {
ResultDto resultDto = new ResultDto();
String logs = "【addShop】 ";
log.info("{}, params : {}", logs, principal.getName());
try {
ShopStringResultDto shopStringResultDto = new ShopStringResultDto();
shopStringResultDto.setId(shopService.addShop(principal.getName(), shopResultDto));
resultDto.setData(shopStringResultDto);
resultDto.setStatus(0);
return ResponseUtil.success(shopService.addShop(principal.getName(), shopResultDto));
} catch (ClientRequestException e) {
log.warn("{}, ClientRequestException : {}", logs, e.getErrorCode().getReason());
return ResponseUtil.error(e.getErrorCode());
} catch (Exception e) {
log.error("{}, Exception : {}", logs, e.getMessage(), e);
dealClientRequestException(resultDto, e);
return ResponseUtil.error(e.getMessage());
}
return resultDto;
}
/**
* 批量新增店铺
*
* @param principal principal
* @param file file
* @return resultDto
*/
@PostMapping("/multiadd")
public ResultDto addShops(Principal principal, @RequestParam("file") MultipartFile file) {
ResultDto resultDto = new ResultDto();
String logs = "【addShops】 ";
log.info("{}, params : {}", logs, principal.getName());
String name = file.getOriginalFilename();
if (name.length() < 6 || !name.substring(name.length() - 5).equals(".xlsx")) {
resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", BrowserErrorCode.INFORMATIONNOTCOMPELETE.getCode());
statusInfo.put("message", "文件格式错误");
resultDto.setStatusInfo(statusInfo);
}
try {
shopService.addShops(principal.getName(), file);
resultDto.setStatus(0);
} catch (ClientRequestException | IOException e) {
return ResponseUtil.success(shopService.addShops(principal.getName(), file));
} catch (ClientRequestException e) {
log.warn("{}, ClientRequestException : {}", logs, e.getErrorCode().getReason());
return ResponseUtil.error(e.getErrorCode());
} catch (Exception e) {
log.error("{}, Exception : {}", logs, e.getMessage(), e);
resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", 40102);
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
return ResponseUtil.error(e.getMessage());
}
return resultDto;
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
......
......@@ -30,154 +30,230 @@ import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@Service
/**
* 商铺操作
*
* @author JMW
*/
@Transactional
@Service
public class ShopServiceImpl implements ShopService {
private final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);
private IpAndShopService ipAndShopService;
private IpResourceService ipResourceService;
private ShopRepository shopRepository;
private AccountRepository accountRepository;
private UserShopRepository userShopRepository;
private GroupRepository groupRepository;
private IpResourceRepository ipResourceRepository;
private SpecialLineRepository specialLineRepository;
private ShopUARepository shopUaRepository;
@Autowired
ShopRepository shopRepository;
public void setIpAndShopService(IpAndShopService ipAndShopService) {
this.ipAndShopService = ipAndShopService;
}
@Autowired
AccountRepository accountRepository;
public void setIpResourceService(IpResourceService ipResourceService) {
this.ipResourceService = ipResourceService;
}
@Autowired
UserShopRepository userShopRepository;
public void setShopRepository(ShopRepository shopRepository) {
this.shopRepository = shopRepository;
}
@Autowired
GroupRepository groupRepository;
public void setAccountRepository(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Autowired
IpResourceRepository ipResourceRepository;
public void setUserShopRepository(UserShopRepository userShopRepository) {
this.userShopRepository = userShopRepository;
}
@Autowired
IpAndShopService ipAndShopService;
public void setGroupRepository(GroupRepository groupRepository) {
this.groupRepository = groupRepository;
}
@Autowired
IpResourceService ipResourceService;
public void setIpResourceRepository(IpResourceRepository ipResourceRepository) {
this.ipResourceRepository = ipResourceRepository;
}
@Autowired
SpecialLineRepository specialLineRepository;
public void setSpecialLineRepository(SpecialLineRepository specialLineRepository) {
this.specialLineRepository = specialLineRepository;
}
@Autowired
ShopUARepository shopUARepository;
public void setShopUaRepository(ShopUARepository shopUaRepository) {
this.shopUaRepository = shopUaRepository;
}
private final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);
/**
* 新增店铺
*
* @param username username
* @param shopResultDto shopResultDto
* @return ID
*/
@Override
public String addShop(String username, ShopResultDto shopResultDto) {
// 1. 对商铺的分组信息校验
if (shopResultDto.getGroup() == null) {
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
}
if (shopResultDto.getGroup() != null) {
Group group = groupRepository.findById(shopResultDto.getGroup())
.orElseThrow(() -> new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST));
groupRepository.findById(shopResultDto.getGroup()).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST));
}
Account account = judgeAccountForAddShop(username);
return saveShopAndGetId(account, shopResultDto);
}
// 2. 对当前用户的 account 信息进行校验
Account account = accountRepository.findByName(username)
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account.getPermission() < 4) {
private final static String XLSX = ".xlsx";
/**
* 批量新增店铺
*
* @param username username
* @param file file
* @return IDS
* @throws IOException IOException
*/
@Override
public List<String> addShops(String username, MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
if (StringUtils.isEmpty(filename) || filename.length() < 6 || !filename.substring(filename.length() - 5).equals(XLSX)) {
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE, "文件格式错误");
}
Account account = judgeAccountForAddShop(username);
List<List<Object>> shops = FileUtil.readExcel(file.getInputStream());
return shops.stream()
.map(shopObject -> saveShopAndGetId(account, getShopResultDto(username, shopObject)))
.collect(Collectors.toList());
}
private final static int PERMISSION_04 = 4;
private final static int SHOP_MAX = 10000;
/**
* 新增店铺时账户判断
* 对当前用户的 account 信息进行校验
*
* @param username username
* @return account
*/
private Account judgeAccountForAddShop(String username) {
Account account = judgeAccount(username);
if (account.getPermission() < PERMISSION_04) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
}
if (account.getShopCount() >= 10000) {
if (account.getShopCount() >= SHOP_MAX) {
throw new ClientRequestException(AccountErrorCode.SHOPMAX);
}
return account;
}
try {
// 3. 将新增的 shop 信息保存并返回 id
String id = getShopId(username, shopResultDto);
// 4. 封装 usershop 并保存到 usershop 表
UserShop userShop = new UserShop();
userShop.setShopId(id);
userShop.setUsername(username);
userShop.setGroupId(shopResultDto.getGroup());
userShopRepository.save(userShop);
/**
* 账户判断
*
* @param username username
* @return account
*/
private Account judgeAccount(String username) {
return accountRepository.findByName(username)
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
}
// 5. 如果当前用户有父账户,则也封装usershop并保存到 usershop 表,区别是 username 与 groupId,同时更新 父账户的商铺数
if (!StringUtils.isEmpty(account.getParent())) {
UserShop userShop1 = new UserShop();
userShop1.setShopId(id);
userShop1.setUsername(account.getParent());
userShop1.setGroupId("-1");
userShopRepository.save(userShop1);
Account parentAccount = accountRepository.findByName(account.getParent())
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
account.setShopCount(parentAccount.getShopCount() + 1);
accountRepository.save(parentAccount);
/**
* 保存店铺信息并获取ID
*
* @param account account
* @param shopResultDto shopResultDto
* @return ID
*/
private String saveShopAndGetId(Account account, ShopResultDto shopResultDto) {
String logs = "【saveShopAndGetId】 ";
try {
shopResultDto.setOwner(account.getName());
Shop shop = new Shop();
shop.of(shopResultDto);
shop.setCreateTime(Instant.now().toEpochMilli());
if (StringUtils.isEmpty(shop.getShopUA())) {
List<String> uaList = shopUaRepository.findAll().stream()
.map(ShopUA::getUaList)
.map(String::valueOf)
.collect(Collectors.toList());
shop.setShopUA(uaList.get(new Random().nextInt(uaList.size())));
}
// 6. 更新当前 account 的商铺数
account.setShopCount(account.getShopCount() + 1);
accountRepository.save(account);
// 7. 返回新增商铺的 id
return id;
return saveUserShopAndAccount(shopRepository.save(shop).getShopId(), shopResultDto.getGroup(), account);
} catch (Exception e) {
logger.error("{}, Exception : {}", logs, e.getMessage(), e);
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
}
}
@Override
public List<String> addShops(String username, MultipartFile file) throws IOException {
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account.getPermission() < 4) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
}
if (account.getShopCount() >= 10000) {
throw new ClientRequestException(AccountErrorCode.SHOPMAX);
}
/**
* 封装 userShop 并保存
* 更新当前 account 的商铺数
*
* @param id id
* @param groupId groupId
* @param account account
*/
private String saveUserShopAndAccount(String id, String groupId, Account account) {
UserShop userShop = new UserShop();
userShop.setShopId(id);
userShop.setUsername(account.getName());
userShop.setGroupId(groupId);
userShopRepository.save(userShop);
List<String> ids = new ArrayList<>();
List<List<Object>> list = FileUtil.readExcel(file.getInputStream());
for (List<Object> l : list) {
ShopResultDto shopResultDto = new ShopResultDto();
shopResultDto.setOwner(username);
shopResultDto.setShopName(l.get(0).toString());
shopResultDto.setShopPlatform(l.get(1).toString());
if (!StringUtils.isEmpty(l.get(2).toString())) {
shopResultDto.setShopAccount(l.get(2).toString());
}
if (!StringUtils.isEmpty(l.get(3).toString())) {
shopResultDto.setShopPassword(l.get(3).toString());
}
// 批量导入店铺时,默认不分组
shopResultDto.setGroup("-1");
account.setShopCount(account.getShopCount() + 1);
accountRepository.save(account);
try {
String id = getShopId(username, shopResultDto);
UserShop userShop = new UserShop();
userShop.setShopId(id);
userShop.setGroupId(shopResultDto.getGroup());
userShop.setUsername(username);
userShopRepository.save(userShop);
if (!StringUtils.isEmpty(account.getParent())) {
UserShop userShop1 = new UserShop();
userShop1.setShopId(id);
userShop1.setGroupId("-1");
userShop1.setUsername(account.getParent());
userShopRepository.save(userShop1);
Account parentAccount = accountRepository.findByName(account.getParent())
.orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
account.setShopCount(parentAccount.getShopCount() + 1);
accountRepository.save(parentAccount);
}
if (!StringUtils.isEmpty(account.getParent())) {
saveUserShopAndAccount(id,"-1", judgeAccount(account.getParent()));
}
account.setShopCount(account.getShopCount() + 1);
accountRepository.save(account);
return id;
}
ids.add(id);
} catch (Exception e) {
logger.error("fail to add shops", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
}
private final static int SHOP_NAME = 0;
private final static int SHOP_PLAT_FORM = 1;
private final static int SHOP_ACCOUNT = 2;
private final static int SHOP_PASSWORD = 3;
/**
* 将Excel文件中的ShopResultDto封装并返回
* 批量导入店铺时,默认不分组
*
* @param username username
* @param shopObject shopObject
* @return shopResultDto
*/
private ShopResultDto getShopResultDto(String username, List<Object> shopObject) {
ShopResultDto shopResultDto = new ShopResultDto();
shopResultDto.setGroup("-1");
shopResultDto.setOwner(username);
shopResultDto.setShopName(shopObject.get(SHOP_NAME).toString());
shopResultDto.setShopPlatform(shopObject.get(SHOP_PLAT_FORM).toString());
String shopAccount = shopObject.get(SHOP_ACCOUNT).toString();
String shopPassword = shopObject.get(SHOP_PASSWORD).toString();
if (!StringUtils.isEmpty(shopAccount)) {
shopResultDto.setShopAccount(shopAccount);
}
return ids;
if (!StringUtils.isEmpty(shopPassword)) {
shopResultDto.setShopPassword(shopPassword);
}
return shopResultDto;
}
@Override
......@@ -456,7 +532,7 @@ public class ShopServiceImpl implements ShopService {
// 绑定了 ip 资源的店铺
if (shopFilterDto.getBindIp() == 1) {
shopIds = ipResourceRepository.findShopIdInList(allIds, false).stream()
.flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
.flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
}
// 未绑定 ip 资源的店铺
if (shopFilterDto.getBindIp() == 2) {
......@@ -472,7 +548,7 @@ public class ShopServiceImpl implements ShopService {
// 临时试用一下
if (shopFilterDto.getBindIp() == 3) {
List<String> shopIds2 = ipResourceRepository.findShopIdInList(allIds, false).stream()
.flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
.flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
allIds.removeAll(shopIds2);
shopIds = allIds;
}
......@@ -568,7 +644,7 @@ public class ShopServiceImpl implements ShopService {
ShopSummary shopSummary = new ShopSummary();
List<String> allShopIds = userShopRepository.findByUsername(username).stream()
.map(UserShop::getShopId).collect(Collectors.toList());
.map(UserShop::getShopId).collect(Collectors.toList());
List<String> unbind = new ArrayList<>();
if (!allShopIds.isEmpty()) {
for (String id : allShopIds) {
......@@ -581,9 +657,9 @@ public class ShopServiceImpl implements ShopService {
shopSummary.setUnbind(unbind.size());
List<String> shopIds = userShopRepository.findByUsername(username).stream()
.map(UserShop::getShopId).collect(Collectors.toList());
.map(UserShop::getShopId).collect(Collectors.toList());
List<String> bind = ipResourceRepository.findShopIdInList(shopIds, false).stream()
.map(IpResource::getId).collect(Collectors.toList());
.map(IpResource::getId).collect(Collectors.toList());
int expired = ipResourceRepository.countByStatusAndIdInAndIsDeleted(1, bind, false);
int willexpired = ipResourceRepository.countByStatusAndIdInAndIsDeleted(2, bind, false);
shopSummary.setExpired(expired);
......@@ -601,9 +677,9 @@ public class ShopServiceImpl implements ShopService {
// 获取当前登录用户绑定了当前商铺的 所有子用户名
List<String> shopUsers = userShopRepository.findByShopId(shopId).stream()
.map(x -> x.getUsername())
.filter(x -> !x.equals(username))
.collect(Collectors.toList());
.map(x -> x.getUsername())
.filter(x -> !x.equals(username))
.collect(Collectors.toList());
return shopUsers;
}
......@@ -740,31 +816,11 @@ public class ShopServiceImpl implements ShopService {
return shopRepository.deleteFavoritesByShopId(shopId, favoriteUrl);
}
private String getShopId(String username, ShopResultDto shopResultDto) {
Shop shop = new Shop();
shopResultDto.setOwner(username);
shop.of(shopResultDto);
shop.setCreateTime(Instant.now().toEpochMilli());
List<ShopUA> all = shopUARepository.findAll();
List<String> uaList = new ArrayList<>();
for (ShopUA shopUA : all) {
uaList.addAll(shopUA.getUaList());
}
if (!uaList.contains(shop.getShopUA())) {
Random random = new Random();
shop.setShopUA(uaList.get(random.nextInt(uaList.size())));
}
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());
.stream().flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(filter, pageable);
}
if (!StringUtils.isEmpty(shopFilterDto.getShopAccount())) {
......
......@@ -10,10 +10,30 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
/**
* 商铺操作
*
* @author JMW
*/
public interface ShopService {
String addShop(String useranme, ShopResultDto shopResultDto);
/**
* 新增店铺操作
*
* @param username username
* @param shopResultDto shopResultDto
* @return id
*/
String addShop(String username, ShopResultDto shopResultDto);
/**
* 批量新增店铺
*
* @param username username
* @param file file
* @return IDS
* @throws IOException IOException
*/
List<String> addShops(String username, MultipartFile file) throws IOException;
String updateShop(String username, ShopResultDto shopResultDto);
......
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