Merge branch 'dev/dev' into release/3.0
This commit is contained in:
File diff suppressed because it is too large
Load Diff
332
src/main/java/com/ai/da/service/impl/AffiliateServiceImpl.java
Normal file
332
src/main/java/com/ai/da/service/impl/AffiliateServiceImpl.java
Normal file
@@ -0,0 +1,332 @@
|
||||
package com.ai.da.service.impl;
|
||||
|
||||
import com.ai.da.common.config.exception.BusinessException;
|
||||
import com.ai.da.common.constant.CommonConstant;
|
||||
import com.ai.da.common.context.UserContext;
|
||||
import com.ai.da.common.response.PageBaseResponse;
|
||||
import com.ai.da.common.response.ResultEnum;
|
||||
import com.ai.da.common.utils.CopyUtil;
|
||||
import com.ai.da.common.utils.RedisUtil;
|
||||
import com.ai.da.common.utils.SendEmailUtil;
|
||||
import com.ai.da.mapper.primary.AffiliateIncomeMapper;
|
||||
import com.ai.da.mapper.primary.AffiliateMapper;
|
||||
import com.ai.da.mapper.primary.SubscriptionInfoMapper;
|
||||
import com.ai.da.mapper.primary.entity.*;
|
||||
import com.ai.da.model.dto.AffiliateEmailParamsDTO;
|
||||
import com.ai.da.model.dto.AffiliateQueryDTO;
|
||||
import com.ai.da.model.vo.AffiliateInvitationDetailsVO;
|
||||
import com.ai.da.model.vo.AffiliateVO;
|
||||
import com.ai.da.model.vo.AuthPrincipalVo;
|
||||
import com.ai.da.service.AccountService;
|
||||
import com.ai.da.service.AffiliateService;
|
||||
import com.ai.da.service.OrderInfoService;
|
||||
import com.ai.da.service.PaymentInfoService;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.mysql.cj.util.StringUtils;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class AffiliateServiceImpl extends ServiceImpl<AffiliateMapper, Affiliate> implements AffiliateService {
|
||||
|
||||
@Resource
|
||||
private OrderInfoService orderInfoService;
|
||||
|
||||
@Resource
|
||||
private AccountService accountService;
|
||||
|
||||
@Resource
|
||||
private PaymentInfoService paymentInfoService;
|
||||
|
||||
@Resource
|
||||
private SubscriptionInfoMapper subscriptionInfoMapper;
|
||||
|
||||
@Resource
|
||||
private AffiliateIncomeMapper affiliateIncomeMapper;
|
||||
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
// 推广者注册
|
||||
public Boolean registerAsAnAffiliate(String promotionMethod){
|
||||
AuthPrincipalVo userHolder = UserContext.getUserHolder();
|
||||
// 判断该用户是否已注册
|
||||
QueryWrapper<Affiliate> qw = new QueryWrapper<>();
|
||||
qw.eq("account_id", userHolder.getId());
|
||||
Affiliate affiliate = baseMapper.selectOne(qw);
|
||||
if (Objects.isNull(affiliate)){
|
||||
affiliate = new Affiliate();
|
||||
affiliate.setAccountId(userHolder.getId());
|
||||
affiliate.setStatus("Pending");
|
||||
affiliate.setCreateTime(LocalDateTime.now());
|
||||
affiliate.setPromotionMethod(promotionMethod);
|
||||
baseMapper.insert(affiliate);
|
||||
// 邮件通知审批者
|
||||
// String merchantEmail = "kimwong@code-create.com.hk";
|
||||
String developer = "xupei3360@163.com";
|
||||
String[] receiverEmail = {/*merchantEmail, */developer};
|
||||
SendEmailUtil.affiliateEmailReminder(receiverEmail, new AffiliateEmailParamsDTO(userHolder.getUsername(), promotionMethod), "new");
|
||||
}else {
|
||||
throw new BusinessException("You have registered an Affiliate", ResultEnum.PROMPT.getCode());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public PageBaseResponse<AffiliateVO> getAffiliateList(AffiliateQueryDTO affiliateQueryDTO){
|
||||
log.info("parameter => {}", affiliateQueryDTO.toString());
|
||||
|
||||
int offset = (affiliateQueryDTO.getPage() - 1) * affiliateQueryDTO.getSize();
|
||||
List<AffiliateVO> affiliateList = baseMapper.getAffiliateList(affiliateQueryDTO.getStatus(),
|
||||
affiliateQueryDTO.getStartTime(),
|
||||
affiliateQueryDTO.getEndTime(),
|
||||
affiliateQueryDTO.getOrder(),
|
||||
affiliateQueryDTO.getAffiliateId(),
|
||||
affiliateQueryDTO.getSize(),
|
||||
offset
|
||||
);
|
||||
if (CollectionUtils.isEmpty(affiliateList)) {
|
||||
return PageBaseResponse.success(new Page<>());
|
||||
}else {
|
||||
int totalCount = baseMapper.queryAffiliateTotalCount(affiliateQueryDTO.getStatus(),
|
||||
affiliateQueryDTO.getStartTime(),
|
||||
affiliateQueryDTO.getEndTime(),
|
||||
affiliateQueryDTO.getAffiliateId()
|
||||
);
|
||||
IPage<AffiliateVO> orderListVOIPage = new Page<>();
|
||||
Integer size = affiliateQueryDTO.getSize();
|
||||
orderListVOIPage.setSize(size);
|
||||
orderListVOIPage.setRecords(affiliateList);
|
||||
orderListVOIPage.setCurrent(affiliateQueryDTO.getPage());
|
||||
orderListVOIPage.setPages((long)Math.ceil((double) totalCount / size));
|
||||
orderListVOIPage.setTotal(totalCount);
|
||||
return PageBaseResponse.success(orderListVOIPage);
|
||||
}
|
||||
/*QueryWrapper<Affiliate> qw = new QueryWrapper<>();
|
||||
qw.eq(!StringUtils.isNullOrEmpty(affiliateQueryDTO.getStatus()), "status", affiliateQueryDTO.getStatus())
|
||||
.gt(!StringUtils.isNullOrEmpty(affiliateQueryDTO.getStartTime()), "create_time", affiliateQueryDTO.getStartTime())
|
||||
.lt(!StringUtils.isNullOrEmpty(affiliateQueryDTO.getEndTime()), "create_time", affiliateQueryDTO.getEndTime())
|
||||
.eq(!Objects.isNull(affiliateQueryDTO.getAffiliateId()), "id", affiliateQueryDTO.getAffiliateId())
|
||||
.orderByDesc(affiliateQueryDTO.getOrder().equals("DESC"), "create_time");
|
||||
Page<Affiliate> affiliatePage = baseMapper.selectPage(new Page<>(affiliateQueryDTO.getPage(), affiliateQueryDTO.getSize()), qw);
|
||||
affiliatePage.convert((Function<Affiliate, AffiliateVO>) affiliate-> {
|
||||
AffiliateVO affiliateVO = CopyUtil.copyObject(affiliate, AffiliateVO.class);
|
||||
affiliateVO.setUsername();
|
||||
});
|
||||
return affiliatePage;*/
|
||||
}
|
||||
|
||||
public AffiliateVO personalAffiliateCenter(){
|
||||
QueryWrapper<Affiliate> qw = new QueryWrapper<>();
|
||||
Long accountId = UserContext.getUserHolder().getId();
|
||||
qw.eq("account_id", accountId);
|
||||
Affiliate affiliate = baseMapper.selectOne(qw);
|
||||
AffiliateVO affiliateVO = CopyUtil.copyObject(affiliate, AffiliateVO.class);
|
||||
affiliateVO.setLinkViewCount(getAffiliateLinkViewCount(affiliate.getId()));
|
||||
return affiliateVO;
|
||||
}
|
||||
|
||||
public double[] getPersonalMonthlyIncome(int year){
|
||||
Long accountId = UserContext.getUserHolder().getId();
|
||||
List<Map<String, Object>> personalMonthlyIncome = affiliateIncomeMapper.getPersonalMonthlyIncome(accountId, year);
|
||||
double[] commissions = new double[12];
|
||||
personalMonthlyIncome.forEach(income -> {
|
||||
int month = Integer.parseInt(income.get("yearMonth").toString());
|
||||
commissions[month-1] = (double)income.get("totalCommission");
|
||||
});
|
||||
|
||||
return commissions;
|
||||
}
|
||||
|
||||
// 审批申请
|
||||
public Boolean applicationApproval(Long id, Boolean isApproved){
|
||||
Affiliate affiliate = baseMapper.selectById(id);
|
||||
|
||||
// 1、更新db状态
|
||||
if (isApproved){
|
||||
// 更新状态
|
||||
affiliate.setStatus("Active");
|
||||
affiliate.setApproved(true);
|
||||
affiliate.setLink(CommonConstant.AFFILIATE_LINK + affiliate.getId());
|
||||
} else {
|
||||
affiliate.setStatus("Refused");
|
||||
affiliate.setApproved(false);
|
||||
}
|
||||
affiliate.setUpdateTime(LocalDateTime.now());
|
||||
baseMapper.updateById(affiliate);
|
||||
|
||||
// 2、将批准结果邮件通知用户
|
||||
Account account = accountService.getById(affiliate.getAccountId());
|
||||
String[] userEmail = {account.getUserEmail()};
|
||||
String userName = account.getUserName();
|
||||
if (isApproved){
|
||||
SendEmailUtil.affiliateEmailReminder(userEmail, new AffiliateEmailParamsDTO(userName), "accepted");
|
||||
}else {
|
||||
SendEmailUtil.affiliateEmailReminder(userEmail, new AffiliateEmailParamsDTO(userName), "refused");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 定时计算佣金
|
||||
public void updateAffiliateInfoWithPayment(){
|
||||
// id存redis
|
||||
String lastTime = redisUtil.getFromString(RedisUtil.PAYMENT_INFO_LAST_SCAN_TIME);
|
||||
String currentTime = LocalDateTime.now().toString();
|
||||
// 1、查上次更新之后有无新订单
|
||||
QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
|
||||
if (!StringUtil.isNullOrEmpty(lastTime)){
|
||||
queryWrapper.gt("create_time", lastTime);
|
||||
}
|
||||
queryWrapper.eq("type","new").eq("trade_state", "paid");
|
||||
|
||||
List<PaymentInfo> paymentInfos = paymentInfoService.getBaseMapper().selectList(queryWrapper);
|
||||
if (!paymentInfos.isEmpty()){
|
||||
paymentInfos.forEach(paymentInfo -> {
|
||||
// 2、根据order_no查付款用户id
|
||||
OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(paymentInfo.getOrderNo());
|
||||
if (Objects.isNull(orderInfo)){
|
||||
return;
|
||||
}
|
||||
Long accountId = orderInfo.getAccountId();
|
||||
// 3、查该用户之前是否有初次订阅的订单
|
||||
QueryWrapper<OrderInfo> qwOrderInfo = new QueryWrapper<>();
|
||||
qwOrderInfo.eq("account_id", accountId).eq("is_first_subscription", 1);
|
||||
List<OrderInfo> orderInfos = orderInfoService.getBaseMapper().selectList(qwOrderInfo);
|
||||
// 该用户首次订阅(非首次订阅,不分配佣金)
|
||||
if (orderInfos.isEmpty()){
|
||||
// 查询是否绑定affiliateId
|
||||
Account account = accountService.getById(accountId);
|
||||
if (!Objects.isNull(account.getInvitationCode())){
|
||||
log.info("结算订单id为{}的佣金", orderInfo.getId());
|
||||
// 3、若有, 直接更新affiliate的所得
|
||||
Affiliate affiliate = baseMapper.selectById(account.getInvitationCode());
|
||||
Float payerTotal = paymentInfo.getPayerTotal();
|
||||
|
||||
if (payerTotal > 0){
|
||||
// 分配新用户首次订阅所付费用的25%作为佣金
|
||||
BigDecimal commission = BigDecimal.valueOf(payerTotal).multiply(new BigDecimal("0.25"));
|
||||
BigDecimal monthlyEarning = BigDecimal.valueOf(affiliate.getMonthlyEarnings()).add(commission);
|
||||
BigDecimal unpaidEarnings = BigDecimal.valueOf(affiliate.getUnpaidEarnings()).add(commission);
|
||||
int visits = affiliate.getVisits() + 1;
|
||||
affiliate.setMonthlyEarnings(monthlyEarning.floatValue());
|
||||
affiliate.setUnpaidEarnings(unpaidEarnings.floatValue());
|
||||
affiliate.setVisits(visits);
|
||||
affiliate.setUpdateTime(LocalDateTime.now());
|
||||
baseMapper.updateById(affiliate);
|
||||
|
||||
orderInfo.setIsCommissionCalculated((byte)1);
|
||||
|
||||
// 4、添加到t_affiliate_income
|
||||
AffiliateIncome affiliateIncome = new AffiliateIncome();
|
||||
affiliateIncome.setAffiliateId(affiliate.getId());
|
||||
affiliateIncome.setAffiliateAccountId(affiliate.getAccountId());
|
||||
affiliateIncome.setInviteeAccountId(accountId);
|
||||
affiliateIncome.setAmount(payerTotal);
|
||||
affiliateIncome.setPaymentInfoId(paymentInfo.getId());
|
||||
affiliateIncome.setPaymentTime(paymentInfo.getCreateTime());
|
||||
affiliateIncome.setCommission(commission.floatValue());
|
||||
affiliateIncome.setCreateTime(LocalDateTime.now());
|
||||
affiliateIncomeMapper.insert(affiliateIncome);
|
||||
}
|
||||
}
|
||||
orderInfo.setIsFirstSubscription((byte)1);
|
||||
orderInfo.setUpdateTime(LocalDateTime.now());
|
||||
orderInfoService.updateById(orderInfo);
|
||||
}
|
||||
});
|
||||
}
|
||||
redisUtil.addToString(RedisUtil.PAYMENT_INFO_LAST_SCAN_TIME, currentTime);
|
||||
}
|
||||
|
||||
public Boolean affiliateLinkViewsIncrease(Long affiliateId) {
|
||||
redisUtil.increaseAffiliateLinkViewCount(affiliateId);
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
private Long getAffiliateLinkViewCount(Long affiliateId) {
|
||||
return redisUtil.getAffiliateLinkViewCount(affiliateId);
|
||||
}
|
||||
|
||||
// 查看每个affiliate带来收入的详情
|
||||
@Override
|
||||
public IPage<AffiliateInvitationDetailsVO> getEachAffiliateGeneratedRevenue(AffiliateQueryDTO affiliateQueryDTO) {
|
||||
if (Objects.isNull(affiliateQueryDTO.getAffiliateId())){
|
||||
throw new BusinessException("Please specify the affiliate ID.", ResultEnum.PROMPT.getCode());
|
||||
}
|
||||
|
||||
QueryWrapper<AffiliateIncome> affiliateIncomeQueryWrapper = new QueryWrapper<>();
|
||||
affiliateIncomeQueryWrapper
|
||||
.gt(!StringUtils.isNullOrEmpty(affiliateQueryDTO.getStartTime()), "create_time", affiliateQueryDTO.getStartTime())
|
||||
.lt(!StringUtils.isNullOrEmpty(affiliateQueryDTO.getEndTime()), "create_time", affiliateQueryDTO.getEndTime())
|
||||
.eq(!Objects.isNull(affiliateQueryDTO.getAffiliateId()), "affiliate_id", affiliateQueryDTO.getAffiliateId())
|
||||
.orderByDesc(affiliateQueryDTO.getOrder().equals("DESC"), "create_time");
|
||||
IPage<AffiliateIncome> affiliateIncomePage = affiliateIncomeMapper.selectPage(new Page<>(affiliateQueryDTO.getPage(), affiliateQueryDTO.getSize()), affiliateIncomeQueryWrapper);
|
||||
return affiliateIncomePage.convert((Function<AffiliateIncome, AffiliateInvitationDetailsVO>) affiliateIncome -> {
|
||||
AffiliateInvitationDetailsVO affiliateInvitationDetailsVO = CopyUtil.copyObject(affiliateIncome, AffiliateInvitationDetailsVO.class);
|
||||
affiliateInvitationDetailsVO.setAccountId(affiliateIncome.getInviteeAccountId());
|
||||
affiliateInvitationDetailsVO.setUsername(accountService.getBaseMapper().selectById(affiliateIncome.getInviteeAccountId()).getUserName());
|
||||
affiliateInvitationDetailsVO.setFirstSubscriptionPaymentAmount(affiliateIncome.getAmount());
|
||||
affiliateInvitationDetailsVO.setCommission(affiliateIncome.getCommission());
|
||||
affiliateInvitationDetailsVO.setTime(affiliateIncome.getPaymentTime());
|
||||
return affiliateInvitationDetailsVO;
|
||||
});
|
||||
}
|
||||
|
||||
public void commissionCalculation(Integer year, Integer month) {
|
||||
if (Objects.isNull(year)) {
|
||||
year = LocalDateTime.now().getYear();
|
||||
}
|
||||
if (Objects.isNull(month)) {
|
||||
month = LocalDateTime.now().getMonthValue();
|
||||
}
|
||||
|
||||
List<Map<String, Object>> monthlyAffiliateIncome = affiliateIncomeMapper.getMonthlyAffiliateIncome(year, month);
|
||||
// 1、总收入(近一个月通过affiliate产生的收入),未支付的金额 affiliate表中unpaid的总和
|
||||
Double totalAmount = 0.0;
|
||||
Double totalCommission = 0.0;
|
||||
if (!monthlyAffiliateIncome.isEmpty()){
|
||||
Map<String, Object> monthlyIncome = monthlyAffiliateIncome.get(0);
|
||||
totalAmount = (Double) monthlyIncome.get("totalAmount");
|
||||
totalCommission = (Double) monthlyIncome.get("totalCommission");
|
||||
}
|
||||
|
||||
// 2、本月新注册的Affiliate
|
||||
Map<String, Long> monthlyApprovedAffiliate = baseMapper.getMonthlyApprovedAffiliate(year, month);
|
||||
Long count = monthlyApprovedAffiliate.get("count");
|
||||
|
||||
AffiliateEmailParamsDTO affiliateEmailParamsDTO = new AffiliateEmailParamsDTO();
|
||||
affiliateEmailParamsDTO.setTotalProgramRevenue(totalAmount.toString());
|
||||
affiliateEmailParamsDTO.setNewApprovedAffiliates(count.toString());
|
||||
affiliateEmailParamsDTO.setUnpaidEarnings(totalCommission.toString());
|
||||
affiliateEmailParamsDTO.setPaidEarnings("0");
|
||||
|
||||
// String merchantEmail = "kimwong@code-create.com.hk";
|
||||
String developer = "xupei3360@163.com";
|
||||
String[] receiverEmail = {/*merchantEmail, */developer};
|
||||
// 邮件通知
|
||||
SendEmailUtil.affiliateEmailReminder(receiverEmail, affiliateEmailParamsDTO, "summary");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Affiliate getByAccountId(Long accountId) {
|
||||
QueryWrapper<Affiliate> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("account_id", accountId).orderByDesc("id").last("limit 1");
|
||||
|
||||
return baseMapper.selectOne(queryWrapper);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import com.ai.da.common.enums.OrderStatusEnum;
|
||||
import com.ai.da.common.enums.PayTypeEnum;
|
||||
import com.ai.da.mapper.primary.entity.OrderInfo;
|
||||
import com.ai.da.mapper.primary.entity.RefundInfo;
|
||||
import com.ai.da.model.dto.ProductPurchaseDTO;
|
||||
import com.ai.da.service.*;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
@@ -23,6 +24,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -54,21 +56,21 @@ public class AliPayServiceImpl implements AliPayService {
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
public String tradeCreate(Integer amount, String returnUrl) {
|
||||
public String tradeCreate(ProductPurchaseDTO productPurchaseDTO, HttpServletRequest request) {
|
||||
|
||||
try {
|
||||
//生成订单
|
||||
log.info("生成订单");
|
||||
OrderInfo orderInfo = orderInfoService.createOrderByProductId(amount, PayTypeEnum.ALIPAY.getType());
|
||||
OrderInfo orderInfo = orderInfoService.createOrderByProductId(productPurchaseDTO.getQuantity(), PayTypeEnum.ALIPAY.getType(), request);
|
||||
|
||||
//调用支付宝接口
|
||||
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
|
||||
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
|
||||
//配置需要的公共请求参数
|
||||
//支付完成后,支付宝发起异步通知的地址
|
||||
request.setNotifyUrl(config.getProperty("alipay.notify-url"));
|
||||
alipayRequest.setNotifyUrl(config.getProperty("alipay.notify-url"));
|
||||
//支付完成后,我们想让页面跳转回aida的页面,配置returnUrl
|
||||
// request.setReturnUrl(config.getProperty("alipay.return-url"));
|
||||
request.setReturnUrl(returnUrl);
|
||||
// alipayRequest.setReturnUrl(config.getProperty("alipay.return-url"));
|
||||
alipayRequest.setReturnUrl(productPurchaseDTO.getReturnUrl());
|
||||
|
||||
//组装当前业务方法的请求参数
|
||||
JSONObject bizContent = new JSONObject();
|
||||
@@ -79,10 +81,10 @@ public class AliPayServiceImpl implements AliPayService {
|
||||
bizContent.put("subject", "积分购买");
|
||||
bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
|
||||
|
||||
request.setBizContent(bizContent.toString());
|
||||
alipayRequest.setBizContent(bizContent.toString());
|
||||
|
||||
//执行请求,调用支付宝接口
|
||||
AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
|
||||
AlipayTradePagePayResponse response = alipayClient.pageExecute(alipayRequest);
|
||||
|
||||
if(response.isSuccess()){
|
||||
log.info("调用成功,返回结果 ===> " + response.getBody());
|
||||
@@ -209,7 +211,7 @@ public class AliPayServiceImpl implements AliPayService {
|
||||
//更新订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.SUCCESS);
|
||||
//记录支付日志
|
||||
paymentInfoService.createPaymentInfoForAliPay(params);
|
||||
paymentInfoService.createPaymentInfoForAliPay(params,"credits");
|
||||
float quantity = Float.parseFloat(totalAmount) / Float.parseFloat(CreditsEventsEnum.PRICE.getValue());
|
||||
// 更新积分
|
||||
creditsService.buyCredits(orderByOrderNo.getAccountId(), quantity);
|
||||
@@ -217,7 +219,8 @@ public class AliPayServiceImpl implements AliPayService {
|
||||
creditsService.insertToCreditsDetail(orderByOrderNo.getAccountId(),
|
||||
CreditsEventsEnum.BUY_CREDITS.getName() + "--Alipay",
|
||||
String.valueOf((Long.parseLong(CreditsEventsEnum.BUY_CREDITS.getValue()) * quantity)),
|
||||
"positive");
|
||||
"positive",
|
||||
orderByOrderNo.getOrderNo());
|
||||
} finally {
|
||||
//要主动释放锁
|
||||
lock.unlock();
|
||||
@@ -312,7 +315,7 @@ public class AliPayServiceImpl implements AliPayService {
|
||||
//如果订单已支付,则更新商户端订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.SUCCESS);
|
||||
//并记录支付日志
|
||||
paymentInfoService.createPaymentInfoForAliPay(alipayTradeQueryResponse);
|
||||
paymentInfoService.createPaymentInfoForAliPay(alipayTradeQueryResponse, "credits");
|
||||
float quantity = orderByOrderNo.getTotalFee() / Float.parseFloat(CreditsEventsEnum.PRICE.getValue());
|
||||
// 更新积分
|
||||
creditsService.buyCredits(orderByOrderNo.getAccountId(), quantity);
|
||||
@@ -320,7 +323,8 @@ public class AliPayServiceImpl implements AliPayService {
|
||||
creditsService.insertToCreditsDetail(orderByOrderNo.getAccountId(),
|
||||
CreditsEventsEnum.BUY_CREDITS.getName() + "--Alipay",
|
||||
String.valueOf((Long.parseLong(CreditsEventsEnum.BUY_CREDITS.getValue()) * quantity)),
|
||||
"positive");
|
||||
"positive",
|
||||
orderByOrderNo.getOrderNo());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -393,7 +397,7 @@ public class AliPayServiceImpl implements AliPayService {
|
||||
// 更新积分状态
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
// creditsService.creditsRefund(orderByOrderNo.getAccountId(), orderByOrderNo.getTotalFee() / Integer.parseInt(CreditsEventsEnum.PRICE.getValue()));
|
||||
creditsService.creditsRefund(orderByOrderNo.getAccountId(), (int)(orderByOrderNo.getTotalFee() / Float.parseFloat(CreditsEventsEnum.PRICE.getValue())));
|
||||
creditsService.creditsRefund(orderByOrderNo.getAccountId(), (int)(orderByOrderNo.getTotalFee() / Float.parseFloat(CreditsEventsEnum.PRICE.getValue())), orderNo);
|
||||
|
||||
} else {
|
||||
log.info("调用失败,返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
|
||||
|
||||
@@ -6,9 +6,12 @@ import com.ai.da.common.enums.OrderStatusEnum;
|
||||
import com.ai.da.common.enums.PayTypeEnum;
|
||||
import com.ai.da.common.utils.AlipayHKEncryptionUtil;
|
||||
import com.ai.da.common.utils.AlipayHKRequestUtil;
|
||||
import com.ai.da.common.utils.SendEmailUtil;
|
||||
import com.ai.da.mapper.primary.AccountMapper;
|
||||
import com.ai.da.mapper.primary.entity.OrderInfo;
|
||||
import com.ai.da.model.dto.AlipayHKCallbackDTO;
|
||||
import com.ai.da.model.dto.AlipayHKRequestDTO;
|
||||
import com.ai.da.model.dto.ProductPurchaseDTO;
|
||||
import com.ai.da.service.*;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
@@ -18,6 +21,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
@@ -54,29 +58,31 @@ public class AlipayHKServiceImpl implements AlipayHKService {
|
||||
private AlipayHKEncryptionUtil alipayHKEncryptionUtil;
|
||||
@Resource
|
||||
private AlipayHKRequestUtil alipayHKRequestUtil;
|
||||
@Resource
|
||||
private AccountMapper accountMapper;
|
||||
|
||||
|
||||
/**
|
||||
* 创建订单
|
||||
*/
|
||||
@Override
|
||||
public String createOrder(Integer amount, String wallet){
|
||||
public String createOrder(ProductPurchaseDTO productPurchaseDTO, HttpServletRequest request){
|
||||
|
||||
try{
|
||||
HashMap<String, Object> param = new HashMap<>();
|
||||
String orderRef = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
|
||||
param.put("order_ref", orderRef);
|
||||
param.put("amount", Float.parseFloat(CreditsEventsEnum.PRICE.getValue()) * amount);
|
||||
param.put("amount", Float.parseFloat(CreditsEventsEnum.PRICE.getValue()) * productPurchaseDTO.getQuantity());
|
||||
param.put("subject", "AiDA Credits Purchase");
|
||||
// ALIPAYHK 或者 ALIPAYCN
|
||||
param.put("wallet", wallet);
|
||||
param.put("wallet", productPurchaseDTO.getWallet());
|
||||
param.put("segment_id", segmentId);
|
||||
// param.put("payment_solution", "WAP");
|
||||
param.put("payment_solution", "PC2MOBILE");
|
||||
log.info("alipay-hk 创建订单,参数信息: {}", param);
|
||||
// 生成订单
|
||||
log.info("创建订单");
|
||||
OrderInfo orderInfo = orderInfoService.createOrderByProductId(amount, PayTypeEnum.ALIPAY_HK.getType());
|
||||
OrderInfo orderInfo = orderInfoService.createOrderByProductId(productPurchaseDTO.getQuantity(), PayTypeEnum.ALIPAY_HK.getType(), request);
|
||||
/*// 加密
|
||||
AlipayHKRequestDTO alipayHKRequestDTO = alipayHKEncryptionUtil.AESCBCWithRSA(param, AlipayHKConstant.CREATE_ORDER);
|
||||
// 请求Alipay服务端
|
||||
@@ -239,7 +245,7 @@ public class AlipayHKServiceImpl implements AlipayHKService {
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.SUCCESS);
|
||||
log.info("Alipay-HK 订单:{} 状态更新成功",orderNo);
|
||||
//记录支付日志
|
||||
paymentInfoService.createPaymentInfoForAliPayHK(alipayHKCallbackDTO);
|
||||
paymentInfoService.createPaymentInfoForAliPayHK(alipayHKCallbackDTO, "credits");
|
||||
log.info("Alipay-HK 订单:{} 支付信息状态更新成功",orderNo);
|
||||
float quantity = Float.parseFloat(totalAmount) / Float.parseFloat(CreditsEventsEnum.PRICE.getValue());
|
||||
// 更新积分
|
||||
@@ -248,8 +254,12 @@ public class AlipayHKServiceImpl implements AlipayHKService {
|
||||
creditsService.insertToCreditsDetail(orderByOrderNo.getAccountId(),
|
||||
CreditsEventsEnum.BUY_CREDITS.getName() + "--AlipayHK",
|
||||
String.valueOf((Long.parseLong(CreditsEventsEnum.BUY_CREDITS.getValue()) * quantity)),
|
||||
"positive");
|
||||
"positive",
|
||||
orderByOrderNo.getOrderNo());
|
||||
log.info("用户:{} 积分信息更新成功",orderByOrderNo.getAccountId());
|
||||
// 填入用户信息,邮件通知Kim
|
||||
String username = accountMapper.selectById(orderByOrderNo.getAccountId()).getUserName();
|
||||
SendEmailUtil.creditsPurchaseReminder(username, String.valueOf(quantity), totalAmount);
|
||||
} finally {
|
||||
//要主动释放锁
|
||||
lock.unlock();
|
||||
|
||||
@@ -216,6 +216,8 @@ public class CollectionElementServiceImpl extends ServiceImpl<CollectionElementM
|
||||
collectionElementMapper.deleteBatchIds(ids);
|
||||
}
|
||||
|
||||
/** 该方法已不再使用 */
|
||||
@Deprecated
|
||||
@Override
|
||||
public GenerateCollectionItemVO generatePrint(CollectionGeneratePrintDTO generatePrintDTO) {
|
||||
Long userId = UserContext.getUserHolder().getId();
|
||||
@@ -607,6 +609,12 @@ public class CollectionElementServiceImpl extends ServiceImpl<CollectionElementM
|
||||
elementVO.setDesignLibraryModelPoint(calculateTemplatePointTemplate(modelPoint, 700, 320, byId.getUrl()));
|
||||
}
|
||||
elementVO.setModelSex(designDTO.getModelSex());
|
||||
elementVO.setRequestIdList(designDTO.getRequestIdList());
|
||||
if (null != designDTO.getDesignNum()) {
|
||||
elementVO.setDesignNum(designDTO.getDesignNum());
|
||||
}else {
|
||||
elementVO.setDesignNum(8);
|
||||
}
|
||||
return elementVO;
|
||||
}
|
||||
|
||||
@@ -908,7 +916,7 @@ public class CollectionElementServiceImpl extends ServiceImpl<CollectionElementM
|
||||
generate.setAccountId(userId);
|
||||
generate.setLevel1Type(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName());
|
||||
generate.setGenerateType("synthesis");
|
||||
generate.setModelName("Image Synthesis Model");
|
||||
// generate.setModelName("Image Synthesis Model");
|
||||
generate.setCreateDate(DateUtil.getByTimeZone(timeZone));
|
||||
return generate;
|
||||
}
|
||||
|
||||
@@ -9,13 +9,19 @@ import com.ai.da.common.utils.DateUtil;
|
||||
import com.ai.da.common.utils.MinioUtil;
|
||||
import com.ai.da.common.utils.RedisUtil;
|
||||
import com.ai.da.mapper.primary.CollectionMapper;
|
||||
import com.ai.da.mapper.primary.MoodboardPositionMapper;
|
||||
import com.ai.da.mapper.primary.entity.Collection;
|
||||
import com.ai.da.mapper.primary.entity.CollectionElement;
|
||||
import com.ai.da.mapper.primary.entity.MoodboardPosition;
|
||||
import com.ai.da.model.vo.CollectionColorVO;
|
||||
import com.ai.da.model.vo.CollectionElementVO;
|
||||
import com.ai.da.model.vo.UserLikeCollectionVO;
|
||||
import com.ai.da.service.CollectionElementService;
|
||||
import com.ai.da.service.CollectionService;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
@@ -25,6 +31,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -45,6 +52,8 @@ public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collect
|
||||
private CollectionElementService collectionElementService;
|
||||
@Resource
|
||||
private MinioUtil minioUtil;
|
||||
@Resource
|
||||
private MoodboardPositionMapper moodboardPositionMapper;
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
@@ -84,7 +93,12 @@ public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collect
|
||||
if (collection.getMoodTemplateId() != null) {
|
||||
CollectionElement byId = collectionElementService.getById(response.getMoodTemplateId());
|
||||
if (null != collection.getMoodboardPosition()) {
|
||||
response.setMoodboardPosition(collection.getMoodboardPosition());
|
||||
String moodboardPositionString = getMoodboardPositionString(collection.getId());
|
||||
if (StringUtils.isBlank(moodboardPositionString)) {
|
||||
response.setMoodboardPosition(collection.getMoodboardPosition());
|
||||
}else {
|
||||
response.setMoodboardPosition(moodboardPositionString);
|
||||
}
|
||||
}
|
||||
if (Objects.nonNull(byId)) {
|
||||
response.setMoodTemplateName(byId.getName());
|
||||
@@ -147,6 +161,68 @@ public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collect
|
||||
return response;
|
||||
}
|
||||
|
||||
private String getMoodboardPositionString(Long id) {
|
||||
QueryWrapper<MoodboardPosition> qw = new QueryWrapper<>();
|
||||
qw.lambda().eq(MoodboardPosition::getCollectionId, id);
|
||||
List<MoodboardPosition> moodboardPositions = moodboardPositionMapper.selectList(qw);
|
||||
if (moodboardPositions != null && !moodboardPositions.isEmpty()) {
|
||||
// 将查询结果转换为 JSON 字符串
|
||||
JSONObject resultJson = new JSONObject();
|
||||
|
||||
// 遍历 MoodboardPosition 列表,根据实际情况填充到 resultJson 中
|
||||
for (MoodboardPosition position : moodboardPositions) {
|
||||
String type = position.getType();
|
||||
String styleData = position.getStyleData();
|
||||
int sequence = position.getSequence(); // 获取 sequence 值
|
||||
|
||||
// 如果 type 字段为 "class",直接将其作为字符串处理
|
||||
if ("class".equals(type)) {
|
||||
// 如果 type 字段还没有对应的 JSONArray,则初始化它
|
||||
if (!resultJson.containsKey(type)) {
|
||||
resultJson.put(type, new ArrayList<>());
|
||||
}
|
||||
|
||||
// 获取对应类型的列表
|
||||
List<String> classList = (List<String>) resultJson.get(type);
|
||||
|
||||
// 确保列表长度足够,可以容纳 `sequence` 索引
|
||||
while (classList.size() <= sequence) {
|
||||
classList.add(""); // 添加空字符串,直到长度大于 `sequence`
|
||||
}
|
||||
|
||||
// 将 class 字段直接存入列表
|
||||
classList.set(sequence, styleData); // 根据 sequence 设置数据
|
||||
|
||||
resultJson.put(type, classList);
|
||||
} else {
|
||||
// 如果 type 字段为其他类型,按照正常方式处理
|
||||
if (!resultJson.containsKey(type)) {
|
||||
resultJson.put(type, new ArrayList<>());
|
||||
}
|
||||
|
||||
// 获取对应类型的列表
|
||||
List<JSONObject> styleList = (List<JSONObject>) resultJson.get(type);
|
||||
|
||||
// 确保列表长度足够,可以容纳 `sequence` 索引
|
||||
while (styleList.size() <= sequence) {
|
||||
styleList.add(new JSONObject()); // 添加空的 JSONObject,直到长度大于 `sequence`
|
||||
}
|
||||
|
||||
// 将解析的样式数据存入正确的索引位置
|
||||
JSONObject styleObject = JSON.parseObject(styleData);
|
||||
styleList.set(sequence, styleObject); // 根据 sequence 设置数据
|
||||
|
||||
resultJson.put(type, styleList);
|
||||
}
|
||||
}
|
||||
|
||||
// 将最终结果转换为字符串
|
||||
return resultJson.toJSONString();
|
||||
} else {
|
||||
return null; // 返回空的 JSON 对象
|
||||
}
|
||||
}
|
||||
|
||||
private List<CollectionColorVO> resolveColorBoard(List<CollectionElement> collectionElements) {
|
||||
return CopyUtil.copyList(collectionElements, CollectionColorVO.class, (o, d) -> {
|
||||
String name = o.getName();
|
||||
|
||||
@@ -4,19 +4,18 @@ import com.ai.da.common.config.exception.BusinessException;
|
||||
import com.ai.da.common.constant.CommonConstant;
|
||||
import com.ai.da.common.context.UserContext;
|
||||
import com.ai.da.common.enums.CreditsEventsEnum;
|
||||
import com.ai.da.common.response.PageBaseResponse;
|
||||
import com.ai.da.common.utils.CopyUtil;
|
||||
import com.ai.da.mapper.primary.AccountMapper;
|
||||
import com.ai.da.mapper.primary.QuestionnaireMapper;
|
||||
import com.ai.da.mapper.primary.ToProductImageResultMapper;
|
||||
import com.ai.da.mapper.primary.TrialOrderMapper;
|
||||
import com.ai.da.common.utils.DateUtil;
|
||||
import com.ai.da.common.utils.MinioUtil;
|
||||
import com.ai.da.mapper.primary.*;
|
||||
import com.ai.da.mapper.primary.entity.Account;
|
||||
import com.ai.da.mapper.primary.entity.Questionnaire;
|
||||
import com.ai.da.mapper.primary.entity.TrialOrder;
|
||||
import com.ai.da.model.dto.AccountAddDTO;
|
||||
import com.ai.da.model.dto.QueryPaymentInfoDTO;
|
||||
import com.ai.da.model.enums.Language;
|
||||
import com.ai.da.model.vo.QuestionnaireFeedbackVO;
|
||||
import com.ai.da.model.vo.QuestionnaireVO;
|
||||
import com.ai.da.model.vo.QueryUserConditionsVO;
|
||||
import com.ai.da.model.vo.*;
|
||||
import com.ai.da.service.*;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
@@ -24,14 +23,26 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.mysql.cj.util.StringUtils;
|
||||
import io.minio.GetPresignedObjectUrlArgs;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
import io.minio.errors.*;
|
||||
import io.minio.http.Method;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.poi.xssf.usermodel.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
@@ -43,9 +54,25 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl<QuestionnaireMappe
|
||||
|
||||
@Resource
|
||||
private AccountService accountService;
|
||||
|
||||
@Resource
|
||||
private AccountLoginLogService accountLoginLogService;
|
||||
@Resource
|
||||
private GenerateService generateService;
|
||||
@Resource
|
||||
private ToProductImageResultMapper toProductImageResultMapper;
|
||||
@Resource
|
||||
private DesignService designService;
|
||||
@Resource
|
||||
private DesignItemService designItemService;
|
||||
@Resource
|
||||
private ChatRobotService chatRobotService;
|
||||
@Resource
|
||||
private TrialOrderMapper trialOrderMapper;
|
||||
@Resource
|
||||
private PaymentInfoMapper paymentInfoMapper;
|
||||
|
||||
@Value("${minio.bucketName.users}")
|
||||
private String userBucket;
|
||||
|
||||
public IPage<TrialOrder> getTrial(QueryUserConditionsVO queryUserConditionsVO) {
|
||||
log.info("getTrial parameter : {},page:{}, size:{}", queryUserConditionsVO, queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize());
|
||||
@@ -211,45 +238,6 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl<QuestionnaireMappe
|
||||
return questionnaireVOS;
|
||||
}
|
||||
|
||||
|
||||
// 输出为pdf 需要自己组装pdf内容
|
||||
// 解决iText不显示中文问题
|
||||
/*public static void main(String[] args) {
|
||||
try {
|
||||
// 创建文档
|
||||
Document document = new Document();
|
||||
PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
|
||||
document.open();
|
||||
|
||||
// 加载字体文件
|
||||
InputStream inputStream = ConvenientInquiryServiceImpl.class.getResourceAsStream("/font/msyhl.ttc");
|
||||
byte[] fontBytes = toByteArray(inputStream);
|
||||
inputStream.close();
|
||||
|
||||
// 创建BaseFont和Font对象
|
||||
BaseFont baseFont = BaseFont.createFont("msyhl.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, fontBytes, null);
|
||||
Font yaHeiFont = new Font(baseFont, 12, Font.NORMAL);
|
||||
|
||||
// 添加带有中文字体的段落
|
||||
document.add(new Paragraph("你好,世界!", yaHeiFont));
|
||||
|
||||
document.close();
|
||||
} catch (DocumentException | IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// 将InputStream转换为字节数组
|
||||
public static byte[] toByteArray(InputStream input) throws IOException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
int n = 0;
|
||||
while (-1 != (n = input.read(buffer))) {
|
||||
output.write(buffer, 0, n);
|
||||
}
|
||||
return output.toByteArray();
|
||||
}*/
|
||||
|
||||
/**
|
||||
* 近期新增用户
|
||||
*/
|
||||
@@ -323,17 +311,6 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl<QuestionnaireMappe
|
||||
return accountIds.size();
|
||||
}
|
||||
|
||||
@Resource
|
||||
private GenerateService generateService;
|
||||
@Resource
|
||||
private ToProductImageResultMapper toProductImageResultMapper;
|
||||
@Resource
|
||||
private DesignService designService;
|
||||
@Resource
|
||||
private DesignItemService designItemService;
|
||||
@Resource
|
||||
private ChatRobotService chatRobotService;
|
||||
|
||||
public Map<String, List<Object>> getActiveUserFunc(String startTime, String endTime, List<Long> ids) {
|
||||
|
||||
log.info("getActiveUserFunc ==> startTime:{}, endTime:{}, accountList:{}", startTime, endTime, ids);
|
||||
@@ -388,9 +365,6 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl<QuestionnaireMappe
|
||||
return resp;
|
||||
}
|
||||
|
||||
@Resource
|
||||
private TrialOrderMapper trialOrderMapper;
|
||||
|
||||
// 试用用户到正式用户的转化率
|
||||
public Map<String, Object> conversionRate(String startTime, String endTime) {
|
||||
|
||||
@@ -457,7 +431,6 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl<QuestionnaireMappe
|
||||
return resp;
|
||||
}
|
||||
|
||||
|
||||
// 新增用户
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Boolean addUser(AccountAddDTO accountAddDTO) {
|
||||
@@ -618,5 +591,217 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl<QuestionnaireMappe
|
||||
// return maps.stream().map(map -> (Long)map.get("id")).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询交易记录
|
||||
* 允许按日期,支付方式,支付金额,商品种类,交易状态,付款人的国家或城市查询,需要分页查询
|
||||
*/
|
||||
public PageBaseResponse<PaymentInfoVO> queryTransactionRecords(QueryPaymentInfoDTO queryPaymentInfoDTO) {
|
||||
Integer size = queryPaymentInfoDTO.getSize();
|
||||
int offset = (queryPaymentInfoDTO.getPage() - 1) * size;
|
||||
String order = "DESC";
|
||||
if (!StringUtil.isNullOrEmpty(queryPaymentInfoDTO.getOrder()) && queryPaymentInfoDTO.getOrder().equals("ASC")) {
|
||||
order = "ASC";
|
||||
}
|
||||
List<PaymentInfoVO> paymentInfoVOS = paymentInfoMapper.queryPaymentInfo(queryPaymentInfoDTO.getPlatform(), queryPaymentInfoDTO.getPayerTotal(),
|
||||
queryPaymentInfoDTO.getType(), queryPaymentInfoDTO.getStatus(),
|
||||
queryPaymentInfoDTO.getCountry(), queryPaymentInfoDTO.getCity(),
|
||||
queryPaymentInfoDTO.getStartTime(), queryPaymentInfoDTO.getEndTime(),
|
||||
size, offset, order, queryPaymentInfoDTO.getPayer());
|
||||
// 查询数据总量
|
||||
Long total = paymentInfoMapper.queryPaymentInfoCount(queryPaymentInfoDTO.getPlatform(), queryPaymentInfoDTO.getPayerTotal(),
|
||||
queryPaymentInfoDTO.getType(), queryPaymentInfoDTO.getStatus(),
|
||||
queryPaymentInfoDTO.getCountry(), queryPaymentInfoDTO.getCity(),
|
||||
queryPaymentInfoDTO.getStartTime(), queryPaymentInfoDTO.getEndTime(), queryPaymentInfoDTO.getPayer());
|
||||
|
||||
// 总页数
|
||||
double totalPage = Math.ceil((double) total / size);
|
||||
// 组装返回参数
|
||||
PageBaseResponse<PaymentInfoVO> response = new PageBaseResponse<>();
|
||||
response.setContent(paymentInfoVOS);
|
||||
response.setPage(queryPaymentInfoDTO.getPage());
|
||||
response.setSize(size);
|
||||
response.setTotal(total);
|
||||
response.setPages((long) totalPage);
|
||||
return response;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> getCities(){
|
||||
List<Map<String, String>> cities = paymentInfoMapper.getCities();
|
||||
List<Map<String, String>> countries = paymentInfoMapper.getCountries();
|
||||
List<String> cityCollect = cities.stream()
|
||||
.map(cityEntry -> cityEntry.get("city"))
|
||||
.collect(Collectors.toList());
|
||||
List<String> countryCollect = countries.stream()
|
||||
.map(cityEntry -> cityEntry.get("country"))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new HashMap<String, List<String>>() {{
|
||||
put("city", cityCollect);
|
||||
put("country", countryCollect);
|
||||
}};
|
||||
}
|
||||
|
||||
public String exportTransactionRecords(QueryPaymentInfoDTO queryPaymentInfoDTO, HttpServletResponse response){
|
||||
// QueryPaymentInfoDTO queryPaymentInfoDTO = JSONObject.parseObject(params, QueryPaymentInfoDTO.class);
|
||||
|
||||
// 查询数据总量
|
||||
Long total = paymentInfoMapper.queryPaymentInfoCount(queryPaymentInfoDTO.getPlatform(), queryPaymentInfoDTO.getPayerTotal(),
|
||||
queryPaymentInfoDTO.getType(), queryPaymentInfoDTO.getStatus(),
|
||||
queryPaymentInfoDTO.getCountry(), queryPaymentInfoDTO.getCity(),
|
||||
queryPaymentInfoDTO.getStartTime(), queryPaymentInfoDTO.getEndTime(), queryPaymentInfoDTO.getPayer());
|
||||
List<PaymentInfoVO> paymentInfoVOS = paymentInfoMapper.queryPaymentInfo(queryPaymentInfoDTO.getPlatform(), queryPaymentInfoDTO.getPayerTotal(),
|
||||
queryPaymentInfoDTO.getType(), queryPaymentInfoDTO.getStatus(),
|
||||
queryPaymentInfoDTO.getCountry(), queryPaymentInfoDTO.getCity(),
|
||||
queryPaymentInfoDTO.getStartTime(), queryPaymentInfoDTO.getEndTime(),
|
||||
total.intValue(), 0, "ASC", queryPaymentInfoDTO.getPayer());
|
||||
try {
|
||||
return excelExport(paymentInfoVOS, response);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Resource
|
||||
private MinioClient minioClient;
|
||||
|
||||
public String excelExport(List<PaymentInfoVO> paymentInfoVOS, HttpServletResponse response) throws IOException {
|
||||
if (paymentInfoVOS == null || paymentInfoVOS.isEmpty()) {
|
||||
log.info("无数据,直接返回,不生成空文件");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 文件名称
|
||||
String time = DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_hh_mm_ss);
|
||||
String fileName = "paymentInfo_" + time + ".xlsx";
|
||||
|
||||
// 创建Excel文件
|
||||
try (XSSFWorkbook workBook = new XSSFWorkbook()) {
|
||||
// 创建Excel工作表(Table),之后的数据都添加到该表中
|
||||
XSSFSheet sheet = workBook.createSheet("数据导出");
|
||||
// 设置列宽
|
||||
sheet.setDefaultColumnWidth(16);
|
||||
|
||||
// 创建标题行
|
||||
XSSFRow titleRow = sheet.createRow(0);
|
||||
String[] title = new String[]{"id", "payer", "platform", "payerTotal", "type", "status",
|
||||
"country", "city", "paymentMethod", "last4", "createTime"};
|
||||
//设置标题字体样式
|
||||
XSSFCellStyle cellStyle = workBook.createCellStyle();
|
||||
XSSFFont font = workBook.createFont();
|
||||
font.setBold(true);//加粗
|
||||
font.setFontHeightInPoints((short) 14);//设置字体大小
|
||||
cellStyle.setFont(font);
|
||||
//设置标题列
|
||||
for (int i = 0; i < title.length; i++) {
|
||||
//创建标题的单元格
|
||||
XSSFCell titleCell = titleRow.createCell(i);
|
||||
//填充标题数值
|
||||
titleCell.setCellValue(title[i]);
|
||||
//设置样式
|
||||
titleCell.setCellStyle(cellStyle);
|
||||
}
|
||||
|
||||
// 填充数据
|
||||
//第一行是标题所以要从第二行开始
|
||||
for (int i = 0; i < paymentInfoVOS.size(); i++) {
|
||||
PaymentInfoVO paymentInfoVO = paymentInfoVOS.get(i);
|
||||
XSSFRow row = sheet.createRow(i + 1);
|
||||
for (int j = 0; j < title.length; j++) {
|
||||
XSSFCell cell = row.createCell(j);
|
||||
String exportKey = title[j];
|
||||
switch (exportKey) {
|
||||
case "id":
|
||||
cell.setCellValue(paymentInfoVO.getId());
|
||||
break;
|
||||
case "payer":
|
||||
cell.setCellValue(paymentInfoVO.getPayer());
|
||||
break;
|
||||
case "platform":
|
||||
cell.setCellValue(paymentInfoVO.getPlatform());
|
||||
break;
|
||||
case "payerTotal":
|
||||
cell.setCellValue(paymentInfoVO.getPayerTotal());
|
||||
break;
|
||||
case "type":
|
||||
cell.setCellValue(paymentInfoVO.getType());
|
||||
break;
|
||||
case "status":
|
||||
cell.setCellValue(paymentInfoVO.getStatus());
|
||||
break;
|
||||
case "country":
|
||||
cell.setCellValue(paymentInfoVO.getCountry());
|
||||
break;
|
||||
case "city":
|
||||
cell.setCellValue(paymentInfoVO.getCity());
|
||||
break;
|
||||
case "paymentMethod":
|
||||
cell.setCellValue(paymentInfoVO.getPaymentMethod());
|
||||
break;
|
||||
case "last4":
|
||||
cell.setCellValue(paymentInfoVO.getLast4());
|
||||
break;
|
||||
case "createTime":
|
||||
cell.setCellValue(paymentInfoVO.getCreateTime());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 将workBook转换为字节数组 直接以文件流的形式返回
|
||||
/*try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
|
||||
workBook.write(byteArrayOutputStream);
|
||||
byte[] bytes = byteArrayOutputStream.toByteArray();
|
||||
|
||||
// 设置响应头
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
|
||||
|
||||
// 将字节数组写入响应流
|
||||
try (OutputStream responseOut = response.getOutputStream()) {
|
||||
responseOut.write(bytes);
|
||||
responseOut.flush();
|
||||
}
|
||||
}*/
|
||||
|
||||
String filePath = UserContext.getUserHolder().getId() + "/transactionDownload" + "/" + fileName;
|
||||
// 将workBook转换为字节数组
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
workBook.write(byteArrayOutputStream);
|
||||
byte[] bytes = byteArrayOutputStream.toByteArray();
|
||||
|
||||
// 上传到 MinIO
|
||||
try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
|
||||
try {
|
||||
minioClient.putObject(PutObjectArgs.builder()
|
||||
.bucket(userBucket)
|
||||
.object(filePath)
|
||||
.stream(inputStream, bytes.length, -1)
|
||||
.contentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
.build());
|
||||
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} catch (MinioException e) {
|
||||
log.error("文件上传失败: " + e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// 获取下载链接
|
||||
String downloadUrl = null;
|
||||
try {
|
||||
downloadUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
|
||||
.bucket(userBucket)
|
||||
.object(filePath)
|
||||
.method(Method.GET)
|
||||
.expiry(60 * 60 * 24) // 设置链接有效期为24小时
|
||||
.build());
|
||||
} catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
|
||||
InvalidResponseException | NoSuchAlgorithmException | XmlParserException | ServerException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return downloadUrl; // 返回下载链接
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
|
||||
return account.getCredits().toString();
|
||||
}
|
||||
|
||||
public void creditsRefund(Long accountId, Integer quantity) {
|
||||
public void creditsRefund(Long accountId, Integer quantity, String orderNo) {
|
||||
BigDecimal existingCredits = accountMapper.selectById(accountId).getCredits();
|
||||
BigDecimal newCredits = new BigDecimal(CreditsEventsEnum.BUY_CREDITS.getValue()).multiply(new BigDecimal(quantity));
|
||||
BigDecimal subtracted = existingCredits.subtract(newCredits);
|
||||
@@ -111,7 +111,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
|
||||
insertToCreditsDetail(accountId,
|
||||
CreditsEventsEnum.REFUND.getName() + "--Stripe",
|
||||
String.valueOf((Long.parseLong(CreditsEventsEnum.BUY_CREDITS.getValue()) * quantity)),
|
||||
"negative");
|
||||
"negative", orderNo);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,7 +122,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
|
||||
* @param changeType 变更类型 : positive->增 negative->减
|
||||
*/
|
||||
@Override
|
||||
public void insertToCreditsDetail(Long accountId, String changeEvent, String credits, String changeType) {
|
||||
public void insertToCreditsDetail(Long accountId, String changeEvent, String credits, String changeType, String orderNo) {
|
||||
CreditsDetail creditsDetail = new CreditsDetail();
|
||||
Account account = accountMapper.selectById(accountId);
|
||||
// BigDecimal finalCredits;
|
||||
@@ -137,6 +137,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
|
||||
creditsDetail.setAccountId(accountId);
|
||||
creditsDetail.setChangeEvent(changeEvent);
|
||||
creditsDetail.setChangedCredits(changeCredits);
|
||||
creditsDetail.setTaskId(orderNo);
|
||||
// creditsDetail.setCredits(finalCredits);
|
||||
creditsDetail.setCredits(account.getCredits());
|
||||
creditsDetail.setCreateTime(LocalDateTime.now());
|
||||
|
||||
@@ -8,9 +8,7 @@ import com.ai.da.common.constant.CommonConstant;
|
||||
import com.ai.da.common.context.UserContext;
|
||||
import com.ai.da.common.enums.*;
|
||||
import com.ai.da.common.utils.*;
|
||||
import com.ai.da.mapper.primary.DesignMapper;
|
||||
import com.ai.da.mapper.primary.GenerateDetailMapper;
|
||||
import com.ai.da.mapper.primary.TDesignPythonOutfitMapper;
|
||||
import com.ai.da.mapper.primary.*;
|
||||
import com.ai.da.mapper.primary.entity.*;
|
||||
import com.ai.da.mapper.primary.entity.Collection;
|
||||
import com.ai.da.model.dto.*;
|
||||
@@ -41,6 +39,7 @@ import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -95,6 +94,9 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
@Resource
|
||||
private TDesignPythonOutfitMapper designPythonOutfitMapper;
|
||||
|
||||
@Resource
|
||||
private MoodboardPositionMapper moodboardPositionMapper;
|
||||
|
||||
@Value("${minio.endpoint}")
|
||||
private String endpoint;
|
||||
@Value("${minio.bucketName.results}")
|
||||
@@ -109,8 +111,17 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
@Resource
|
||||
private DesignBatchMapper designBatchMapper;
|
||||
|
||||
@Resource
|
||||
private UserLikeSortMapper userLikeSortMapper;
|
||||
|
||||
private final ConcurrentHashMap<String, Map<String, Object>> designContext = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
@Override
|
||||
public DesignCollectionVO designCollection(DesignCollectionDTO designDTO) {
|
||||
public String designCollection(DesignCollectionDTO designDTO) {
|
||||
AuthPrincipalVo userInfo = UserContext.getUserHolder();
|
||||
//校验collection element
|
||||
ValidateElementVO elementVO = collectionElementService.validateElement(designDTO);
|
||||
@@ -283,8 +294,8 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
// return saveDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone());
|
||||
// }
|
||||
|
||||
private DesignCollectionVO designOrRedesignOperateNew(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo,
|
||||
Long collectionIdParam, ValidateElementVO elementVO) {
|
||||
private String designOrRedesignOperateNew(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo,
|
||||
Long collectionIdParam, ValidateElementVO elementVO) {
|
||||
if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) {
|
||||
//编辑sketchBoard
|
||||
collectionElementService.editSketchBoardsElement(elementVO, designDTO.getSketchBoards());
|
||||
@@ -297,16 +308,10 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
Long collectionId;
|
||||
if (null == collectionIdParam) {
|
||||
collectionId = collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId(), designDTO.getMoodboardPosition());
|
||||
String moodboardPosition = designDTO.getMoodboardPosition();
|
||||
parseMoodboardPosition(moodboardPosition, collectionId);
|
||||
}else {
|
||||
collectionId = collectionIdParam;
|
||||
// Collection byId = collectionService.getById(collectionIdParam);
|
||||
// if (!designDTO.getMoodboardPostion().equals(byId.getMoodboardPosition())) {
|
||||
// byId.setMoodboardPosition(designDTO.getMoodboardPostion());
|
||||
// }
|
||||
// if (!designDTO.getMoodTemplateId().equals(byId.getMoodTemplateId())) {
|
||||
// byId.setMoodTemplateId(designDTO.getMoodTemplateId());
|
||||
// }
|
||||
// collectionService.updateById(byId);
|
||||
}
|
||||
List<Long> elementIds = getElementId(elementVO);
|
||||
//批量关联element 到 collection
|
||||
@@ -336,7 +341,9 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
log.info("增加image_id关联运行时间:" + totalTimeInSeconds + " 秒");
|
||||
//design
|
||||
startTime = System.currentTimeMillis();
|
||||
JSONObject responseJSONObject = pythonService.designNew(pythonObjects);
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
pythonObjects.setRequestId(requestId);
|
||||
JSONObject responseJSONObject = pythonService.designStream(pythonObjects);
|
||||
endTime = System.currentTimeMillis();
|
||||
totalTimeInSeconds = (endTime - startTime) / 1000;
|
||||
log.info("design python端运行时间:" + totalTimeInSeconds + " 秒");
|
||||
@@ -350,10 +357,94 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
endTime = System.currentTimeMillis();
|
||||
totalTimeInSeconds = (endTime - startTime) / 1000;
|
||||
log.info("处理关联关系运行时间:" + totalTimeInSeconds + " 秒");
|
||||
|
||||
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put("pythonObjects", pythonObjects); // 转换后的 Python 请求参数
|
||||
context.put("designId", designId); // 设计 ID
|
||||
context.put("collectionId", collectionId); // 集合 ID
|
||||
context.put("userInfo", userInfo); // 用户信息
|
||||
context.put("timeZone", designDTO.getTimeZone()); // 时区
|
||||
context.put("singleOverall", designDTO.getSingleOverall()); // 其他设计参数
|
||||
context.put("requestIdList", elementVO.getRequestIdList());
|
||||
|
||||
// 将上下文存入全局设计上下文中
|
||||
designContext.put(requestId, context);
|
||||
|
||||
//保存python返回信息;保存designItem和detail
|
||||
return savePythonDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone(), responseJSONObject, designDTO.getSingleOverall());
|
||||
// return savePythonDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone(), responseJSONObject, designDTO.getSingleOverall());
|
||||
return requestId;
|
||||
}
|
||||
|
||||
private void parseMoodboardPosition(String moodboardPosition, Long collectionIdParam) {
|
||||
if (!StringUtils.isEmpty(moodboardPosition)) {
|
||||
// 将 JSON 字符串解析为 JSONObject
|
||||
JSONObject moodboardPositionJson = JSONObject.parseObject(moodboardPosition);
|
||||
|
||||
// 准备保存的 MoodboardPosition 列表
|
||||
List<MoodboardPosition> moodboardPositions = new ArrayList<>();
|
||||
|
||||
// 遍历 JSON 对象的 key(即样式类型)
|
||||
for (String key : moodboardPositionJson.keySet()) {
|
||||
// 特殊处理 "class" 字段
|
||||
if ("class".equals(key)) {
|
||||
// 获取 "class" 字段的值并将其转为 List<String>
|
||||
JSONArray classArray = moodboardPositionJson.getJSONArray(key);
|
||||
if (classArray != null) {
|
||||
|
||||
for (int j = 0; j < classArray.size(); j++) {
|
||||
// 将 classList 存入 MoodboardPosition(或者其他结构)
|
||||
|
||||
MoodboardPosition position = new MoodboardPosition()
|
||||
.setCollectionId(collectionIdParam) // 关联 Collection ID
|
||||
.setType(key) // 样式类型
|
||||
.setStyleData(classArray.getString(j)) // 设置 class 字段
|
||||
.setSequence(j) // 根据索引值设置顺序
|
||||
.setCreateTime(LocalDateTime.now()) // 创建时间
|
||||
.setUpdateTime(LocalDateTime.now()); // 更新时间
|
||||
|
||||
// 添加到列表中
|
||||
moodboardPositions.add(position);
|
||||
}
|
||||
}
|
||||
continue; // 跳过 "class" 字段的常规处理
|
||||
}
|
||||
|
||||
JSONArray styleArray = moodboardPositionJson.getJSONArray(key);
|
||||
if (styleArray != null) {
|
||||
for (int i = 0; i < styleArray.size(); i++) {
|
||||
// 获取当前样式数据
|
||||
JSONObject styleData = styleArray.getJSONObject(i);
|
||||
|
||||
// 构建 MoodboardPosition 实例
|
||||
MoodboardPosition position = new MoodboardPosition()
|
||||
.setCollectionId(collectionIdParam) // 关联 Collection ID
|
||||
.setType(key) // 样式类型
|
||||
.setStyleData(styleData.toJSONString()) // 样式数据存为 JSON 字符串
|
||||
.setSequence(i) // 根据索引值设置顺序
|
||||
.setCreateTime(LocalDateTime.now()) // 创建时间
|
||||
.setUpdateTime(LocalDateTime.now()); // 更新时间
|
||||
|
||||
// 添加到列表中
|
||||
moodboardPositions.add(position);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 如果解析结果非空,保存到数据库
|
||||
if (!moodboardPositions.isEmpty()) {
|
||||
for (MoodboardPosition position : moodboardPositions) {
|
||||
moodboardPositionMapper.insert(position);
|
||||
}
|
||||
log.info("成功解析并保存 {} 条 MoodboardPosition 数据", moodboardPositions.size());
|
||||
} else {
|
||||
log.warn("未找到可保存的 MoodboardPosition 数据");
|
||||
}
|
||||
} else {
|
||||
log.warn("传入的 moodboardPosition 字段为空");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void relationImageId(DesignPythonObjects pythonObjects) {
|
||||
if (Objects.isNull(pythonObjects)) {
|
||||
@@ -601,6 +692,152 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
@Resource
|
||||
private MinioUtil minioUtil;
|
||||
|
||||
private DesignCollectionVO savePythonDesignItemAndDetailSingle(DesignPythonObjects pythonObjects, Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone, JSONObject outfit, String singleOverall, Map<String, Object> context) {
|
||||
Object designCollectionVO = context.get("DesignCollectionVO");
|
||||
DesignCollectionVO response;
|
||||
List<DesignCollectionItemVO> designCollectionItems = Lists.newArrayList();
|
||||
if (null == designCollectionVO) {
|
||||
response = new DesignCollectionVO();
|
||||
response.setDesignId(designId);
|
||||
response.setCollectionId(collectionId);
|
||||
response.setProcessId(pythonObjects.getProcess_id());
|
||||
}else {
|
||||
response = (DesignCollectionVO) designCollectionVO;
|
||||
designCollectionItems = response.getDesignCollectionItems();
|
||||
}
|
||||
|
||||
response.setDesignCollectionItems(designCollectionItems);
|
||||
|
||||
|
||||
DesignPythonObject item = new DesignPythonObject();
|
||||
String objectSign = outfit.getString("objectSign");
|
||||
// log.info(objectSign);
|
||||
for (DesignPythonObject object : pythonObjects.getObjects()) {
|
||||
if (object.getObjectSign().equals(objectSign)) {
|
||||
item = object;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
DesignItem designItem = new DesignItem();
|
||||
designItem.setAccountId(userInfo.getId());
|
||||
designItem.setCollectionId(collectionId);
|
||||
designItem.setDesignId(designId);
|
||||
designItem.setCreateDate(DateUtil.getByTimeZone(timeZone));
|
||||
//生成的八张图片
|
||||
designItem.setDesignUrl(item.getBasic().getSave_name());
|
||||
designItem.setHasLike((byte) 0);
|
||||
//生成designItem
|
||||
Long designItemId = designItemService.saveOne(designItem);
|
||||
// python design返回入库及封装
|
||||
// JSONObject outfit = data.getJSONObject(i + "");
|
||||
// if (null == outfit) {
|
||||
// continue;
|
||||
// }
|
||||
TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit();
|
||||
designPythonOutfit.setDesignItemId(designItemId);
|
||||
designPythonOutfit.setUserId(userInfo.getId());
|
||||
designPythonOutfit.setDesignId(designId);
|
||||
designPythonOutfit.setCollectionId(collectionId);
|
||||
String synthesisUrl = outfit.getString("synthesis_url");
|
||||
if (!StringUtils.isEmpty(synthesisUrl)) {
|
||||
designPythonOutfit.setDesignUrl(synthesisUrl);
|
||||
} else {
|
||||
throw new BusinessException("design.interface.exception");
|
||||
}
|
||||
designPythonOutfitService.save(designPythonOutfit);
|
||||
|
||||
JSONArray layers = outfit.getJSONArray("layers");
|
||||
List<TDesignPythonOutfitDetail> list = new ArrayList<>();
|
||||
DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO();
|
||||
designCollectionItemVO.setObjectSign(objectSign);
|
||||
for (int i1 = 0; i1 < layers.size(); i1++) {
|
||||
JSONObject jsonObject = layers.getJSONObject(i1);
|
||||
TDesignPythonOutfitDetail designPythonOutfitDetail = new TDesignPythonOutfitDetail();
|
||||
designPythonOutfitDetail.setDesignId(designId);
|
||||
designPythonOutfitDetail.setDesignPythonOutfitId(designPythonOutfit.getId());
|
||||
designPythonOutfitDetail.setPosition(jsonObject.getString("position"));
|
||||
designPythonOutfitDetail.setImageSize(jsonObject.getString("image_size"));
|
||||
designPythonOutfitDetail.setImageUrl(jsonObject.getString("image_url"));
|
||||
if (singleOverall.equals(SingleOverallEnum.SINGLE.getRealName())) {
|
||||
designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl());
|
||||
}
|
||||
designPythonOutfitDetail.setImageCategory(jsonObject.getString("image_category"));
|
||||
designPythonOutfitDetail.setMaskUrl(jsonObject.getString("mask_url"));
|
||||
designPythonOutfitDetail.setUserId(userInfo.getId());
|
||||
designPythonOutfitDetail.setPriority(Integer.parseInt(jsonObject.getString("priority")));
|
||||
designPythonOutfitDetail.setCreateDate(LocalDateTime.now());
|
||||
list.add(designPythonOutfitDetail);
|
||||
}
|
||||
designPythonOutfitDetailService.saveBatch(list);
|
||||
designCollectionItemVO.setDesignItemId(designItemId);
|
||||
designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl());
|
||||
designCollectionItemVO.setDesignOutfitId(designPythonOutfit.getId());
|
||||
String designUrl = designPythonOutfit.getDesignUrl();
|
||||
if (!StringUtils.isEmpty(designUrl) && designUrl.contains("/")) {
|
||||
int firstIndex = designUrl.indexOf("/");
|
||||
designCollectionItemVO.setDesignOutfitUrl(minioUtil.getPreSignedUrl(designUrl.substring(0, firstIndex) + "/" + designUrl.substring(firstIndex + 1), 24 * 60));
|
||||
}
|
||||
//response
|
||||
designCollectionItems.add(designCollectionItemVO);
|
||||
|
||||
List<DesignItemDetail> designItemDetails = Lists.newArrayList();
|
||||
Map<String, Integer> typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0],
|
||||
d -> Math.abs(d.getPriority()),
|
||||
(existing, replacement) -> replacement));
|
||||
Map<String, String> typeAndUndividedLayer = designItemService.setTypeAndUndividedLayer(layers);
|
||||
for (DesignPythonItem detail : item.getItems()) {
|
||||
if (null == detail) {
|
||||
continue;
|
||||
}
|
||||
DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class);
|
||||
designItemDetail.setAccountId(userInfo.getId());
|
||||
designItemDetail.setDesignId(designId);
|
||||
designItemDetail.setDesignItemId(designItemId);
|
||||
designItemDetail.setCollectionElementId(detail.getElementId());
|
||||
designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone));
|
||||
designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType().toLowerCase()));
|
||||
if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) {
|
||||
designItemDetail.setPath(detail.getBody_path());
|
||||
//BODY不关联businessId
|
||||
designItemDetail.setBusinessId(0L);
|
||||
}
|
||||
designItemDetail.setIconPath(detail.getIcon());
|
||||
designItemDetail.setPriority(typePriority.get(detail.getType().toLowerCase()));
|
||||
if (!detail.getType().equals("Body")){
|
||||
DesignPythonItemPrint printObject = detail.getPrint().getOverall();
|
||||
// designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath());
|
||||
designItemDetail.setPrintPath(CollectionUtils.isEmpty(printObject.getPrint_path_list()) ? "" : printObject.getPrint_path_list().get(0));
|
||||
}
|
||||
designItemDetailService.save(designItemDetail);
|
||||
if (!SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType()) && !StringUtil.isNullOrEmpty(designItemDetail.getPrintPath())) {
|
||||
DesignItemDetailPrint print = new DesignItemDetailPrint();
|
||||
print.setDesignItemDetailId(designItemDetail.getId());
|
||||
print.setPrintType("print");
|
||||
print.setPath(designItemDetail.getPrintPath());
|
||||
print.setSingleOrOverall("overall");
|
||||
print.setPosition("[0.0,0.0]");
|
||||
// print.setScale(1d);
|
||||
// todo mark 将print默认scale置为0.3
|
||||
print.setScale(0.3d);
|
||||
print.setAngle(0.0);
|
||||
print.setPriority(1);
|
||||
QueryWrapper<CollectionElement> getPrintboardLevel2TypeQw = new QueryWrapper<>();
|
||||
getPrintboardLevel2TypeQw.lambda().eq(CollectionElement::getUrl, print.getPath());
|
||||
getPrintboardLevel2TypeQw.lambda().orderByDesc(CollectionElement::getCreateDate);
|
||||
getPrintboardLevel2TypeQw.last("limit 1");
|
||||
CollectionElement one = collectionElementService.getOne(getPrintboardLevel2TypeQw);
|
||||
print.setLevel2Type(one.getLevel2Type());
|
||||
print.setCreateDate(LocalDateTime.now());
|
||||
designItemDetailPrintService.save(print);
|
||||
}
|
||||
}
|
||||
synchronized (context) {
|
||||
context.put("DesignCollectionVO", response);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
private DesignCollectionVO savePythonDesignItemAndDetail(DesignPythonObjects pythonObjects
|
||||
, Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone, JSONObject responseJSONObject, String singleOverall) {
|
||||
DesignCollectionVO response = new DesignCollectionVO();
|
||||
@@ -612,6 +849,7 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
if (data == null) {
|
||||
throw new BusinessException("design.interface.exception");
|
||||
}
|
||||
|
||||
for (int i = 0; i < pythonObjects.getObjects().size(); i++) {
|
||||
DesignPythonObject item = pythonObjects.getObjects().get(i);
|
||||
DesignItem designItem = new DesignItem();
|
||||
@@ -641,6 +879,7 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
throw new BusinessException("design.interface.exception");
|
||||
}
|
||||
designPythonOutfitService.save(designPythonOutfit);
|
||||
|
||||
JSONArray layers = outfit.getJSONArray("layers");
|
||||
List<TDesignPythonOutfitDetail> list = new ArrayList<>();
|
||||
DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO();
|
||||
@@ -750,7 +989,7 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
//生成designItem
|
||||
Long designItemId = designItemService.saveOne(designItem);
|
||||
//response
|
||||
designCollectionItems.add(new DesignCollectionItemVO(designItemId, designItem.getDesignUrl(), null, null));
|
||||
designCollectionItems.add(new DesignCollectionItemVO(designItemId, designItem.getDesignUrl(), null, null, null));
|
||||
|
||||
List<DesignItemDetail> designItemDetails = Lists.newArrayList();
|
||||
item.getItems().forEach(detail -> {
|
||||
@@ -797,7 +1036,7 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
}
|
||||
|
||||
@Override
|
||||
public DesignCollectionVO reDesignCollection(ReDesignCollectionDTO reDesignDTO) {
|
||||
public String reDesignCollection(ReDesignCollectionDTO reDesignDTO) {
|
||||
//校验collection
|
||||
Collection collection = collectionService.getById(reDesignDTO.getCollectionId());
|
||||
if (Objects.isNull(collection)) {
|
||||
@@ -819,7 +1058,7 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
Design oldDesign = selectByCollectionId(reDesignDTO.getCollectionId());
|
||||
//删除老的关联的design
|
||||
deleteByCollectionId(reDesignDTO.getCollectionId());
|
||||
designItemService.deleteByCollectionId(reDesignDTO.getCollectionId());
|
||||
// designItemService.deleteByCollectionId(reDesignDTO.getCollectionId());
|
||||
designItemDetailService.deleteByDesignId(oldDesign.getId());
|
||||
//redesign
|
||||
return designOrRedesignOperateNew(CopyUtil.copyObject(
|
||||
@@ -849,15 +1088,15 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
}
|
||||
List<DesignItem> designItems = designItemService.getByDesignId(designId);
|
||||
if (CollectionUtils.isEmpty(designItems)) {
|
||||
return new DesignCollectionVO(designId, design.getCollectionId(), null, null);
|
||||
return new DesignCollectionVO(designId, design.getCollectionId(), null, null, null);
|
||||
}
|
||||
return new DesignCollectionVO(designId, design.getCollectionId(), coverDesignItemToVO(designItems), null);
|
||||
return new DesignCollectionVO(designId, design.getCollectionId(), coverDesignItemToVO(designItems), null, null);
|
||||
}
|
||||
|
||||
private List<DesignCollectionItemVO> coverDesignItemToVO(List<DesignItem> designItems) {
|
||||
List<DesignCollectionItemVO> response = Lists.newArrayList();
|
||||
designItems.forEach(designItem -> {
|
||||
response.add(new DesignCollectionItemVO(designItem.getId(), designItem.getDesignUrl(), null, null));
|
||||
response.add(new DesignCollectionItemVO(designItem.getId(), designItem.getDesignUrl(), null, null, null));
|
||||
});
|
||||
return response;
|
||||
}
|
||||
@@ -874,7 +1113,9 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
}
|
||||
String pictureName = null;
|
||||
UserLike userLike;
|
||||
Boolean isFirst = true;
|
||||
if (Objects.nonNull(userGroupId)) {
|
||||
isFirst = false;
|
||||
UserLikeGroup userLikeGroup = userLikeGroupService.getById(userGroupId);
|
||||
if (Objects.isNull(userLikeGroup)) {
|
||||
throw new BusinessException("userLikeGroup.not.found");
|
||||
@@ -920,6 +1161,35 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
designItem.getDesignId(), designLikeDTO.getDesignItemId(), designLikeDTO.getDesignPythonOutfitId(), tDesignPythonOutfits.get(0).getDesignUrl(), designLikeDTO.getTimeZone());
|
||||
}
|
||||
userLikeService.save(userLike);
|
||||
Integer sortParam = 1;
|
||||
Long userLikeSortId;
|
||||
if (isFirst) {
|
||||
UserLikeSort userLikeSort = new UserLikeSort();
|
||||
userLikeSort.setUserLikeGroupId(userGroupId);
|
||||
userLikeSort.setUserLikeId(userLike.getId());
|
||||
userLikeSort.setSort(1);
|
||||
userLikeSortMapper.insert(userLikeSort);
|
||||
userLikeSortId = userLikeSort.getId();
|
||||
}else {
|
||||
QueryWrapper<UserLikeSort> qw = new QueryWrapper<>();
|
||||
qw.lambda().eq(UserLikeSort::getUserLikeGroupId, userGroupId);
|
||||
qw.lambda().orderByDesc(UserLikeSort::getSort);
|
||||
List<UserLikeSort> userLikeSorts = userLikeSortMapper.selectList(qw);
|
||||
UserLikeSort userLikeSort = new UserLikeSort();
|
||||
if (CollectionUtils.isEmpty(userLikeSorts)) {
|
||||
userLikeSort.setUserLikeGroupId(userGroupId);
|
||||
userLikeSort.setUserLikeId(userLike.getId());
|
||||
userLikeSort.setSort(1);
|
||||
}else {
|
||||
Integer sort = userLikeSorts.get(0).getSort();
|
||||
userLikeSort.setUserLikeGroupId(userGroupId);
|
||||
userLikeSort.setUserLikeId(userLike.getId());
|
||||
userLikeSort.setSort(sort + 1);
|
||||
}
|
||||
userLikeSortMapper.insert(userLikeSort);
|
||||
sortParam = userLikeSort.getSort();
|
||||
userLikeSortId = userLikeSort.getId();
|
||||
}
|
||||
groupDetailId = userLike.getId();
|
||||
String designUrl = designPythonOutfitMapper.selectById(userLike.getDesignOutfitId()).getDesignUrl();
|
||||
if (designUrl.contains("/")) {
|
||||
@@ -928,7 +1198,7 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
}
|
||||
//修改designItem为like状态
|
||||
designItemService.updateLikeStatus(designLikeDTO.getDesignItemId(), (byte) 1);
|
||||
return new DesignLikeVO(userGroupId, groupDetailId, pictureName);
|
||||
return new DesignLikeVO(userLikeSortId, userGroupId, groupDetailId, pictureName, userLike.getId(), sortParam);
|
||||
}
|
||||
|
||||
private List<Long> validateMergeElement(List<CollectionElement> oldElements, List<DesignItemDetail> designItemDetails) {
|
||||
@@ -1010,9 +1280,32 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
//group 下面没有元素时候 直接删除
|
||||
// userLikeGroupService.removeById(userLike.getUserLikeGroupId());
|
||||
}
|
||||
|
||||
QueryWrapper<UserLikeSort> qw = new QueryWrapper<>();
|
||||
qw.lambda().eq(UserLikeSort::getUserLikeGroupId, userLike.getUserLikeGroupId());
|
||||
qw.lambda().orderByDesc(UserLikeSort::getSort);
|
||||
List<UserLikeSort> userLikeSorts = userLikeSortMapper.selectList(qw);
|
||||
UserLikeSort userLikeSort = getUserLikeSortByUserLikeId(userLike.getId());
|
||||
Long userLikeSortId = userLikeSort.getId();
|
||||
for (UserLikeSort likeSort : userLikeSorts) {
|
||||
if (Objects.equals(likeSort.getId(), userLikeSortId)) {
|
||||
userLikeSortMapper.deleteById(likeSort);
|
||||
break;
|
||||
}else {
|
||||
likeSort.setSort(likeSort.getSort() - 1);
|
||||
userLikeSortMapper.updateById(likeSort);
|
||||
}
|
||||
}
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
private UserLikeSort getUserLikeSortByUserLikeId(Long userLikeId) {
|
||||
QueryWrapper<UserLikeSort> qw = new QueryWrapper<>();
|
||||
qw.lambda().eq(UserLikeSort::getUserLikeId, userLikeId);
|
||||
UserLikeSort userLikeSort = userLikeSortMapper.selectOne(qw);
|
||||
return userLikeSort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateHighDesign(GenerateHighDesignDTO generateHighDesignDTO) {
|
||||
DesignItem designItem = designItemService.getById(generateHighDesignDTO.getDesignItemId());
|
||||
@@ -1389,4 +1682,334 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Boolean receiveDesignResults(JSONObject responseJSONObject) {
|
||||
// String requestId = "UUID.randomUUID().toString()";
|
||||
String requestId = responseJSONObject.getString("requestId");
|
||||
Map<String, Object> context;
|
||||
synchronized (designContext) {
|
||||
context = designContext.get(requestId);
|
||||
if (context == null) {
|
||||
log.error("上下文数据缺失,无法完成操作");
|
||||
return false;
|
||||
}
|
||||
|
||||
DesignPythonObjects pythonObjects = (DesignPythonObjects) context.get("pythonObjects");
|
||||
Long designId = (Long) context.get("designId");
|
||||
Long collectionId = (Long) context.get("collectionId");
|
||||
AuthPrincipalVo userInfo = (AuthPrincipalVo) context.get("userInfo");
|
||||
String timeZone = (String) context.get("timeZone");
|
||||
String singleOverall = (String) context.get("singleOverall");
|
||||
|
||||
DesignCollectionVO designCollectionVO = savePythonDesignItemAndDetailSingle(pythonObjects, designId, collectionId, userInfo, timeZone, responseJSONObject, singleOverall, context);
|
||||
|
||||
// log.info(designContext.toString());
|
||||
designContext.put(requestId, context);
|
||||
}
|
||||
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DesignCollectionVO getDesignResult(String requestId, List<String> objectSignList) {
|
||||
// Map<String, Object> stringObjectMap = designContext.get("UUID.randomUUID().toString()");
|
||||
Map<String, Object> stringObjectMap = designContext.get(requestId);
|
||||
// log.info(stringObjectMap.toString());
|
||||
DesignCollectionVO result = (DesignCollectionVO) stringObjectMap.get("DesignCollectionVO");
|
||||
if (Objects.isNull(result)) {
|
||||
DesignCollectionVO noneResult = new DesignCollectionVO();
|
||||
noneResult.setUnfinishedList(objectSignList);
|
||||
return noneResult;
|
||||
}
|
||||
for (DesignCollectionItemVO designCollectionItem : result.getDesignCollectionItems()) {
|
||||
String objectSign = designCollectionItem.getObjectSign();
|
||||
objectSignList.remove(objectSign);
|
||||
}
|
||||
result.setUnfinishedList(objectSignList);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String designCloud(DesignCollectionDTO designDTO) {
|
||||
AuthPrincipalVo userInfo = UserContext.getUserHolder();
|
||||
//校验collection element
|
||||
ValidateElementVO elementVO = collectionElementService.validateElement(designDTO);
|
||||
//design
|
||||
return designBatch(designDTO, userInfo, null, elementVO);
|
||||
}
|
||||
|
||||
private String designBatch(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, Long collectionIdParam, ValidateElementVO elementVO) {
|
||||
if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) {
|
||||
//编辑sketchBoard
|
||||
collectionElementService.editSketchBoardsElement(elementVO, designDTO.getSketchBoards());
|
||||
}
|
||||
if (CollectionUtil.isNotEmpty(designDTO.getPrintBoards())) {
|
||||
//编辑printBoard
|
||||
collectionElementService.editPrintBoardsElement(elementVO, designDTO.getPrintBoards());
|
||||
}
|
||||
//保存collection
|
||||
Long collectionId;
|
||||
if (null == collectionIdParam) {
|
||||
collectionId = collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId(), designDTO.getMoodboardPosition());
|
||||
}else {
|
||||
collectionId = collectionIdParam;
|
||||
}
|
||||
List<Long> elementIds = getElementId(elementVO);
|
||||
//批量关联element 到 collection
|
||||
collectionElementService.relationCollection(elementIds, collectionId);
|
||||
//library转化为collection(生成)
|
||||
saveCollectionElemntsByLibrarys(elementVO, collectionId);
|
||||
//generate转化为collection(生成)
|
||||
saveCollectionElemntsByGenerates(elementVO, collectionId);
|
||||
//保存颜色版
|
||||
collectionElementService.saveColorBoard(designDTO.getColorBoards(), collectionId, designDTO.getTimeZone());
|
||||
//保存design
|
||||
Long designId = saveOne(designDTO, collectionId, userInfo.getId());
|
||||
//计算library
|
||||
// calculateLibraryAndSysFile(designDTO, elementVO, userInfo);
|
||||
//组装design入参
|
||||
long startTime = System.currentTimeMillis();
|
||||
DesignPythonObjects pythonObjects = pythonService.covertDesignParam(designDTO.getSystemScale(),
|
||||
designDTO.getSingleOverall(), designDTO.getSwitchCategory(), elementVO, designDTO.getProcessId());
|
||||
long endTime = System.currentTimeMillis();
|
||||
long totalTimeInSeconds = (endTime - startTime) / 1000;
|
||||
log.info("组装入参运行时间:" + totalTimeInSeconds + " 秒");
|
||||
// pythonObjects增加image_id关联
|
||||
startTime = System.currentTimeMillis();
|
||||
List<Long> imageIds = relationImageIds(pythonObjects);
|
||||
endTime = System.currentTimeMillis();
|
||||
totalTimeInSeconds = (endTime - startTime) / 1000;
|
||||
log.info("增加image_id关联运行时间:" + totalTimeInSeconds + " 秒");
|
||||
//design
|
||||
startTime = System.currentTimeMillis();
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
pythonObjects.setRequestId(requestId);
|
||||
AuthPrincipalVo userHolder = UserContext.getUserHolder();
|
||||
String taskId = pythonService.designBatch(pythonObjects, userHolder.getId(), elementVO.getDesignNum(), requestId);
|
||||
|
||||
DesignBatch designBatch = new DesignBatch();
|
||||
|
||||
designBatch.setAccountId(userInfo.getId());
|
||||
designBatch.setDesignId(designId);
|
||||
designBatch.setCollectionId(collectionId);
|
||||
designBatch.setTaskId(taskId);
|
||||
designBatch.setCreateTime(LocalDateTime.now());
|
||||
designBatch.setStatus(0);
|
||||
designBatch.setTotalNum(elementVO.getDesignNum());
|
||||
designBatchMapper.insert(designBatch);
|
||||
|
||||
endTime = System.currentTimeMillis();
|
||||
totalTimeInSeconds = (endTime - startTime) / 1000;
|
||||
log.info("design python端运行时间:" + totalTimeInSeconds + " 秒");
|
||||
//生成library
|
||||
startTime = System.currentTimeMillis();
|
||||
generateLibrary(elementVO, designDTO.getTimeZone());
|
||||
//处理关联关系,修复element覆盖得情况
|
||||
List<CollectionElement> relationElements = collectionElementService.getByOnlyCollectionId(collectionId);
|
||||
List<Long> relationElementIds = relationElements.stream().map(CollectionElement::getId).collect(Collectors.toList());
|
||||
handleCollectionElementRelation(collectionId, null != collectionIdParam, relationElementIds);
|
||||
endTime = System.currentTimeMillis();
|
||||
totalTimeInSeconds = (endTime - startTime) / 1000;
|
||||
log.info("处理关联关系运行时间:" + totalTimeInSeconds + " 秒");
|
||||
|
||||
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put("pythonObjects", pythonObjects); // 转换后的 Python 请求参数
|
||||
context.put("designId", designId); // 设计 ID
|
||||
context.put("collectionId", collectionId); // 集合 ID
|
||||
context.put("userInfo", userInfo); // 用户信息
|
||||
context.put("timeZone", designDTO.getTimeZone()); // 时区
|
||||
context.put("singleOverall", designDTO.getSingleOverall()); // 其他设计参数
|
||||
context.put("requestIdList", elementVO.getRequestIdList());
|
||||
|
||||
// 将上下文存入全局设计上下文中
|
||||
designContext.put(taskId, context);
|
||||
return taskId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processDesignBatch(Map<String, Object> designBatchResult) {
|
||||
Object progress = designBatchResult.get("progress");
|
||||
if (progress instanceof String) {
|
||||
if (progress.equals("0/100")) {
|
||||
return;
|
||||
}
|
||||
if (progress.equals("ok")) {
|
||||
String taskId = (String) designBatchResult.get("task_id");
|
||||
QueryWrapper<DesignBatch> qw = new QueryWrapper<>();
|
||||
qw.lambda().eq(DesignBatch::getTaskId, taskId);
|
||||
List<DesignBatch> designBatches = designBatchMapper.selectList(qw);
|
||||
if (CollectionUtil.isNotEmpty(designBatches)) {
|
||||
DesignBatch designBatch = designBatches.get(0);
|
||||
designBatch.setStatus(1);
|
||||
designBatchMapper.updateById(designBatch);
|
||||
}
|
||||
}
|
||||
}else {
|
||||
String taskId = (String) designBatchResult.get("task_id");
|
||||
QueryWrapper<DesignBatch> qw = new QueryWrapper<>();
|
||||
qw.lambda().eq(DesignBatch::getTaskId, taskId);
|
||||
List<DesignBatch> designBatches = designBatchMapper.selectList(qw);
|
||||
if (CollectionUtil.isNotEmpty(designBatches)) {
|
||||
DesignBatch designBatch = designBatches.get(0);
|
||||
if (designBatch.getCompletedNum() == null) {
|
||||
designBatch.setCompletedNum(1);
|
||||
}else {
|
||||
designBatch.setCompletedNum(designBatch.getCompletedNum() + 1);
|
||||
}
|
||||
designBatchMapper.updateById(designBatch);
|
||||
}
|
||||
|
||||
Integer i = (Integer) progress;
|
||||
Map<String, Object> context;
|
||||
synchronized (designContext) {
|
||||
context = designContext.get(taskId);
|
||||
if (context == null) {
|
||||
log.error("上下文数据缺失,无法完成操作");
|
||||
return;
|
||||
}
|
||||
|
||||
DesignPythonObjects pythonObjects = (DesignPythonObjects) context.get("pythonObjects");
|
||||
Long designId = (Long) context.get("designId");
|
||||
Long collectionId = (Long) context.get("collectionId");
|
||||
AuthPrincipalVo userInfo = (AuthPrincipalVo) context.get("userInfo");
|
||||
String timeZone = (String) context.get("timeZone");
|
||||
String singleOverall = (String) context.get("singleOverall");
|
||||
|
||||
DesignPythonObject item = pythonObjects.getObjects().get(i);
|
||||
DesignItem designItem = new DesignItem();
|
||||
designItem.setAccountId(userInfo.getId());
|
||||
designItem.setCollectionId(collectionId);
|
||||
designItem.setDesignId(designId);
|
||||
designItem.setCreateDate(DateUtil.getByTimeZone(timeZone));
|
||||
//生成的八张图片
|
||||
designItem.setDesignUrl(item.getBasic().getSave_name());
|
||||
designItem.setHasLike((byte) 0);
|
||||
//生成designItem
|
||||
Long designItemId = designItemService.saveOne(designItem);
|
||||
// python design返回入库及封装
|
||||
JSONObject outfit = (JSONObject) designBatchResult.get("result");
|
||||
if (null == outfit) {
|
||||
return;
|
||||
}
|
||||
TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit();
|
||||
designPythonOutfit.setDesignItemId(designItemId);
|
||||
designPythonOutfit.setUserId(userInfo.getId());
|
||||
designPythonOutfit.setDesignId(designId);
|
||||
designPythonOutfit.setCollectionId(collectionId);
|
||||
String synthesisUrl = outfit.getString("synthesis_url");
|
||||
if (!StringUtils.isEmpty(synthesisUrl)) {
|
||||
designPythonOutfit.setDesignUrl(synthesisUrl);
|
||||
} else {
|
||||
throw new BusinessException("design.interface.exception");
|
||||
}
|
||||
designPythonOutfitService.save(designPythonOutfit);
|
||||
|
||||
JSONArray layers = outfit.getJSONArray("layers");
|
||||
List<TDesignPythonOutfitDetail> list = new ArrayList<>();
|
||||
DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO();
|
||||
for (int i1 = 0; i1 < layers.size(); i1++) {
|
||||
JSONObject jsonObject = layers.getJSONObject(i1);
|
||||
TDesignPythonOutfitDetail designPythonOutfitDetail = new TDesignPythonOutfitDetail();
|
||||
designPythonOutfitDetail.setDesignId(designId);
|
||||
designPythonOutfitDetail.setDesignPythonOutfitId(designPythonOutfit.getId());
|
||||
designPythonOutfitDetail.setPosition(jsonObject.getString("position"));
|
||||
designPythonOutfitDetail.setImageSize(jsonObject.getString("image_size"));
|
||||
designPythonOutfitDetail.setImageUrl(jsonObject.getString("image_url"));
|
||||
if (singleOverall.equals(SingleOverallEnum.SINGLE.getRealName())) {
|
||||
designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl());
|
||||
}
|
||||
designPythonOutfitDetail.setImageCategory(jsonObject.getString("image_category"));
|
||||
designPythonOutfitDetail.setMaskUrl(jsonObject.getString("mask_url"));
|
||||
designPythonOutfitDetail.setUserId(userInfo.getId());
|
||||
designPythonOutfitDetail.setPriority(Integer.parseInt(jsonObject.getString("priority")));
|
||||
designPythonOutfitDetail.setCreateDate(LocalDateTime.now());
|
||||
list.add(designPythonOutfitDetail);
|
||||
}
|
||||
designPythonOutfitDetailService.saveBatch(list);
|
||||
designCollectionItemVO.setDesignItemId(designItemId);
|
||||
designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl());
|
||||
designCollectionItemVO.setDesignOutfitId(designPythonOutfit.getId());
|
||||
String designUrl = designPythonOutfit.getDesignUrl();
|
||||
if (!StringUtils.isEmpty(designUrl) && designUrl.contains("/")) {
|
||||
int firstIndex = designUrl.indexOf("/");
|
||||
designCollectionItemVO.setDesignOutfitUrl(minioUtil.getPreSignedUrl(designUrl.substring(0, firstIndex) + "/" + designUrl.substring(firstIndex + 1), 24 * 60));
|
||||
}
|
||||
//response
|
||||
// designCollectionItems.add(designCollectionItemVO);
|
||||
|
||||
List<DesignItemDetail> designItemDetails = Lists.newArrayList();
|
||||
Map<String, Integer> typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0],
|
||||
d -> Math.abs(d.getPriority()),
|
||||
(existing, replacement) -> replacement));
|
||||
Map<String, String> typeAndUndividedLayer = designItemService.setTypeAndUndividedLayer(layers);
|
||||
for (DesignPythonItem detail : item.getItems()) {
|
||||
if (null == detail) {
|
||||
continue;
|
||||
}
|
||||
DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class);
|
||||
designItemDetail.setAccountId(userInfo.getId());
|
||||
designItemDetail.setDesignId(designId);
|
||||
designItemDetail.setDesignItemId(designItemId);
|
||||
designItemDetail.setCollectionElementId(detail.getElementId());
|
||||
designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone));
|
||||
designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType().toLowerCase()));
|
||||
if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) {
|
||||
designItemDetail.setPath(detail.getBody_path());
|
||||
//BODY不关联businessId
|
||||
designItemDetail.setBusinessId(0L);
|
||||
}
|
||||
designItemDetail.setIconPath(detail.getIcon());
|
||||
designItemDetail.setPriority(typePriority.get(detail.getType().toLowerCase()));
|
||||
if (!detail.getType().equals("Body")){
|
||||
DesignPythonItemPrint printObject = detail.getPrint().getOverall();
|
||||
// designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath());
|
||||
designItemDetail.setPrintPath(CollectionUtils.isEmpty(printObject.getPrint_path_list()) ? "" : printObject.getPrint_path_list().get(0));
|
||||
}
|
||||
designItemDetailService.save(designItemDetail);
|
||||
if (!SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType()) && !StringUtil.isNullOrEmpty(designItemDetail.getPrintPath())) {
|
||||
DesignItemDetailPrint print = new DesignItemDetailPrint();
|
||||
print.setDesignItemDetailId(designItemDetail.getId());
|
||||
print.setPrintType("print");
|
||||
print.setPath(designItemDetail.getPrintPath());
|
||||
print.setSingleOrOverall("overall");
|
||||
print.setPosition("[0.0,0.0]");
|
||||
// print.setScale(1d);
|
||||
// todo mark 将print默认scale置为0.3
|
||||
print.setScale(0.3d);
|
||||
print.setAngle(0.0);
|
||||
print.setPriority(1);
|
||||
QueryWrapper<CollectionElement> getPrintboardLevel2TypeQw = new QueryWrapper<>();
|
||||
getPrintboardLevel2TypeQw.lambda().eq(CollectionElement::getUrl, print.getPath());
|
||||
getPrintboardLevel2TypeQw.lambda().orderByDesc(CollectionElement::getCreateDate);
|
||||
getPrintboardLevel2TypeQw.last("limit 1");
|
||||
CollectionElement one = collectionElementService.getOne(getPrintboardLevel2TypeQw);
|
||||
print.setLevel2Type(one.getLevel2Type());
|
||||
print.setCreateDate(LocalDateTime.now());
|
||||
designItemDetailPrintService.save(print);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// for (int i = 0; i < pythonObjects.getObjects().size(); i++) {
|
||||
//
|
||||
// }
|
||||
// response.setProcessId(pythonObjects.getProcess_id());
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean sort(UserLikeSortDTO userLikeSortDTO) {
|
||||
// QueryWrapper<UserLikeSort> qw = new QueryWrapper<>();
|
||||
// qw.lambda().eq(UserLikeSort::getUserLikeGroupId, userLikeSortDTO.getUserLikeGroupId());
|
||||
// userLikeSortMapper.delete(qw);
|
||||
for (UserLikeSort userLikeSort : userLikeSortDTO.getUserLikeSortList()) {
|
||||
userLikeSortMapper.updateById(userLikeSort);
|
||||
}
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -289,7 +289,7 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
|
||||
if (b) creditsService.insertToCreditsDetail(accountId,
|
||||
CreditsEventsEnum.TO_PRODUCT_IMAGE.getName(),
|
||||
CreditsEventsEnum.TO_PRODUCT_IMAGE.getValue(),
|
||||
"negative");
|
||||
"negative", null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -524,7 +524,7 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
|
||||
times = 1;
|
||||
}
|
||||
}
|
||||
// Slogan 参数校验
|
||||
// Slogan 参数校验 slogan目前只能开一个接口。所以只有生产环境上能使用
|
||||
if (generateThroughImageTextDTO.getLevel2Type().equals(CollectionLevel2TypeEnum.SLOGAN.getRealName())) {
|
||||
if (StringUtil.isNullOrEmpty(generateThroughImageTextDTO.getSloganBase64())) {
|
||||
log.error("Printboard-Slogan模式下,slogan image为空");
|
||||
@@ -592,7 +592,7 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
|
||||
// 2、判断用户当前积分是否够本次生成消耗
|
||||
Boolean preDeduction = creditsService.creditsPreDeduction(creditsEventsEnum, 1);
|
||||
if (!preDeduction) {
|
||||
throw new BusinessException("remaining.credits.insufficient");
|
||||
throw new BusinessException("remaining.credits.insufficient", ResultEnum.WARNING.getCode());
|
||||
}
|
||||
|
||||
// 3、生成唯一id 使用uuid,由于uuid重复的几率很小,故取消对uuid重复性的校验
|
||||
@@ -772,7 +772,7 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
|
||||
if (b) creditsService.insertToCreditsDetail(accountId,
|
||||
CreditsEventsEnum.RELIGHT.getName(),
|
||||
CreditsEventsEnum.RELIGHT.getValue(),
|
||||
"negative");
|
||||
"negative", null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,15 +4,20 @@ package com.ai.da.service.impl;
|
||||
import com.ai.da.common.context.UserContext;
|
||||
import com.ai.da.common.enums.CreditsEventsEnum;
|
||||
import com.ai.da.common.enums.OrderStatusEnum;
|
||||
import com.ai.da.common.enums.ProductEnum;
|
||||
import com.ai.da.common.response.PageBaseResponse;
|
||||
import com.ai.da.common.utils.OrderNoUtils;
|
||||
import com.ai.da.common.utils.RequestInfoUtil;
|
||||
import com.ai.da.mapper.primary.OrderInfoMapper;
|
||||
import com.ai.da.mapper.primary.PaymentInfoMapper;
|
||||
import com.ai.da.mapper.primary.ProductMapper;
|
||||
import com.ai.da.mapper.primary.entity.OrderInfo;
|
||||
import com.ai.da.mapper.primary.entity.PaymentInfo;
|
||||
import com.ai.da.model.dto.QueryPageByTimeDTO;
|
||||
import com.ai.da.model.vo.AuthPrincipalVo;
|
||||
import com.ai.da.service.OrderInfoService;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
@@ -21,11 +26,14 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@@ -34,8 +42,12 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
@Resource
|
||||
private ProductMapper productMapper;
|
||||
|
||||
@Resource
|
||||
private PaymentInfoMapper paymentInfoMapper;
|
||||
|
||||
@Override
|
||||
public OrderInfo createOrderByProductId(Integer amount, String paymentType) {
|
||||
public OrderInfo createOrderByProductId(Integer amount, String paymentType, HttpServletRequest request) {
|
||||
|
||||
|
||||
//查找已存在但未支付的订单
|
||||
/*OrderInfo orderInfo = this.getNoPayOrderByProductId(amount, paymentType);
|
||||
@@ -51,20 +63,61 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
//生成订单
|
||||
OrderInfo orderInfo = new OrderInfo();
|
||||
orderInfo.setAccountId(accountId);
|
||||
orderInfo.setTitle("积分购买 X" + amount );
|
||||
orderInfo.setTitle("积分购买 X" + amount);
|
||||
orderInfo.setOrderNo(OrderNoUtils.getOrderNo()); //订单号 ??
|
||||
// orderInfo.setProductId(amount);
|
||||
// orderInfo.setTotalFee(Integer.parseInt(CreditsEventsEnum.PRICE.getValue()) * amount); // 元 HKD
|
||||
orderInfo.setTotalFee(Float.parseFloat(CreditsEventsEnum.PRICE.getValue()) * amount); // 元 HKD
|
||||
setIPLocation(paymentType, request, orderInfo);
|
||||
baseMapper.insert(orderInfo);
|
||||
return orderInfo;
|
||||
}
|
||||
|
||||
private void setIPLocation(String paymentType, HttpServletRequest request, OrderInfo orderInfo) {
|
||||
orderInfo.setOrderStatus(OrderStatusEnum.NOT_PAY.getType()); //未支付
|
||||
orderInfo.setPaymentType(paymentType);
|
||||
baseMapper.insert(orderInfo);
|
||||
if (!Objects.isNull(request)){
|
||||
String ipAddress = RequestInfoUtil.getIpAddress(request);
|
||||
if (!StringUtil.isNullOrEmpty(ipAddress)) {
|
||||
Map ipLocation = RequestInfoUtil.getIPLocation(ipAddress);
|
||||
if (ipLocation != null && !ipLocation.get("status").equals("fail")) {
|
||||
orderInfo.setCountry(ipLocation.get("country").toString());
|
||||
orderInfo.setCity(ipLocation.get("city").toString());
|
||||
orderInfo.setIpAddress(ipLocation.get("query").toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public OrderInfo createOrderByProductId(Integer amount, String paymentType, ProductEnum product, HttpServletRequest request) {
|
||||
|
||||
//获取商品信息
|
||||
// Product product = productMapper.selectById(amount);
|
||||
String title;
|
||||
if (product.equals(ProductEnum.CreditsProduct)) {
|
||||
title = "积分购买 X" + amount;
|
||||
} else {
|
||||
title = product.getName();
|
||||
}
|
||||
AuthPrincipalVo userHolder = UserContext.getUserHolder();
|
||||
Long accountId = userHolder.getId();
|
||||
|
||||
//生成订单
|
||||
OrderInfo orderInfo = new OrderInfo();
|
||||
orderInfo.setAccountId(accountId);
|
||||
orderInfo.setTitle(title);
|
||||
orderInfo.setOrderNo(OrderNoUtils.getOrderNo()); // 自定义订单号
|
||||
// orderInfo.setProductId(amount);
|
||||
// orderInfo.setTotalFee(Integer.parseInt(CreditsEventsEnum.PRICE.getValue()) * amount); // 元 HKD
|
||||
orderInfo.setTotalFee((float) (product.getPrice() * amount)); // 元 HKD
|
||||
setIPLocation(paymentType, request, orderInfo);
|
||||
baseMapper.insert(orderInfo);
|
||||
return orderInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储订单二维码
|
||||
*
|
||||
* @param orderNo
|
||||
* @param codeUrl
|
||||
*/
|
||||
@@ -82,6 +135,7 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
|
||||
/**
|
||||
* 查询订单列表,并倒序查询
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
@@ -93,6 +147,7 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
|
||||
/**
|
||||
* 根据订单号更新订单状态
|
||||
*
|
||||
* @param orderNo
|
||||
* @param orderStatus
|
||||
*/
|
||||
@@ -112,6 +167,7 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
|
||||
/**
|
||||
* 根据订单号获取订单状态
|
||||
*
|
||||
* @param orderNo
|
||||
* @return
|
||||
*/
|
||||
@@ -121,7 +177,7 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("order_no", orderNo);
|
||||
OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
|
||||
if(orderInfo == null){
|
||||
if (orderInfo == null) {
|
||||
return null;
|
||||
}
|
||||
return orderInfo.getOrderStatus();
|
||||
@@ -129,6 +185,7 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
|
||||
/**
|
||||
* 查询创建超过minutes分钟并且未支付的订单
|
||||
*
|
||||
* @param minutes
|
||||
* @return
|
||||
*/
|
||||
@@ -149,6 +206,7 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
|
||||
/**
|
||||
* 根据订单号获取订单
|
||||
*
|
||||
* @param orderNo
|
||||
* @return
|
||||
*/
|
||||
@@ -166,6 +224,7 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
/**
|
||||
* 根据商品id查询未支付订单
|
||||
* 防止重复创建订单对象
|
||||
*
|
||||
* @param productId
|
||||
* @return
|
||||
*/
|
||||
@@ -181,16 +240,16 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageBaseResponse<OrderInfo> getOrderByPage(QueryPageByTimeDTO queryPageByTimeDTO){
|
||||
public PageBaseResponse<OrderInfo> getOrderByPage(QueryPageByTimeDTO queryPageByTimeDTO) {
|
||||
QueryWrapper<OrderInfo> qw = new QueryWrapper<>();
|
||||
qw.eq("account_id",UserContext.getUserHolder().getId());
|
||||
qw.eq("account_id", UserContext.getUserHolder().getId());
|
||||
|
||||
String startTime = queryPageByTimeDTO.getStartTime();
|
||||
String endTime = queryPageByTimeDTO.getEndTime();
|
||||
if (StringUtil.isNullOrEmpty(startTime)){
|
||||
if (StringUtil.isNullOrEmpty(startTime)) {
|
||||
startTime = "2024-02-01 00:00:00";
|
||||
}
|
||||
if (StringUtil.isNullOrEmpty(endTime)){
|
||||
if (StringUtil.isNullOrEmpty(endTime)) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
endTime = now.format(dateTimeFormatter);
|
||||
@@ -206,11 +265,28 @@ public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo
|
||||
return PageBaseResponse.success(orderInfo);
|
||||
}
|
||||
|
||||
public void updateOrderNoById(Long id, String orderNo){
|
||||
public void updateOrderNoById(Long id, String orderNo) {
|
||||
OrderInfo orderInfo = new OrderInfo();
|
||||
orderInfo.setId(id);
|
||||
orderInfo.setOrderNo(orderNo);
|
||||
|
||||
baseMapper.updateById(orderInfo);
|
||||
}
|
||||
|
||||
public void updateTotalFeeByOrderNo(String orderNo) {
|
||||
QueryWrapper<PaymentInfo> qw = new QueryWrapper<>();
|
||||
qw.eq("order_no", orderNo);
|
||||
List<PaymentInfo> paymentInfos = paymentInfoMapper.selectList(qw);
|
||||
Float sum = paymentInfos.stream()
|
||||
.map(PaymentInfo::getPayerTotal)
|
||||
.reduce(0f, Float::sum);
|
||||
|
||||
baseMapper.update(
|
||||
new OrderInfo(),
|
||||
new UpdateWrapper<OrderInfo>()
|
||||
.eq("order_no", orderNo)
|
||||
.set("total_fee", sum)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.ai.da.common.utils.paypalRequest.AuthenticationRequest;
|
||||
import com.ai.da.common.utils.paypalRequest.WebhookVerifyRequest;
|
||||
import com.ai.da.mapper.primary.entity.OrderInfo;
|
||||
import com.ai.da.mapper.primary.entity.RefundInfo;
|
||||
import com.ai.da.model.dto.ProductPurchaseDTO;
|
||||
import com.ai.da.service.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.gson.Gson;
|
||||
@@ -84,17 +85,17 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public HashMap<String, String> createOrder(Integer amount, String returnUrl) throws SerializeException {
|
||||
public HashMap<String, String> createOrder(ProductPurchaseDTO productPurchaseDTO, HttpServletRequest request) throws SerializeException {
|
||||
// 生成订单
|
||||
log.info("生成订单");
|
||||
OrderInfo orderInfo = orderInfoService.createOrderByProductId(amount, PayTypeEnum.PAYPAL.getType());
|
||||
OrderInfo orderInfo = orderInfoService.createOrderByProductId(productPurchaseDTO.getQuantity(), PayTypeEnum.PAYPAL.getType(), request);
|
||||
|
||||
OrdersCreateRequest request = new OrdersCreateRequest();
|
||||
request.header("prefer", "return=representation");
|
||||
request.requestBody(buildRequestBody(String.valueOf(orderInfo.getTotalFee()), returnUrl));
|
||||
OrdersCreateRequest paypalRequest = new OrdersCreateRequest();
|
||||
paypalRequest.header("prefer", "return=representation");
|
||||
paypalRequest.requestBody(buildRequestBody(String.valueOf(orderInfo.getTotalFee()), productPurchaseDTO.getReturnUrl()));
|
||||
HttpResponse<Order> response = null;
|
||||
try {
|
||||
response = payPalClient.client(mode, clientId, clientSecret).execute(request);
|
||||
response = payPalClient.client(mode, clientId, clientSecret).execute(paypalRequest);
|
||||
} catch (Exception e) {
|
||||
log.error("调用paypal订单创建失败,失败原因 ===> {}", e.getMessage());
|
||||
throw new BusinessException("Order creation failed");
|
||||
@@ -441,11 +442,11 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
* 申请退款
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Boolean refundOrder(String orderId, String reason) throws IOException {
|
||||
public Boolean refundOrder(String orderNo, String reason) throws IOException {
|
||||
|
||||
RefundInfo refundByOrderNo = refundsInfoService.createRefundByOrderNo(orderId, reason);
|
||||
RefundInfo refundByOrderNo = refundsInfoService.createRefundByOrderNo(orderNo, reason);
|
||||
|
||||
OrdersGetRequest ordersGetRequest = new OrdersGetRequest(orderId);
|
||||
OrdersGetRequest ordersGetRequest = new OrdersGetRequest(orderNo);
|
||||
PayPalClient payPalClient = new PayPalClient();
|
||||
HttpResponse<com.paypal.orders.Order> ordersGetResponse = null;
|
||||
ordersGetRequest.authorization("Bearer " + getOAuth());
|
||||
@@ -461,7 +462,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
request.authorization("Bearer " + getOAuth());
|
||||
request.prefer("return=representation");
|
||||
|
||||
OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderId);
|
||||
OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
request.requestBody(buildRefundRequestBody(String.valueOf(orderInfo.getTotalFee()), reason));
|
||||
HttpResponse<com.paypal.payments.Refund> response = null;
|
||||
try {
|
||||
@@ -476,7 +477,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
//进行数据库操作,修改状态为已退款(配合回调和退款查询确定退款成功)
|
||||
|
||||
//更新订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderId, OrderStatusEnum.REFUND_SUCCESS);
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.REFUND_SUCCESS);
|
||||
|
||||
refundsInfoService.updateRefundForPayPal(
|
||||
refundByOrderNo.getId(),
|
||||
@@ -485,14 +486,14 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
AliPayTradeStateEnum.REFUND_SUCCESS.getType()); //退款成功
|
||||
|
||||
// 更新积分状态
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderId);
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
// creditsService.creditsRefund(orderByOrderNo.getAccountId(), orderByOrderNo.getTotalFee() / Integer.parseInt(CreditsEventsEnum.PRICE.getValue()));
|
||||
creditsService.creditsRefund(orderByOrderNo.getAccountId(), (int)(orderByOrderNo.getTotalFee() / Float.parseFloat(CreditsEventsEnum.PRICE.getValue())));
|
||||
creditsService.creditsRefund(orderByOrderNo.getAccountId(), (int)(orderByOrderNo.getTotalFee() / Float.parseFloat(CreditsEventsEnum.PRICE.getValue())), orderNo);
|
||||
log.info("退款成功");
|
||||
result = Boolean.TRUE;
|
||||
} else {
|
||||
//更新订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderId, OrderStatusEnum.REFUND_ABNORMAL);
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.REFUND_ABNORMAL);
|
||||
|
||||
//更新退款单
|
||||
refundsInfoService.updateRefundForPayPal(
|
||||
@@ -571,21 +572,21 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
|
||||
// 处理当前订单
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void processOrder(String orderId) {
|
||||
public void processOrder(String orderNo) {
|
||||
// 1、确定当前订单是否已经被扣款
|
||||
OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderId);
|
||||
OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
if (orderInfo.getOrderStatus().equals(OrderStatusEnum.SUCCESS.getType())) {
|
||||
// 直接返回
|
||||
return;
|
||||
}
|
||||
// 发起扣款请求
|
||||
Order capturedOrder = captureOrder(orderId);
|
||||
Order capturedOrder = captureOrder(orderNo);
|
||||
// 业务处理
|
||||
if (PayPalOrderStatusEnum.COMPLETED.getStatus().equals(capturedOrder.status())) {
|
||||
//更新订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderId, OrderStatusEnum.SUCCESS);
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.SUCCESS);
|
||||
//记录支付日志
|
||||
paymentInfoService.createPaymentInfoForPayPal(capturedOrder);
|
||||
paymentInfoService.createPaymentInfoForPayPal(capturedOrder, "credits");
|
||||
float quantity = orderInfo.getTotalFee() / Float.parseFloat(CreditsEventsEnum.PRICE.getValue());
|
||||
// 更新积分
|
||||
creditsService.buyCredits(orderInfo.getAccountId(), quantity);
|
||||
@@ -593,7 +594,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
creditsService.insertToCreditsDetail(orderInfo.getAccountId(),
|
||||
CreditsEventsEnum.BUY_CREDITS.getName() + "--PayPal",
|
||||
String.valueOf((Long.parseLong(CreditsEventsEnum.BUY_CREDITS.getValue()) * quantity)),
|
||||
"positive");
|
||||
"positive", orderNo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -628,7 +629,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
//如果订单已支付,则更新商户端订单状态
|
||||
orderInfoService.updateStatusByOrderNo(orderNo, OrderStatusEnum.SUCCESS);
|
||||
//并记录支付日志
|
||||
paymentInfoService.createPaymentInfoForPayPal(result);
|
||||
paymentInfoService.createPaymentInfoForPayPal(result, "credits");
|
||||
float quantity = orderByOrderNo.getTotalFee() / Float.parseFloat(CreditsEventsEnum.PRICE.getValue());
|
||||
// 更新积分
|
||||
// creditsService.buyCredits(orderByOrderNo.getAccountId(),orderByOrderNo.getTotalFee() / Integer.parseInt(CreditsEventsEnum.PRICE.getValue()));
|
||||
@@ -637,7 +638,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService {
|
||||
creditsService.insertToCreditsDetail(orderByOrderNo.getAccountId(),
|
||||
CreditsEventsEnum.BUY_CREDITS.getName() + "--Paypal",
|
||||
String.valueOf((Long.parseLong(CreditsEventsEnum.BUY_CREDITS.getValue()) * quantity)),
|
||||
"positive");
|
||||
"positive", orderNo);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,27 +1,53 @@
|
||||
package com.ai.da.service.impl;
|
||||
|
||||
import com.ai.da.common.context.UserContext;
|
||||
import com.ai.da.common.enums.PayTypeEnum;
|
||||
import com.ai.da.common.response.PageBaseResponse;
|
||||
import com.ai.da.mapper.primary.PaymentInfoMapper;
|
||||
import com.ai.da.mapper.primary.entity.OrderInfo;
|
||||
import com.ai.da.mapper.primary.entity.PaymentInfo;
|
||||
import com.ai.da.model.dto.AlipayHKCallbackDTO;
|
||||
import com.ai.da.service.PaymentInfoService;
|
||||
import com.ai.da.model.dto.QueryPageByTimeDTO;
|
||||
import com.ai.da.model.vo.OrderListVO;
|
||||
import com.ai.da.service.*;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.google.gson.Gson;
|
||||
import com.paypal.orders.Order;
|
||||
import com.stripe.Stripe;
|
||||
import com.stripe.exception.StripeException;
|
||||
import com.stripe.model.Charge;
|
||||
import com.stripe.model.Invoice;
|
||||
import com.stripe.model.Subscription;
|
||||
import com.stripe.model.checkout.Session;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
|
||||
|
||||
@Resource
|
||||
private StripeService stripeService;
|
||||
|
||||
@Resource
|
||||
private OrderInfoService orderInfoService;
|
||||
|
||||
/**
|
||||
* 记录支付日志:微信支付
|
||||
* @param plainText
|
||||
@@ -50,7 +76,6 @@ public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, Payme
|
||||
paymentInfo.setOrderNo(orderNo);
|
||||
paymentInfo.setPaymentType(PayTypeEnum.WXPAY.getType());
|
||||
paymentInfo.setTransactionId(transactionId);
|
||||
paymentInfo.setTradeType(tradeType);
|
||||
paymentInfo.setTradeState(tradeState);
|
||||
// 原来的单位是:分 Int 现改为:元 Float
|
||||
paymentInfo.setPayerTotal(payerTotal / 100.0F);
|
||||
@@ -64,7 +89,7 @@ public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, Payme
|
||||
* @param params
|
||||
*/
|
||||
@Override
|
||||
public void createPaymentInfoForAliPay(Map<String, String> params) {
|
||||
public void createPaymentInfoForAliPay(Map<String, String> params, String type) {
|
||||
|
||||
log.info("记录支付日志");
|
||||
|
||||
@@ -83,20 +108,26 @@ public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, Payme
|
||||
paymentInfo.setOrderNo(orderNo);
|
||||
paymentInfo.setPaymentType(PayTypeEnum.ALIPAY.getType());
|
||||
paymentInfo.setTransactionId(transactionId);
|
||||
paymentInfo.setTradeType("电脑网站支付");
|
||||
paymentInfo.setTradeState(tradeStatus);
|
||||
// 原来的单位是分 Int 现改为元 Long
|
||||
paymentInfo.setPayerTotal(totalAmountInt / 100.0F);
|
||||
paymentInfo.setType(type);
|
||||
|
||||
Gson gson = new Gson();
|
||||
String json = gson.toJson(params, HashMap.class);
|
||||
paymentInfo.setContent(json);
|
||||
|
||||
// 获取订单信息
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
if (!Objects.isNull(orderByOrderNo)){
|
||||
paymentInfo.setCountry(orderByOrderNo.getCountry());
|
||||
paymentInfo.setCity(orderByOrderNo.getCity());
|
||||
paymentInfo.setIpAddress(orderByOrderNo.getIpAddress());
|
||||
}
|
||||
baseMapper.insert(paymentInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createPaymentInfoForPayPal(Order order) {
|
||||
public void createPaymentInfoForPayPal(Order order, String type) {
|
||||
|
||||
log.info("记录支付日志");
|
||||
|
||||
@@ -107,20 +138,26 @@ public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, Payme
|
||||
paymentInfo.setOrderNo(order.id());
|
||||
paymentInfo.setPaymentType(PayTypeEnum.PAYPAL.getType());
|
||||
paymentInfo.setTransactionId(order.id());
|
||||
paymentInfo.setTradeType("电脑网站支付");
|
||||
paymentInfo.setTradeState(order.status());
|
||||
// todo 确认这里的数据单位是不是元
|
||||
// 确认这里的数据单位是不是元
|
||||
paymentInfo.setPayerTotal(totalAmountFloat);
|
||||
paymentInfo.setType(type);
|
||||
|
||||
Gson gson = new Gson();
|
||||
String json = gson.toJson(order, Order.class);
|
||||
paymentInfo.setContent(json);
|
||||
|
||||
// 获取订单信息
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(order.id());
|
||||
if (!Objects.isNull(orderByOrderNo)){
|
||||
paymentInfo.setCountry(orderByOrderNo.getCountry());
|
||||
paymentInfo.setCity(orderByOrderNo.getCity());
|
||||
paymentInfo.setIpAddress(orderByOrderNo.getIpAddress());
|
||||
}
|
||||
baseMapper.insert(paymentInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createPaymentInfoForAliPayHK(AlipayHKCallbackDTO alipayHKCallbackDTO) {
|
||||
public void createPaymentInfoForAliPayHK(AlipayHKCallbackDTO alipayHKCallbackDTO, String type) {
|
||||
|
||||
log.info("记录支付日志");
|
||||
|
||||
@@ -139,21 +176,27 @@ public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, Payme
|
||||
paymentInfo.setOrderNo(orderNo);
|
||||
paymentInfo.setPaymentType(PayTypeEnum.ALIPAY_HK.getType());
|
||||
paymentInfo.setTransactionId(transactionId);
|
||||
paymentInfo.setTradeType("电脑网站支付");
|
||||
paymentInfo.setTradeState(tradeStatus);
|
||||
paymentInfo.setPayerTotal(totalAmountFloat);
|
||||
paymentInfo.setType(type);
|
||||
|
||||
Gson gson = new Gson();
|
||||
String json = gson.toJson(alipayHKCallbackDTO);
|
||||
paymentInfo.setContent(json);
|
||||
|
||||
// 获取订单信息
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
if (!Objects.isNull(orderByOrderNo)){
|
||||
paymentInfo.setCountry(orderByOrderNo.getCountry());
|
||||
paymentInfo.setCity(orderByOrderNo.getCity());
|
||||
paymentInfo.setIpAddress(orderByOrderNo.getIpAddress());
|
||||
}
|
||||
baseMapper.insert(paymentInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createPaymentInfoForStripe(Session session){
|
||||
public void createOrUpdatePaymentInfoForStripe(Session session){
|
||||
String orderId = session.getMetadata().get("orderId");
|
||||
String status = session.getStatus();
|
||||
// 获取transactionId,从sessionId更改为invoiceId
|
||||
String sessionId = session.getId();
|
||||
Long amountTotal = session.getAmountTotal();
|
||||
// stripe 的支付金额单位是分
|
||||
@@ -163,22 +206,173 @@ public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, Payme
|
||||
paymentInfo.setOrderNo(orderId);
|
||||
paymentInfo.setPaymentType(PayTypeEnum.STRIPE.getType());
|
||||
paymentInfo.setTransactionId(sessionId);
|
||||
paymentInfo.setTradeType("电脑网站支付");
|
||||
paymentInfo.setTradeState(status);
|
||||
paymentInfo.setPayerTotal(divide);
|
||||
Gson gson = new Gson();
|
||||
String json = gson.toJson(session);
|
||||
paymentInfo.setContent(json);
|
||||
|
||||
// 获取订单信息
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderId);
|
||||
if (!Objects.isNull(orderByOrderNo)){
|
||||
paymentInfo.setCountry(orderByOrderNo.getCountry());
|
||||
paymentInfo.setCity(orderByOrderNo.getCity());
|
||||
paymentInfo.setIpAddress(orderByOrderNo.getIpAddress());
|
||||
}
|
||||
baseMapper.insert(paymentInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaymentInfo getPaymentInfoByOrderId(String orderId){
|
||||
QueryWrapper<PaymentInfo> qw = new QueryWrapper<>();
|
||||
qw.eq("order_no", orderId);
|
||||
@Value("${stripe.private-key}")
|
||||
private String privateKey;
|
||||
public PaymentInfo createOrUpdatePaymentInfoForStripe(Invoice invoice){
|
||||
Stripe.apiKey = privateKey;
|
||||
// 获取transactionId,从sessionId更改为invoiceId
|
||||
String invoiceId = invoice.getId();
|
||||
|
||||
return baseMapper.selectOne(qw);
|
||||
QueryWrapper<PaymentInfo> qw = new QueryWrapper<>();
|
||||
qw.eq("transaction_id", invoiceId);
|
||||
PaymentInfo paymentInfo = baseMapper.selectOne(qw);
|
||||
String status = invoice.getStatus();
|
||||
// 判断当前支付是否已经被记录,确保同一个支付不会被重复记录
|
||||
if (Objects.isNull(paymentInfo)){
|
||||
String orderNo;
|
||||
try {
|
||||
if (invoice.getBillingReason().equals("manual")){
|
||||
// 手动创建的发票,针对one-time支付
|
||||
orderNo = invoice.getLines().getData().get(0).getPrice().getMetadata().get("orderId");
|
||||
}else {
|
||||
String subscriptionId = invoice.getSubscription();
|
||||
// 从subscription中获取orderNo
|
||||
orderNo = Subscription.retrieve(subscriptionId).getDescription().replace("AiDA - ", "");
|
||||
}
|
||||
} catch (StripeException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Long amountTotal;
|
||||
if (status.equals("paid")){
|
||||
amountTotal = invoice.getAmountPaid();
|
||||
}else {
|
||||
amountTotal = invoice.getAmountDue();
|
||||
}
|
||||
|
||||
// stripe 的支付金额单位是分,在我们数据库中金额单位为 元
|
||||
Float divide = new BigDecimal(amountTotal).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).floatValue();
|
||||
String type = invoice.getBillingReason().equals("subscription_create") ? "new" :
|
||||
invoice.getBillingReason().equals("subscription_cycle") ? "renewal" : invoice.getBillingReason();
|
||||
|
||||
// 获取支付方式
|
||||
Map<String, String> paymentMethod = stripeService.getPaymentMethodByInvoiceId(invoiceId);
|
||||
// 获取订单信息
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
|
||||
paymentInfo = new PaymentInfo();
|
||||
paymentInfo.setOrderNo(orderNo);
|
||||
paymentInfo.setPaymentType(PayTypeEnum.STRIPE.getType());
|
||||
paymentInfo.setTransactionId(invoiceId);
|
||||
// 使用invoice的状态
|
||||
paymentInfo.setTradeState(status);
|
||||
paymentInfo.setPayerTotal(divide);
|
||||
Gson gson = new Gson();
|
||||
String json = gson.toJson(invoice);
|
||||
paymentInfo.setContent(json);
|
||||
paymentInfo.setType(type);
|
||||
paymentInfo.setNotified(0);
|
||||
paymentInfo.setPaymentMethod(paymentMethod.get("paymentMethod"));
|
||||
paymentInfo.setLast4(paymentMethod.get("last4"));
|
||||
paymentInfo.setHostedInvoiceUrl(invoice.getHostedInvoiceUrl());
|
||||
paymentInfo.setCreateTime(LocalDateTime.now());
|
||||
if (!Objects.isNull(orderByOrderNo)){
|
||||
paymentInfo.setCountry(orderByOrderNo.getCountry());
|
||||
paymentInfo.setCity(orderByOrderNo.getCity());
|
||||
paymentInfo.setIpAddress(orderByOrderNo.getIpAddress());
|
||||
}
|
||||
baseMapper.insert(paymentInfo);
|
||||
}else {
|
||||
paymentInfo.setTradeState(status);
|
||||
paymentInfo.setUpdateTime(LocalDateTime.now());
|
||||
baseMapper.updateById(paymentInfo);
|
||||
}
|
||||
return paymentInfo;
|
||||
}
|
||||
|
||||
public PaymentInfo createOrUpdatePaymentInfoForStripe(Charge charge){
|
||||
Stripe.apiKey = privateKey;
|
||||
QueryWrapper<PaymentInfo> qw = new QueryWrapper<>();
|
||||
qw.eq("transaction_id", charge.getInvoice());
|
||||
PaymentInfo paymentInfo = baseMapper.selectOne(qw);
|
||||
Charge.PaymentMethodDetails paymentMethodDetails = charge.getPaymentMethodDetails();
|
||||
String paymentMethod;
|
||||
String last4 = "N/A";
|
||||
switch (paymentMethodDetails.getType()){
|
||||
case "alipay":
|
||||
paymentMethod = "Alipay";
|
||||
break;
|
||||
case "bancontact":
|
||||
paymentMethod = "BanContact";
|
||||
break;
|
||||
case "card":
|
||||
Charge.PaymentMethodDetails.Card card = paymentMethodDetails.getCard();
|
||||
String brand = card.getBrand();
|
||||
brand = brand.substring(0, 1).toUpperCase() + brand.substring(1);
|
||||
paymentMethod = brand + " " + card.getFunding() + "card";
|
||||
last4 = card.getLast4();
|
||||
break;
|
||||
case "eps":
|
||||
Charge.PaymentMethodDetails.Eps eps = paymentMethodDetails.getEps();
|
||||
paymentMethod = eps.getBank();
|
||||
break;
|
||||
case "giropay":
|
||||
paymentMethod = "GiroPay";
|
||||
break;
|
||||
case "ideal":
|
||||
Charge.PaymentMethodDetails.Ideal ideal = paymentMethodDetails.getIdeal();
|
||||
paymentMethod = ideal.getBank();
|
||||
break;
|
||||
case "link":
|
||||
paymentMethod = "Link";
|
||||
break;
|
||||
default:
|
||||
paymentMethod = "N/A";
|
||||
}
|
||||
if (Objects.isNull(paymentInfo)){
|
||||
Stripe.apiKey = privateKey;
|
||||
|
||||
String orderNo = charge.getDescription().replace("AiDA - ", "");
|
||||
OrderInfo orderByOrderNo = orderInfoService.getOrderByOrderNo(orderNo);
|
||||
Float divide = new BigDecimal(charge.getAmount()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).floatValue();
|
||||
paymentInfo = new PaymentInfo();
|
||||
paymentInfo.setOrderNo(orderNo);
|
||||
paymentInfo.setTransactionId(charge.getInvoice());
|
||||
paymentInfo.setPaymentType(PayTypeEnum.STRIPE.getType());
|
||||
paymentInfo.setTradeState(charge.getStatus());
|
||||
paymentInfo.setPayerTotal(divide);
|
||||
paymentInfo.setNotified(0);
|
||||
paymentInfo.setPaymentMethod(paymentMethod);
|
||||
paymentInfo.setLast4(last4);
|
||||
paymentInfo.setCreateTime(LocalDateTime.now());
|
||||
if (!Objects.isNull(orderByOrderNo)){
|
||||
paymentInfo.setCountry(orderByOrderNo.getCountry());
|
||||
paymentInfo.setCity(orderByOrderNo.getCity());
|
||||
paymentInfo.setIpAddress(orderByOrderNo.getIpAddress());
|
||||
}
|
||||
baseMapper.insert(paymentInfo);
|
||||
}else {
|
||||
paymentInfo.setTradeState(charge.getStatus());
|
||||
paymentInfo.setPaymentMethod(paymentMethod);
|
||||
paymentInfo.setLast4(last4);
|
||||
paymentInfo.setUpdateTime(LocalDateTime.now());
|
||||
baseMapper.updateById(paymentInfo);
|
||||
}
|
||||
|
||||
return paymentInfo;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<PaymentInfo> getPaymentInfoByOrderNo(String orderId, String order){
|
||||
QueryWrapper<PaymentInfo> qw = new QueryWrapper<>();
|
||||
qw.eq("order_no", orderId).orderByDesc(order.equals("DESC"),"id");
|
||||
|
||||
return baseMapper.selectList(qw);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -190,4 +384,37 @@ public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, Payme
|
||||
|
||||
baseMapper.updateById(paymentInfo);
|
||||
}
|
||||
|
||||
public PageBaseResponse<OrderListVO> getPaymentInfo(QueryPageByTimeDTO queryPageByTimeDTO){
|
||||
Long accountId = UserContext.getUserHolder().getId();
|
||||
|
||||
String startTime = queryPageByTimeDTO.getStartTime();
|
||||
String endTime = queryPageByTimeDTO.getEndTime();
|
||||
if (StringUtil.isNullOrEmpty(startTime)) {
|
||||
startTime = "2024-02-01 00:00:00";
|
||||
}
|
||||
if (StringUtil.isNullOrEmpty(endTime)) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
endTime = now.format(dateTimeFormatter);
|
||||
}
|
||||
|
||||
int offset = (queryPageByTimeDTO.getPage() - 1) * queryPageByTimeDTO.getSize();
|
||||
List<OrderListVO> orderListVOS = baseMapper.selectPageOrderList(accountId, startTime, endTime, offset,
|
||||
queryPageByTimeDTO.getSize(), queryPageByTimeDTO.getId());
|
||||
|
||||
if (CollectionUtils.isEmpty(orderListVOS)) {
|
||||
return PageBaseResponse.success(new Page<>());
|
||||
}else {
|
||||
int totalCount = baseMapper.queryOrderListTotalCount(accountId, startTime, endTime, queryPageByTimeDTO.getId());
|
||||
IPage<OrderListVO> orderListVOIPage = new Page<>();
|
||||
Integer size = queryPageByTimeDTO.getSize();
|
||||
orderListVOIPage.setSize(size);
|
||||
orderListVOIPage.setRecords(orderListVOS);
|
||||
orderListVOIPage.setCurrent(queryPageByTimeDTO.getPage());
|
||||
orderListVOIPage.setPages((long)Math.ceil((double) totalCount / size));
|
||||
orderListVOIPage.setTotal(totalCount);
|
||||
return PageBaseResponse.success(orderListVOIPage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -149,7 +149,7 @@ public class SuperResolutionServiceImpl extends ServiceImpl<TaskListMapper, Task
|
||||
creditsService.insertToCreditsDetail(accountId,
|
||||
CreditsEventsEnum.SUPER_RESOLUTION.getName(),
|
||||
CreditsEventsEnum.SUPER_RESOLUTION.getValue(),
|
||||
"negative");
|
||||
"negative", null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.ai.da.mapper.primary.entity.Tags;
|
||||
import com.ai.da.service.TagsService;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -19,7 +20,10 @@ public class TagsServiceImpl extends ServiceImpl<TagsMapper, Tags> implements Ta
|
||||
public List<Tags> getTags(String tagPrefix){
|
||||
// 1、根据tag前缀,查询
|
||||
QueryWrapper<Tags> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.likeRight("tag_name", tagPrefix);
|
||||
if (!StringUtil.isNullOrEmpty(tagPrefix)) {
|
||||
queryWrapper.like("tag_name", tagPrefix);
|
||||
}
|
||||
queryWrapper.orderByDesc("id").last("limit 10");
|
||||
|
||||
// 需返回标签内容和id
|
||||
return baseMapper.selectList(queryWrapper);
|
||||
|
||||
@@ -5,11 +5,14 @@ import com.ai.da.common.config.exception.BusinessException;
|
||||
import com.ai.da.common.constant.CommonConstant;
|
||||
import com.ai.da.common.context.UserContext;
|
||||
import com.ai.da.common.enums.CreditsEventsEnum;
|
||||
import com.ai.da.common.response.ResultEnum;
|
||||
import com.ai.da.common.utils.*;
|
||||
import com.ai.da.mapper.primary.*;
|
||||
import com.ai.da.mapper.primary.entity.*;
|
||||
import com.ai.da.mapper.secondary.AttributeRetrievalMapper;
|
||||
import com.ai.da.mapper.secondary.entity.AttributeRecognitionJSON;
|
||||
import com.ai.da.model.dto.PortfolioDTO;
|
||||
import com.ai.da.model.dto.ProductImageInitializeDTO;
|
||||
import com.ai.da.model.dto.ProductImageLikeDTO;
|
||||
import com.ai.da.model.dto.ToProductImageDTO;
|
||||
import com.ai.da.model.vo.*;
|
||||
@@ -82,6 +85,10 @@ public class UserLikeGroupServiceImpl extends ServiceImpl<UserLikeGroupMapper, U
|
||||
private CollectionElementMapper collectionElementMapper;
|
||||
@Resource
|
||||
private AttributeRetrievalMapper attributeRetrievalMapper;
|
||||
@Resource
|
||||
private ProductImageAttributeMapper productImageAttributeMapper;
|
||||
@Resource
|
||||
private UserLikeSortMapper userLikeSortMapper;
|
||||
|
||||
@Override
|
||||
public void deleteUserGroup(Long userGroupId) {
|
||||
@@ -147,6 +154,22 @@ public class UserLikeGroupServiceImpl extends ServiceImpl<UserLikeGroupMapper, U
|
||||
}
|
||||
List<UserLikeVO> userLikeVOS = userLikeService.getGroupDetail(userGroupId);
|
||||
String sex = null;
|
||||
|
||||
QueryWrapper<UserLikeSort> userLikeSortQw = new QueryWrapper<>();
|
||||
userLikeSortQw.lambda().eq(UserLikeSort::getUserLikeGroupId, userGroupId);
|
||||
List<UserLikeSort> userLikeSortList = userLikeSortMapper.selectList(userLikeSortQw);
|
||||
if (CollectionUtil.isEmpty(userLikeSortList)) {
|
||||
Integer sort = 1;
|
||||
for (UserLikeVO userLikeVO : userLikeVOS) {
|
||||
UserLikeSort userLikeSort = new UserLikeSort();
|
||||
userLikeSort.setUserLikeId(userLikeVO.getId());
|
||||
userLikeSort.setUserLikeGroupId(userGroupId);
|
||||
userLikeSort.setSort(sort);
|
||||
userLikeSortMapper.insert(userLikeSort);
|
||||
sort ++;
|
||||
}
|
||||
}
|
||||
|
||||
userLikeVOS.forEach(o -> {
|
||||
TDesignPythonOutfit tDesignPythonOutfit1 = designPythonOutfitMapper.selectById(o.getDesignOutfitId());
|
||||
o.setUrl(tDesignPythonOutfit1.getDesignUrl());
|
||||
@@ -162,6 +185,15 @@ public class UserLikeGroupServiceImpl extends ServiceImpl<UserLikeGroupMapper, U
|
||||
TDesignPythonOutfit tDesignPythonOutfit = tDesignPythonOutfits.get(0);
|
||||
o.setDesignOutfitId(tDesignPythonOutfit.getId());
|
||||
}
|
||||
|
||||
QueryWrapper<UserLikeSort> userLikeSortQueryWrapper = new QueryWrapper<>();
|
||||
userLikeSortQueryWrapper.lambda().eq(UserLikeSort::getUserLikeId, o.getId());
|
||||
List<UserLikeSort> userLikeSorts = userLikeSortMapper.selectList(userLikeSortQueryWrapper);
|
||||
if (CollectionUtil.isNotEmpty(userLikeSorts)) {
|
||||
UserLikeSort userLikeSort = userLikeSorts.get(0);
|
||||
o.setSort(userLikeSort.getSort());
|
||||
o.setUserLikeSortId(userLikeSort.getId());
|
||||
}
|
||||
});
|
||||
UserLikeCollectionVO userLikeCollection = collectionService.chooseCollection(group.getCollectionId());
|
||||
Integer beenPublished = 0;
|
||||
@@ -243,7 +275,7 @@ public class UserLikeGroupServiceImpl extends ServiceImpl<UserLikeGroupMapper, U
|
||||
// 判断用户当前积分是否够本次生成消耗
|
||||
Boolean preDeduction = creditsService.creditsPreDeduction(CreditsEventsEnum.TO_PRODUCT_IMAGE, toProductImageDTO.getToProductImageVOList().size());
|
||||
if (!preDeduction) {
|
||||
throw new BusinessException("Not enough Credits");
|
||||
throw new BusinessException("Your remaining credits are insufficient for this generation. Please recharge.", ResultEnum.WARNING.getCode());
|
||||
}
|
||||
|
||||
AuthPrincipalVo userHolder = UserContext.getUserHolder();
|
||||
@@ -509,7 +541,7 @@ public class UserLikeGroupServiceImpl extends ServiceImpl<UserLikeGroupMapper, U
|
||||
// 判断用户当前积分是否够本次生成消耗
|
||||
Boolean preDeduction = creditsService.creditsPreDeduction(CreditsEventsEnum.RELIGHT, toProductImageDTO.getToProductImageVOList().size());
|
||||
if (!preDeduction) {
|
||||
throw new BusinessException("Not enough Credits");
|
||||
throw new BusinessException("Your remaining credits are insufficient for this generation. Please recharge.", ResultEnum.WARNING.getCode());
|
||||
}
|
||||
|
||||
AuthPrincipalVo userHolder = UserContext.getUserHolder();
|
||||
@@ -836,4 +868,53 @@ public class UserLikeGroupServiceImpl extends ServiceImpl<UserLikeGroupMapper, U
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public Boolean productImageInitialize(ProductImageInitializeDTO productImageInitializeDTO) {
|
||||
|
||||
AuthPrincipalVo authPrincipalVo = UserContext.getUserHolder();
|
||||
accountService.getById(authPrincipalVo.getId());
|
||||
|
||||
for (Long libraryId : productImageInitializeDTO.getLibraryIds()) {
|
||||
Library library = libraryMapper.selectById(libraryId);
|
||||
String url = library.getUrl();
|
||||
String gender = library.getLevel2Type();
|
||||
|
||||
String clothCategory = pythonService.getClothCategory(url, gender);
|
||||
JSONObject attributeRecognition = pythonService.getAttributeRecognition(url, clothCategory, gender);
|
||||
JSONObject data = attributeRecognition.getJSONObject("data");
|
||||
JSONObject attrDict = ((JSONObject) data.getJSONArray("list").get(0)).getJSONObject("attr_dict");
|
||||
AttributeRecognitionJSON attrDictJSON = attrDict.toJavaObject(AttributeRecognitionJSON.class);
|
||||
ProductImageAttribute productImageAttribute = toAttrDict(attrDictJSON);
|
||||
productImageAttributeMapper.insert(productImageAttribute);
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private ProductImageAttribute toAttrDict(AttributeRecognitionJSON attrDictJSON) {
|
||||
ProductImageAttribute attributeRetrieval = new ProductImageAttribute();
|
||||
// attributeRetrieval.setImgName(attrDictJSON.getImgName().get(0));
|
||||
// attributeRetrieval.setLength(attrDictJSON.getLength().get(0));
|
||||
// attributeRetrieval.setSleeveLength(attrDictJSON.getSleeveLength().get(0));
|
||||
// attributeRetrieval.setSleeveShape(attrDictJSON.getSleeveShape().get(0));
|
||||
// attributeRetrieval.setSleeveShoulder(attrDictJSON.getSleeveShoulder().get(0));
|
||||
// attributeRetrieval.setNeckline(attrDictJSON.getNeckline().get(0));
|
||||
// attributeRetrieval.setCollar(attrDictJSON.getCollar().get(0));
|
||||
if (CollectionUtil.isNotEmpty(attrDictJSON.getDesign()) && attrDictJSON.getDesign().get(0) != null) {
|
||||
attributeRetrieval.setDesign(attrDictJSON.getDesign().get(0));
|
||||
}
|
||||
if (CollectionUtil.isNotEmpty(attrDictJSON.getSilhouette()) && attrDictJSON.getSilhouette().get(0) != null) {
|
||||
attributeRetrieval.setSilhouette(attrDictJSON.getSilhouette().get(0));
|
||||
}
|
||||
if (CollectionUtil.isNotEmpty(attrDictJSON.getType()) && attrDictJSON.getType().get(0) != null) {
|
||||
attributeRetrieval.setType(attrDictJSON.getType().get(0));
|
||||
}
|
||||
if (CollectionUtil.isNotEmpty(attrDictJSON.getSubtype()) && attrDictJSON.getSubtype().get(0) != null) {
|
||||
attributeRetrieval.setSubtype(attrDictJSON.getSubtype().get(0));
|
||||
}
|
||||
if (CollectionUtil.isNotEmpty(attrDictJSON.getOpeningType()) && attrDictJSON.getOpeningType().get(0) != null) {
|
||||
attributeRetrieval.setOpeningType(attrDictJSON.getOpeningType().get(0));
|
||||
}
|
||||
return attributeRetrieval;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user