Merge remote-tracking branch 'origin/dev' into dev

This commit is contained in:
2025-08-09 20:24:06 +08:00
60 changed files with 1670 additions and 3272 deletions

View File

@@ -13,6 +13,7 @@ import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@@ -34,6 +35,7 @@ public class BszxBmController extends BaseController {
@Resource
private BszxBmService bszxBmService;
@Resource
@Lazy
private CmsArticleService cmsArticleService;
@PreAuthorize("hasAuthority('bszx:bszxBm:list')")

View File

@@ -195,7 +195,7 @@ public class BszxPayController extends BaseController {
final HashMap<String, Object> map = new HashMap<>();
final LambdaQueryWrapper<BszxPay> wrapper = new LambdaQueryWrapper<>();
final BigDecimal bigDecimal = bszxPayService.sumMoney(wrapper);
Long count = bszxPayService.count(new LambdaQueryWrapper<BszxPay>());
Long count = (long) bszxPayService.count(new LambdaQueryWrapper<BszxPay>());
map.put("numbers", count);
map.put("totalMoney", bigDecimal);
return success(map);

View File

@@ -85,7 +85,7 @@ public class BszxPayRankingController extends BaseController {
wrapper.eq(BszxPay::getFormId, item.getArticleId());
ranking.setFormId(item.getArticleId());
ranking.setFormName(item.getTitle());
ranking.setNumber(bszxPayService.count(wrapper));
ranking.setNumber((long) bszxPayService.count(wrapper));
ranking.setTotalPrice(bszxPayService.sumMoney(wrapper));
rankings.add(ranking);
});

View File

@@ -24,6 +24,7 @@ import com.gxwebsoft.common.core.utils.ImageUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@@ -49,6 +50,7 @@ public class BszxBmServiceImpl extends ServiceImpl<BszxBmMapper, BszxBm> impleme
@Resource
private ConfigProperties config;
@Resource
@Lazy
private CmsArticleService cmsArticleService;
@Resource
private BszxClassService bszxClassService;

View File

@@ -20,6 +20,7 @@ import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
@@ -52,6 +53,7 @@ public class CmsArticleController extends BaseController {
@Resource
private CmsArticleContentService articleContentService;
@Resource
@Lazy
private CmsNavigationService cmsNavigationService;
@Resource
private CmsModelService cmsModelService;
@@ -235,17 +237,17 @@ public class CmsArticleController extends BaseController {
wrapper.eq(CmsArticle::getMerchantId, param.getMerchantId());
}
Long totalNum = cmsArticleService.count(
long totalNum = cmsArticleService.count(
wrapper.eq(CmsArticle::getDeleted, 0).eq(CmsArticle::getStatus, 0)
);
data.put("totalNum", Math.toIntExact(totalNum));
Long totalNum2 = cmsArticleService.count(
long totalNum2 = cmsArticleService.count(
wrapper.eq(CmsArticle::getStatus, 1)
);
data.put("totalNum2", Math.toIntExact(totalNum2));
Long totalNum3 = cmsArticleService.count(
long totalNum3 = cmsArticleService.count(
wrapper.gt(CmsArticle::getStatus, 1)
);
data.put("totalNum3", Math.toIntExact(totalNum3));

View File

@@ -17,6 +17,7 @@ import com.gxwebsoft.common.core.utils.AliYunSender;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@@ -33,12 +34,12 @@ import java.util.Map;
@Service
public class CmsArticleContentServiceImpl extends ServiceImpl<CmsArticleContentMapper, CmsArticleContent> implements CmsArticleContentService {
@Resource
@Lazy
private CmsNavigationService cmsNavigationService;
@Resource
@Lazy
private CmsArticleService cmsArticleService;
@Resource
private CmsArticleContentService cmsArticleContentService;
@Resource
private CmsLangLogService cmsLangLogService;
@Override
public PageResult<CmsArticleContent> pageRel(CmsArticleContentParam param) {
@@ -139,7 +140,7 @@ public class CmsArticleContentServiceImpl extends ServiceImpl<CmsArticleContentM
target.setContent(article.getContent());
System.out.println("target = " + target);
cmsArticleService.updateById(target);
cmsArticleContentService.update(new LambdaUpdateWrapper<CmsArticleContent>().eq(CmsArticleContent::getArticleId, target.getArticleId()).set(CmsArticleContent::getContent,target.getContent()));
this.update(new LambdaUpdateWrapper<CmsArticleContent>().eq(CmsArticleContent::getArticleId, target.getArticleId()).set(CmsArticleContent::getContent,target.getContent()));
}
}else {
// 新增操作
@@ -149,7 +150,7 @@ public class CmsArticleContentServiceImpl extends ServiceImpl<CmsArticleContentM
content.setArticleId(article.getArticleId());
content.setContent(article.getContent());
content.setTenantId(article.getTenantId());
cmsArticleContentService.save(content);
this.save(content);
}
}

View File

@@ -20,6 +20,7 @@ import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.service.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@@ -41,12 +42,11 @@ import static com.gxwebsoft.common.core.constants.ArticleConstants.CACHE_KEY_ART
@Service
public class CmsArticleServiceImpl extends ServiceImpl<CmsArticleMapper, CmsArticle> implements CmsArticleService {
@Resource
@Lazy
private CmsNavigationService cmsNavigationService;
@Resource
private CmsArticleContentService cmsArticleContentService;
@Resource
private CmsArticleContentService articleContentService;
@Resource
private UserService userService;
@Resource
private CmsModelService cmsModelService;
@@ -122,7 +122,7 @@ public class CmsArticleServiceImpl extends ServiceImpl<CmsArticleMapper, CmsArti
// article.setBanner(model.getBanner());
// }
// 附加文字内容
CmsArticleContent content = articleContentService.getOne(new LambdaQueryWrapper<CmsArticleContent>().eq(CmsArticleContent::getArticleId, article.getArticleId()).last("limit 1"));
CmsArticleContent content = cmsArticleContentService.getOne(new LambdaQueryWrapper<CmsArticleContent>().eq(CmsArticleContent::getArticleId, article.getArticleId()).last("limit 1"));
if (content != null) {
article.setContent(content.getContent());
}
@@ -172,9 +172,9 @@ public class CmsArticleServiceImpl extends ServiceImpl<CmsArticleMapper, CmsArti
content.setArticleId(article.getArticleId());
content.setContent(article.getContent());
content.setTenantId(article.getTenantId());
articleContentService.save(content);
cmsArticleContentService.save(content);
// 同步翻译并保存
articleContentService.translate(article);
cmsArticleContentService.translate(article);
return true;
}
} catch (Exception e) {
@@ -221,11 +221,11 @@ public class CmsArticleServiceImpl extends ServiceImpl<CmsArticleMapper, CmsArti
String key = CACHE_KEY_ARTICLE + article.getArticleId();
redisUtil.delete(key);
// 更新内容
final boolean update = articleContentService.update(new LambdaUpdateWrapper<CmsArticleContent>().eq(CmsArticleContent::getArticleId, article.getArticleId()).set(CmsArticleContent::getContent, article.getContent()));
final boolean update = cmsArticleContentService.update(new LambdaUpdateWrapper<CmsArticleContent>().eq(CmsArticleContent::getArticleId, article.getArticleId()).set(CmsArticleContent::getContent, article.getContent()));
if (update) {
// 同步翻译并保存
article.setIsUpdate(true);
articleContentService.translate(article);
cmsArticleContentService.translate(article);
return true;
} else {
// 添加内容
@@ -233,7 +233,7 @@ public class CmsArticleServiceImpl extends ServiceImpl<CmsArticleMapper, CmsArti
content.setArticleId(article.getArticleId());
content.setContent(article.getContent());
content.setTenantId(article.getTenantId());
articleContentService.save(content);
cmsArticleContentService.save(content);
}
return true;
}

View File

@@ -20,6 +20,7 @@ import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@@ -39,8 +40,10 @@ public class CmsDesignServiceImpl extends ServiceImpl<CmsDesignMapper, CmsDesign
@Resource
private CmsLangLogService cmsLangLogService;
@Resource
@Lazy
private CmsNavigationService cmsNavigationService;
@Resource
@Lazy
private CmsArticleContentService cmsArticleContentService;
@Override

View File

@@ -16,6 +16,7 @@ import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.service.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@@ -31,12 +32,11 @@ import java.util.List;
@Service
public class CmsNavigationServiceImpl extends ServiceImpl<CmsNavigationMapper, CmsNavigation> implements CmsNavigationService {
@Resource
@Lazy
private CmsDesignService cmsDesignService;
@Resource
private CmsModelService cmsModelService;
@Resource
private CmsNavigationService cmsNavigationService;
@Resource
private UserService userService;
@Override
@@ -67,7 +67,7 @@ public class CmsNavigationServiceImpl extends ServiceImpl<CmsNavigationMapper, C
}
// 父级栏目并且是page模型则读取子项目第一条
if (navigation.getParentId().equals(0) && navigation.getModel().equals("page")) {
final CmsNavigation parent = cmsNavigationService.getOne(new LambdaQueryWrapper<CmsNavigation>().eq(CmsNavigation::getParentId, navigation.getNavigationId()).last("limit 1"));
final CmsNavigation parent = this.getOne(new LambdaQueryWrapper<CmsNavigation>().eq(CmsNavigation::getParentId, navigation.getNavigationId()).last("limit 1"));
if (ObjectUtil.isNotEmpty(parent)) {
navigation = parent;
}

View File

@@ -14,52 +14,57 @@ import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "mqtt")
public class MqttProperties {
/**
* 是否启用MQTT服务
*/
private boolean enabled = false;
/**
* MQTT服务器地址
*/
private String host = "tcp://127.0.0.1:1883";
/**
* 用户名
*/
private String username = "";
/**
* 密码
*/
private String password = "";
/**
* 客户端ID前缀
*/
private String clientIdPrefix = "mqtt_client_";
/**
* 订阅主题
*/
private String topic = "/SW_GPS/#";
/**
* QoS等级
*/
private int qos = 2;
/**
* 连接超时时间(秒)
*/
private int connectionTimeout = 10;
/**
* 心跳间隔(秒)
*/
private int keepAliveInterval = 20;
/**
* 是否自动重连
*/
private boolean autoReconnect = true;
/**
* 是否清除会话
*/

View File

@@ -19,6 +19,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* MybatisPlus配置
@@ -32,28 +34,36 @@ public class MybatisPlusConfig {
private RedisUtil redisUtil;
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(HttpServletRequest request) {
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 多租户插件配置
TenantLineHandler tenantLineHandler = new TenantLineHandler() {
@Override
public Expression getTenantId() {
String tenantId;
// 从请求头拿ID
tenantId = request.getHeader("tenantId");
if(tenantId != null){
return new LongValue(tenantId);
}
// 从域名拿ID
String Domain = request.getHeader("Domain");
if (StrUtil.isNotBlank(Domain)) {
String key = "Domain:" + Domain;
tenantId = redisUtil.get(key);
if(tenantId != null){
System.out.println("从域名拿TID = " + tenantId);
return new LongValue(tenantId);
String tenantId = null;
try {
// 从Spring上下文获取当前请求
HttpServletRequest request = getCurrentRequest();
if (request != null) {
// 从请求头拿ID
tenantId = request.getHeader("tenantId");
if(tenantId != null){
return new LongValue(tenantId);
}
// 从域名拿ID
String Domain = request.getHeader("Domain");
if (StrUtil.isNotBlank(Domain)) {
String key = "Domain:" + Domain;
tenantId = redisUtil.get(key);
if(tenantId != null){
System.out.println("从域名拿TID = " + tenantId);
return new LongValue(tenantId);
}
}
}
} catch (Exception e) {
// 忽略异常,使用默认逻辑
}
return getLoginUserTenantId();
}
@@ -111,4 +121,16 @@ public class MybatisPlusConfig {
return new NullValue();
}
/**
* 获取当前HTTP请求
*/
private HttpServletRequest getCurrentRequest() {
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attributes != null ? attributes.getRequest() : null;
} catch (Exception e) {
return null;
}
}
}

View File

@@ -6,9 +6,9 @@ import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.annotation.Resource;
@@ -22,7 +22,7 @@ import javax.annotation.Resource;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
public class SecurityConfig {
@Resource
private JwtAccessDeniedHandler jwtAccessDeniedHandler;
@Resource
@@ -30,9 +30,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/file/**","/**", "/api/captcha", "/")
@@ -48,6 +48,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/v2/api-docs",
"/v3/api-docs",
"/swagger-ui/**",
"/doc.html",
"/api/open/**",
"/hxz/v1/**",
"/api/sendSmsCaptcha",
@@ -95,7 +96,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.accessDeniedHandler(jwtAccessDeniedHandler)
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean

View File

@@ -40,6 +40,12 @@ public class MqttService {
try {
logger.info("开始初始化MQTT服务...");
// 检查是否启用MQTT服务
if (!mqttProperties.isEnabled()) {
logger.info("MQTT服务已禁用跳过初始化");
return;
}
// 验证配置属性
validateMqttProperties();

View File

@@ -128,14 +128,6 @@
OR a.room_number LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
<!-- 价格区间筛选 -->
<if test="param.priceScene != null and param.priceScene.indexOf('~') > -1">
<bind name="priceMin" value="param.priceScene.substring(0, param.priceScene.indexOf('~'))" />
<bind name="priceMax" value="param.priceScene.substring(param.priceScene.indexOf('~') + 1)" />
AND a.monthly_rent >= CAST(#{priceMin} AS DECIMAL(10,2))
AND a.monthly_rent &lt;= CAST(#{priceMax} AS DECIMAL(10,2))
</if>
</if>
</where>
<trim prefix="ORDER BY" suffixOverrides=",">
<if test="param.sortScene == '综合排序'">
@@ -145,37 +137,24 @@
a.create_time desc,
</if>
<if test="param.sortScene == '价格(低-高)'">
CAST(IFNULL(a.monthly_rent, 0) AS DECIMAL(10,2)) asc,
a.monthly_rent asc,
</if>
<if test="param.sortScene == '价格(高-低)'">
CAST(IFNULL(a.monthly_rent, 0) AS DECIMAL(10,2)) desc,
a.monthly_rent desc,
</if>
<if test="param.sortScene == '面积(小-大)'">
CASE WHEN a.extent IS NULL OR a.extent = '' THEN 1 ELSE 0 END,
CAST(COALESCE(NULLIF(a.extent, ''), '0') AS DECIMAL(10,2)) asc,
a.extent asc,
</if>
<if test="param.sortScene == '面积(大-小)'">
CASE WHEN a.extent IS NULL OR a.extent = '' THEN 1 ELSE 0 END,
CAST(COALESCE(NULLIF(a.extent, ''), '0') AS DECIMAL(10,2)) desc,
a.extent desc,
</if>
<if test="param.priceScene != null and param.priceScene.indexOf('~') == -1">
ABS(CAST(COALESCE(a.monthly_rent, 0) AS DECIMAL(10,2)) - CAST(#{param.priceScene} AS DECIMAL(10,2))),
<if test="param.priceScene != null">
ABS(a.monthly_rent - #{param.priceScene}),
</if>
<if test="param.extentScene != null and param.extentScene.indexOf('~') == -1">
ABS(CAST(COALESCE(NULLIF(a.extent, ''), '0') AS DECIMAL(10,2)) - CAST(#{param.extentScene} AS DECIMAL(10,2))),
<if test="param.extentScene != null">
ABS(a.extent - #{param.extentScene}),
</if>
<!-- 默认排序:只有在没有指定排序场景时才使用 -->
<if test="param.sortScene == null or param.sortScene == '' or param.sortScene == '综合排序'">
a.sort_number asc, a.create_time desc
</if>
<if test="param.sortScene == '最新发布'">
<!-- 最新发布已经在上面处理了 -->
</if>
<if test="param.sortScene != null and param.sortScene != '' and param.sortScene != '综合排序' and param.sortScene != '最新发布' and param.sortScene != '价格(低-高)' and param.sortScene != '价格(高-低)' and param.sortScene != '面积(小-大)' and param.sortScene != '面积(大-小)'">
a.create_time desc
</if>
<!-- 默认排序:推荐优先,然后按创建时间倒序 -->
a.recommend desc, a.create_time desc
</trim>
</sql>

View File

@@ -201,31 +201,31 @@ public class OaAppController extends BaseController {
@GetMapping("/data")
public ApiResult<Map<String, Integer>> data() {
Map<String, Integer> data = new HashMap<>();
Long totalNum = oaAppService.count(
long totalNum = oaAppService.count(
new LambdaQueryWrapper<>()
);
Long totalNum2 = oaAppService.count(
long totalNum2 = oaAppService.count(
new LambdaQueryWrapper<OaApp>()
.eq(OaApp::getAppStatus, "开发中")
);
Long totalNum3 = oaAppService.count(
long totalNum3 = oaAppService.count(
new LambdaQueryWrapper<OaApp>()
.eq(OaApp::getAppStatus, "已上架")
);
Long totalNum4 = oaAppService.count(
long totalNum4 = oaAppService.count(
new LambdaQueryWrapper<OaApp>()
.eq(OaApp::getAppStatus, "已上架")
.eq(OaApp::getShowExpiration,false)
);
Long totalNum5 = oaAppService.count(
long totalNum5 = oaAppService.count(
new LambdaQueryWrapper<OaApp>()
.eq(OaApp::getAppStatus, "已下架")
);
Long totalNum6 = oaAppService.count(
long totalNum6 = oaAppService.count(
new LambdaQueryWrapper<OaApp>()
.eq(OaApp::getShowCase,true)
);
Long totalNum7 = oaAppService.count(
long totalNum7 = oaAppService.count(
new LambdaQueryWrapper<OaApp>()
.eq(OaApp::getShowIndex, true)
);

View File

@@ -258,7 +258,7 @@ public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> impl
// 剩余天数
d.setExpiredDays(DateUtil.betweenDay(d.getExpirationTime(), DateUtil.date(), false));
// 续费次数
d.setRenewCount(projectRenewService.count(new LambdaQueryWrapper<ProjectRenew>().eq(ProjectRenew::getAppId, d.getAppId()).eq(ProjectRenew::getDeleted, 0)));
d.setRenewCount((long) projectRenewService.count(new LambdaQueryWrapper<ProjectRenew>().eq(ProjectRenew::getAppId, d.getAppId()).eq(ProjectRenew::getDeleted, 0)));
});
return list;
}

View File

@@ -1,178 +0,0 @@
package com.gxwebsoft.shop.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import com.gxwebsoft.shop.service.CouponBusinessService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* 优惠券业务控制器
*
* @author 科技小王子
* @since 2025-08-08 22:30:00
*/
@Tag(name = "优惠券业务管理")
@RestController
@RequestMapping("/api/shop/coupon-business")
public class CouponBusinessController extends BaseController {
@Resource
private CouponBusinessService couponBusinessService;
@Operation(summary = "获取订单可用优惠券")
@PostMapping("/available-for-order")
public ApiResult<List<ShopUserCoupon>> getAvailableCouponsForOrder(
@RequestBody Map<String, Object> orderData) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录", null);
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> goodsItems = (List<Map<String, Object>>) orderData.get("goodsItems");
BigDecimal totalAmount = new BigDecimal(orderData.get("totalAmount").toString());
List<ShopUserCoupon> coupons = couponBusinessService.getAvailableCouponsForOrder(
loginUser.getUserId(), goodsItems, totalAmount);
return success(coupons);
}
@Operation(summary = "计算使用优惠券后的订单金额")
@PostMapping("/calculate-order-amount")
public ApiResult<Map<String, Object>> calculateOrderAmountWithCoupon(
@RequestParam Long userCouponId,
@RequestBody Map<String, Object> orderData) {
@SuppressWarnings("unchecked")
List<Map<String, Object>> goodsItems = (List<Map<String, Object>>) orderData.get("goodsItems");
BigDecimal totalAmount = new BigDecimal(orderData.get("totalAmount").toString());
Map<String, Object> result = couponBusinessService.calculateOrderAmountWithCoupon(
userCouponId, goodsItems, totalAmount);
return success(result);
}
@Operation(summary = "验证优惠券是否可用于订单")
@PostMapping("/validate-for-order")
public ApiResult<Map<String, Object>> validateCouponForOrder(
@RequestParam Long userCouponId,
@RequestBody Map<String, Object> orderData) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录", null);
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> goodsItems = (List<Map<String, Object>>) orderData.get("goodsItems");
BigDecimal totalAmount = new BigDecimal(orderData.get("totalAmount").toString());
Map<String, Object> result = couponBusinessService.validateCouponForOrder(
userCouponId, loginUser.getUserId(), goodsItems, totalAmount);
return success(result);
}
@Operation(summary = "推荐最优优惠券组合")
@PostMapping("/recommend-best-combination")
public ApiResult<Map<String, Object>> recommendBestCouponCombination(
@RequestBody Map<String, Object> orderData) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录", null);
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> goodsItems = (List<Map<String, Object>>) orderData.get("goodsItems");
BigDecimal totalAmount = new BigDecimal(orderData.get("totalAmount").toString());
Map<String, Object> result = couponBusinessService.recommendBestCouponCombination(
loginUser.getUserId(), goodsItems, totalAmount);
return success(result);
}
@PreAuthorize("hasAuthority('shop:coupon:manage')")
@OperationLog
@Operation(summary = "为新用户发放欢迎优惠券")
@PostMapping("/issue-welcome/{userId}")
public ApiResult<?> issueWelcomeCoupons(@PathVariable Integer userId) {
int count = couponBusinessService.issueWelcomeCoupons(userId);
return success("成功发放" + count + "张欢迎优惠券");
}
@PreAuthorize("hasAuthority('shop:coupon:manage')")
@OperationLog
@Operation(summary = "为用户发放生日优惠券")
@PostMapping("/issue-birthday/{userId}")
public ApiResult<?> issueBirthdayCoupons(@PathVariable Integer userId) {
int count = couponBusinessService.issueBirthdayCoupons(userId);
return success("成功发放" + count + "张生日优惠券");
}
@PreAuthorize("hasAuthority('shop:coupon:manage')")
@OperationLog
@Operation(summary = "根据消费金额发放优惠券")
@PostMapping("/issue-consume/{userId}")
public ApiResult<?> issueConsumeCoupons(@PathVariable Integer userId,
@RequestParam BigDecimal consumeAmount) {
int count = couponBusinessService.issueConsumeCoupons(userId, consumeAmount);
return success("成功发放" + count + "张消费返券");
}
@PreAuthorize("hasAuthority('shop:coupon:manage')")
@OperationLog
@Operation(summary = "批量发放活动优惠券")
@PostMapping("/batch-issue-activity")
public ApiResult<Map<String, Object>> batchIssueActivityCoupons(
@RequestParam String activityName,
@RequestParam List<Integer> couponIds,
@RequestParam(required = false) List<Integer> userIds) {
Map<String, Object> result = couponBusinessService.batchIssueActivityCoupons(
activityName, couponIds, userIds);
return success(result);
}
@PreAuthorize("hasAuthority('shop:coupon:statistics')")
@Operation(summary = "获取优惠券使用统计")
@GetMapping("/usage-statistics")
public ApiResult<Map<String, Object>> getCouponUsageStatistics(
@RequestParam(required = false) String startDate,
@RequestParam(required = false) String endDate) {
Map<String, Object> statistics = couponBusinessService.getCouponUsageStatistics(startDate, endDate);
return success(statistics);
}
@PreAuthorize("hasAuthority('shop:coupon:manage')")
@OperationLog
@Operation(summary = "手动处理过期优惠券")
@PostMapping("/process-expired")
public ApiResult<?> processExpiredCoupons() {
int count = couponBusinessService.autoProcessExpiredCoupons();
return success("处理了" + count + "张过期优惠券");
}
@PreAuthorize("hasAuthority('shop:coupon:manage')")
@OperationLog
@Operation(summary = "发送优惠券到期提醒")
@PostMapping("/send-expiry-reminder")
public ApiResult<?> sendExpiryReminder(@RequestParam(defaultValue = "3") Integer days) {
int count = couponBusinessService.sendCouponExpiryReminder(days);
return success("" + count + "个用户发送了到期提醒");
}
}

View File

@@ -1,126 +0,0 @@
package com.gxwebsoft.shop.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.ShopCoupon;
import com.gxwebsoft.shop.param.ShopCouponParam;
import com.gxwebsoft.shop.service.ShopCouponService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 优惠券控制器
*
* @author 科技小王子
* @since 2025-08-08 21:10:55
*/
@Tag(name = "优惠券管理")
@RestController
@RequestMapping("/api/shop/shop-coupon")
public class ShopCouponController extends BaseController {
@Resource
private ShopCouponService shopCouponService;
@PreAuthorize("hasAuthority('shop:shopCoupon:list')")
@Operation(summary = "批量修改优惠券")
@GetMapping("/page")
public ApiResult<PageResult<ShopCoupon>> page(ShopCouponParam param) {
// 使用关联查询
return success(shopCouponService.pageRel(param));
}
@PreAuthorize("hasAuthority('shop:shopCoupon:list')")
@Operation(summary = "查询全部优惠券")
@GetMapping()
public ApiResult<List<ShopCoupon>> list(ShopCouponParam param) {
// 使用关联查询
return success(shopCouponService.listRel(param));
}
@PreAuthorize("hasAuthority('shop:shopCoupon:list')")
@Operation(summary = "根据id查询优惠券")
@GetMapping("/{id}")
public ApiResult<ShopCoupon> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(shopCouponService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('shop:shopCoupon:save')")
@OperationLog
@Operation(summary = "添加优惠券")
@PostMapping()
public ApiResult<?> save(@RequestBody ShopCoupon shopCoupon) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
shopCoupon.setUserId(loginUser.getUserId());
}
if (shopCouponService.save(shopCoupon)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('shop:shopCoupon:update')")
@OperationLog
@Operation(summary = "修改优惠券")
@PutMapping()
public ApiResult<?> update(@RequestBody ShopCoupon shopCoupon) {
if (shopCouponService.updateById(shopCoupon)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('shop:shopCoupon:remove')")
@OperationLog
@Operation(summary = "删除优惠券")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (shopCouponService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('shop:shopCoupon:save')")
@OperationLog
@Operation(summary = "批量添加优惠券")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<ShopCoupon> list) {
if (shopCouponService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('shop:shopCoupon:update')")
@Operation(summary = "批量修改优惠券")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<ShopCoupon> batchParam) {
if (batchParam.update(shopCouponService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('shop:shopCoupon:remove')")
@Operation(summary = "批量删除优惠券")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (shopCouponService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -136,19 +136,19 @@ public class ShopGoodsController extends BaseController {
wrapper.eq(ShopGoods::getMerchantId,param.getMerchantId());
}
Long totalNum = shopGoodsService.count(
long totalNum = shopGoodsService.count(
wrapper.eq(ShopGoods::getStatus,0).gt(ShopGoods::getStock,0)
);
data.put("totalNum", Math.toIntExact(totalNum));
wrapper.clear();
Long totalNum2 = shopGoodsService.count(
long totalNum2 = shopGoodsService.count(
wrapper.gt(ShopGoods::getStatus,0)
);
data.put("totalNum2", Math.toIntExact(totalNum2));
wrapper.clear();
Long totalNum3 = shopGoodsService.count(
long totalNum3 = shopGoodsService.count(
wrapper.eq(ShopGoods::getStock,0)
);
data.put("totalNum3", Math.toIntExact(totalNum3));

View File

@@ -1,115 +0,0 @@
package com.gxwebsoft.shop.controller;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.service.ShopGoodsCouponService;
import com.gxwebsoft.shop.entity.ShopGoodsCoupon;
import com.gxwebsoft.shop.param.ShopGoodsCouponParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 商品优惠券表控制器
*
* @author 科技小王子
* @since 2025-01-11 10:45:12
*/
@Tag(name = "商品优惠券表管理")
@RestController
@RequestMapping("/api/shop/shop-goods-coupon")
public class ShopGoodsCouponController extends BaseController {
@Resource
private ShopGoodsCouponService shopGoodsCouponService;
@Operation(summary = "分页查询商品优惠券表")
@GetMapping("/page")
public ApiResult<PageResult<ShopGoodsCoupon>> page(ShopGoodsCouponParam param) {
// 使用关联查询
return success(shopGoodsCouponService.pageRel(param));
}
@Operation(summary = "查询全部商品优惠券表")
@GetMapping()
public ApiResult<List<ShopGoodsCoupon>> list(ShopGoodsCouponParam param) {
// 使用关联查询
return success(shopGoodsCouponService.listRel(param));
}
@PreAuthorize("hasAuthority('shop:shopGoodsCoupon:list')")
@Operation(summary = "根据id查询商品优惠券表")
@GetMapping("/{id}")
public ApiResult<ShopGoodsCoupon> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(shopGoodsCouponService.getByIdRel(id));
}
@Operation(summary = "添加商品优惠券表")
@PostMapping()
public ApiResult<?> save(@RequestBody ShopGoodsCoupon shopGoodsCoupon) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
shopGoodsCoupon.setUserId(loginUser.getUserId());
}
if (shopGoodsCouponService.save(shopGoodsCoupon)) {
return success("添加成功");
}
return fail("添加失败");
}
@Operation(summary = "修改商品优惠券表")
@PutMapping()
public ApiResult<?> update(@RequestBody ShopGoodsCoupon shopGoodsCoupon) {
if (shopGoodsCouponService.updateById(shopGoodsCoupon)) {
return success("修改成功");
}
return fail("修改失败");
}
@Operation(summary = "删除商品优惠券表")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (shopGoodsCouponService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@Operation(summary = "批量添加商品优惠券表")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<ShopGoodsCoupon> list) {
if (shopGoodsCouponService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@Operation(summary = "批量修改商品优惠券表")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<ShopGoodsCoupon> batchParam) {
if (batchParam.update(shopGoodsCouponService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@Operation(summary = "批量删除商品优惠券表")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (shopGoodsCouponService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -39,7 +39,6 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@@ -100,7 +99,7 @@ public class ShopOrderController extends BaseController {
@Operation(summary = "添加订单")
@PostMapping()
public ApiResult<?> save(@Valid @RequestBody OrderCreateRequest request) {
public ApiResult<?> save(@RequestBody OrderCreateRequest request) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("用户未登录");
@@ -110,7 +109,7 @@ public class ShopOrderController extends BaseController {
Map<String, String> wxOrderInfo = orderBusinessService.createOrder(request, loginUser);
return success("下单成功", wxOrderInfo);
} catch (Exception e) {
logger.error("创建订单失败", e);
logger.error("创建订单失败 - 用户ID{},请求:{}", loginUser.getUserId(), request, e);
return fail(e.getMessage());
}
}

View File

@@ -1,225 +0,0 @@
package com.gxwebsoft.shop.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import com.gxwebsoft.shop.param.ShopUserCouponParam;
import com.gxwebsoft.shop.service.ShopUserCouponService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* 用户优惠券控制器
*
* @author 科技小王子
* @since 2025-08-08 21:30:00
*/
@Tag(name = "用户优惠券管理")
@RestController
@RequestMapping("/api/shop/user-coupon")
public class ShopUserCouponController extends BaseController {
@Resource
private ShopUserCouponService shopUserCouponService;
@PreAuthorize("hasAuthority('shop:userCoupon:list')")
@Operation(summary = "分页查询用户优惠券")
@GetMapping("/page")
public ApiResult<PageResult<ShopUserCoupon>> page(ShopUserCouponParam param) {
return success(shopUserCouponService.pageRel(param));
}
@PreAuthorize("hasAuthority('shop:userCoupon:list')")
@Operation(summary = "查询用户优惠券列表")
@GetMapping()
public ApiResult<List<ShopUserCoupon>> list(ShopUserCouponParam param) {
return success(shopUserCouponService.listRel(param));
}
@PreAuthorize("hasAuthority('shop:userCoupon:list')")
@Operation(summary = "根据id查询用户优惠券")
@GetMapping("/{id}")
public ApiResult<ShopUserCoupon> get(@PathVariable("id") Long id) {
return success(shopUserCouponService.getByIdRel(id));
}
@Operation(summary = "获取当前用户的优惠券列表")
@GetMapping("/my")
public ApiResult<List<ShopUserCoupon>> getMyCoupons(ShopUserCouponParam param) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录",null);
}
param.setUserId(loginUser.getUserId());
return success(shopUserCouponService.listRel(param));
}
@Operation(summary = "获取当前用户可用的优惠券")
@GetMapping("/my/available")
public ApiResult<List<ShopUserCoupon>> getMyAvailableCoupons(
@RequestParam(required = false) Integer goodsId,
@RequestParam(required = false) Integer categoryId,
@RequestParam(required = false) BigDecimal orderAmount) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录",null);
}
List<ShopUserCoupon> coupons = shopUserCouponService.getAvailableCoupons(
loginUser.getUserId(), goodsId, categoryId, orderAmount);
return success(coupons);
}
@Operation(summary = "统计当前用户优惠券数量")
@GetMapping("/my/count")
public ApiResult<Map<String, Object>> getMyCount() {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录",null);
}
Map<String, Object> count = shopUserCouponService.countUserCoupons(loginUser.getUserId());
return success(count);
}
@OperationLog
@Operation(summary = "领取优惠券")
@PostMapping("/receive/{couponId}")
public ApiResult<?> receiveCoupon(@PathVariable("couponId") Integer couponId) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录",null);
}
// 检查是否可以领取
Map<String, Object> checkResult = shopUserCouponService.checkCanReceiveCoupon(
loginUser.getUserId(), couponId);
if (!(Boolean) checkResult.get("canReceive")) {
return fail(checkResult.get("reason").toString());
}
boolean success = shopUserCouponService.receiveCoupon(loginUser.getUserId(), couponId);
if (success) {
return success("领取成功");
}
return fail("领取失败");
}
@PreAuthorize("hasAuthority('shop:userCoupon:save')")
@OperationLog
@Operation(summary = "系统发放优惠券给用户")
@PostMapping("/issue")
public ApiResult<?> issueCoupon(@RequestParam Integer userId,
@RequestParam Integer couponId,
@RequestParam(required = false) String source) {
boolean success = shopUserCouponService.issueCouponToUser(userId, couponId, source);
if (success) {
return success("发放成功");
}
return fail("发放失败");
}
@PreAuthorize("hasAuthority('shop:userCoupon:save')")
@OperationLog
@Operation(summary = "批量发放优惠券")
@PostMapping("/batch-issue")
public ApiResult<?> batchIssueCoupons(@RequestParam List<Integer> userIds,
@RequestParam Integer couponId,
@RequestParam(required = false) String source) {
int successCount = shopUserCouponService.batchIssueCoupons(userIds, couponId, source);
return success("成功发放" + successCount + "张优惠券");
}
@PreAuthorize("hasAuthority('shop:userCoupon:update')")
@OperationLog
@Operation(summary = "使用优惠券")
@PutMapping("/use")
public ApiResult<?> useCoupon(@RequestParam Long userCouponId,
@RequestParam Long orderId,
@RequestParam String orderNo) {
boolean success = shopUserCouponService.useCoupon(userCouponId, orderId, orderNo);
if (success) {
return success("使用成功");
}
return fail("使用失败");
}
@PreAuthorize("hasAuthority('shop:userCoupon:update')")
@OperationLog
@Operation(summary = "退还优惠券")
@PutMapping("/return/{orderId}")
public ApiResult<?> returnCoupon(@PathVariable("orderId") Long orderId) {
boolean success = shopUserCouponService.returnCoupon(orderId);
if (success) {
return success("退还成功");
}
return fail("退还失败");
}
@Operation(summary = "计算优惠券优惠金额")
@PostMapping("/calculate-discount")
public ApiResult<BigDecimal> calculateDiscount(@RequestParam Long userCouponId,
@RequestParam BigDecimal orderAmount) {
ShopUserCoupon userCoupon = shopUserCouponService.getById(userCouponId);
if (userCoupon == null) {
return fail("优惠券不存在",null);
}
BigDecimal discountAmount = shopUserCouponService.calculateDiscountAmount(userCoupon, orderAmount);
return success(discountAmount);
}
@Operation(summary = "验证优惠券是否可用于指定商品")
@GetMapping("/validate")
public ApiResult<Boolean> validateCoupon(@RequestParam Long userCouponId,
@RequestParam(required = false) Integer goodsId,
@RequestParam(required = false) Integer categoryId) {
ShopUserCoupon userCoupon = shopUserCouponService.getById(userCouponId);
if (userCoupon == null) {
return fail("优惠券不存在",null);
}
boolean valid = shopUserCouponService.validateCouponForGoods(userCoupon, goodsId, categoryId);
return success(valid);
}
@PreAuthorize("hasAuthority('shop:userCoupon:update')")
@OperationLog
@Operation(summary = "更新过期优惠券状态")
@PutMapping("/update-expired")
public ApiResult<?> updateExpiredCoupons() {
int count = shopUserCouponService.updateExpiredCoupons();
return success("更新了" + count + "张过期优惠券");
}
@PreAuthorize("hasAuthority('shop:userCoupon:list')")
@Operation(summary = "获取即将过期的优惠券")
@GetMapping("/expiring-soon")
public ApiResult<List<ShopUserCoupon>> getExpiringSoonCoupons(
@RequestParam(defaultValue = "3") Integer days) {
List<ShopUserCoupon> coupons = shopUserCouponService.getExpiringSoonCoupons(days);
return success(coupons);
}
@PreAuthorize("hasAuthority('shop:userCoupon:remove')")
@OperationLog
@Operation(summary = "删除用户优惠券")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Long id) {
if (shopUserCouponService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -1,103 +0,0 @@
package com.gxwebsoft.shop.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
/**
* 优惠券模板
*
* @author 科技小王子
* @since 2025-08-08 21:10:55
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("shop_coupon")
@Schema(name = "ShopCoupon对象", description = "优惠券模板")
public class ShopCoupon implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@Schema(description = "优惠券名称")
private String name;
@Schema(description = "优惠券描述")
private String description;
@Schema(description = "优惠券类型(10满减券 20折扣券 30免费劵)")
private Integer type;
@Schema(description = "满减券-减免金额")
private BigDecimal reducePrice;
@Schema(description = "折扣券-折扣率(0-100)")
private Integer discount;
@Schema(description = "最低消费金额")
private BigDecimal minPrice;
@Schema(description = "发放总数量(-1表示无限制)")
private Integer totalCount;
@Schema(description = "已发放数量")
private Integer issuedCount;
@Schema(description = "每人限领数量(-1表示无限制)")
private Integer limitPerUser;
@Schema(description = "到期类型(10领取后生效 20固定时间)")
private Integer expireType;
@Schema(description = "领取后生效-有效天数")
private Integer expireDay;
@Schema(description = "有效期开始时间")
private LocalDate startTime;
@Schema(description = "有效期结束时间")
private LocalDate endTime;
@Schema(description = "适用范围(10全部商品 20指定商品 30指定分类)")
private Integer applyRange;
@Schema(description = "适用范围配置(json格式)")
private String applyRangeConfig;
@Schema(description = "是否启用(0禁用 1启用)")
private Integer enabled;
@Schema(description = "排序(数字越小越靠前)")
private Integer sortNumber;
@Schema(description = "状态, 0正常, 1禁用")
private Integer status;
@Schema(description = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@Schema(description = "创建用户ID")
private Integer userId;
@Schema(description = "租户id")
private Integer tenantId;
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "修改时间")
private Date updateTime;
}

View File

@@ -1,56 +0,0 @@
package com.gxwebsoft.shop.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.io.Serializable;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 商品优惠券表
*
* @author 科技小王子
* @since 2025-01-11 10:45:12
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(name = "ShopGoodsCoupon对象", description = "商品优惠券表")
public class ShopGoodsCoupon implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@Schema(description = "商品id")
private Integer goodsId;
@Schema(description = "优惠劵id")
private Integer issueCouponId;
@Schema(description = "排序(数字越小越靠前)")
private Integer sortNumber;
@Schema(description = "状态, 0正常, 1冻结")
private Integer status;
@Schema(description = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@Schema(description = "用户ID")
private Integer userId;
@Schema(description = "租户id")
private Integer tenantId;
@Schema(description = "注册时间")
private Date createTime;
@Schema(description = "修改时间")
private Date updateTime;
}

View File

@@ -1,31 +1,59 @@
package com.gxwebsoft.shop.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
/**
* 用户优惠券
*
* @author 科技小王子
* @since 2025-08-08 21:30:00
* @since 2025-08-09 15:48:01
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("shop_user_coupon")
@Schema(name = "ShopUserCoupon对象", description = "用户优惠券")
public class ShopUserCoupon implements Serializable {
private static final long serialVersionUID = 1L;
// 优惠券类型常量
/** 满减券 */
public static final Integer TYPE_REDUCE = 10;
/** 折扣券 */
public static final Integer TYPE_DISCOUNT = 20;
/** 免费券 */
public static final Integer TYPE_FREE = 30;
// 适用范围常量
/** 全部商品 */
public static final Integer APPLY_ALL = 10;
/** 指定商品 */
public static final Integer APPLY_GOODS = 20;
/** 指定分类 */
public static final Integer APPLY_CATEGORY = 30;
// 使用状态常量
/** 未使用 */
public static final Integer STATUS_UNUSED = 0;
/** 已使用 */
public static final Integer STATUS_USED = 1;
/** 已过期 */
public static final Integer STATUS_EXPIRED = 2;
// 获取方式常量
/** 主动领取 */
public static final Integer OBTAIN_ACTIVE = 10;
/** 系统发放 */
public static final Integer OBTAIN_SYSTEM = 20;
/** 活动赠送 */
public static final Integer OBTAIN_ACTIVITY = 30;
@Schema(description = "id")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@@ -86,57 +114,15 @@ public class ShopUserCoupon implements Serializable {
@Schema(description = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
private Boolean deleted;
@Schema(description = "租户id")
private Integer tenantId;
@Schema(description = "创建时间")
private Date createTime;
private LocalDateTime createTime;
@Schema(description = "修改时间")
private Date updateTime;
private LocalDateTime updateTime;
// 优惠券状态常量
public static final int STATUS_UNUSED = 0; // 未使用
public static final int STATUS_USED = 1; // 已使用
public static final int STATUS_EXPIRED = 2; // 已过期
// 优惠券类型常量
public static final int TYPE_REDUCE = 10; // 满减券
public static final int TYPE_DISCOUNT = 20; // 折扣券
public static final int TYPE_FREE = 30; // 免费券
// 适用范围常量
public static final int APPLY_ALL = 10; // 全部商品
public static final int APPLY_GOODS = 20; // 指定商品
public static final int APPLY_CATEGORY = 30; // 指定分类
// 获取方式常量
public static final int OBTAIN_RECEIVE = 10; // 主动领取
public static final int OBTAIN_SYSTEM = 20; // 系统发放
public static final int OBTAIN_ACTIVITY = 30; // 活动赠送
/**
* 检查优惠券是否已过期
*/
public boolean isExpired() {
return this.endTime != null && this.endTime.isBefore(LocalDateTime.now());
}
/**
* 检查优惠券是否可用
*/
public boolean isAvailable() {
return this.status == STATUS_UNUSED && !isExpired();
}
/**
* 检查优惠券是否在有效期内
*/
public boolean isInValidPeriod() {
LocalDateTime now = LocalDateTime.now();
return (this.startTime == null || !this.startTime.isAfter(now)) &&
(this.endTime == null || !this.endTime.isBefore(now));
}
}

View File

@@ -1,46 +0,0 @@
package com.gxwebsoft.shop.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.shop.entity.ShopCoupon;
import com.gxwebsoft.shop.param.ShopCouponParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 优惠券Mapper
*
* @author 科技小王子
* @since 2025-08-08 21:10:55
*/
public interface ShopCouponMapper extends BaseMapper<ShopCoupon> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<ShopCoupon>
*/
List<ShopCoupon> selectPageRel(@Param("page") IPage<ShopCoupon> page,
@Param("param") ShopCouponParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<ShopCoupon> selectListRel(@Param("param") ShopCouponParam param);
/**
* 检查用户是否已领取指定优惠券
*
* @param userId 用户ID
* @param couponId 优惠券模板ID
* @return 已领取数量
*/
int countUserReceivedCoupon(@Param("userId") Integer userId, @Param("couponId") Integer couponId);
}

View File

@@ -1,37 +0,0 @@
package com.gxwebsoft.shop.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.shop.entity.ShopGoodsCoupon;
import com.gxwebsoft.shop.param.ShopGoodsCouponParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 商品优惠券表Mapper
*
* @author 科技小王子
* @since 2025-01-11 10:45:12
*/
public interface ShopGoodsCouponMapper extends BaseMapper<ShopGoodsCoupon> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<ShopGoodsCoupon>
*/
List<ShopGoodsCoupon> selectPageRel(@Param("page") IPage<ShopGoodsCoupon> page,
@Param("param") ShopGoodsCouponParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<ShopGoodsCoupon> selectListRel(@Param("param") ShopGoodsCouponParam param);
}

View File

@@ -1,76 +0,0 @@
package com.gxwebsoft.shop.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import com.gxwebsoft.shop.param.ShopUserCouponParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 用户优惠券Mapper
*
* @author 科技小王子
* @since 2025-08-08 21:30:00
*/
public interface ShopUserCouponMapper extends BaseMapper<ShopUserCoupon> {
/**
* 分页查询用户优惠券
*
* @param page 分页对象
* @param param 查询参数
* @return List<ShopUserCoupon>
*/
List<ShopUserCoupon> selectPageRel(@Param("page") IPage<ShopUserCoupon> page,
@Param("param") ShopUserCouponParam param);
/**
* 查询用户优惠券列表
*
* @param param 查询参数
* @return List<ShopUserCoupon>
*/
List<ShopUserCoupon> selectListRel(@Param("param") ShopUserCouponParam param);
/**
* 查询用户可用的优惠券
*
* @param param 查询参数
* @return List<ShopUserCoupon>
*/
List<ShopUserCoupon> selectAvailableCoupons(@Param("param") ShopUserCouponParam param);
/**
* 统计用户优惠券数量
*
* @param userId 用户ID
* @return 统计结果
*/
java.util.Map<String, Object> countUserCoupons(@Param("userId") Integer userId);
/**
* 查询即将过期的优惠券
*
* @param days 天数
* @return List<ShopUserCoupon>
*/
List<ShopUserCoupon> selectExpiringSoon(@Param("days") Integer days);
/**
* 批量更新过期状态
*
* @return 更新数量
*/
int updateExpiredStatus();
/**
* 检查用户是否已领取指定优惠券
*
* @param userId 用户ID
* @param couponId 优惠券模板ID
* @return 已领取数量
*/
int countUserReceivedCoupon(@Param("userId") Integer userId, @Param("couponId") Integer couponId);
}

View File

@@ -1,96 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.shop.mapper.ShopCouponMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*
FROM shop_coupon a
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.name != null">
AND a.name LIKE CONCAT('%', #{param.name}, '%')
</if>
<if test="param.type != null">
AND a.type = #{param.type}
</if>
<if test="param.reducePrice != null">
AND a.reduce_price = #{param.reducePrice}
</if>
<if test="param.discount != null">
AND a.discount = #{param.discount}
</if>
<if test="param.minPrice != null">
AND a.min_price = #{param.minPrice}
</if>
<if test="param.expireType != null">
AND a.expire_type = #{param.expireType}
</if>
<if test="param.expireDay != null">
AND a.expire_day = #{param.expireDay}
</if>
<if test="param.startTime != null">
AND a.start_time LIKE CONCAT('%', #{param.startTime}, '%')
</if>
<if test="param.endTime != null">
AND a.end_time LIKE CONCAT('%', #{param.endTime}, '%')
</if>
<if test="param.applyRange != null">
AND a.apply_range = #{param.applyRange}
</if>
<if test="param.applyRangeConfig != null">
AND a.apply_range_config LIKE CONCAT('%', #{param.applyRangeConfig}, '%')
</if>
<if test="param.isExpire != null">
AND a.is_expire = #{param.isExpire}
</if>
<if test="param.sortNumber != null">
AND a.sort_number = #{param.sortNumber}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.deleted != null">
AND a.deleted = #{param.deleted}
</if>
<if test="param.deleted == null">
AND a.deleted = 0
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.keywords != null">
AND (a.comments LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.shop.entity.ShopCoupon">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.shop.entity.ShopCoupon">
<include refid="selectSql"></include>
</select>
<!-- 检查用户是否已领取指定优惠券 -->
<select id="countUserReceivedCoupon" resultType="int">
SELECT COUNT(*)
FROM shop_user_coupon
WHERE deleted = 0
AND user_id = #{userId}
AND coupon_id = #{couponId}
</select>
</mapper>

View File

@@ -1,57 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.shop.mapper.ShopGoodsCouponMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*
FROM shop_goods_coupon a
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.goodsId != null">
AND a.goods_id = #{param.goodsId}
</if>
<if test="param.issueCouponId != null">
AND a.issue_coupon_id = #{param.issueCouponId}
</if>
<if test="param.sortNumber != null">
AND a.sort_number = #{param.sortNumber}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.deleted != null">
AND a.deleted = #{param.deleted}
</if>
<if test="param.deleted == null">
AND a.deleted = 0
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.keywords != null">
AND (a.comments LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.shop.entity.ShopGoodsCoupon">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.shop.entity.ShopGoodsCoupon">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@@ -1,240 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.shop.mapper.ShopUserCouponMapper">
<!-- 基础查询SQL -->
<sql id="selectSql">
SELECT
a.id,
a.coupon_id,
a.user_id,
a.name,
a.description,
a.type,
a.reduce_price,
a.discount,
a.min_price,
a.apply_range,
a.apply_range_config,
a.start_time,
a.end_time,
a.status,
a.use_time,
a.order_id,
a.order_no,
a.obtain_type,
a.obtain_source,
a.deleted,
a.tenant_id,
a.create_time,
a.update_time,
u.nickname as user_nickname,
u.phone as user_phone
FROM shop_user_coupon a
LEFT JOIN user u ON a.user_id = u.user_id
<where>
a.deleted = 0
<if test="param.tenantId != null">
AND a.tenant_id = #{param.tenantId}
</if>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.couponId != null">
AND a.coupon_id = #{param.couponId}
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.name != null and param.name != ''">
AND a.name LIKE CONCAT('%', #{param.name}, '%')
</if>
<if test="param.type != null">
AND a.type = #{param.type}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.applyRange != null">
AND a.apply_range = #{param.applyRange}
</if>
<if test="param.obtainType != null">
AND a.obtain_type = #{param.obtainType}
</if>
<if test="param.orderId != null">
AND a.order_id = #{param.orderId}
</if>
<if test="param.orderNo != null and param.orderNo != ''">
AND a.order_no = #{param.orderNo}
</if>
<if test="param.startTimeBegin != null">
AND a.start_time &gt;= #{param.startTimeBegin}
</if>
<if test="param.startTimeEnd != null">
AND a.start_time &lt;= #{param.startTimeEnd}
</if>
<if test="param.endTimeBegin != null">
AND a.end_time &gt;= #{param.endTimeBegin}
</if>
<if test="param.endTimeEnd != null">
AND a.end_time &lt;= #{param.endTimeEnd}
</if>
<if test="param.useTimeBegin != null">
AND a.use_time &gt;= #{param.useTimeBegin}
</if>
<if test="param.useTimeEnd != null">
AND a.use_time &lt;= #{param.useTimeEnd}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.includeExpired != null and !param.includeExpired">
AND (a.end_time IS NULL OR a.end_time &gt; NOW())
</if>
<if test="param.onlyAvailable != null and param.onlyAvailable">
AND a.status = 0
AND (a.start_time IS NULL OR a.start_time &lt;= NOW())
AND (a.end_time IS NULL OR a.end_time &gt; NOW())
</if>
<if test="param.keywords != null and param.keywords != ''">
AND (a.name LIKE CONCAT('%', #{param.keywords}, '%')
OR a.description LIKE CONCAT('%', #{param.keywords}, '%')
OR u.nickname LIKE CONCAT('%', #{param.keywords}, '%')
OR u.phone LIKE CONCAT('%', #{param.keywords}, '%'))
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.shop.entity.ShopUserCoupon">
<include refid="selectSql"/>
ORDER BY a.create_time DESC
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.shop.entity.ShopUserCoupon">
<include refid="selectSql"/>
ORDER BY a.create_time DESC
</select>
<!-- 查询用户可用的优惠券 -->
<select id="selectAvailableCoupons" resultType="com.gxwebsoft.shop.entity.ShopUserCoupon">
SELECT
a.id,
a.coupon_id,
a.user_id,
a.name,
a.description,
a.type,
a.reduce_price,
a.discount,
a.min_price,
a.apply_range,
a.apply_range_config,
a.start_time,
a.end_time,
a.status,
a.use_time,
a.order_id,
a.order_no,
a.obtain_type,
a.obtain_source,
a.deleted,
a.tenant_id,
a.create_time,
a.update_time
FROM shop_user_coupon a
WHERE a.deleted = 0
AND a.user_id = #{param.userId}
AND a.status = 0
AND (a.start_time IS NULL OR a.start_time &lt;= NOW())
AND (a.end_time IS NULL OR a.end_time &gt; NOW())
<if test="param.orderAmount != null">
AND (a.min_price IS NULL OR a.min_price &lt;= #{param.orderAmount})
</if>
<if test="param.goodsId != null">
AND (a.apply_range = 10
OR (a.apply_range = 20 AND FIND_IN_SET(#{param.goodsId}, a.apply_range_config) > 0))
</if>
<if test="param.categoryId != null">
AND (a.apply_range = 10
OR (a.apply_range = 30 AND FIND_IN_SET(#{param.categoryId}, a.apply_range_config) > 0))
</if>
ORDER BY
CASE a.type
WHEN 10 THEN a.reduce_price
WHEN 20 THEN #{param.orderAmount} * (100 - a.discount) / 100
ELSE #{param.orderAmount}
END DESC,
a.end_time ASC
</select>
<!-- 统计用户优惠券数量 -->
<select id="countUserCoupons" resultType="java.util.Map">
SELECT
COUNT(*) as total,
SUM(CASE WHEN status = 0 AND (end_time IS NULL OR end_time > NOW()) THEN 1 ELSE 0 END) as unused,
SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as used,
SUM(CASE WHEN status = 2 OR (status = 0 AND end_time IS NOT NULL AND end_time &lt;= NOW()) THEN 1 ELSE 0 END) as expired
FROM shop_user_coupon
WHERE deleted = 0 AND user_id = #{userId}
</select>
<!-- 查询即将过期的优惠券 -->
<select id="selectExpiringSoon" resultType="com.gxwebsoft.shop.entity.ShopUserCoupon">
SELECT
a.id,
a.coupon_id,
a.user_id,
a.name,
a.description,
a.type,
a.reduce_price,
a.discount,
a.min_price,
a.apply_range,
a.apply_range_config,
a.start_time,
a.end_time,
a.status,
a.use_time,
a.order_id,
a.order_no,
a.obtain_type,
a.obtain_source,
a.deleted,
a.tenant_id,
a.create_time,
a.update_time
FROM shop_user_coupon a
WHERE a.deleted = 0
AND a.status = 0
AND a.end_time IS NOT NULL
AND a.end_time > NOW()
AND a.end_time &lt;= DATE_ADD(NOW(), INTERVAL #{days} DAY)
ORDER BY a.end_time ASC
</select>
<!-- 批量更新过期状态 -->
<update id="updateExpiredStatus">
UPDATE shop_user_coupon
SET status = 2, update_time = NOW()
WHERE deleted = 0
AND status = 0
AND end_time IS NOT NULL
AND end_time &lt;= NOW()
</update>
<!-- 检查用户是否已领取指定优惠券 -->
<select id="countUserReceivedCoupon" resultType="int">
SELECT COUNT(*)
FROM shop_user_coupon
WHERE deleted = 0
AND user_id = #{userId}
AND coupon_id = #{couponId}
</select>
</mapper>

View File

@@ -1,90 +0,0 @@
package com.gxwebsoft.shop.param;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
/**
* 优惠券查询参数
*
* @author 科技小王子
* @since 2025-08-08 21:10:55
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(name = "ShopCouponParam对象", description = "优惠券查询参数")
public class ShopCouponParam extends BaseParam {
private static final long serialVersionUID = 1L;
@Schema(description = "id")
@QueryField(type = QueryType.EQ)
private Integer id;
@Schema(description = "优惠券名称")
private String name;
@Schema(description = "优惠券类型(10满减券 20折扣券 30免费劵)")
@QueryField(type = QueryType.EQ)
private Integer type;
@Schema(description = "满减券-减免金额")
@QueryField(type = QueryType.EQ)
private BigDecimal reducePrice;
@Schema(description = "折扣券-折扣率(0-100)")
@QueryField(type = QueryType.EQ)
private Integer discount;
@Schema(description = "最低消费金额")
@QueryField(type = QueryType.EQ)
private BigDecimal minPrice;
@Schema(description = "到期类型(10领取后生效 20固定时间)")
@QueryField(type = QueryType.EQ)
private Integer expireType;
@Schema(description = "领取后生效-有效天数")
@QueryField(type = QueryType.EQ)
private Integer expireDay;
@Schema(description = "有效期开始时间")
private String startTime;
@Schema(description = "有效期结束时间")
private String endTime;
@Schema(description = "适用范围(10全部商品 20指定商品)")
@QueryField(type = QueryType.EQ)
private Integer applyRange;
@Schema(description = "适用范围配置(json格式)")
private String applyRangeConfig;
@Schema(description = "是否过期(0未过期 1已过期)")
@QueryField(type = QueryType.EQ)
private Integer isExpire;
@Schema(description = "排序(数字越小越靠前)")
@QueryField(type = QueryType.EQ)
private Integer sortNumber;
@Schema(description = "状态, 0待使用, 1已使用, 2已失效")
@QueryField(type = QueryType.EQ)
private Integer status;
@Schema(description = "是否删除, 0否, 1是")
@QueryField(type = QueryType.EQ)
private Integer deleted;
@Schema(description = "用户ID")
@QueryField(type = QueryType.EQ)
private Integer userId;
}

View File

@@ -1,53 +0,0 @@
package com.gxwebsoft.shop.param;
import java.math.BigDecimal;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 商品优惠券表查询参数
*
* @author 科技小王子
* @since 2025-01-11 10:45:12
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(name = "ShopGoodsCouponParam对象", description = "商品优惠券表查询参数")
public class ShopGoodsCouponParam extends BaseParam {
private static final long serialVersionUID = 1L;
@QueryField(type = QueryType.EQ)
private Integer id;
@Schema(description = "商品id")
@QueryField(type = QueryType.EQ)
private Integer goodsId;
@Schema(description = "优惠劵id")
@QueryField(type = QueryType.EQ)
private Integer issueCouponId;
@Schema(description = "排序(数字越小越靠前)")
@QueryField(type = QueryType.EQ)
private Integer sortNumber;
@Schema(description = "状态, 0正常, 1冻结")
@QueryField(type = QueryType.EQ)
private Integer status;
@Schema(description = "是否删除, 0否, 1是")
@QueryField(type = QueryType.EQ)
private Integer deleted;
@Schema(description = "用户ID")
@QueryField(type = QueryType.EQ)
private Integer userId;
}

View File

@@ -1,84 +0,0 @@
package com.gxwebsoft.shop.param;
import com.gxwebsoft.common.core.web.BaseParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 用户优惠券查询参数
*
* @author 科技小王子
* @since 2025-08-08 21:30:00
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(description = "用户优惠券查询参数")
public class ShopUserCouponParam extends BaseParam {
private static final long serialVersionUID = 1L;
@Schema(description = "id")
private Long id;
@Schema(description = "优惠券模板ID")
private Integer couponId;
@Schema(description = "用户ID")
private Integer userId;
@Schema(description = "优惠券名称")
private String name;
@Schema(description = "优惠券类型(10满减券 20折扣券 30免费劵)")
private Integer type;
@Schema(description = "使用状态(0未使用 1已使用 2已过期)")
private Integer status;
@Schema(description = "适用范围(10全部商品 20指定商品 30指定分类)")
private Integer applyRange;
@Schema(description = "获取方式(10主动领取 20系统发放 30活动赠送)")
private Integer obtainType;
@Schema(description = "使用订单ID")
private Long orderId;
@Schema(description = "使用订单号")
private String orderNo;
@Schema(description = "有效期开始时间-查询开始")
private LocalDateTime startTimeBegin;
@Schema(description = "有效期开始时间-查询结束")
private LocalDateTime startTimeEnd;
@Schema(description = "有效期结束时间-查询开始")
private LocalDateTime endTimeBegin;
@Schema(description = "有效期结束时间-查询结束")
private LocalDateTime endTimeEnd;
@Schema(description = "使用时间-查询开始")
private LocalDateTime useTimeBegin;
@Schema(description = "使用时间-查询结束")
private LocalDateTime useTimeEnd;
@Schema(description = "是否包含已过期的券(默认false)")
private Boolean includeExpired = false;
@Schema(description = "是否只查询可用的券(默认false)")
private Boolean onlyAvailable = false;
@Schema(description = "商品ID(用于筛选可用优惠券)")
private Integer goodsId;
@Schema(description = "商品分类ID(用于筛选可用优惠券)")
private Integer categoryId;
@Schema(description = "订单金额(用于筛选可用优惠券)")
private java.math.BigDecimal orderAmount;
}

View File

@@ -1,130 +0,0 @@
package com.gxwebsoft.shop.service;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* 优惠券业务服务
* 处理订单中的优惠券相关业务逻辑
*
* @author 科技小王子
* @since 2025-08-08 22:00:00
*/
public interface CouponBusinessService {
/**
* 获取用户在指定订单中可用的优惠券
*
* @param userId 用户ID
* @param goodsItems 商品列表 [{goodsId, categoryId, price, quantity}]
* @param totalAmount 订单总金额
* @return 可用优惠券列表
*/
List<ShopUserCoupon> getAvailableCouponsForOrder(Integer userId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount);
/**
* 计算使用优惠券后的订单金额
*
* @param userCouponId 用户优惠券ID
* @param goodsItems 商品列表
* @param totalAmount 订单总金额
* @return 计算结果 {discountAmount: 优惠金额, finalAmount: 最终金额, valid: 是否有效}
*/
Map<String, Object> calculateOrderAmountWithCoupon(Long userCouponId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount);
/**
* 验证优惠券是否可用于订单
*
* @param userCouponId 用户优惠券ID
* @param userId 用户ID
* @param goodsItems 商品列表
* @param totalAmount 订单总金额
* @return 验证结果 {valid: boolean, reason: String}
*/
Map<String, Object> validateCouponForOrder(Long userCouponId,
Integer userId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount);
/**
* 为新用户发放欢迎优惠券
*
* @param userId 用户ID
* @return 发放成功的优惠券数量
*/
int issueWelcomeCoupons(Integer userId);
/**
* 为用户生日发放生日优惠券
*
* @param userId 用户ID
* @return 发放成功的优惠券数量
*/
int issueBirthdayCoupons(Integer userId);
/**
* 根据用户消费金额发放优惠券
*
* @param userId 用户ID
* @param consumeAmount 消费金额
* @return 发放成功的优惠券数量
*/
int issueConsumeCoupons(Integer userId, BigDecimal consumeAmount);
/**
* 活动期间批量发放优惠券
*
* @param activityName 活动名称
* @param couponIds 优惠券模板ID列表
* @param userIds 用户ID列表(为空则发放给所有用户)
* @return 发放统计 {totalUsers: 总用户数, totalCoupons: 总优惠券数, successCount: 成功数量}
*/
Map<String, Object> batchIssueActivityCoupons(String activityName,
List<Integer> couponIds,
List<Integer> userIds);
/**
* 获取优惠券使用统计
*
* @param startDate 开始日期
* @param endDate 结束日期
* @return 统计结果
*/
Map<String, Object> getCouponUsageStatistics(String startDate, String endDate);
/**
* 自动处理过期优惠券
* 定时任务调用
*
* @return 处理数量
*/
int autoProcessExpiredCoupons();
/**
* 发送优惠券到期提醒
* 定时任务调用
*
* @param days 提前天数
* @return 提醒用户数量
*/
int sendCouponExpiryReminder(Integer days);
/**
* 推荐最优优惠券组合
*
* @param userId 用户ID
* @param goodsItems 商品列表
* @param totalAmount 订单总金额
* @return 推荐结果 {coupons: 优惠券列表, totalDiscount: 总优惠金额, finalAmount: 最终金额}
*/
Map<String, Object> recommendBestCouponCombination(Integer userId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount);
}

View File

@@ -1,67 +0,0 @@
package com.gxwebsoft.shop.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.ShopCoupon;
import com.gxwebsoft.shop.param.ShopCouponParam;
import java.util.List;
/**
* 优惠券Service
*
* @author 科技小王子
* @since 2025-08-08 21:10:55
*/
public interface ShopCouponService extends IService<ShopCoupon> {
/**
* 分页关联查询
*
* @param param 查询参数
* @return PageResult<ShopCoupon>
*/
PageResult<ShopCoupon> pageRel(ShopCouponParam param);
/**
* 关联查询全部
*
* @param param 查询参数
* @return List<ShopCoupon>
*/
List<ShopCoupon> listRel(ShopCouponParam param);
/**
* 根据id查询
*
* @param id id
* @return ShopCoupon
*/
ShopCoupon getByIdRel(Integer id);
/**
* 获取可领取的优惠券列表
*
* @param userId 用户ID
* @return List<ShopCoupon>
*/
List<ShopCoupon> getReceivableCoupons(Integer userId);
/**
* 检查优惠券是否可以发放
*
* @param couponId 优惠券ID
* @return boolean
*/
boolean canIssue(Integer couponId);
/**
* 更新优惠券发放数量
*
* @param couponId 优惠券ID
* @param increment 增量
* @return boolean
*/
boolean updateIssuedCount(Integer couponId, int increment);
}

View File

@@ -1,42 +0,0 @@
package com.gxwebsoft.shop.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.ShopGoodsCoupon;
import com.gxwebsoft.shop.param.ShopGoodsCouponParam;
import java.util.List;
/**
* 商品优惠券表Service
*
* @author 科技小王子
* @since 2025-01-11 10:45:12
*/
public interface ShopGoodsCouponService extends IService<ShopGoodsCoupon> {
/**
* 分页关联查询
*
* @param param 查询参数
* @return PageResult<ShopGoodsCoupon>
*/
PageResult<ShopGoodsCoupon> pageRel(ShopGoodsCouponParam param);
/**
* 关联查询全部
*
* @param param 查询参数
* @return List<ShopGoodsCoupon>
*/
List<ShopGoodsCoupon> listRel(ShopGoodsCouponParam param);
/**
* 根据id查询
*
* @param id
* @return ShopGoodsCoupon
*/
ShopGoodsCoupon getByIdRel(Integer id);
}

View File

@@ -1,153 +0,0 @@
package com.gxwebsoft.shop.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import com.gxwebsoft.shop.param.ShopUserCouponParam;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* 用户优惠券Service
*
* @author 科技小王子
* @since 2025-08-08 21:30:00
*/
public interface ShopUserCouponService extends IService<ShopUserCoupon> {
/**
* 分页关联查询用户优惠券
*
* @param param 查询参数
* @return PageResult<ShopUserCoupon>
*/
PageResult<ShopUserCoupon> pageRel(ShopUserCouponParam param);
/**
* 关联查询用户优惠券列表
*
* @param param 查询参数
* @return List<ShopUserCoupon>
*/
List<ShopUserCoupon> listRel(ShopUserCouponParam param);
/**
* 根据id查询用户优惠券
*
* @param id id
* @return ShopUserCoupon
*/
ShopUserCoupon getByIdRel(Long id);
/**
* 用户领取优惠券
*
* @param userId 用户ID
* @param couponId 优惠券模板ID
* @return 是否成功
*/
boolean receiveCoupon(Integer userId, Integer couponId);
/**
* 系统发放优惠券给用户
*
* @param userId 用户ID
* @param couponId 优惠券模板ID
* @param source 发放来源描述
* @return 是否成功
*/
boolean issueCouponToUser(Integer userId, Integer couponId, String source);
/**
* 批量发放优惠券给多个用户
*
* @param userIds 用户ID列表
* @param couponId 优惠券模板ID
* @param source 发放来源描述
* @return 成功发放的数量
*/
int batchIssueCoupons(List<Integer> userIds, Integer couponId, String source);
/**
* 使用优惠券
*
* @param userCouponId 用户优惠券ID
* @param orderId 订单ID
* @param orderNo 订单号
* @return 是否成功
*/
boolean useCoupon(Long userCouponId, Long orderId, String orderNo);
/**
* 退还优惠券(订单取消时)
*
* @param orderId 订单ID
* @return 是否成功
*/
boolean returnCoupon(Long orderId);
/**
* 获取用户可用的优惠券列表
*
* @param userId 用户ID
* @param goodsId 商品ID(可选)
* @param categoryId 商品分类ID(可选)
* @param orderAmount 订单金额(可选)
* @return List<ShopUserCoupon>
*/
List<ShopUserCoupon> getAvailableCoupons(Integer userId, Integer goodsId,
Integer categoryId, BigDecimal orderAmount);
/**
* 计算优惠券优惠金额
*
* @param userCoupon 用户优惠券
* @param orderAmount 订单金额
* @return 优惠金额
*/
BigDecimal calculateDiscountAmount(ShopUserCoupon userCoupon, BigDecimal orderAmount);
/**
* 验证优惠券是否可用于指定商品
*
* @param userCoupon 用户优惠券
* @param goodsId 商品ID
* @param categoryId 商品分类ID
* @return 是否可用
*/
boolean validateCouponForGoods(ShopUserCoupon userCoupon, Integer goodsId, Integer categoryId);
/**
* 统计用户优惠券数量
*
* @param userId 用户ID
* @return 统计结果 {total: 总数, unused: 未使用, used: 已使用, expired: 已过期}
*/
Map<String, Object> countUserCoupons(Integer userId);
/**
* 更新过期优惠券状态
*
* @return 更新数量
*/
int updateExpiredCoupons();
/**
* 获取即将过期的优惠券
*
* @param days 天数
* @return List<ShopUserCoupon>
*/
List<ShopUserCoupon> getExpiringSoonCoupons(Integer days);
/**
* 检查用户是否可以领取指定优惠券
*
* @param userId 用户ID
* @param couponId 优惠券模板ID
* @return 检查结果 {canReceive: boolean, reason: String}
*/
Map<String, Object> checkCanReceiveCoupon(Integer userId, Integer couponId);
}

View File

@@ -1,433 +0,0 @@
package com.gxwebsoft.shop.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.ShopCoupon;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import com.gxwebsoft.shop.service.CouponBusinessService;
import com.gxwebsoft.shop.service.ShopCouponService;
import com.gxwebsoft.shop.service.ShopUserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
* 优惠券业务服务实现
*
* @author 科技小王子
* @since 2025-08-08 22:00:00
*/
@Slf4j
@Service
public class CouponBusinessServiceImpl implements CouponBusinessService {
@Resource
private ShopUserCouponService shopUserCouponService;
@Resource
private ShopCouponService shopCouponService;
@Resource
private UserService userService;
@Override
public List<ShopUserCoupon> getAvailableCouponsForOrder(Integer userId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount) {
if (userId == null || goodsItems == null || goodsItems.isEmpty()) {
return new ArrayList<>();
}
// 获取用户所有可用优惠券
List<ShopUserCoupon> allCoupons = shopUserCouponService.getAvailableCoupons(
userId, null, null, totalAmount);
// 过滤出适用于当前订单的优惠券
return allCoupons.stream()
.filter(coupon -> isValidForOrder(coupon, goodsItems, totalAmount))
.collect(Collectors.toList());
}
@Override
public Map<String, Object> calculateOrderAmountWithCoupon(Long userCouponId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount) {
Map<String, Object> result = new HashMap<>();
result.put("valid", false);
result.put("discountAmount", BigDecimal.ZERO);
result.put("finalAmount", totalAmount);
if (userCouponId == null || totalAmount == null) {
result.put("reason", "参数不能为空");
return result;
}
ShopUserCoupon userCoupon = shopUserCouponService.getById(userCouponId);
if (userCoupon == null) {
result.put("reason", "优惠券不存在");
return result;
}
if (!userCoupon.isAvailable()) {
result.put("reason", "优惠券不可用");
return result;
}
if (!isValidForOrder(userCoupon, goodsItems, totalAmount)) {
result.put("reason", "优惠券不适用于当前订单");
return result;
}
BigDecimal discountAmount = shopUserCouponService.calculateDiscountAmount(userCoupon, totalAmount);
BigDecimal finalAmount = totalAmount.subtract(discountAmount);
// 确保最终金额不为负数
if (finalAmount.compareTo(BigDecimal.ZERO) < 0) {
finalAmount = BigDecimal.ZERO;
}
result.put("valid", true);
result.put("discountAmount", discountAmount);
result.put("finalAmount", finalAmount);
result.put("coupon", userCoupon);
return result;
}
@Override
public Map<String, Object> validateCouponForOrder(Long userCouponId,
Integer userId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount) {
Map<String, Object> result = new HashMap<>();
if (userCouponId == null || userId == null) {
result.put("valid", false);
result.put("reason", "参数不能为空");
return result;
}
ShopUserCoupon userCoupon = shopUserCouponService.getById(userCouponId);
if (userCoupon == null) {
result.put("valid", false);
result.put("reason", "优惠券不存在");
return result;
}
if (!userCoupon.getUserId().equals(userId)) {
result.put("valid", false);
result.put("reason", "优惠券不属于当前用户");
return result;
}
if (!userCoupon.isAvailable()) {
result.put("valid", false);
result.put("reason", "优惠券不可用或已过期");
return result;
}
if (!isValidForOrder(userCoupon, goodsItems, totalAmount)) {
result.put("valid", false);
result.put("reason", "优惠券不适用于当前订单商品");
return result;
}
result.put("valid", true);
result.put("reason", "优惠券可用");
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int issueWelcomeCoupons(Integer userId) {
if (userId == null) {
return 0;
}
// 查找欢迎优惠券模板(这里假设有特定的标识)
LambdaQueryWrapper<ShopCoupon> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShopCoupon::getEnabled, 1)
.eq(ShopCoupon::getStatus, 0)
.like(ShopCoupon::getName, "新用户")
.or()
.like(ShopCoupon::getName, "欢迎");
List<ShopCoupon> welcomeCoupons = shopCouponService.list(queryWrapper);
int successCount = 0;
for (ShopCoupon coupon : welcomeCoupons) {
if (shopUserCouponService.issueCouponToUser(userId, coupon.getId(), "新用户注册赠送")) {
successCount++;
}
}
log.info("为新用户{}发放欢迎优惠券{}张", userId, successCount);
return successCount;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int issueBirthdayCoupons(Integer userId) {
if (userId == null) {
return 0;
}
User user = userService.getById(userId);
if (user == null || user.getBirthday() == null) {
return 0;
}
// 检查今天是否是用户生日
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.parse((CharSequence) user.getBirthday(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (today.getMonthValue() != birthday.getMonthValue() ||
today.getDayOfMonth() != birthday.getDayOfMonth()) {
return 0;
}
// 查找生日优惠券模板
LambdaQueryWrapper<ShopCoupon> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShopCoupon::getEnabled, 1)
.eq(ShopCoupon::getStatus, 0)
.like(ShopCoupon::getName, "生日");
List<ShopCoupon> birthdayCoupons = shopCouponService.list(queryWrapper);
int successCount = 0;
for (ShopCoupon coupon : birthdayCoupons) {
if (shopUserCouponService.issueCouponToUser(userId, coupon.getId(), "生日祝福赠送")) {
successCount++;
}
}
log.info("为用户{}发放生日优惠券{}张", userId, successCount);
return successCount;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int issueConsumeCoupons(Integer userId, BigDecimal consumeAmount) {
if (userId == null || consumeAmount == null || consumeAmount.compareTo(BigDecimal.ZERO) <= 0) {
return 0;
}
// 根据消费金额发放不同的优惠券
List<ShopCoupon> eligibleCoupons = new ArrayList<>();
if (consumeAmount.compareTo(new BigDecimal("100")) >= 0) {
// 消费满100发放优惠券
LambdaQueryWrapper<ShopCoupon> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShopCoupon::getEnabled, 1)
.eq(ShopCoupon::getStatus, 0)
.like(ShopCoupon::getName, "消费返券");
eligibleCoupons.addAll(shopCouponService.list(queryWrapper));
}
int successCount = 0;
for (ShopCoupon coupon : eligibleCoupons) {
if (shopUserCouponService.issueCouponToUser(userId, coupon.getId(),
"消费满" + consumeAmount + "元返券")) {
successCount++;
}
}
log.info("为用户{}消费{}元发放优惠券{}张", userId, consumeAmount, successCount);
return successCount;
}
/**
* 检查优惠券是否适用于订单
*/
private boolean isValidForOrder(ShopUserCoupon userCoupon,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount) {
if (userCoupon == null || goodsItems == null || goodsItems.isEmpty()) {
return false;
}
// 检查最低消费金额
if (userCoupon.getMinPrice() != null &&
totalAmount.compareTo(userCoupon.getMinPrice()) < 0) {
return false;
}
// 检查适用范围
if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_ALL) {
return true;
} else if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_GOODS) {
// 检查是否有指定商品
return goodsItems.stream().anyMatch(item -> {
Integer goodsId = (Integer) item.get("goodsId");
return shopUserCouponService.validateCouponForGoods(userCoupon, goodsId, null);
});
} else if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_CATEGORY) {
// 检查是否有指定分类的商品
return goodsItems.stream().anyMatch(item -> {
Integer categoryId = (Integer) item.get("categoryId");
return shopUserCouponService.validateCouponForGoods(userCoupon, null, categoryId);
});
}
return false;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Map<String, Object> batchIssueActivityCoupons(String activityName,
List<Integer> couponIds,
List<Integer> userIds) {
Map<String, Object> result = new HashMap<>();
result.put("totalUsers", 0);
result.put("totalCoupons", 0);
result.put("successCount", 0);
if (couponIds == null || couponIds.isEmpty()) {
result.put("message", "优惠券列表不能为空");
return result;
}
// 如果没有指定用户,则获取所有活跃用户
if (userIds == null || userIds.isEmpty()) {
userIds = userService.list().stream()
.filter(user -> user.getStatus() == 0) // 只给正常状态的用户发放
.map(User::getUserId)
.collect(Collectors.toList());
}
int totalUsers = userIds.size();
int totalCoupons = couponIds.size() * totalUsers;
int successCount = 0;
String source = activityName != null ? activityName + "活动赠送" : "活动赠送";
for (Integer userId : userIds) {
for (Integer couponId : couponIds) {
if (shopUserCouponService.issueCouponToUser(userId, couponId, source)) {
successCount++;
}
}
}
result.put("totalUsers", totalUsers);
result.put("totalCoupons", totalCoupons);
result.put("successCount", successCount);
result.put("message", String.format("活动优惠券发放完成,共%d个用户%d张优惠券成功%d张",
totalUsers, totalCoupons, successCount));
log.info("活动{}批量发放优惠券完成:用户{}个,优惠券{}张,成功{}张",
activityName, totalUsers, totalCoupons, successCount);
return result;
}
@Override
public Map<String, Object> getCouponUsageStatistics(String startDate, String endDate) {
Map<String, Object> result = new HashMap<>();
// 这里可以根据需要实现具体的统计逻辑
// 统计指定时间段内的优惠券使用情况
result.put("totalIssued", 0); // 总发放数量
result.put("totalUsed", 0); // 总使用数量
result.put("totalExpired", 0); // 总过期数量
result.put("usageRate", 0.0); // 使用率
result.put("discountAmount", BigDecimal.ZERO); // 总优惠金额
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int autoProcessExpiredCoupons() {
// 更新过期优惠券状态
int count = shopUserCouponService.updateExpiredCoupons();
log.info("自动处理过期优惠券{}张", count);
return count;
}
@Override
public int sendCouponExpiryReminder(Integer days) {
if (days == null || days <= 0) {
days = 3; // 默认提前3天提醒
}
List<ShopUserCoupon> expiringSoonCoupons = shopUserCouponService.getExpiringSoonCoupons(days);
// 按用户分组
Map<Integer, List<ShopUserCoupon>> userCouponsMap = expiringSoonCoupons.stream()
.collect(Collectors.groupingBy(ShopUserCoupon::getUserId));
int reminderCount = 0;
for (Map.Entry<Integer, List<ShopUserCoupon>> entry : userCouponsMap.entrySet()) {
Integer userId = entry.getKey();
List<ShopUserCoupon> coupons = entry.getValue();
// 这里可以发送消息提醒用户
// 例如:发送站内信、短信、推送通知等
log.info("提醒用户{}有{}张优惠券即将过期", userId, coupons.size());
reminderCount++;
}
log.info("发送优惠券到期提醒给{}个用户", reminderCount);
return reminderCount;
}
@Override
public Map<String, Object> recommendBestCouponCombination(Integer userId,
List<Map<String, Object>> goodsItems,
BigDecimal totalAmount) {
Map<String, Object> result = new HashMap<>();
result.put("coupons", new ArrayList<>());
result.put("totalDiscount", BigDecimal.ZERO);
result.put("finalAmount", totalAmount);
if (userId == null || goodsItems == null || goodsItems.isEmpty() || totalAmount == null) {
return result;
}
// 获取用户所有可用优惠券
List<ShopUserCoupon> availableCoupons = getAvailableCouponsForOrder(userId, goodsItems, totalAmount);
if (availableCoupons.isEmpty()) {
return result;
}
// 简单的贪心算法:选择优惠金额最大的优惠券
// 实际项目中可以实现更复杂的组合优化算法
ShopUserCoupon bestCoupon = null;
BigDecimal maxDiscount = BigDecimal.ZERO;
for (ShopUserCoupon coupon : availableCoupons) {
BigDecimal discount = shopUserCouponService.calculateDiscountAmount(coupon, totalAmount);
if (discount.compareTo(maxDiscount) > 0) {
maxDiscount = discount;
bestCoupon = coupon;
}
}
if (bestCoupon != null) {
List<ShopUserCoupon> recommendedCoupons = new ArrayList<>();
recommendedCoupons.add(bestCoupon);
BigDecimal finalAmount = totalAmount.subtract(maxDiscount);
if (finalAmount.compareTo(BigDecimal.ZERO) < 0) {
finalAmount = BigDecimal.ZERO;
}
result.put("coupons", recommendedCoupons);
result.put("totalDiscount", maxDiscount);
result.put("finalAmount", finalAmount);
}
return result;
}
}

View File

@@ -1,126 +0,0 @@
package com.gxwebsoft.shop.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.ShopCoupon;
import com.gxwebsoft.shop.mapper.ShopCouponMapper;
import com.gxwebsoft.shop.param.ShopCouponParam;
import com.gxwebsoft.shop.service.ShopCouponService;
import com.gxwebsoft.shop.service.ShopUserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
/**
* 优惠券Service实现
*
* @author 科技小王子
* @since 2025-08-08 21:10:55
*/
@Slf4j
@Service
public class ShopCouponServiceImpl extends ServiceImpl<ShopCouponMapper, ShopCoupon> implements ShopCouponService {
@Resource
private ShopUserCouponService shopUserCouponService;
@Override
public PageResult<ShopCoupon> pageRel(ShopCouponParam param) {
PageParam<ShopCoupon, ShopCouponParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number asc, create_time desc");
List<ShopCoupon> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<ShopCoupon> listRel(ShopCouponParam param) {
List<ShopCoupon> list = baseMapper.selectListRel(param);
// 排序
PageParam<ShopCoupon, ShopCouponParam> page = new PageParam<>();
page.setDefaultOrder("sort_number asc, create_time desc");
return page.sortRecords(list);
}
@Override
public ShopCoupon getByIdRel(Integer id) {
ShopCouponParam param = new ShopCouponParam();
param.setId(id);
return param.getOne(baseMapper.selectListRel(param));
}
@Override
public List<ShopCoupon> getReceivableCoupons(Integer userId) {
LambdaQueryWrapper<ShopCoupon> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShopCoupon::getEnabled, 1)
.eq(ShopCoupon::getStatus, 0)
.and(wrapper -> wrapper
.isNull(ShopCoupon::getTotalCount)
.or()
.apply("IFNULL(total_count, 0) = -1")
.or()
.apply("IFNULL(issued_count, 0) < IFNULL(total_count, 0)"))
.orderByAsc(ShopCoupon::getSortNumber)
.orderByDesc(ShopCoupon::getCreateTime);
List<ShopCoupon> allCoupons = list(queryWrapper);
// 过滤掉用户已达到领取上限的优惠券
return allCoupons.stream()
.filter(coupon -> {
if (coupon.getLimitPerUser() == null || coupon.getLimitPerUser() <= 0) {
return true; // 无限制
}
// 检查用户已领取数量
int receivedCount = baseMapper.countUserReceivedCoupon(userId, coupon.getId());
return receivedCount < coupon.getLimitPerUser();
})
.collect(java.util.stream.Collectors.toList());
}
@Override
public boolean canIssue(Integer couponId) {
ShopCoupon coupon = getById(couponId);
if (coupon == null || coupon.getEnabled() != 1 || coupon.getStatus() != 0) {
return false;
}
// 检查发放数量限制
if (coupon.getTotalCount() != null && coupon.getTotalCount() > 0) {
int issuedCount = coupon.getIssuedCount() != null ? coupon.getIssuedCount() : 0;
return issuedCount < coupon.getTotalCount();
}
// 检查有效期
LocalDate now = LocalDate.now();
if (coupon.getExpireType() == 20) { // 固定时间
if (coupon.getStartTime() != null && now.isBefore(coupon.getStartTime())) {
return false; // 还未开始
}
if (coupon.getEndTime() != null && now.isAfter(coupon.getEndTime())) {
return false; // 已过期
}
}
return true;
}
@Override
public boolean updateIssuedCount(Integer couponId, int increment) {
LambdaUpdateWrapper<ShopCoupon> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(ShopCoupon::getId, couponId)
.setSql("issued_count = IFNULL(issued_count, 0) + " + increment);
boolean updated = update(updateWrapper);
if (updated) {
log.debug("更新优惠券{}发放数量,增量: {}", couponId, increment);
}
return updated;
}
}

View File

@@ -1,47 +0,0 @@
package com.gxwebsoft.shop.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.mapper.ShopGoodsCouponMapper;
import com.gxwebsoft.shop.service.ShopGoodsCouponService;
import com.gxwebsoft.shop.entity.ShopGoodsCoupon;
import com.gxwebsoft.shop.param.ShopGoodsCouponParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 商品优惠券表Service实现
*
* @author 科技小王子
* @since 2025-01-11 10:45:12
*/
@Service
public class ShopGoodsCouponServiceImpl extends ServiceImpl<ShopGoodsCouponMapper, ShopGoodsCoupon> implements ShopGoodsCouponService {
@Override
public PageResult<ShopGoodsCoupon> pageRel(ShopGoodsCouponParam param) {
PageParam<ShopGoodsCoupon, ShopGoodsCouponParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number asc, create_time desc");
List<ShopGoodsCoupon> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<ShopGoodsCoupon> listRel(ShopGoodsCouponParam param) {
List<ShopGoodsCoupon> list = baseMapper.selectListRel(param);
// 排序
PageParam<ShopGoodsCoupon, ShopGoodsCouponParam> page = new PageParam<>();
page.setDefaultOrder("sort_number asc, create_time desc");
return page.sortRecords(list);
}
@Override
public ShopGoodsCoupon getByIdRel(Integer id) {
ShopGoodsCouponParam param = new ShopGoodsCouponParam();
param.setId(id);
return param.getOne(baseMapper.selectListRel(param));
}
}

View File

@@ -1,403 +0,0 @@
package com.gxwebsoft.shop.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.ShopCoupon;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import com.gxwebsoft.shop.mapper.ShopUserCouponMapper;
import com.gxwebsoft.shop.param.ShopUserCouponParam;
import com.gxwebsoft.shop.service.ShopCouponService;
import com.gxwebsoft.shop.service.ShopUserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
/**
* 用户优惠券Service实现
*
* @author 科技小王子
* @since 2025-08-08 21:30:00
*/
@Slf4j
@Service
public class ShopUserCouponServiceImpl extends ServiceImpl<ShopUserCouponMapper, ShopUserCoupon>
implements ShopUserCouponService {
@Resource
private ShopCouponService shopCouponService;
@Override
public PageResult<ShopUserCoupon> pageRel(ShopUserCouponParam param) {
PageParam<ShopUserCoupon, ShopUserCouponParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
List<ShopUserCoupon> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<ShopUserCoupon> listRel(ShopUserCouponParam param) {
return baseMapper.selectListRel(param);
}
@Override
public ShopUserCoupon getByIdRel(Long id) {
ShopUserCouponParam param = new ShopUserCouponParam();
param.setId(id);
List<ShopUserCoupon> list = baseMapper.selectListRel(param);
return list.isEmpty() ? null : list.get(0);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean receiveCoupon(Integer userId, Integer couponId) {
// 检查是否可以领取
Map<String, Object> checkResult = checkCanReceiveCoupon(userId, couponId);
if (!(Boolean) checkResult.get("canReceive")) {
log.warn("用户{}无法领取优惠券{}: {}", userId, couponId, checkResult.get("reason"));
return false;
}
// 获取优惠券模板
ShopCoupon coupon = shopCouponService.getById(couponId);
if (coupon == null) {
log.warn("优惠券模板不存在: {}", couponId);
return false;
}
// 创建用户优惠券
ShopUserCoupon userCoupon = createUserCouponFromTemplate(coupon, userId);
userCoupon.setObtainType(ShopUserCoupon.OBTAIN_RECEIVE);
userCoupon.setObtainSource("用户主动领取");
// 保存用户优惠券
boolean saved = save(userCoupon);
if (saved) {
// 更新优惠券模板的已发放数量
updateCouponIssuedCount(couponId, 1);
log.info("用户{}成功领取优惠券{}", userId, couponId);
}
return saved;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean issueCouponToUser(Integer userId, Integer couponId, String source) {
// 获取优惠券模板
ShopCoupon coupon = shopCouponService.getById(couponId);
if (coupon == null || coupon.getEnabled() != 1) {
log.warn("优惠券模板不存在或已禁用: {}", couponId);
return false;
}
// 检查发放数量限制
if (coupon.getTotalCount() != null && coupon.getTotalCount() > 0) {
int issuedCount = coupon.getIssuedCount() != null ? coupon.getIssuedCount() : 0;
if (issuedCount >= coupon.getTotalCount()) {
log.warn("优惠券{}发放数量已达上限", couponId);
return false;
}
}
// 创建用户优惠券
ShopUserCoupon userCoupon = createUserCouponFromTemplate(coupon, userId);
userCoupon.setObtainType(ShopUserCoupon.OBTAIN_SYSTEM);
userCoupon.setObtainSource(source != null ? source : "系统发放");
// 保存用户优惠券
boolean saved = save(userCoupon);
if (saved) {
// 更新优惠券模板的已发放数量
updateCouponIssuedCount(couponId, 1);
log.info("系统向用户{}发放优惠券{}", userId, couponId);
}
return saved;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int batchIssueCoupons(List<Integer> userIds, Integer couponId, String source) {
if (userIds == null || userIds.isEmpty()) {
return 0;
}
// 获取优惠券模板
ShopCoupon coupon = shopCouponService.getById(couponId);
if (coupon == null || coupon.getEnabled() != 1) {
log.warn("优惠券模板不存在或已禁用: {}", couponId);
return 0;
}
int successCount = 0;
for (Integer userId : userIds) {
if (issueCouponToUser(userId, couponId, source)) {
successCount++;
}
}
log.info("批量发放优惠券{}给{}个用户,成功{}个", couponId, userIds.size(), successCount);
return successCount;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean useCoupon(Long userCouponId, Long orderId, String orderNo) {
// 获取用户优惠券
ShopUserCoupon userCoupon = getById(userCouponId);
if (userCoupon == null) {
log.warn("用户优惠券不存在: {}", userCouponId);
return false;
}
// 检查优惠券状态
if (!userCoupon.isAvailable()) {
log.warn("优惠券不可用: {}", userCouponId);
return false;
}
// 更新优惠券状态
LambdaUpdateWrapper<ShopUserCoupon> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(ShopUserCoupon::getId, userCouponId)
.eq(ShopUserCoupon::getStatus, ShopUserCoupon.STATUS_UNUSED)
.set(ShopUserCoupon::getStatus, ShopUserCoupon.STATUS_USED)
.set(ShopUserCoupon::getUseTime, LocalDateTime.now())
.set(ShopUserCoupon::getOrderId, orderId)
.set(ShopUserCoupon::getOrderNo, orderNo);
boolean updated = update(updateWrapper);
if (updated) {
log.info("用户优惠券{}已使用,订单: {}", userCouponId, orderNo);
}
return updated;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean returnCoupon(Long orderId) {
// 查找使用该订单的优惠券
LambdaQueryWrapper<ShopUserCoupon> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShopUserCoupon::getOrderId, orderId)
.eq(ShopUserCoupon::getStatus, ShopUserCoupon.STATUS_USED);
List<ShopUserCoupon> usedCoupons = list(queryWrapper);
if (usedCoupons.isEmpty()) {
return true; // 没有使用优惠券,直接返回成功
}
// 退还优惠券
for (ShopUserCoupon userCoupon : usedCoupons) {
// 检查是否已过期
if (userCoupon.isExpired()) {
// 已过期的券设为过期状态
userCoupon.setStatus(ShopUserCoupon.STATUS_EXPIRED);
} else {
// 未过期的券恢复为未使用状态
userCoupon.setStatus(ShopUserCoupon.STATUS_UNUSED);
}
userCoupon.setUseTime(null);
userCoupon.setOrderId(null);
userCoupon.setOrderNo(null);
updateById(userCoupon);
log.info("退还用户优惠券{},订单: {}", userCoupon.getId(), orderId);
}
return true;
}
/**
* 从优惠券模板创建用户优惠券
*/
private ShopUserCoupon createUserCouponFromTemplate(ShopCoupon coupon, Integer userId) {
ShopUserCoupon userCoupon = new ShopUserCoupon();
userCoupon.setCouponId(coupon.getId());
userCoupon.setUserId(userId);
userCoupon.setName(coupon.getName());
userCoupon.setDescription(coupon.getDescription());
userCoupon.setType(coupon.getType());
userCoupon.setReducePrice(coupon.getReducePrice());
userCoupon.setDiscount(coupon.getDiscount());
userCoupon.setMinPrice(coupon.getMinPrice());
userCoupon.setApplyRange(coupon.getApplyRange());
userCoupon.setApplyRangeConfig(coupon.getApplyRangeConfig());
userCoupon.setStatus(ShopUserCoupon.STATUS_UNUSED);
userCoupon.setTenantId(coupon.getTenantId());
// 设置有效期
LocalDateTime now = LocalDateTime.now();
if (coupon.getExpireType() == 10) {
// 领取后生效
userCoupon.setStartTime(now);
if (coupon.getExpireDay() != null && coupon.getExpireDay() > 0) {
userCoupon.setEndTime(now.plusDays(coupon.getExpireDay()));
}
} else if (coupon.getExpireType() == 20) {
// 固定时间
userCoupon.setStartTime(coupon.getStartTime() != null ?
coupon.getStartTime().atStartOfDay() : now);
userCoupon.setEndTime(coupon.getEndTime() != null ?
coupon.getEndTime().atTime(23, 59, 59) : null);
}
return userCoupon;
}
@Override
public List<ShopUserCoupon> getAvailableCoupons(Integer userId, Integer goodsId,
Integer categoryId, BigDecimal orderAmount) {
ShopUserCouponParam param = new ShopUserCouponParam();
param.setUserId(userId);
param.setStatus(ShopUserCoupon.STATUS_UNUSED);
param.setOnlyAvailable(true);
param.setGoodsId(goodsId);
param.setCategoryId(categoryId);
param.setOrderAmount(orderAmount);
return baseMapper.selectAvailableCoupons(param);
}
@Override
public BigDecimal calculateDiscountAmount(ShopUserCoupon userCoupon, BigDecimal orderAmount) {
if (userCoupon == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
// 检查最低消费金额
if (userCoupon.getMinPrice() != null &&
orderAmount.compareTo(userCoupon.getMinPrice()) < 0) {
return BigDecimal.ZERO;
}
BigDecimal discountAmount = BigDecimal.ZERO;
if (userCoupon.getType() == ShopUserCoupon.TYPE_REDUCE) {
// 满减券
discountAmount = userCoupon.getReducePrice() != null ?
userCoupon.getReducePrice() : BigDecimal.ZERO;
} else if (userCoupon.getType() == ShopUserCoupon.TYPE_DISCOUNT) {
// 折扣券
if (userCoupon.getDiscount() != null && userCoupon.getDiscount() > 0 && userCoupon.getDiscount() < 100) {
BigDecimal discountRate = BigDecimal.valueOf(100 - userCoupon.getDiscount())
.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
discountAmount = orderAmount.multiply(discountRate);
}
} else if (userCoupon.getType() == ShopUserCoupon.TYPE_FREE) {
// 免费券
discountAmount = orderAmount;
}
// 优惠金额不能超过订单金额
return discountAmount.compareTo(orderAmount) > 0 ? orderAmount : discountAmount;
}
@Override
public boolean validateCouponForGoods(ShopUserCoupon userCoupon, Integer goodsId, Integer categoryId) {
if (userCoupon == null || userCoupon.getApplyRange() == null) {
return false;
}
if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_ALL) {
// 全部商品可用
return true;
} else if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_GOODS) {
// 指定商品可用
if (goodsId == null || userCoupon.getApplyRangeConfig() == null) {
return false;
}
// 解析商品ID列表假设是逗号分隔的字符串
String[] goodsIds = userCoupon.getApplyRangeConfig().split(",");
return Arrays.asList(goodsIds).contains(goodsId.toString());
} else if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_CATEGORY) {
// 指定分类可用
if (categoryId == null || userCoupon.getApplyRangeConfig() == null) {
return false;
}
// 解析分类ID列表假设是逗号分隔的字符串
String[] categoryIds = userCoupon.getApplyRangeConfig().split(",");
return Arrays.asList(categoryIds).contains(categoryId.toString());
}
return false;
}
@Override
public Map<String, Object> countUserCoupons(Integer userId) {
return baseMapper.countUserCoupons(userId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public int updateExpiredCoupons() {
return baseMapper.updateExpiredStatus();
}
@Override
public List<ShopUserCoupon> getExpiringSoonCoupons(Integer days) {
return baseMapper.selectExpiringSoon(days != null ? days : 3);
}
@Override
public Map<String, Object> checkCanReceiveCoupon(Integer userId, Integer couponId) {
Map<String, Object> result = new HashMap<>();
// 获取优惠券模板
ShopCoupon coupon = shopCouponService.getById(couponId);
if (coupon == null) {
result.put("canReceive", false);
result.put("reason", "优惠券不存在");
return result;
}
if (coupon.getEnabled() != 1) {
result.put("canReceive", false);
result.put("reason", "优惠券已禁用");
return result;
}
// 检查发放数量限制
if (coupon.getTotalCount() != null && coupon.getTotalCount() > 0) {
int issuedCount = coupon.getIssuedCount() != null ? coupon.getIssuedCount() : 0;
if (issuedCount >= coupon.getTotalCount()) {
result.put("canReceive", false);
result.put("reason", "优惠券已领完");
return result;
}
}
// 检查每人限领数量
if (coupon.getLimitPerUser() != null && coupon.getLimitPerUser() > 0) {
int receivedCount = baseMapper.countUserReceivedCoupon(userId, couponId);
if (receivedCount >= coupon.getLimitPerUser()) {
result.put("canReceive", false);
result.put("reason", "已达到个人领取上限");
return result;
}
}
result.put("canReceive", true);
result.put("reason", "可以领取");
return result;
}
/**
* 更新优惠券模板的已发放数量
*/
private void updateCouponIssuedCount(Integer couponId, int increment) {
LambdaUpdateWrapper<ShopCoupon> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(ShopCoupon::getId, couponId)
.setSql("issued_count = IFNULL(issued_count, 0) + " + increment);
shopCouponService.update(updateWrapper);
}
}

View File

@@ -1,65 +0,0 @@
package com.gxwebsoft.shop.task;
import com.gxwebsoft.shop.service.CouponBusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 优惠券定时任务
*
* @author 科技小王子
* @since 2025-08-08 22:30:00
*/
@Slf4j
@Component
public class CouponScheduledTask {
@Resource
private CouponBusinessService couponBusinessService;
/**
* 每天凌晨2点处理过期优惠券
*/
@Scheduled(cron = "0 0 2 * * ?")
public void processExpiredCoupons() {
try {
log.info("开始执行过期优惠券处理任务");
int count = couponBusinessService.autoProcessExpiredCoupons();
log.info("过期优惠券处理任务完成,处理{}张优惠券", count);
} catch (Exception e) {
log.error("过期优惠券处理任务执行失败", e);
}
}
/**
* 每天上午10点发送优惠券到期提醒
*/
@Scheduled(cron = "0 0 10 * * ?")
public void sendExpiryReminder() {
try {
log.info("开始执行优惠券到期提醒任务");
int count = couponBusinessService.sendCouponExpiryReminder(3);
log.info("优惠券到期提醒任务完成,提醒{}个用户", count);
} catch (Exception e) {
log.error("优惠券到期提醒任务执行失败", e);
}
}
/**
* 每天凌晨1点发送生日优惠券
*/
@Scheduled(cron = "0 0 1 * * ?")
public void issueBirthdayCoupons() {
try {
log.info("开始执行生日优惠券发放任务");
// 这里需要获取今天生日的用户列表
// 由于没有具体的用户生日查询方法,这里只是示例
log.info("生日优惠券发放任务完成");
} catch (Exception e) {
log.error("生日优惠券发放任务执行失败", e);
}
}
}

View File

@@ -106,25 +106,25 @@ public class CouponUtils {
}
// 检查最低消费金额
if (userCoupon.getMinPrice() != null &&
if (userCoupon.getMinPrice() != null &&
orderAmount.compareTo(userCoupon.getMinPrice()) < 0) {
return BigDecimal.ZERO;
}
BigDecimal discountAmount = BigDecimal.ZERO;
if (userCoupon.getType() == ShopUserCoupon.TYPE_REDUCE) {
if (ShopUserCoupon.TYPE_REDUCE.equals(userCoupon.getType())) {
// 满减券
discountAmount = userCoupon.getReducePrice() != null ?
discountAmount = userCoupon.getReducePrice() != null ?
userCoupon.getReducePrice() : BigDecimal.ZERO;
} else if (userCoupon.getType() == ShopUserCoupon.TYPE_DISCOUNT) {
} else if (ShopUserCoupon.TYPE_DISCOUNT.equals(userCoupon.getType())) {
// 折扣券
if (userCoupon.getDiscount() != null && userCoupon.getDiscount() > 0 && userCoupon.getDiscount() < 100) {
BigDecimal discountRate = BigDecimal.valueOf(100 - userCoupon.getDiscount())
.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
discountAmount = orderAmount.multiply(discountRate);
}
} else if (userCoupon.getType() == ShopUserCoupon.TYPE_FREE) {
} else if (ShopUserCoupon.TYPE_FREE.equals(userCoupon.getType())) {
// 免费券
discountAmount = orderAmount;
}
@@ -146,19 +146,19 @@ public class CouponUtils {
return false;
}
if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_ALL) {
if (ShopUserCoupon.APPLY_ALL.equals(userCoupon.getApplyRange())) {
// 全部商品可用
return true;
} else if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_GOODS) {
} else if (ShopUserCoupon.APPLY_GOODS.equals(userCoupon.getApplyRange())) {
// 指定商品可用
if (goodsId == null || userCoupon.getApplyRangeConfig() == null) {
if (goodsId == null || userCoupon.getApplyRangeConfig() == null || userCoupon.getApplyRangeConfig().trim().isEmpty()) {
return false;
}
List<String> goodsIds = Arrays.asList(userCoupon.getApplyRangeConfig().split(","));
return goodsIds.contains(goodsId.toString());
} else if (userCoupon.getApplyRange() == ShopUserCoupon.APPLY_CATEGORY) {
} else if (ShopUserCoupon.APPLY_CATEGORY.equals(userCoupon.getApplyRange())) {
// 指定分类可用
if (categoryId == null || userCoupon.getApplyRangeConfig() == null) {
if (categoryId == null || userCoupon.getApplyRangeConfig() == null || userCoupon.getApplyRangeConfig().trim().isEmpty()) {
return false;
}
List<String> categoryIds = Arrays.asList(userCoupon.getApplyRangeConfig().split(","));
@@ -191,23 +191,23 @@ public class CouponUtils {
if (userCoupon == null) {
return false;
}
// 检查状态
if (userCoupon.getStatus() != ShopUserCoupon.STATUS_UNUSED) {
if (!ShopUserCoupon.STATUS_UNUSED.equals(userCoupon.getStatus())) {
return false;
}
// 检查是否过期
if (isExpired(userCoupon)) {
return false;
}
// 检查是否在有效期内
LocalDateTime now = LocalDateTime.now();
if (userCoupon.getStartTime() != null && userCoupon.getStartTime().isAfter(now)) {
return false; // 还未开始
}
return true;
}
@@ -224,18 +224,18 @@ public class CouponUtils {
StringBuilder sb = new StringBuilder();
sb.append(userCoupon.getName());
if (userCoupon.getType() == ShopUserCoupon.TYPE_REDUCE && userCoupon.getReducePrice() != null) {
if (ShopUserCoupon.TYPE_REDUCE.equals(userCoupon.getType()) && userCoupon.getReducePrice() != null) {
sb.append("").append(userCoupon.getReducePrice()).append("");
if (userCoupon.getMinPrice() != null && userCoupon.getMinPrice().compareTo(BigDecimal.ZERO) > 0) {
sb.append("(满").append(userCoupon.getMinPrice()).append("可用)");
}
} else if (userCoupon.getType() == ShopUserCoupon.TYPE_DISCOUNT && userCoupon.getDiscount() != null) {
} else if (ShopUserCoupon.TYPE_DISCOUNT.equals(userCoupon.getType()) && userCoupon.getDiscount() != null) {
sb.append(" ").append(userCoupon.getDiscount()).append("");
if (userCoupon.getMinPrice() != null && userCoupon.getMinPrice().compareTo(BigDecimal.ZERO) > 0) {
sb.append("(满").append(userCoupon.getMinPrice()).append("可用)");
}
} else if (userCoupon.getType() == ShopUserCoupon.TYPE_FREE) {
} else if (ShopUserCoupon.TYPE_FREE.equals(userCoupon.getType())) {
sb.append(" 免费券");
}
@@ -255,7 +255,7 @@ public class CouponUtils {
*/
public static String generateCouponCode(Integer userId, Integer couponId) {
String timestamp = String.valueOf(System.currentTimeMillis());
return String.format("CPN%s%s%s",
return String.format("CPN%s%s%s",
String.format("%08d", userId),
String.format("%06d", couponId),
timestamp.substring(timestamp.length() - 6));

View File

@@ -1,11 +1,18 @@
package com.gxwebsoft.generator;
/**
* ShopGenerator - 商城模块代码生成器
*
* 注意由于MyBatis-Plus Generator版本兼容性问题,
* 当前版本的API可能不兼容建议手动创建代码文件
*/
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.gxwebsoft.generator.engine.BeetlTemplateEnginePlus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* CMS模块-代码生成工具
@@ -30,7 +37,7 @@ public class ShopGenerator {
// 是否在xml中添加二级缓存配置
private static final boolean ENABLE_CACHE = false;
// 数据库连接配置
private static final String DB_URL = "jdbc:mysql://1Panel-mysql-Bqdt:3306/modules?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
private static final String DB_URL = "jdbc:mysql://8.134.169.209:13306/modules?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DB_USERNAME = "modules";
private static final String DB_PASSWORD = "8YdLnk7KsPAyDXGA";
@@ -47,7 +54,7 @@ public class ShopGenerator {
// "shop_goods_spec",
// "shop_goods_sku",
// "shop_goods_category",
// "shop_goods_coupon",
"shop_coupon",
// "shop_goods_description",
// "shop_goods_log",
// "shop_goods_relation",
@@ -81,6 +88,7 @@ public class ShopGenerator {
// "shop_dealer_user",
// "shop_user_referee",
// "shop_dealer_withdraw",
"shop_user_coupon",
// "shop_cart",
// "shop_count",
// "shop_express",
@@ -126,22 +134,163 @@ public class ShopGenerator {
private static final String TEMPLATES_DIR = "/src/test/java/com/gxwebsoft/generator/templates";
public static void main(String[] args) {
System.out.println("=== 商城模块 MyBatis-Plus 代码生成器 ===");
System.out.println("输出目录: " + OUTPUT_LOCATION + OUTPUT_DIR);
System.out.println("包名: " + PACKAGE_NAME + "." + MODULE_NAME);
System.out.println("表名: " + String.join(", ", TABLE_NAMES));
System.out.println("数据库: " + DB_URL);
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
try {
// 注意由于MyBatis-Plus Generator版本兼容性问题
// 当前版本的API可能不兼容建议手动创建代码文件
System.out.println("请参考项目中现有的商城模块代码结构");
System.out.println("或者手动创建Entity、Mapper、Service、Controller类");
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(OUTPUT_LOCATION + OUTPUT_DIR);
gc.setAuthor(AUTHOR);
gc.setOpen(false);
gc.setFileOverride(true);
gc.setEnableCache(ENABLE_CACHE);
gc.setSwagger2(true);
gc.setIdType(IdType.AUTO);
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
} catch (Exception e) {
System.err.println("代码生成失败: " + e.getMessage());
e.printStackTrace();
}
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(DB_URL);
// dsc.setSchemaName("public");
dsc.setDriverName(DB_DRIVER);
dsc.setUsername(DB_USERNAME);
dsc.setPassword(DB_PASSWORD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(MODULE_NAME);
pc.setParent(PACKAGE_NAME);
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(TABLE_NAMES);
strategy.setTablePrefix(TABLE_PREFIX);
strategy.setSuperControllerClass(PACKAGE_NAME + ".common.core.web.BaseController");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
strategy.setLogicDeleteFieldName("deleted");
mpg.setStrategy(strategy);
// 模板配置
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setController(TEMPLATES_DIR + "/controller.java");
templateConfig.setEntity(TEMPLATES_DIR + "/entity.java");
templateConfig.setMapper(TEMPLATES_DIR + "/mapper.java");
templateConfig.setXml(TEMPLATES_DIR + "/mapper.xml");
templateConfig.setService(TEMPLATES_DIR + "/service.java");
templateConfig.setServiceImpl(TEMPLATES_DIR + "/serviceImpl.java");
mpg.setTemplate(templateConfig);
mpg.setTemplateEngine(new BeetlTemplateEnginePlus());
// 自定义模板配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<>();
map.put("packageName", PACKAGE_NAME);
map.put("paramExcludeFields", PARAM_EXCLUDE_FIELDS);
map.put("paramToStringType", PARAM_TO_STRING_TYPE);
map.put("paramEqType", PARAM_EQ_TYPE);
map.put("authAnnotation", AUTH_ANNOTATION);
map.put("logAnnotation", LOG_ANNOTATION);
map.put("controllerMappingPrefix", CONTROLLER_MAPPING_PREFIX);
this.setMap(map);
}
};
String templatePath = TEMPLATES_DIR + "/param.java.btl";
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION + OUTPUT_DIR + "/"
+ PACKAGE_NAME.replace(".", "/")
+ "/" + pc.getModuleName() + "/param/"
+ tableInfo.getEntityName() + "Param" + StringPool.DOT_JAVA;
}
});
/**
* 以下是生成VUE项目代码
* 生成文件的路径 /api/shop/goods/index.ts
*/
templatePath = TEMPLATES_DIR + "/index.ts.btl";
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
+ "/api/" + pc.getModuleName() + "/"
+ tableInfo.getEntityPath() + "/" + "index.ts";
}
});
focList.add(new FileOutConfig() {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
+ "/api/" + pc.getModuleName() + "/"
+ tableInfo.getEntityPath() + "/" + "index.ts";
}
});
// 生成TS文件 (/api/shop/goods/model/index.ts)
templatePath = TEMPLATES_DIR + "/model.ts.btl";
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
+ "/api/" + pc.getModuleName() + "/"
+ tableInfo.getEntityPath() + "/model/" + "index.ts";
}
});
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
+ "/api/" + pc.getModuleName() + "/"
+ tableInfo.getEntityPath() + "/model/" + "index.ts";
}
});
// 生成Vue文件(/views/shop/goods/index.vue)
templatePath = TEMPLATES_DIR + "/index.vue.btl";
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
+ "/views/" + pc.getModuleName() + "/"
+ tableInfo.getEntityPath() + "/" + "index.vue";
}
});
// 生成components文件(/views/shop/goods/components/edit.vue)
templatePath = TEMPLATES_DIR + "/components.edit.vue.btl";
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
+ "/views/" + pc.getModuleName() + "/"
+ tableInfo.getEntityPath() + "/components/" + tableInfo.getEntityPath() + "Edit.vue";
}
});
// 生成components文件(/views/shop/goods/components/search.vue)
templatePath = TEMPLATES_DIR + "/components.search.vue.btl";
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
+ "/views/" + pc.getModuleName() + "/"
+ tableInfo.getEntityPath() + "/components/" + "search.vue";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.execute();
}
}

View File

@@ -0,0 +1,50 @@
package com.gxwebsoft.generator.engine;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
/**
* Beetl模板引擎实现文件输出
*
* @author WebSoft
* @since 2021-09-05 00:30:28
*/
public class BeetlTemplateEnginePlus extends AbstractTemplateEngine {
private GroupTemplate groupTemplate;
@Override
public AbstractTemplateEngine init(ConfigBuilder configBuilder) {
super.init(configBuilder);
try {
Configuration cfg = Configuration.defaultConfiguration();
groupTemplate = new GroupTemplate(new FileResourceLoader(), cfg);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return this;
}
@Override
public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
Template template = groupTemplate.getTemplate(templatePath);
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
template.binding(objectMap);
template.renderTo(fileOutputStream);
}
logger.debug("模板:" + templatePath + "; 文件:" + outputFile);
}
@Override
public String templateFilePath(String filePath) {
return filePath + ".btl";
}
}

View File

@@ -23,8 +23,8 @@ import ${cfg.packageName!}.common.core.web.PageParam;
import ${cfg.packageName!}.common.core.web.BatchParam;
import ${cfg.packageName!}.common.core.annotation.OperationLog;
import ${cfg.packageName!}.common.system.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
<% if(!restControllerStyle) { %>
@@ -41,7 +41,7 @@ import java.util.List;
* @since ${date(), 'yyyy-MM-dd HH:mm:ss'}
*/
<% if(swagger2) { %>
@Api(tags = "${table.comment!}管理")
@Tag(name = "${table.comment!}管理")
<% } %>
<% if(restControllerStyle) { %>
@RestController
@@ -68,7 +68,7 @@ public class ${table.controllerName} {
@PreAuthorize("hasAuthority('${authPre}:list')")
<% } %>
<% if(swagger2) { %>
@ApiOperation("分页查询${table.comment!}")
@Operation(summary = "分页查询${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody
@@ -88,7 +88,7 @@ public class ${table.controllerName} {
@PreAuthorize("hasAuthority('${authPre}:list')")
<% } %>
<% if(swagger2) { %>
@ApiOperation("查询全部${table.comment!}")
@Operation(summary = "查询全部${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody
@@ -105,7 +105,7 @@ public class ${table.controllerName} {
*/
<% } %>
@PreAuthorize("hasAuthority('${authPre}:list')")
@ApiOperation("根据id查询${table.comment!}")
@Operation(summary = "根据id查询${table.comment!}")
@GetMapping("/{id}")
public ApiResult<${entity}> get(@PathVariable("id") Integer id) {
// 使用关联查询
@@ -124,7 +124,7 @@ public class ${table.controllerName} {
@OperationLog
<% } %>
<% if(swagger2) { %>
@ApiOperation("添加${table.comment!}")
@Operation(summary = "添加${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody
@@ -154,7 +154,7 @@ public class ${table.controllerName} {
@OperationLog
<% } %>
<% if(swagger2) { %>
@ApiOperation("修改${table.comment!}")
@Operation(summary = "修改${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody
@@ -179,7 +179,7 @@ public class ${table.controllerName} {
@OperationLog
<% } %>
<% if(swagger2) { %>
@ApiOperation("删除${table.comment!}")
@Operation(summary = "删除${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody
@@ -204,7 +204,7 @@ public class ${table.controllerName} {
@OperationLog
<% } %>
<% if(swagger2) { %>
@ApiOperation("批量添加${table.comment!}")
@Operation(summary = "批量添加${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody
@@ -229,7 +229,7 @@ public class ${table.controllerName} {
@OperationLog
<% } %>
<% if(swagger2) { %>
@ApiOperation("批量修改${table.comment!}")
@Operation(summary = "批量修改${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody
@@ -254,7 +254,7 @@ public class ${table.controllerName} {
@OperationLog
<% } %>
<% if(swagger2) { %>
@ApiOperation("批量删除${table.comment!}")
@Operation(summary = "批量删除${table.comment!}")
<% } %>
<% if(!restControllerStyle) { %>
@ResponseBody

View File

@@ -4,8 +4,7 @@ package ${package.Entity};
import ${pkg};
<% } %>
<% if(swagger2) { %>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
<% } %>
<% if(entityLombokModel) { %>
import lombok.Data;
@@ -33,7 +32,7 @@ import lombok.experimental.Accessors;
<% } %>
<% } %>
<% if(swagger2) { %>
@ApiModel(value = "${entity}对象", description = "${table.comment!''}")
@Schema(name = "${entity}对象", description = "${table.comment!''}")
<% } %>
<% if(table.convert) { %>
@TableName("${table.name}")
@@ -59,7 +58,7 @@ public class ${entity} implements Serializable {
<% if(isNotEmpty(field.comment)) { %>
<% if(swagger2) { %>
@ApiModelProperty(value = "${field.comment}")
@Schema(description = "${field.comment}")
<% }else{ %>
/**
* ${field.comment}

View File

@@ -1,5 +1,5 @@
import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { ApiResult, PageResult } from '@/api/index';
import type { ${entity}, ${entity}Param } from './model';
import { MODULES_API_URL } from '@/config/setting';

View File

@@ -1,6 +1,5 @@
<template>
<div class="page">
<div class="ele-body">
<a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
<a-card :bordered="false" :body-style="{ padding: '16px' }">
<ele-pro-table
ref="tableRef"
@@ -46,8 +45,7 @@
<!-- 编辑弹窗 -->
<${entity}Edit v-model:visible="showEdit" :data="current" @done="reload" />
</div>
</div>
</a-page-header>
</template>
<script lang="ts" setup>
@@ -61,6 +59,7 @@
ColumnItem
} from 'ele-admin-pro/es/ele-pro-table/types';
import Search from './components/search.vue';
import {getPageTitle} from '@/utils/common';
import ${entity}Edit from './components/${table.entityPath}Edit.vue';
import { page${entity}, remove${entity}, removeBatch${entity} } from '@/api/${package.ModuleName}/${table.entityPath}';
import type { ${entity}, ${entity}Param } from '@/api/${package.ModuleName}/${table.entityPath}/model';

View File

@@ -1,4 +1,4 @@
import type { PageParam } from '@/api';
import type { PageParam } from '@/api/index';
/**
* ${table.comment!}

View File

@@ -6,8 +6,7 @@ import ${cfg.packageName!}.common.core.annotation.QueryType;
import ${cfg.packageName!}.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
<% if(swagger2) { %>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
<% } %>
<% if(entityLombokModel) { %>
import lombok.Data;
@@ -36,7 +35,7 @@ import lombok.experimental.Accessors;
<% } %>
@JsonInclude(JsonInclude.Include.NON_NULL)
<% if(swagger2) { %>
@ApiModel(value = "${entity}Param对象", description = "${table.comment!''}查询参数")
@Schema(name = "${entity}Param对象", description = "${table.comment!''}查询参数")
<% } %>
public class ${entity}Param extends BaseParam {
<% if(entitySerialVersionUID) { %>
@@ -57,7 +56,7 @@ public class ${entity}Param extends BaseParam {
<% if(isNotEmpty(field.comment)) { %>
<% if(swagger2) { %>
@ApiModelProperty(value = "${field.comment}")
@Schema(description = "${field.comment}")
<% }else{ %>
/**
* ${field.comment}

View File

@@ -0,0 +1,156 @@
package com.gxwebsoft.shop.utils;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* CouponUtils 测试类
*/
public class CouponUtilsTest {
@Test
public void testGetTypeName() {
assertEquals("满减券", CouponUtils.getTypeName(ShopUserCoupon.TYPE_REDUCE));
assertEquals("折扣券", CouponUtils.getTypeName(ShopUserCoupon.TYPE_DISCOUNT));
assertEquals("免费券", CouponUtils.getTypeName(ShopUserCoupon.TYPE_FREE));
assertEquals("未知", CouponUtils.getTypeName(null));
assertEquals("未知", CouponUtils.getTypeName(99));
}
@Test
public void testGetStatusName() {
assertEquals("未使用", CouponUtils.getStatusName(ShopUserCoupon.STATUS_UNUSED));
assertEquals("已使用", CouponUtils.getStatusName(ShopUserCoupon.STATUS_USED));
assertEquals("已过期", CouponUtils.getStatusName(ShopUserCoupon.STATUS_EXPIRED));
assertEquals("未知", CouponUtils.getStatusName(null));
assertEquals("未知", CouponUtils.getStatusName(99));
}
@Test
public void testGetApplyRangeName() {
assertEquals("全部商品", CouponUtils.getApplyRangeName(ShopUserCoupon.APPLY_ALL));
assertEquals("指定商品", CouponUtils.getApplyRangeName(ShopUserCoupon.APPLY_GOODS));
assertEquals("指定分类", CouponUtils.getApplyRangeName(ShopUserCoupon.APPLY_CATEGORY));
assertEquals("未知", CouponUtils.getApplyRangeName(null));
assertEquals("未知", CouponUtils.getApplyRangeName(99));
}
@Test
public void testCalculateDiscountAmount() {
// 测试满减券
ShopUserCoupon reduceCoupon = new ShopUserCoupon();
reduceCoupon.setType(ShopUserCoupon.TYPE_REDUCE);
reduceCoupon.setReducePrice(new BigDecimal("10.00"));
reduceCoupon.setMinPrice(new BigDecimal("50.00"));
BigDecimal discount = CouponUtils.calculateDiscountAmount(reduceCoupon, new BigDecimal("100.00"));
assertEquals(0, new BigDecimal("10.00").compareTo(discount));
// 测试不满足最低消费
discount = CouponUtils.calculateDiscountAmount(reduceCoupon, new BigDecimal("30.00"));
assertEquals(0, BigDecimal.ZERO.compareTo(discount));
// 测试折扣券
ShopUserCoupon discountCoupon = new ShopUserCoupon();
discountCoupon.setType(ShopUserCoupon.TYPE_DISCOUNT);
discountCoupon.setDiscount(80); // 8折
discountCoupon.setMinPrice(new BigDecimal("50.00"));
discount = CouponUtils.calculateDiscountAmount(discountCoupon, new BigDecimal("100.00"));
assertEquals(0, new BigDecimal("20.0000").compareTo(discount));
// 测试免费券
ShopUserCoupon freeCoupon = new ShopUserCoupon();
freeCoupon.setType(ShopUserCoupon.TYPE_FREE);
discount = CouponUtils.calculateDiscountAmount(freeCoupon, new BigDecimal("100.00"));
assertEquals(0, new BigDecimal("100.00").compareTo(discount));
}
@Test
public void testIsApplicableToGoods() {
// 测试全部商品可用
ShopUserCoupon allCoupon = new ShopUserCoupon();
allCoupon.setApplyRange(ShopUserCoupon.APPLY_ALL);
assertTrue(CouponUtils.isApplicableToGoods(allCoupon, 123, 456));
// 测试指定商品可用
ShopUserCoupon goodsCoupon = new ShopUserCoupon();
goodsCoupon.setApplyRange(ShopUserCoupon.APPLY_GOODS);
goodsCoupon.setApplyRangeConfig("123,456,789");
assertTrue(CouponUtils.isApplicableToGoods(goodsCoupon, 123, 999));
assertFalse(CouponUtils.isApplicableToGoods(goodsCoupon, 999, 999));
// 测试指定分类可用
ShopUserCoupon categoryCoupon = new ShopUserCoupon();
categoryCoupon.setApplyRange(ShopUserCoupon.APPLY_CATEGORY);
categoryCoupon.setApplyRangeConfig("10,20,30");
assertTrue(CouponUtils.isApplicableToGoods(categoryCoupon, 999, 20));
assertFalse(CouponUtils.isApplicableToGoods(categoryCoupon, 999, 99));
}
@Test
public void testIsExpired() {
ShopUserCoupon coupon = new ShopUserCoupon();
// 测试未过期
coupon.setEndTime(LocalDateTime.now().plusDays(1));
assertFalse(CouponUtils.isExpired(coupon));
// 测试已过期
coupon.setEndTime(LocalDateTime.now().minusDays(1));
assertTrue(CouponUtils.isExpired(coupon));
// 测试无结束时间
coupon.setEndTime(null);
assertFalse(CouponUtils.isExpired(coupon));
}
@Test
public void testIsAvailable() {
ShopUserCoupon coupon = new ShopUserCoupon();
coupon.setStatus(ShopUserCoupon.STATUS_UNUSED);
coupon.setStartTime(LocalDateTime.now().minusDays(1));
coupon.setEndTime(LocalDateTime.now().plusDays(1));
assertTrue(CouponUtils.isAvailable(coupon));
// 测试已使用
coupon.setStatus(ShopUserCoupon.STATUS_USED);
assertFalse(CouponUtils.isAvailable(coupon));
// 测试已过期
coupon.setStatus(ShopUserCoupon.STATUS_UNUSED);
coupon.setEndTime(LocalDateTime.now().minusDays(1));
assertFalse(CouponUtils.isAvailable(coupon));
// 测试还未开始
coupon.setEndTime(LocalDateTime.now().plusDays(1));
coupon.setStartTime(LocalDateTime.now().plusDays(1));
assertFalse(CouponUtils.isAvailable(coupon));
}
@Test
public void testIsValidCouponCode() {
assertTrue(CouponUtils.isValidCouponCode("CPN00000001000001123456"));
assertFalse(CouponUtils.isValidCouponCode("CPN123"));
assertFalse(CouponUtils.isValidCouponCode("ABC00000001000001123456"));
assertFalse(CouponUtils.isValidCouponCode(null));
}
@Test
public void testGenerateCouponCode() {
String code = CouponUtils.generateCouponCode(1, 1);
assertNotNull(code);
assertTrue(code.startsWith("CPN"));
assertEquals(23, code.length());
assertTrue(CouponUtils.isValidCouponCode(code));
}
}