提交Salon旧接口清理与安全配置基线

This commit is contained in:
2026-11-01 14:43:04 +08:00
parent f30abbc26c
commit 203dac2370
49 changed files with 73 additions and 19388 deletions
@@ -4,6 +4,8 @@ import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* JWT 配置。
*/
@@ -15,7 +17,7 @@ public class JwtProperties {
/**
* HS512 密钥,生产环境请通过 Nacos 覆盖。
*/
private String secret = "jayucloud-salon-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
private String secret;
/**
* Token 发行者。
@@ -41,4 +43,11 @@ public class JwtProperties {
* 时钟偏移容忍,单位秒。
*/
private long clockSkewSeconds = 30;
@PostConstruct
public void validate() {
if (secret == null || secret.trim().length() < 64) {
throw new IllegalStateException("jayucloud-salon.security.jwt.secret 未配置或长度不足 64 位");
}
}
}
@@ -1,52 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin;
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CampaignDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CampaignService;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CampaignVO;
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/admin/campaign")
@RequiredArgsConstructor
public class AdminCampaignController {
private final CampaignService campaignService;
private final AdminScopeHelper adminScopeHelper;
private final SecurityAuditSupport securityAuditSupport;
@GetMapping("/list")
@RequirePermission("campaign:view")
public Result<PageResultVO<CampaignVO>> list(HttpServletRequest request,
@RequestParam(required = false) Integer status,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
return Result.success(campaignService.listCampaigns(shopId, status, page, size));
}
@PostMapping("/save")
@RequirePermission("campaign:manage")
public Result<CampaignVO> save(HttpServletRequest request, @RequestBody CampaignDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()));
try {
CampaignVO result = campaignService.saveCampaign(dto);
securityAuditSupport.success(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "campaignId=" + result.getId());
return Result.success(result);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "reason=" + exception.getMessage());
throw exception;
}
}
}
@@ -1,182 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin;
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO;
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
* 后台优惠券管理控制器
*/
@RestController
@RequestMapping("/admin/coupon")
@RequiredArgsConstructor
public class AdminCouponController {
/**
* Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CouponService couponService;
/**
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserService userService;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
/**
* 创建优惠券
*/
@PostMapping("/create")
@RequirePermission("coupon:create")
@OperationGuard(action = "admin-coupon-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
public Result<Long> createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId());
Long couponId = couponService.createCoupon(couponDTO, shopId);
return Result.success(couponId);
}
/**
* 更新优惠券
*/
@PutMapping("/update/{id}")
@RequirePermission("coupon:edit")
@OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
public Result<Boolean> updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券");
Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId());
shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId);
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
return Result.success(success);
}
/**
* 删除优惠券
*/
@DeleteMapping("/delete/{id}")
@RequirePermission("coupon:delete")
@OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
public Result<Boolean> deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券");
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.deleteCoupon(id, shopId);
return Result.success(success);
}
/**
* 获取优惠券详情
*/
@GetMapping("/detail/{id}")
@RequirePermission("coupon:view")
public Result<CouponVO> getCouponById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO != null) {
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券");
}
return Result.success(couponVO);
}
/**
* 获取优惠券列表
*/
@GetMapping("/list")
@RequirePermission("coupon:view")
public Result<PageResultVO<CouponVO>> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
PageResultVO<CouponVO> pageResult = couponService.listCoupons(page, size, shopId);
return Result.success(pageResult);
}
/**
* 获取所有优惠券
*/
@GetMapping("/list/all")
@RequirePermission("coupon:view")
public Result<List<CouponVO>> listAllCoupons(HttpServletRequest request, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
List<CouponVO> coupons = couponService.listAllCoupons();
Long resolvedShopId = shopId;
if (resolvedShopId != null) {
coupons = coupons.stream()
.filter(coupon -> resolvedShopId.equals(coupon.getShopId()))
.collect(Collectors.toList());
}
return Result.success(coupons);
}
/**
* 为用户分配优惠券
*/
@PostMapping("/assign")
@RequirePermission("coupon:assign")
@OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
public Result<Boolean> assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(couponId);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
return Result.success(success);
}
/**
* 发放优惠券
*/
@PostMapping("/distribute")
@RequirePermission("coupon:assign")
@OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
public Result<Boolean> distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(couponId);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
for (Long userId : userIds) {
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
}
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
return Result.success(success);
}
}
@@ -1,190 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO;
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.UserCouponVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 优惠券控制器
*/
@RestController
@RequestMapping("/coupon")
@RequiredArgsConstructor
public class CouponController {
/**
* Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CouponService couponService;
/**
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserService userService;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
/**
* 创建优惠券
*/
@PostMapping("/create")
@RequirePermission("coupon:create")
public Result<Long> createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId());
Long couponId = couponService.createCoupon(couponDTO, shopId);
return Result.success(couponId);
}
/**
* 更新优惠券
*/
@PutMapping("/update/{id}")
@RequirePermission("coupon:edit")
public Result<Boolean> updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券");
Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId());
shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId);
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
return Result.success(success);
}
/**
* 删除优惠券
*/
@DeleteMapping("/delete/{id}")
@RequirePermission("coupon:delete")
public Result<Boolean> deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券");
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.deleteCoupon(id, shopId);
return Result.success(success);
}
/**
* 获取优惠券详情
*/
@GetMapping("/detail/{id}")
@RequirePermission("coupon:view")
public Result<CouponVO> getCouponById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO != null) {
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券");
}
return Result.success(couponVO);
}
/**
* 获取优惠券列表
*/
@GetMapping("/list")
@RequirePermission("coupon:view")
public Result<PageResultVO<CouponVO>> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
PageResultVO<CouponVO> pageResult = couponService.listCoupons(page, size, shopId);
return Result.success(pageResult);
}
/**
* 为用户分配优惠券
*/
@PostMapping("/assign")
@RequirePermission("coupon:assign")
public Result<Boolean> assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(couponId);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
return Result.success(success);
}
/**
* 获取用户优惠券列表
*/
@GetMapping("/user/list")
public Result<List<UserCouponVO>> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) {
List<UserCouponVO> userCoupons = couponService.listUserCoupons(userId, status);
return Result.success(userCoupons);
}
/**
* 使用优惠券
*/
@PostMapping("/use")
public Result<Boolean> useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) {
boolean success = couponService.useCoupon(userCouponId, userId);
return Result.success(success);
}
/**
* 获取商品可用的优惠券
*/
@GetMapping("/available")
public Result<List<UserCouponVO>> getAvailableCoupons(
@RequestParam(required = false, defaultValue = "") String productTags,
@RequestParam Double productPrice,
@RequestParam(required = false) Long shopId,
@RequestAttribute("userId") Long userId
) {
List<UserCouponVO> availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId);
return Result.success(availableCoupons);
}
/**
* 发放优惠券
*/
@PostMapping("/distribute")
@RequirePermission("coupon:assign")
public Result<Boolean> distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(couponId);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
for (Long userId : userIds) {
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
}
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
return Result.success(success);
}
}
@@ -1,25 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.GrowthService;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.GrowthSummaryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/growth")
@RequiredArgsConstructor
public class GrowthController {
private final GrowthService growthService;
@GetMapping("/summary")
public Result<GrowthSummaryVO> summary(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(growthService.getSummary(userId));
}
}
@@ -1,65 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.ProductLikeService;
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
/**
* 商品点赞控制器
*
* @author xiaowang
* @date 2026-03-05
*/
@RestController
@RequestMapping("/product-like")
@RequiredArgsConstructor
public class ProductLikeController {
/**
* Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ProductLikeService productLikeService;
/**
* 点赞商品
*
* @param userId 当前用户ID
* @param productId 商品ID
* @return 是否成功
*/
@PostMapping("/like/{productId}")
@OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
public Result<Boolean> likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
productLikeService.addLike(userId, productId);
return Result.success(true);
}
/**
* 取消点赞商品
*
* @param userId 当前用户ID
* @param productId 商品ID
* @return 是否成功
*/
@PostMapping("/unlike/{productId}")
@OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
public Result<Boolean> unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
productLikeService.removeLike(userId, productId);
return Result.success(true);
}
/**
* 检查用户是否已点赞商品
*
* @param userId 当前用户ID
* @param productId 商品ID
* @return 是否已点赞
*/
@GetMapping("/check/{productId}")
public Result<Boolean> checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
boolean isLiked = productLikeService.isProductLiked(userId, productId);
return Result.success(isLiked);
}
}
@@ -1,99 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipBenefitDTO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipBenefitVO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipBenefitService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* VIP权益信息表 Controller
* 对应数据库表 t_vip_benefit
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController
@RequestMapping({"/vip-benefit", "/api/vip-benefit"})
@RequiredArgsConstructor
public class VipBenefitController {
/**
* Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final VipBenefitService vipBenefitService;
/**
* 创建VIP权益
*
* @param vipBenefitDTO VIP权益DTO
* @return VIP权益ID
*/
@PostMapping("/create")
public Result<Long> createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) {
Long id = vipBenefitService.createVipBenefit(vipBenefitDTO);
return Result.success(id);
}
/**
* 更新VIP权益
*
* @param id VIP权益ID
* @param vipBenefitDTO VIP权益DTO
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) {
boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO);
return Result.success(success);
}
/**
* 删除VIP权益
*
* @param id VIP权益ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteVipBenefit(@PathVariable Long id) {
boolean success = vipBenefitService.deleteVipBenefit(id);
return Result.success(success);
}
/**
* 根据ID查询VIP权益
*
* @param id VIP权益ID
* @return VIP权益VO
*/
@GetMapping("/get/{id}")
public Result<VipBenefitVO> getVipBenefitById(@PathVariable Long id) {
VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id);
return Result.success(vipBenefitVO);
}
/**
* 查询所有VIP权益
*
* @return VIP权益VO列表
*/
@GetMapping("/list/all")
public Result<List<VipBenefitVO>> listAllVipBenefits() {
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listAllVipBenefits();
return Result.success(vipBenefitVOs);
}
/**
* 根据所需VIP等级查询VIP权益
*
* @param requiredVipLevel 所需VIP等级
* @return VIP权益VO列表
*/
@GetMapping("/list/requiredVipLevel/{requiredVipLevel}")
public Result<List<VipBenefitVO>> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) {
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel);
return Result.success(vipBenefitVOs);
}
}
@@ -1,99 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipInfoDTO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipInfoVO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 用户VIP信息表 Controller
* 对应数据库表 t_vip_info
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController
@RequestMapping({"/vip-info", "/api/vip-info"})
@RequiredArgsConstructor
public class VipInfoController {
/**
* Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final VipInfoService vipInfoService;
/**
* 创建VIP信息
*
* @param vipInfoDTO VIP信息DTO
* @return VIP信息ID
*/
@PostMapping("/create")
public Result<Long> createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) {
Long id = vipInfoService.createVipInfo(vipInfoDTO);
return Result.success(id);
}
/**
* 更新VIP信息
*
* @param id VIP信息ID
* @param vipInfoDTO VIP信息DTO
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) {
boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO);
return Result.success(success);
}
/**
* 删除VIP信息
*
* @param id VIP信息ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteVipInfo(@PathVariable Long id) {
boolean success = vipInfoService.deleteVipInfo(id);
return Result.success(success);
}
/**
* 根据ID查询VIP信息
*
* @param id VIP信息ID
* @return VIP信息VO
*/
@GetMapping("/get/{id}")
public Result<VipInfoVO> getVipInfoById(@PathVariable Long id) {
VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id);
return Result.success(vipInfoVO);
}
/**
* 查询所有VIP信息
*
* @return VIP信息VO列表
*/
@GetMapping("/list/all")
public Result<List<VipInfoVO>> listAllVipInfos() {
List<VipInfoVO> vipInfoVOs = vipInfoService.listAllVipInfos();
return Result.success(vipInfoVOs);
}
/**
* 根据VIP等级查询VIP信息
*
* @param vipLevel VIP等级
* @return VIP信息VO列表
*/
@GetMapping("/list/vipLevel/{vipLevel}")
public Result<List<VipInfoVO>> listVipInfosByVipLevel(@PathVariable String vipLevel) {
List<VipInfoVO> vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel);
return Result.success(vipInfoVOs);
}
}
@@ -1,113 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipRechargePlanDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipRechargePlanService;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipRechargePlanVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"})
/**
* VipRechargePlanController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class VipRechargePlanController {
/**
* Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final VipRechargePlanService vipRechargePlanService;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
@GetMapping("/admin/list")
@RequirePermission("user:vip:manage")
/**
* Purpose: listAdmin supports VipRechargePlanController.java by holding or executing the list admin business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<List<VipRechargePlanVO>> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId));
}
@PostMapping("/admin/create")
@RequirePermission("user:vip:manage")
@OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交")
/**
* Create a new record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param dto parameter `dto` supplied by the caller
* @return Result<Long> result consumed by the caller or returned to the frontend
*/
public Result<Long> create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(vipRechargePlanService.createPlan(currentUser, dto));
}
@PutMapping("/admin/{id}")
@RequirePermission("user:vip:manage")
@OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交")
/**
* Update an existing record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param id parameter `id` supplied by the caller
* @param dto parameter `dto` supplied by the caller
* @return Result<Boolean> result consumed by the caller or returned to the frontend
*/
public Result<Boolean> update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto));
}
@PutMapping("/admin/{id}/status")
@RequirePermission("user:vip:manage")
/**
* Change the enabled/status flag of one record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param id parameter `id` supplied by the caller
* @param status parameter `status` supplied by the caller
* @return Result<Boolean> result consumed by the caller or returned to the frontend
*/
public Result<Boolean> updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status));
}
@GetMapping("/my/list")
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<List<VipRechargePlanVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<VipRechargePlanVO>> listMy(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(vipRechargePlanService.listMyPlans(userId));
}
@GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"})
/**
* Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<List<String>> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId));
}
}
@@ -1,100 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistAddWithGroupDTO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistDTO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistGroupDTO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistMoveDTO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.WishlistService;
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistGroupVO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistInspirationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/wishlist")
public class WishlistController {
@Autowired
private WishlistService wishlistService;
@PostMapping("/add")
@OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
public Result<?> addToWishlist(@RequestBody Map<String, Long> request, @RequestAttribute("userId") Long userId) {
wishlistService.addToWishlist(userId, request.get("productId"));
return Result.success("ok");
}
@PostMapping("/add-with-group")
@OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
public Result<?> addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) {
wishlistService.addToWishlist(userId, request);
return Result.success("ok");
}
@PostMapping("/remove")
@OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
public Result<?> removeFromWishlist(@RequestBody Map<String, Long> request, @RequestAttribute("userId") Long userId) {
wishlistService.removeFromWishlist(userId, request.get("productId"));
return Result.success("ok");
}
@GetMapping("/check")
public Result<Boolean> checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.isInWishlist(userId, productId));
}
@GetMapping("/list")
public Result<List<WishlistDTO>> getWishlist(@RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.getWishlistByUserId(userId));
}
@GetMapping("/groups")
public Result<List<WishlistGroupVO>> listGroups(@RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.listGroups(userId));
}
@PostMapping("/groups")
public Result<Long> createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.createGroup(userId, request));
}
@PutMapping("/groups/{id}")
public Result<Boolean> updateGroup(
@PathVariable Long id,
@RequestBody WishlistGroupDTO request,
@RequestAttribute("userId") Long userId
) {
return Result.success(wishlistService.updateGroup(userId, id, request));
}
@DeleteMapping("/groups/{id}")
public Result<Boolean> deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.deleteGroup(userId, id));
}
@PostMapping("/move")
@OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
public Result<Boolean> moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.moveWishlist(userId, request));
}
@GetMapping("/inspiration")
public Result<WishlistInspirationVO> getInspiration(@RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.getInspiration(userId));
}
}
@@ -1,116 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.order.controller.front;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.order.dto.CartDTO;
import com.xiaowang.jayucloud.salon.core.modules.order.service.CartService;
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CartVO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping("/cart")
/**
* CartController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class CartController {
@Resource
/**
* Purpose: cartService supports CartController.java by holding or executing the cart service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private CartService cartService;
@PostMapping("/add")
@OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作")
/**
* Add a new record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param cartDTO parameter `cartDTO` supplied by the caller
* @param request parameter `request` supplied by the caller
* @return Result<Void> result consumed by the caller or returned to the frontend
*/
public Result<Void> addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
cartService.addToCart(userId, cartDTO);
return Result.success();
}
@DeleteMapping("/remove/{productId}")
@OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
/**
* Remove a record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param productId parameter `productId` supplied by the caller
* @param request parameter `request` supplied by the caller
* @return Result<Void> result consumed by the caller or returned to the frontend
*/
public Result<Void> removeFromCart(@PathVariable Long productId, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
cartService.removeFromCart(userId, productId);
return Result.success();
}
@PostMapping("/batch-remove")
@OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
/**
* Run business method `batchRemoveFromCart`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param cartItemIds parameter `cartItemIds` supplied by the caller
* @param request parameter `request` supplied by the caller
* @return Result<Void> result consumed by the caller or returned to the frontend
*/
public Result<Void> batchRemoveFromCart(@RequestBody List<Long> cartItemIds, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
cartService.batchRemoveFromCart(userId, cartItemIds);
return Result.success();
}
@PutMapping("/update")
@OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作")
/**
* Update an existing record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param cartDTO parameter `cartDTO` supplied by the caller
* @param request parameter `request` supplied by the caller
* @return Result<Void> result consumed by the caller or returned to the frontend
*/
public Result<Void> updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
cartService.updateCartQuantity(userId, cartDTO);
return Result.success();
}
@GetMapping("/list")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<List<CartVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<CartVO>> getCartList(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
List<CartVO> cartList = cartService.getCartList(userId);
return Result.success(cartList);
}
@DeleteMapping("/clear")
@OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
/**
* Run business method `clearCart`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<Void> result consumed by the caller or returned to the frontend
*/
public Result<Void> clearCart(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
cartService.clearCart(userId);
return Result.success();
}
}
@@ -1,62 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.admin;
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO;
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.RefundOrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/admin/payment")
@RequiredArgsConstructor
public class AdminPaymentController {
private final PaymentService paymentService;
private final AdminScopeHelper adminScopeHelper;
private final SecurityAuditSupport securityAuditSupport;
@PostMapping("/order/{orderId}/manual-confirm")
@RequirePermission("payment:manage")
public Result<PaymentOrderVO> manualConfirm(HttpServletRequest request,
@PathVariable Long orderId,
@RequestParam(required = false) String remark) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
try {
PaymentOrderVO result = paymentService.manualConfirmOrderPaid(currentUser.getId(), orderId, remark);
securityAuditSupport.success(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId);
return Result.success(result);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage());
throw exception;
}
}
@PostMapping("/order/{orderId}/manual-refund")
@RequirePermission("refund:manage")
public Result<RefundOrderVO> manualRefund(HttpServletRequest request,
@PathVariable Long orderId,
@RequestParam(required = false) Long afterSaleId,
@RequestParam(required = false) String remark) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
try {
RefundOrderVO result = paymentService.manualRefundOrder(currentUser.getId(), orderId, afterSaleId, remark);
securityAuditSupport.success(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId);
return Result.success(result);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage());
throw exception;
}
}
}
@@ -1,99 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceChangeDetailDTO;
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO;
import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceChangeDetailService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 用户余额变动明细表 Controller
* 对应数据库表 t_balance_change_detail
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController
@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"})
@RequiredArgsConstructor
public class BalanceChangeDetailController {
/**
* Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final BalanceChangeDetailService balanceChangeDetailService;
/**
* 创建余额变动明细
*
* @param balanceChangeDetailDTO 余额变动明细DTO
* @return 余额变动明细ID
*/
@PostMapping("/create")
public Result<Long> createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) {
Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO);
return Result.success(id);
}
/**
* 更新余额变动明细
*
* @param id 余额变动明细ID
* @param balanceChangeDetailDTO 余额变动明细DTO
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) {
boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO);
return Result.success(success);
}
/**
* 删除余额变动明细
*
* @param id 余额变动明细ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteBalanceChangeDetail(@PathVariable Long id) {
boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id);
return Result.success(success);
}
/**
* 根据ID查询余额变动明细
*
* @param id 余额变动明细ID
* @return 余额变动明细VO
*/
@GetMapping("/get/{id}")
public Result<BalanceChangeDetailVO> getBalanceChangeDetailById(@PathVariable Long id) {
BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id);
return Result.success(balanceChangeDetailVO);
}
/**
* 查询所有余额变动明细
*
* @return 余额变动明细VO列表
*/
@GetMapping("/list/all")
public Result<List<BalanceChangeDetailVO>> listAllBalanceChangeDetails() {
List<BalanceChangeDetailVO> balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails();
return Result.success(balanceChangeDetailVOs);
}
/**
* 根据用户ID查询余额变动明细
*
* @param userId 用户ID
* @return 余额变动明细VO列表
*/
@GetMapping("/list/user/{userId}")
public Result<List<BalanceChangeDetailVO>> listBalanceChangeDetailsByUserId(@PathVariable Long userId) {
List<BalanceChangeDetailVO> balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId);
return Result.success(balanceChangeDetailVOs);
}
}
@@ -1,99 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceDTO;
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceVO;
import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 用户余额信息表 Controller
* 对应数据库表 t_balance
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController
@RequestMapping({"/balance", "/api/balance"})
@RequiredArgsConstructor
public class BalanceController {
/**
* Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final BalanceService balanceService;
/**
* 创建余额
*
* @param balanceDTO 余额DTO
* @return 余额ID
*/
@PostMapping("/create")
public Result<Long> createBalance(@RequestBody BalanceDTO balanceDTO) {
Long id = balanceService.createBalance(balanceDTO);
return Result.success(id);
}
/**
* 更新余额
*
* @param id 余额ID
* @param balanceDTO 余额DTO
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) {
boolean success = balanceService.updateBalance(id, balanceDTO);
return Result.success(success);
}
/**
* 删除余额
*
* @param id 余额ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteBalance(@PathVariable Long id) {
boolean success = balanceService.deleteBalance(id);
return Result.success(success);
}
/**
* 根据ID查询余额
*
* @param id 余额ID
* @return 余额VO
*/
@GetMapping("/get/{id}")
public Result<BalanceVO> getBalanceById(@PathVariable Long id) {
BalanceVO balanceVO = balanceService.getBalanceById(id);
return Result.success(balanceVO);
}
/**
* 查询所有余额
*
* @return 余额VO列表
*/
@GetMapping("/list/all")
public Result<List<BalanceVO>> listAllBalances() {
List<BalanceVO> balanceVOs = balanceService.listAllBalances();
return Result.success(balanceVOs);
}
/**
* 根据用户ID查询余额
*
* @param userId 用户ID
* @return 余额VO
*/
@GetMapping("/get/user/{userId}")
public Result<BalanceVO> getBalanceByUserId(@PathVariable Long userId) {
BalanceVO balanceVO = balanceService.getBalanceByUserId(userId);
return Result.success(balanceVO);
}
}
@@ -3,22 +3,17 @@ package com.xiaowang.jayucloud.salon.core.modules.user.controller.admin;
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.user.dto.AdminUserBalanceChangeDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.dto.AdminUserVipOverrideDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserRelationUpdateDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.artist.support.BookableArtistSupport;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO;
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO;
import lombok.Data;
@@ -42,10 +37,6 @@ public class AdminUserController {
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserService userService;
/**
* Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserAssetService userAssetService;
/**
* Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -334,101 +325,6 @@ public class AdminUserController {
}
}
@GetMapping("/{id}/asset")
@RequirePermission("user:balance:view")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param id parameter `id` supplied by the caller
* @return Result<UserAssetVO> result consumed by the caller or returned to the frontend
*/
public Result<UserAssetVO> getUserAsset(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户资产");
UserAssetVO assetVO = userAssetService.getUserAsset(targetUser.getId());
return Result.success(assetVO);
}
@GetMapping("/{id}/balance/history")
@RequirePermission("user:balance:view")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param id parameter `id` supplied by the caller
* @return Result<List<BalanceChangeDetailVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<BalanceChangeDetailVO>> getUserBalanceHistory(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户余额流水");
List<BalanceChangeDetailVO> history = userAssetService.listBalanceHistory(targetUser.getId());
return Result.success(history);
}
@PostMapping("/{id}/balance/change")
@RequirePermission("user:balance:manage")
@OperationGuard(action = "admin-user-balance-change", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
public Result<UserAssetVO> changeUserBalance(
HttpServletRequest request,
@PathVariable Long id,
@RequestBody AdminUserBalanceChangeDTO balanceChangeDTO
) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额");
try {
UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO);
securityAuditSupport.success(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id);
return Result.success(assetVO);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id + ",reason=" + exception.getMessage());
throw exception;
}
}
@PostMapping("/{id}/vip/override")
@RequirePermission("user:vip:manage")
@OperationGuard(action = "admin-user-vip-override", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
public Result<UserAssetVO> overrideUserVip(
HttpServletRequest request,
@PathVariable Long id,
@RequestBody AdminUserVipOverrideDTO vipOverrideDTO
) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP");
try {
UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO);
securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id);
return Result.success(assetVO);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id + ",reason=" + exception.getMessage());
throw exception;
}
}
@PostMapping("/{id}/vip/recalculate")
@RequirePermission("user:vip:manage")
@OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
/**
* Run business method `recalculateUserVip`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param id parameter `id` supplied by the caller
* @return Result<UserAssetVO> result consumed by the caller or returned to the frontend
*/
public Result<UserAssetVO> recalculateUserVip(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP");
try {
UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId());
securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id);
return Result.success(assetVO);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id + ",reason=" + exception.getMessage());
throw exception;
}
}
@GetMapping("/info")
/**
* Load data by the supplied parameter.
@@ -10,14 +10,11 @@ import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelp
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ChunkUploadSessionVO;
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO;
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO;
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.InviteCodeVO;
import com.xiaowang.jayucloud.salon.core.modules.integration.vo.WechatMiniLoginResultVO;
import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
@@ -77,10 +74,6 @@ public class UserController {
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserService userService;
/**
* Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserAssetService userAssetService;
/**
* Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -229,30 +222,6 @@ public class UserController {
return Result.success(success);
}
@GetMapping("/asset/me")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<UserAssetVO> result consumed by the caller or returned to the frontend
*/
public Result<UserAssetVO> getMyAsset(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userAssetService.getUserAsset(userId));
}
@GetMapping("/balance/history/me")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<List<BalanceChangeDetailVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<BalanceChangeDetailVO>> getMyBalanceHistory(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userAssetService.listBalanceHistory(userId));
}
/**
* 根据ID查询用户
*
@@ -18,8 +18,8 @@ spring:
# 是否将当前服务注册到 Nacos。
register-enabled: true
# Nacos 认证信息可由运行环境覆盖。
username: ${NACOS_USERNAME:jayucloud}
password: ${NACOS_PASSWORD:122503wcy....}
username: ${NACOS_USERNAME:}
password: ${NACOS_PASSWORD:}
config:
# Nacos 配置中心与服务发现使用同一运行环境参数。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848}
@@ -34,8 +34,8 @@ spring:
# 是否启用配置中心。
enabled: true
# Nacos 认证信息可由运行环境覆盖。
username: ${NACOS_USERNAME:jayucloud}
password: ${NACOS_PASSWORD:122503wcy....}
username: ${NACOS_USERNAME:}
password: ${NACOS_PASSWORD:}
# Core 与 Gateway 共享的公共配置文件。
shared-configs:
- data-id: infra.yaml
+2 -41
View File
@@ -34,7 +34,7 @@
* App page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, h, onMounted, onUnmounted, provide, ref, watch } from 'vue'
import { computed, h, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ConfigProvider, Modal } from 'ant-design-vue'
import type { ButtonProps } from 'ant-design-vue/es/button/buttonTypes'
@@ -42,7 +42,6 @@ import type { ThemeConfig } from 'ant-design-vue/es/config-provider/context'
import { CheckOutlined } from '@ant-design/icons-vue'
import BottomNav from './components/BottomNav.vue'
import SystemMessageCard from './components/SystemMessageCard.vue'
import { cartApi } from './api/cart'
/**
* Purpose: SystemMessageVO supports App.vue by holding or executing the system message vo page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
@@ -78,7 +77,7 @@ const adminThemeRefreshOptions = { mode: 'admin' as const }
const customerThemeRefreshOptions = { mode: 'customer' as const }
const isAdminShell = computed(() => route.path.startsWith('/admin') || route.matched.some(r => r.meta.isAdmin))
const bottomNavRouteNames = new Set(['home', 'products', 'cart', 'profile'])
const bottomNavRouteNames = new Set(['home', 'products', 'profile'])
/** isHiddenNav is a reactive state variable used by the template and event handlers. */
const isHiddenNav = computed(() => {
@@ -119,39 +118,9 @@ const antdTheme = computed<ThemeConfig>(() => ({
}
}))
// 全局购物车数量状态
/** cartCount is a reactive state variable used by the template and event handlers. */
const cartCount = ref(0)
/** checkingPopupMessages is a reactive state variable used by the template and event handlers. */
const checkingPopupMessages = ref(false)
// 加载购物车数量
/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartCount = async () => {
try {
// 检查用户是否已登录
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (!token) {
cartCount.value = 0
return
}
const response = await cartApi.getCartList() as any
const data = response || []
const cartList = Array.isArray(data) ? data : []
const totalQuantity = cartList.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0)
cartCount.value = totalQuantity
} catch (error) {
cartCount.value = 0
}
}
// 提供更新购物车数量的方法
/** updateCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const updateCartCount = async () => {
await loadCartCount()
}
/**
* Purpose: resolveSystemMessageActionPath supports App.vue by holding or executing the resolve system message action path page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -235,23 +204,15 @@ const checkPopupMessages = async () => {
}
}
provide('updateCartCount', updateCartCount)
provide('cartCount', cartCount)
// 监听路由变化,更新购物车数量
watch(() => route.path, async () => {
// 检查当前是否是后台页面,如果是则不加载购物车数据
const isAdminPage = route.matched.some(r => r.meta.isAdmin)
await refreshShopTheme(isAdminPage ? adminThemeRefreshOptions : customerThemeRefreshOptions)
if (!isAdminPage) {
await loadCartCount()
await checkPopupMessages()
}
})
// 页面加载时获取购物车数量
loadCartCount()
onMounted(async () => {
stopThemeSync = setupShopThemeSync()
await router.isReady()
-79
View File
@@ -1,79 +0,0 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: CartItem supports cart.ts by holding or executing the cart item page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface CartItem {
productId: IdType
quantity: number
}
/**
* cartApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const cartApi = {
// 添加作品到购物车
/**
* `addToCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param item: CartItem caller-supplied value for `item: CartItem`
*/
addToCart: (item: CartItem) => {
return api.post('/cart/add', item)
},
// 从购物车移除作品
/**
* `removeFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
removeFromCart: (productId: IdType) => {
return api.delete(`/cart/remove/${productId}`)
},
// 批量从购物车移除作品
/**
* `batchRemoveFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]`
*/
batchRemoveFromCart: (cartItemIds: IdType[]) => {
return api.post('/cart/batch-remove', cartItemIds)
},
// 更新购物车作品数量
/**
* `updateCartQuantity` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param item: CartItem caller-supplied value for `item: CartItem`
*/
updateCartQuantity: (item: CartItem) => {
return api.put('/cart/update', item)
},
// 获取购物车列表
/**
* `getCartList` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
getCartList: () => {
return api.get('/cart/list')
},
// 清空购物车
/**
* `clearCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
clearCart: () => {
return api.delete('/cart/clear')
}
}
-221
View File
@@ -1,221 +0,0 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import request from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: Coupon supports coupon.ts by holding or executing the coupon page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface Coupon {
id: IdType
couponCode: string
couponName: string
couponType: number
couponTypeName: string
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
usedCount: number
remainingCount: number
startTime: string
endTime: string
status: number
statusName: string
shopId?: IdType
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTags: Tag[]
unavailableTags: Tag[]
}
/**
* Purpose: Tag supports coupon.ts by holding or executing the tag page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface Tag {
id: IdType
tagName?: string
}
/**
* Purpose: UserCoupon supports coupon.ts by holding or executing the user coupon page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UserCoupon {
id: IdType
couponId: IdType
couponName: string
couponType: number
couponTypeName: string
discountValue: string
minAmount: string
reduceAmount: string
startTime: string
endTime: string
status: number
statusName: string
obtainTime: string
useTime: string
sourceType?: string
requiredVipLevel?: string
autoMatched?: boolean
}
/**
* Purpose: CreateCouponRequest supports coupon.ts by holding or executing the create coupon request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CreateCouponRequest {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime: string
endTime: string
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTagIds: IdType[]
unavailableTagIds: IdType[]
}
/**
* Purpose: CouponListResponse supports coupon.ts by holding or executing the coupon list response page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CouponListResponse {
list: Coupon[]
total: number
page: number
size: number
}
/**
* couponApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const couponApi = {
// 创建优惠券
/**
* `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest`
*/
createCoupon: (data: CreateCouponRequest) => {
return request({
url: '/coupon/create',
method: 'post',
data
})
},
// 更新优惠券
/**
* `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
* @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest`
*/
updateCoupon: (id: IdType, data: CreateCouponRequest) => {
return request({
url: `/coupon/update/${id}`,
method: 'put',
data
})
},
// 删除优惠券
/**
* `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
deleteCoupon: (id: IdType) => {
return request({
url: `/coupon/delete/${id}`,
method: 'delete'
})
},
// 获取优惠券详情
/**
* `getCouponById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
getCouponById: (id: IdType) => {
return request({
url: `/coupon/detail/${id}`,
method: 'get'
})
},
// 获取优惠券列表
/**
* `listCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }`
*/
listCoupons: (params: { page: number; size: number; shopId?: IdType }) => {
return request({
url: '/coupon/list',
method: 'get',
params
})
},
// 为用户分配优惠券
/**
* `assignCouponToUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param userId: IdType caller-supplied value for `userId: IdType`
* @param couponId: IdType caller-supplied value for `couponId: IdType`
*/
assignCouponToUser: (userId: IdType, couponId: IdType) => {
return request({
url: '/coupon/assign',
method: 'post',
params: { userId, couponId }
})
},
// 获取用户优惠券列表
listUserCoupons: async (status?: number): Promise<UserCoupon[]> => {
return await request({
url: '/coupon/user/list',
method: 'get',
params: { status }
}) as UserCoupon[]
},
// 使用优惠券
/**
* `useCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param userCouponId: IdType caller-supplied value for `userCouponId: IdType`
*/
useCoupon: (userCouponId: IdType) => {
return request({
url: '/coupon/use',
method: 'post',
params: { userCouponId }
})
},
// 获取作品可用的优惠券
getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise<UserCoupon[]> => {
return await request({
url: '/coupon/available',
method: 'get',
params: { productTags, productPrice, shopId }
}) as UserCoupon[]
}
}
-3
View File
@@ -5,7 +5,6 @@
import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import { adminAuthApi } from './admin'
import { wishlistApi } from './wishlist'
import { message, Modal } from 'ant-design-vue'
import { API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id'
@@ -393,6 +392,4 @@ export const fileApi = {
}
}
export { wishlistApi }
export default api
-51
View File
@@ -1,51 +0,0 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* productLikeApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const productLikeApi = {
/**
* 点赞作品
* @param productId 作品ID
*/
/**
* `likeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
likeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/like/${productId}`)
},
/**
* 取消点赞作品
* @param productId 作品ID
*/
/**
* `unlikeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
unlikeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/unlike/${productId}`)
},
/**
* 检查用户是否已点赞作品
* @param productId 作品ID
*/
/**
* `checkLikeStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
checkLikeStatus: (productId: IdType) => {
return api.get<boolean>(`/product-like/check/${productId}`)
}
}
-123
View File
@@ -1,123 +0,0 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: WishlistItem supports wishlist.ts by holding or executing the wishlist item page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface WishlistItem {
id: IdType
userId: IdType
productId: IdType
groupId?: IdType | null
groupName?: string | null
note?: string | null
sortOrder?: number | null
product: {
id: IdType
shopId: IdType | null
shopName?: string
title: string
description: string
imageFileIds?: string
imageUrls?: string[]
price: number
tags?: string
tagList?: string[]
tagInfos?: any[]
likeCount?: number
collectCount?: number
approximateDuration?: string
bookableArtists?: string
availableCoupons?: string
createTime: string
updateTime: string
}
}
export interface WishlistGroup {
id: IdType
name: string
sortOrder: number
itemCount: number
items?: WishlistItem[]
}
export interface WishlistInspiration {
total: number
groups: WishlistGroup[]
}
export interface WishlistGroupPayload {
name: string
sortOrder?: number
}
export interface WishlistAddWithGroupPayload {
productId: IdType
groupId?: IdType | null
note?: string
sortOrder?: number
}
export interface WishlistMovePayload {
wishlistId?: IdType
productId?: IdType
groupId?: IdType | null
note?: string
sortOrder?: number
}
/**
* wishlistApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const wishlistApi = {
addToWishlist: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>('/wishlist/add', { productId }) as unknown as boolean
},
removeFromWishlist: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>('/wishlist/remove', { productId }) as unknown as boolean
},
checkWishlist: async (productId: IdType): Promise<boolean> => {
return await api.get<boolean>(`/wishlist/check?productId=${productId}`) as unknown as boolean
},
getWishlist: async (): Promise<WishlistItem[]> => {
return await api.get<WishlistItem[]>('/wishlist/list') as unknown as WishlistItem[]
},
getGroups: async (): Promise<WishlistGroup[]> => {
return await api.get<WishlistGroup[]>('/wishlist/groups') as unknown as WishlistGroup[]
},
createGroup: async (payload: WishlistGroupPayload): Promise<IdType> => {
return await api.post<IdType>('/wishlist/groups', payload) as unknown as IdType
},
updateGroup: async (id: IdType, payload: WishlistGroupPayload): Promise<boolean> => {
return await api.put<boolean>(`/wishlist/groups/${id}`, payload) as unknown as boolean
},
deleteGroup: async (id: IdType): Promise<boolean> => {
return await api.delete<boolean>(`/wishlist/groups/${id}`) as unknown as boolean
},
addWithGroup: async (payload: WishlistAddWithGroupPayload): Promise<boolean> => {
return await api.post<boolean>('/wishlist/add-with-group', payload) as unknown as boolean
},
moveWishlist: async (payload: WishlistMovePayload): Promise<boolean> => {
return await api.post<boolean>('/wishlist/move', payload) as unknown as boolean
},
getInspiration: async (): Promise<WishlistInspiration> => {
return await api.get<WishlistInspiration>('/wishlist/inspiration') as unknown as WishlistInspiration
}
}
+2 -43
View File
@@ -19,15 +19,6 @@
<span class="nav-label">作品集</span>
</button>
<button class="nav-item" :class="{ active: currentRoute === 'cart' }" type="button" @click="handleNavClick('cart')">
<a-badge :count="cartCount" :offset="[0, 0]">
<div class="nav-icon">
<ShoppingCartOutlined :style="{ fontSize: '25px' }" />
</div>
</a-badge>
<span class="nav-label">购物车</span>
</button>
<button class="nav-item" :class="{ active: currentRoute === 'profile' }" type="button" @click="handleNavClick('profile')">
<a-badge :dot="hasNotification" :offset="[0, 0]">
<div class="nav-icon">
@@ -45,9 +36,9 @@
* BottomNav page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, inject, onMounted, ref } from 'vue'
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { HomeOutlined, ShoppingOutlined, ShoppingCartOutlined, UserOutlined } from '@ant-design/icons-vue'
import { HomeOutlined, ShoppingOutlined, UserOutlined } from '@ant-design/icons-vue'
/**
* Purpose: router supports BottomNav.vue by holding or executing the router page or API role.
@@ -60,38 +51,10 @@ const router = useRouter()
*/
const route = useRoute()
// 注入全局购物车数量状态
const cartCount = inject('cartCount', ref(0))
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
// 是否有未读通知
/** hasNotification is a reactive state variable used by the template and event handlers. */
const hasNotification = computed(() => true)
// 加载购物车数量
/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartCount = async () => {
// 这里我们不需要做任何事情,因为全局状态会自动更新
// 但我们仍然需要这个方法,因为 App.vue 会调用它
}
// 页面加载时获取购物车数量
onMounted(() => {
// 检查当前是否是后台页面,如果是则不加载购物车数据
const isAdminPage = window.location.pathname.startsWith('/admin')
if (!isAdminPage) {
// 调用全局更新方法
updateCartCount()
}
})
// 提供一个方法让其他组件调用更新购物车数量
defineExpose({
loadCartCount
})
// 根据当前路由判断激活的导航项
/** currentRoute is a reactive state variable used by the template and event handlers. */
const currentRoute = computed(() => {
@@ -100,9 +63,7 @@ const currentRoute = computed(() => {
if (path === '/') return 'home'
if (path === '/products') return 'products'
if (path === '/product') return 'products'
if (path === '/cart') return 'cart'
if (path === '/profile') return 'profile'
if (path === '/wishlist') return 'profile'
return 'home'
})
@@ -113,8 +74,6 @@ const handleNavClick = (tab: string) => {
router.push('/home')
} else if (tab === 'products') {
router.push('/products')
} else if (tab === 'cart') {
router.push('/cart')
} else if (tab === 'profile') {
router.push('/profile')
}
-41
View File
@@ -1,41 +0,0 @@
import { cartApi } from '@/api/cart'
import { toOptionalIdString } from '@/utils/id'
/**
* Purpose: fetchCartProductIdSet supports cart-state.ts by holding or executing the fetch cart product id set page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const fetchCartProductIdSet = async () => {
try {
const response = await cartApi.getCartList() as unknown as Array<{ productId?: string | number }>
return new Set(
(Array.isArray(response) ? response : [])
.map(item => toOptionalIdString(item && item.productId))
.filter((id): id is string => Boolean(id))
)
} catch (error) {
return new Set<string>()
}
}
/**
* Purpose: hasCartProduct supports cart-state.ts by holding or executing the has cart product page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const hasCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
const normalizedId = toOptionalIdString(productId)
return Boolean(normalizedId && cartProductIdSet.has(normalizedId))
}
/**
* Purpose: withAddedCartProduct supports cart-state.ts by holding or executing the with added cart product page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const withAddedCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
const next = new Set(cartProductIdSet || [])
const normalizedId = toOptionalIdString(productId)
if (normalizedId) {
next.add(normalizedId)
}
return next
}
+1 -4
View File
@@ -10,16 +10,13 @@ describe('recovery utils', () => {
it('adds default routes and primary action state', () => {
const actions = buildRecoveryActions([
{ key: 'retry', text: '重试' },
{ key: 'orders', text: '查看订单' },
{ key: 'cart', text: '返回购物车' }
{ key: 'orders', text: '查看订单' }
])
const retryAction = actions[0]
const ordersAction = actions[1]
const cartAction = actions[2]
expect(retryAction?.primary).toBe(true)
expect(ordersAction?.route).toBe('/orders')
expect(cartAction?.route).toBe('/cart')
expect(recoveryRouteFor('products')).toBe('/products')
})
})
+1 -2
View File
@@ -1,4 +1,4 @@
export type RecoveryActionKey = 'retry' | 'orders' | 'cart' | 'products' | 'profile' | 'contact'
export type RecoveryActionKey = 'retry' | 'orders' | 'products' | 'profile' | 'contact'
export interface RecoveryAction {
key: RecoveryActionKey
@@ -9,7 +9,6 @@ export interface RecoveryAction {
const DEFAULT_ROUTES: Record<string, string> = {
orders: '/orders',
cart: '/cart',
products: '/products',
profile: '/profile'
}
@@ -10,11 +10,7 @@ const USER_ACTION_PREFIXES = [
'/help',
'/product/',
'/shop/',
'/coupons',
'/vip-center',
'/cart',
'/notifications',
'/wishlist',
'/profile',
'/settings',
'/artist-orders',
@@ -81,15 +77,5 @@ export const buildSystemMessageActionPath = (message: MessageLike) => {
if (businessType === 'SHOP' && businessId) {
return `/shop/${encodeURIComponent(businessId)}`
}
if (businessType === 'VIP') {
return '/vip-center'
}
if (businessType === 'COUPON') {
return '/coupons'
}
if (businessType === 'CART') {
return '/cart'
}
return ''
}
File diff suppressed because it is too large Load Diff
-446
View File
@@ -1,446 +0,0 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button type="text" class="back-btn" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>我的优惠券</h1>
<div class="placeholder"></div>
</header>
<div class="coupon-section">
<a-card :bordered="false" class="filter-card">
<a-segmented
v-model:value="activeFilter"
:options="filterOptions"
class="filter-segmented"
/>
</a-card>
<a-card v-if="loading" :bordered="false" class="content-card">
<a-skeleton :paragraph="{ rows: 3 }" />
</a-card>
<a-card v-else-if="coupons.length === 0" :bordered="false" class="content-card">
<a-empty description="暂无优惠券">
<a-button type="primary">去领取</a-button>
</a-empty>
</a-card>
<div v-else class="coupon-list">
<a-card
v-for="coupon in filteredCoupons"
:key="coupon.id"
class="coupon-card"
:class="{ 'expired': coupon.status === 3 }"
>
<div class="coupon-content">
<div class="coupon-value">
{{ coupon.couponType === 1 ? `${coupon.discountValue}折` : `¥${coupon.reduceAmount}` }}
</div>
<div class="coupon-info">
<div class="coupon-name">{{ coupon.couponName }}</div>
<div class="coupon-condition" v-if="coupon.couponType === 2">
满{{ coupon.minAmount }}元可用
</div>
<div class="coupon-time">
{{ formatDate(coupon.startTime) }} 至 {{ formatDate(coupon.endTime) }}
</div>
<div :class="['coupon-status', getStatusClass(coupon.status)]">
{{ coupon.statusName }}
</div>
</div>
</div>
</a-card>
</div>
</div>
</div>
</template>
<script setup lang="ts">
/**
* CouponView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { couponApi } from '@/api/coupon'
/**
* Purpose: router supports CouponView.vue by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const router = useRouter()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/**
* Purpose: coupons supports CouponView.vue by holding or executing the coupons page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const coupons = ref<any[]>([])
/** activeFilter is a reactive state variable used by the template and event handlers. */
const activeFilter = ref('all')
/**
* Purpose: filterOptions supports CouponView.vue by holding or executing the filter options page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const filterOptions = [
{ label: '全部', value: 'all' },
{ label: '未使用', value: 'available' },
{ label: '已使用', value: 'used' },
{ label: '已过期', value: 'expired' }
]
/** filteredCoupons is a reactive state variable used by the template and event handlers. */
const filteredCoupons = computed(() => {
if (activeFilter.value === 'all') {
return coupons.value
} else if (activeFilter.value === 'available') {
return coupons.value.filter(coupon => coupon.status === 1)
} else if (activeFilter.value === 'used') {
return coupons.value.filter(coupon => coupon.status === 2)
} else if (activeFilter.value === 'expired') {
return coupons.value.filter(coupon => coupon.status === 3)
}
return coupons.value
})
/** loadCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCoupons = async () => {
loading.value = true
try {
const response = await couponApi.listUserCoupons() as any
coupons.value = response || []
} catch (error) {
console.error('获取优惠券列表失败:', error)
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
/** getStatusClass is a local helper used by this page script. */
const getStatusClass = (status: number) => {
switch (status) {
case 1:
return 'available'
case 2:
return 'used'
case 3:
return 'expired'
default:
return ''
}
}
/** formatDate is a local helper used by this page script. */
const formatDate = (dateString: string) => {
if (!dateString) return ''
const date = new Date(dateString)
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
onMounted(() => {
loadCoupons()
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background:
linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)),
var(--theme-background-image),
var(--theme-page-bg);
background-size: cover, cover, auto;
background-position: center top;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
padding: 10px 15px;
background: rgba(255, 255, 255, 0.92);
border-bottom: 1px solid var(--theme-border);
backdrop-filter: blur(14px);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
color: var(--text-primary);
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-primary);
}
.placeholder {
width: 40px;
}
.coupon-section {
padding: 15px;
}
.filter-card {
border-radius: 14px;
margin-bottom: 15px;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.filter-segmented {
width: 100%;
}
.content-card {
border-radius: 14px;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
padding: 40px 20px;
}
.coupon-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.coupon-card {
border-radius: 14px;
overflow: hidden;
background: var(--theme-gradient-soft);
border: 1px solid var(--theme-border);
transition: all 0.3s ease;
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.coupon-card:hover {
transform: translateY(-2px);
box-shadow: 0 18px 44px rgba(122, 67, 88, 0.12);
}
.coupon-card.expired {
opacity: 0.66;
background: var(--theme-card-bg);
}
.coupon-content {
display: flex;
align-items: center;
gap: 20px;
padding: 20px;
}
.coupon-value {
font-size: 24px;
font-weight: 700;
color: var(--theme-primary);
padding: 20px;
background: var(--theme-primary-soft);
border-radius: 8px;
min-width: 100px;
text-align: center;
}
.coupon-card.expired .coupon-value {
color: var(--text-secondary);
background: var(--theme-primary-soft);
}
.coupon-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
}
.coupon-name {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
}
.coupon-condition {
font-size: 12px;
color: var(--theme-primary);
}
.coupon-time {
font-size: 12px;
color: var(--text-secondary);
}
.coupon-status {
font-size: 12px;
font-weight: 600;
padding: 2px 8px;
border-radius: 8px;
align-self: flex-start;
}
.coupon-status.available {
background: var(--theme-primary-soft);
color: var(--theme-primary);
}
.coupon-status.used {
background: var(--theme-primary-soft);
color: var(--text-secondary);
}
.coupon-status.expired {
background: var(--theme-primary-soft);
color: var(--theme-accent);
}
:deep(.ant-segmented) {
background: var(--theme-primary-soft);
}
:deep(.ant-segmented-item-selected) {
background: var(--theme-primary);
color: #fff;
}
:deep(.ant-btn-primary) {
background: var(--theme-primary);
border-color: var(--theme-primary);
}
.mobile-container {
padding-top: 68px;
background:
radial-gradient(circle at 84% 0%, color-mix(in srgb, var(--theme-primary) 26%, transparent), transparent 32%),
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 78%, transparent), var(--theme-page-bg));
}
.header {
height: 64px;
padding: 12px 18px 10px;
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
}
.header h1 {
font-size: 17px;
font-weight: 820;
}
.back-btn {
border-radius: 999px;
background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent);
}
.coupon-section {
padding: 18px;
}
.filter-card,
.content-card {
border-radius: 22px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 18px 40px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
.coupon-list {
gap: 14px;
}
.coupon-card {
position: relative;
overflow: hidden;
border-radius: 24px;
background:
linear-gradient(135deg, color-mix(in srgb, var(--theme-card-bg) 88%, transparent), color-mix(in srgb, var(--theme-primary) 20%, var(--theme-card-bg)));
box-shadow: 0 20px 42px color-mix(in srgb, var(--theme-neutral) 9%, transparent);
}
.coupon-card::before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 112px;
width: 1px;
background: linear-gradient(var(--theme-border) 52%, transparent 0);
background-size: 1px 12px;
}
.coupon-content {
gap: 18px;
padding: 18px;
}
.coupon-value {
min-width: 78px;
padding: 16px 8px;
border-radius: 18px;
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 24%, var(--theme-card-bg));
font-family: Georgia, 'Times New Roman', serif;
}
.coupon-name {
font-weight: 820;
}
.coupon-condition,
.coupon-status.available {
color: var(--theme-primary-action);
}
:deep(.ant-segmented) {
width: 100%;
padding: 4px;
border-radius: 16px;
background: color-mix(in srgb, var(--theme-primary) 16%, var(--theme-card-bg));
}
:deep(.ant-segmented-item) {
border-radius: 13px;
}
:deep(.ant-segmented-item-selected) {
background: var(--theme-card-bg);
color: var(--theme-primary-action);
box-shadow: 0 10px 20px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
:deep(.ant-btn-primary) {
border-color: transparent;
background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary));
}
@media (min-width: 992px) {
.coupon-section {
max-width: 960px;
margin: 0 auto;
padding: 24px;
}
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,755 +0,0 @@
<script setup lang="ts">
import { computed, onMounted, ref, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import {
CrownOutlined,
HistoryOutlined,
LeftOutlined,
PayCircleOutlined,
ScissorOutlined,
StarFilled,
TrophyOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { userApi, type BalanceHistoryItem, type UserAssetVO } from '@/api/user'
const router = useRouter()
const loading = shallowRef(false)
const visibleHistoryCount = shallowRef(3)
const asset = ref<UserAssetVO | null>(null)
const history = ref<BalanceHistoryItem[]>([])
interface LevelStep {
name: string
amount: number
}
const levelSteps: [LevelStep, ...LevelStep[]] = [
{ name: '普通会员', amount: 0 },
{ name: '玫瑰金会员', amount: 1000 },
{ name: '钻石会员', amount: 5000 }
]
const money = (value?: number | string) => {
const amount = Number(value || 0)
return Number.isFinite(amount)
? amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
: '0.00'
}
const formatTime = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '--'
const sceneText = (scene?: string) => {
const map: Record<string, string> = {
MANUAL_RECHARGE: '手工充值',
MANUAL_DEDUCT: '手工扣减',
ORDER_PAY: '订单消费',
ORDER_REFUND: '订单退款',
RECHARGE: '会员充值',
CONSUME: '余额消费'
}
return map[scene || ''] || scene || '余额变动'
}
const sceneIcon = (item: BalanceHistoryItem) => {
const scene = item.changeScene || item.type || ''
if (Number(item.amount) > 0 || scene.includes('RECHARGE') || scene.includes('REFUND')) {
return PayCircleOutlined
}
if (scene.includes('ORDER') || scene.includes('CONSUME')) {
return ScissorOutlined
}
return HistoryOutlined
}
const memberLevel = computed(() => asset.value?.vipLevel || '普通会员')
const totalRecharge = computed(() => Number(asset.value?.totalRechargeAmount || 0))
const balanceAmount = computed(() => Number(asset.value?.balance || 0))
const visibleHistory = computed(() => history.value.slice(0, visibleHistoryCount.value))
const canLoadMoreHistory = computed(() => visibleHistoryCount.value < history.value.length)
const currentStep = computed(() => {
return [...levelSteps].reverse().find(step => totalRecharge.value >= step.amount) || levelSteps[0]
})
const nextStep = computed(() => levelSteps.find(step => step.amount > totalRecharge.value))
const levelProgress = computed(() => {
const next = nextStep.value
if (!next) return 100
const current = currentStep.value
const range = Math.max(next.amount - current.amount, 1)
return Math.min(100, Math.max(8, ((totalRecharge.value - current.amount) / range) * 100))
})
const nextLevelText = computed(() => nextStep.value ? `下一等级:${nextStep.value.name}` : '已达最高等级')
const remainingAmountText = computed(() => {
return nextStep.value ? '等级按已有业务记录自动计算' : '当前等级已达最高等级'
})
const validityText = computed(() => {
const start = formatTime(asset.value?.vipStartTime)
const expire = formatTime(asset.value?.vipExpireTime)
if (start === '--' && expire === '--') return '长期有效'
if (expire === '--') return `${start} 起生效`
return `${start} - ${expire}`
})
const loadMoreHistory = () => {
visibleHistoryCount.value += 3
}
const loadData = async () => {
loading.value = true
try {
const [assetRes, historyRes] = await Promise.all([
userApi.getMyAsset(),
userApi.getMyBalanceHistory()
])
asset.value = assetRes
history.value = historyRes || []
} catch (error: any) {
message.error(error?.message || '获取 VIP 信息失败')
} finally {
loading.value = false
}
}
onMounted(loadData)
</script>
<template>
<div class="vip-center">
<header class="vip-topbar">
<button class="topbar-button" type="button" aria-label="返回" @click="router.back()">
<LeftOutlined />
</button>
<h1>会员权益</h1>
<span class="topbar-button-placeholder" aria-hidden="true"></span>
</header>
<a-spin :spinning="loading">
<main class="vip-main">
<section class="vip-hero-card">
<div class="hero-glow hero-glow--top"></div>
<div class="hero-glow hero-glow--bottom"></div>
<div class="hero-content">
<div class="hero-head">
<div>
<span class="vip-kicker">当前会员等级</span>
<h2>{{ memberLevel }} <StarFilled /></h2>
</div>
<div class="fingerprint-badge">
<CrownOutlined />
</div>
</div>
<div class="hero-stats">
<div>
<span>可用余额</span>
<strong><small>¥</small>{{ money(balanceAmount) }}</strong>
</div>
<div>
<span>累计充值</span>
<strong><small>¥</small>{{ money(totalRecharge) }}</strong>
</div>
</div>
<div class="level-progress">
<div>
<span>等级进度</span>
<span>{{ nextLevelText }}</span>
</div>
<div class="progress-track">
<i :style="{ width: `${levelProgress}%` }"></i>
</div>
<p>{{ remainingAmountText }}</p>
</div>
</div>
<TrophyOutlined class="hero-watermark" />
</section>
<section class="vip-section member-info-section">
<div class="section-head">
<h3>会员信息</h3>
</div>
<div class="info-grid">
<article>
<span>生效周期</span>
<strong>{{ validityText }}</strong>
</article>
<article>
<span>最近充值</span>
<strong>{{ formatTime(asset?.lastRechargeTime) }}</strong>
</article>
<article>
<span>等级来源</span>
<strong>{{ asset?.manualOverride ? '后台指定' : '自动计算' }}</strong>
</article>
<article>
<span>当前权益</span>
<strong>{{ asset?.benefitInfo || '暂无额外权益说明' }}</strong>
</article>
</div>
</section>
<section class="vip-section account-notice">
<div class="section-head">
<h3>权益说明</h3>
</div>
<p>当前页面仅展示已有会员权益、余额和历史记录,不提供在线充值或订阅操作。</p>
</section>
<section class="vip-section history-section">
<div class="section-head">
<h3>最近动态</h3>
</div>
<div v-if="visibleHistory.length" class="history-card">
<article
v-for="item in visibleHistory"
:key="String(item.id)"
class="history-row"
>
<span class="history-icon" :class="{ 'history-icon--income': Number(item.amount) > 0 }">
<component :is="sceneIcon(item)" />
</span>
<div class="history-copy">
<strong>{{ sceneText(item.changeScene || item.type) }}</strong>
<span>{{ formatTime(item.changeTime) }}</span>
<em v-if="item.remark">{{ item.remark }}</em>
</div>
<div class="history-amount">
<strong :class="{ income: Number(item.amount) > 0 }">
{{ Number(item.amount) > 0 ? '+' : '' }}¥{{ money(item.amount) }}
</strong>
<span v-if="item.afterBalance !== undefined">余额: ¥{{ money(item.afterBalance) }}</span>
</div>
</article>
</div>
<a-empty v-else description="暂无余额变动" />
<button v-if="canLoadMoreHistory" class="load-more-button" type="button" @click="loadMoreHistory">
加载更多交易记录
</button>
</section>
</main>
</a-spin>
</div>
</template>
<style scoped>
.vip-center {
--vip-bg: var(--theme-page-bg);
--vip-surface: rgba(255, 255, 255, 0.82);
--vip-surface-strong: rgba(255, 255, 255, 0.94);
--vip-surface-low: var(--theme-page-bg);
--vip-surface-mid: var(--theme-primary-soft);
--vip-surface-high: var(--theme-secondary);
--vip-text: var(--text-primary);
--vip-muted: var(--text-secondary);
--vip-outline: var(--theme-border);
--vip-outline-soft: color-mix(in srgb, var(--theme-border) 54%, transparent);
--vip-primary: var(--theme-primary);
--vip-blush: var(--theme-secondary);
--vip-blush-soft: var(--theme-primary-soft);
--vip-blush-dim: #9CCDBB;
--vip-gold: var(--theme-primary-action);
--vip-gold-soft: var(--theme-secondary);
--vip-neutral: var(--text-secondary);
--vip-neutral-soft: var(--theme-border);
--vip-hero-text: #FFFFFF;
--vip-shadow: rgba(23, 33, 31, 0.1);
min-height: 100vh;
color: var(--vip-text);
background:
radial-gradient(circle at 84% 0%, rgba(184, 228, 212, 0.38), transparent 34%),
radial-gradient(circle at 4% 18%, rgba(36, 123, 99, 0.1), transparent 30%),
linear-gradient(180deg, var(--vip-bg) 0%, var(--vip-surface-low) 46%, var(--vip-bg) 100%);
}
.vip-topbar {
position: sticky;
top: 0;
z-index: 30;
display: grid;
grid-template-columns: 42px minmax(0, 1fr) 42px;
align-items: center;
width: min(100%, var(--app-mobile-max-width, 480px));
min-height: 64px;
margin: 0 auto;
padding: 8px 20px;
background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent);
box-shadow: 0 8px 28px rgba(23, 33, 31, 0.06);
backdrop-filter: blur(18px);
}
.vip-topbar h1 {
margin: 0;
color: var(--vip-primary);
font-family: Georgia, 'Times New Roman', serif;
font-size: 24px;
font-weight: 700;
line-height: 1.15;
text-align: center;
}
.topbar-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
padding: 0;
border: 0;
border-radius: 999px;
color: var(--vip-primary);
background: var(--vip-surface-strong);
box-shadow: 0 12px 24px rgba(23, 33, 31, 0.08);
cursor: pointer;
}
.topbar-button :deep(.anticon) {
font-size: 21px;
}
.topbar-button-placeholder {
width: 40px;
height: 40px;
}
.vip-main {
display: grid;
gap: 32px;
width: min(100%, var(--app-mobile-max-width, 480px));
margin: 0 auto;
padding: 22px 20px 42px;
}
.vip-hero-card {
position: relative;
overflow: hidden;
padding: 28px;
border-radius: 32px;
color: var(--vip-hero-text);
background:
linear-gradient(135deg, var(--vip-primary) 0%, var(--vip-blush) 55%, var(--vip-gold-soft) 100%);
box-shadow: 0 26px 54px rgba(124, 83, 87, 0.22);
}
.hero-glow {
position: absolute;
width: 210px;
height: 210px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.13);
filter: blur(18px);
}
.hero-glow--top {
top: -74px;
right: -78px;
}
.hero-glow--bottom {
bottom: -118px;
left: -86px;
background: rgba(254, 212, 136, 0.24);
}
.hero-content {
position: relative;
z-index: 1;
display: grid;
gap: 22px;
}
.hero-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.vip-kicker,
.section-head button,
.plan-title {
font-size: 12px;
font-weight: 800;
line-height: 1.2;
letter-spacing: 0;
text-transform: uppercase;
}
.vip-kicker {
display: block;
margin-bottom: 6px;
opacity: 0.78;
}
.hero-head h2 {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font-family: Georgia, 'Times New Roman', serif;
font-size: 28px;
font-weight: 700;
line-height: 1.15;
}
.hero-head h2 :deep(.anticon) {
color: var(--vip-gold-soft);
font-size: 18px;
}
.fingerprint-badge {
display: grid;
flex: 0 0 auto;
width: 52px;
height: 52px;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.28);
border-radius: 18px;
background: rgba(255, 255, 255, 0.18);
backdrop-filter: blur(12px);
}
.fingerprint-badge :deep(.anticon) {
font-size: 28px;
}
.hero-stats {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.hero-stats > div {
min-width: 0;
padding: 14px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 16px;
background: rgba(255, 255, 255, 0.12);
backdrop-filter: blur(10px);
}
.hero-stats span,
.level-progress span,
.level-progress p {
color: rgba(255, 255, 255, 0.74);
font-size: 12px;
line-height: 1.35;
}
.hero-stats strong {
display: flex;
align-items: baseline;
gap: 3px;
min-width: 0;
margin-top: 6px;
overflow-wrap: anywhere;
color: var(--vip-hero-text);
font-family: Georgia, 'Times New Roman', serif;
font-size: 22px;
line-height: 1.1;
}
.hero-stats small,
.plan-price small {
font-family: inherit;
font-size: 13px;
}
.level-progress {
display: grid;
gap: 8px;
}
.level-progress > div:first-child {
display: flex;
justify-content: space-between;
gap: 10px;
}
.progress-track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.2);
}
.progress-track i {
display: block;
height: 100%;
border-radius: inherit;
background: var(--vip-hero-text);
box-shadow: 0 0 14px rgba(255, 255, 255, 0.5);
}
.level-progress p {
margin: 0;
}
.hero-watermark {
position: absolute;
right: 20px;
bottom: -26px;
color: rgba(255, 255, 255, 0.1);
font-size: 118px;
}
.vip-section {
display: grid;
gap: 18px;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.section-head h3 {
margin: 0;
color: var(--vip-text);
font-family: Georgia, 'Times New Roman', serif;
font-size: 24px;
font-weight: 700;
line-height: 1.2;
}
.section-head button {
border: 0;
color: var(--vip-primary);
background: transparent;
cursor: pointer;
}
.benefit-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.benefit-card,
.member-info-section,
.plan-card,
.history-card {
border: 1px solid rgba(212, 194, 195, 0.5);
background: var(--vip-surface);
box-shadow: 0 20px 40px var(--vip-shadow);
backdrop-filter: blur(16px);
}
.benefit-card {
display: grid;
justify-items: center;
gap: 10px;
min-height: 164px;
padding: 20px 14px;
border-radius: 18px;
text-align: center;
}
.benefit-icon {
display: grid;
width: 50px;
height: 50px;
place-items: center;
border-radius: 999px;
font-size: 24px;
}
.benefit-card--rose .benefit-icon {
color: var(--vip-primary);
background: var(--vip-blush-soft);
}
.benefit-card--gold .benefit-icon {
color: var(--vip-gold);
background: rgba(254, 212, 136, 0.72);
}
.benefit-card--slate .benefit-icon {
color: var(--vip-neutral);
background: rgba(194, 193, 191, 0.48);
}
.benefit-card--cream .benefit-icon {
color: var(--vip-primary);
background: var(--vip-surface-high);
}
.benefit-card strong {
color: var(--vip-text);
font-size: 14px;
font-weight: 850;
}
.benefit-card p {
display: -webkit-box;
margin: 0;
overflow: hidden;
color: var(--vip-muted);
font-size: 12px;
line-height: 1.45;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.member-info-section {
padding: 18px;
border-radius: 24px;
}
.info-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.info-grid article {
min-width: 0;
padding: 13px;
border: 1px solid var(--vip-outline-soft);
border-radius: 16px;
background: rgba(252, 242, 234, 0.78);
}
.info-grid span,
.history-copy span,
.history-copy em,
.history-amount span {
display: block;
color: var(--vip-muted);
font-size: 12px;
line-height: 1.35;
}
.info-grid strong {
display: block;
margin-top: 6px;
overflow-wrap: anywhere;
color: var(--vip-text);
font-size: 13px;
font-weight: 800;
line-height: 1.35;
}
.account-notice {
padding: 18px;
border: 1px solid var(--vip-outline-soft);
border-radius: 24px;
background: color-mix(in srgb, var(--vip-surface) 86%, transparent);
}
.account-notice p {
margin: 0;
color: var(--vip-muted);
font-size: 13px;
line-height: 1.7;
}
.history-card {
overflow: hidden;
border-radius: 24px;
}
.history-row {
display: grid;
grid-template-columns: 42px minmax(0, 1fr) auto;
gap: 12px;
align-items: center;
padding: 16px;
border-bottom: 1px solid var(--vip-outline-soft);
}
.history-row:last-child {
border-bottom: 0;
}
.history-icon {
display: grid;
width: 40px;
height: 40px;
place-items: center;
border-radius: 999px;
color: var(--vip-muted);
background: var(--vip-surface-high);
}
.history-icon--income {
color: var(--vip-primary);
background: var(--vip-blush-soft);
}
.history-copy {
min-width: 0;
}
.history-copy strong {
display: block;
overflow: hidden;
color: var(--vip-text);
font-size: 14px;
font-weight: 850;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-copy em {
margin-top: 3px;
overflow: hidden;
font-style: normal;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-amount {
min-width: 88px;
text-align: right;
}
.history-amount strong {
display: block;
color: var(--vip-text);
font-size: 13px;
font-weight: 900;
white-space: nowrap;
}
.history-amount strong.income {
color: var(--vip-gold);
}
.load-more-button {
width: 100%;
min-height: 44px;
border: 0;
border-radius: 16px;
color: var(--vip-primary);
background: rgba(232, 180, 184, 0.22);
font-weight: 850;
cursor: pointer;
}
@media (max-width: 370px) {
.vip-main {
padding-right: 14px;
padding-left: 14px;
}
.vip-hero-card {
padding: 22px;
}
.hero-stats,
.benefit-grid,
.info-grid {
grid-template-columns: 1fr;
}
}
@media (min-width: 768px) {
.vip-topbar {
border-top-left-radius: 32px;
border-top-right-radius: 32px;
}
}
</style>
@@ -1,520 +0,0 @@
<template>
<div class="mobile-container">
<header class="header">
<div class="back-btn" @click="handleBackClick">
<el-icon><ArrowLeft /></el-icon>
</div>
<h1>我的收藏</h1>
<div class="empty"></div>
</header>
<div v-if="groups.length" class="group-tabs">
<button
class="group-tab"
:class="{ 'group-tab--active': activeGroupId === null }"
type="button"
@click="activeGroupId = null"
>
All
</button>
<button
v-for="group in groups"
:key="String(group.id)"
class="group-tab"
:class="{ 'group-tab--active': sameId(activeGroupId, group.id) }"
type="button"
@click="activeGroupId = group.id"
>
{{ group.name }}
</button>
</div>
<div class="wishlist-items">
<div v-for="item in visibleWishlistItems" :key="item.id" class="wishlist-item">
<div class="item-image" @click="handleProductClick(item.product.id)">
<img
v-if="getProductImages(item.product).length > 0"
:src="getProductImages(item.product)[0]"
:alt="item.product.title"
loading="lazy"
decoding="async"
/>
<div v-else class="image-placeholder" :style="{ backgroundColor: getRandomColor() }">
<span>{{ item.product.title ? item.product.title[0] : '作' }}</span>
</div>
</div>
<div class="item-details">
<h3 class="item-name" @click="handleProductClick(item.product.id)">{{ item.product.title }}</h3>
<div class="item-group">{{ item.groupName || '最近想做' }}</div>
<p v-if="item.note" class="item-note">{{ item.note }}</p>
<p class="item-price">¥{{ Number(item.product.price || 0).toFixed(2) }}</p>
<div class="item-actions">
<el-button
size="small"
:type="isProductInCart(item.product.id) ? 'info' : 'primary'"
@click="handleAddToCart(item.product.id)"
>
{{ isProductInCart(item.product.id) ? '购物车已有' : '加入购物车' }}
</el-button>
<el-icon class="delete-icon" @click="handleRemoveItem(item.product.id)"><Delete /></el-icon>
</div>
</div>
</div>
</div>
<div v-if="wishlistItems.length === 0" class="empty-wishlist">
<el-icon :size="60" :style="{ color: 'var(--theme-primary)' }"><StarFilled /></el-icon>
<p>收藏列表为空</p>
<el-button type="primary" @click="handleBrowseProducts">
浏览作品
</el-button>
</div>
</div>
</template>
<script setup lang="ts">
/**
* WishlistView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, ref, onMounted, inject } from 'vue'
import { ArrowLeft, Delete, StarFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
/**
* Purpose: WishlistItem supports WishlistView.vue by holding or executing the wishlist item page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { wishlistApi, type WishlistGroup, type WishlistItem } from '@/api/wishlist'
import { cartApi } from '@/api/cart'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state'
import { resolvePublicImageUrls, resolvePublicImageUrlsSync } from '@/utils/public-image-assets'
import type { PublicImageRecord } from '@/utils/public-image-assets'
/**
* Purpose: router supports WishlistView.vue by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const router = useRouter()
/**
* Purpose: updateCartCount supports WishlistView.vue by holding or executing the update cart count page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
/**
* Purpose: wishlistItems supports WishlistView.vue by holding or executing the wishlist items page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const wishlistItems = ref<WishlistItem[]>([])
const groups = ref<WishlistGroup[]>([])
const activeGroupId = ref<IdType | null>(null)
/**
* Purpose: imageUrls supports WishlistView.vue by holding or executing the image urls page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const imageUrls = ref<Record<string, string[]>>({})
/** cartProductIdSet is a reactive state variable used by the template and event handlers. */
const cartProductIdSet = ref(new Set<string>())
/**
* Purpose: DEFAULT_PRODUCT_IMAGE supports WishlistView.vue by holding or executing the default product image page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
const visibleWishlistItems = computed(() => {
if (activeGroupId.value === null) {
return wishlistItems.value
}
return wishlistItems.value.filter(item => sameId(item.groupId, activeGroupId.value))
})
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
/** fetchWishlist is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchWishlist = async () => {
try {
const [response, nextGroups, nextCartProductIdSet] = await Promise.all([
wishlistApi.getWishlist(),
wishlistApi.getGroups(),
fetchCartProductIdSet()
])
cartProductIdSet.value = nextCartProductIdSet
groups.value = nextGroups
wishlistItems.value = response as unknown as WishlistItem[]
await loadImageUrls(response as unknown as WishlistItem[])
} catch (error: any) {
console.error('获取收藏列表失败:', error)
ElMessage.error(error?.message || '获取收藏列表失败')
}
}
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (items: WishlistItem[]) => {
for (const item of items) {
const productKey = String(item.product.id)
const cachedUrls = resolvePublicImageUrlsSync(item.product as PublicImageRecord, '')
if (cachedUrls.length) {
imageUrls.value[productKey] = cachedUrls
}
const urls = await resolvePublicImageUrls(item.product as PublicImageRecord, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[productKey] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: { id: IdType }): string[] => {
return imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
}
/** isProductInCart is a local helper used by this page script. */
const isProductInCart = (productId: IdType) => hasCartProduct(cartProductIdSet.value, productId)
/** handleAddToCart is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleAddToCart = async (productId: IdType) => {
if (isProductInCart(productId)) {
ElMessage.info('购物车已有')
return
}
try {
await runWithGlobalLoading(() => cartApi.addToCart({ productId, quantity: 1 }))
cartProductIdSet.value = withAddedCartProduct(cartProductIdSet.value, productId)
await updateCartCount()
ElMessage.success('已添加到购物车')
} catch (error: any) {
console.error('添加到购物车失败:', error)
ElMessage.error(error?.message || '添加到购物车失败')
}
}
/** handleRemoveItem is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleRemoveItem = async (productId: IdType) => {
try {
await runWithGlobalLoading(() => wishlistApi.removeFromWishlist(productId))
wishlistItems.value = wishlistItems.value.filter(item => !sameId(item.productId, productId))
ElMessage.success('已从收藏中移除')
} catch (error: any) {
console.error('移除收藏失败:', error)
ElMessage.error(error?.message || '移除收藏失败')
}
}
/** handleBrowseProducts is a local helper used by this page script. */
const handleBrowseProducts = () => {
router.push('/products')
}
/** handleProductClick is a local helper used by this page script. */
const handleProductClick = (productId: IdType) => {
router.push(`/product/${productId}`)
}
/** getRandomColor is a local helper used by this page script. */
const getRandomColor = () => {
return 'var(--theme-primary-soft)'
}
onMounted(() => {
fetchWishlist()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
padding-top: 60px;
background:
linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)),
var(--theme-background-image),
var(--theme-page-bg);
background-size: cover, cover, auto;
background-position: center top;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
padding: 10px 15px;
background: rgba(255, 255, 255, 0.92);
border-bottom: 1px solid var(--theme-border);
backdrop-filter: blur(14px);
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: var(--text-primary);
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: bold;
color: var(--text-primary);
}
.empty {
width: 40px;
}
.group-tabs {
display: flex;
gap: 8px;
overflow-x: auto;
padding: 14px 16px 0;
}
.group-tab {
flex: 0 0 auto;
height: 32px;
padding: 0 12px;
border: 1px solid var(--theme-border);
border-radius: 8px;
background: var(--theme-card-bg);
color: var(--text-secondary);
font-size: 13px;
line-height: 30px;
white-space: nowrap;
}
.group-tab--active {
border-color: var(--theme-primary);
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-weight: 600;
}
.wishlist-items {
padding: 16px;
padding-bottom: 28px;
}
.wishlist-item {
display: flex;
gap: 15px;
padding: 15px;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
border-radius: 16px;
margin-bottom: 15px;
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.item-image {
width: 80px;
height: 80px;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
cursor: pointer;
}
.item-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.image-placeholder {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
font-weight: bold;
color: rgba(0, 0, 0, 0.1);
border: 1px solid var(--theme-border);
}
.item-details {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.item-name {
font-size: 16px;
font-weight: bold;
margin: 0 0 5px 0;
color: var(--text-primary);
}
.item-group {
width: fit-content;
max-width: 100%;
margin-bottom: 6px;
padding: 2px 8px;
border-radius: 8px;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 12px;
line-height: 18px;
}
.item-note {
margin: 0 0 8px;
color: var(--text-secondary);
font-size: 13px;
line-height: 18px;
word-break: break-word;
}
.item-price {
color: var(--theme-primary);
font-weight: bold;
margin: 0 0 10px 0;
}
.item-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
.delete-icon {
color: var(--theme-accent);
cursor: pointer;
font-size: 20px;
}
.empty-wishlist {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 16px;
padding: 64px 20px;
color: var(--text-secondary);
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
border-radius: 18px;
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.empty-wishlist p {
margin: 20px 0;
font-size: 16px;
}
:deep(.el-button--primary) {
--el-button-bg-color: var(--theme-primary);
--el-button-border-color: var(--theme-primary);
--el-button-hover-bg-color: var(--theme-accent);
--el-button-hover-border-color: var(--theme-accent);
}
:deep(.el-button--info) {
--el-button-bg-color: var(--theme-primary-soft);
--el-button-border-color: var(--theme-border);
--el-button-text-color: var(--theme-accent);
--el-button-hover-bg-color: var(--theme-primary-soft);
--el-button-hover-border-color: var(--theme-border);
--el-button-hover-text-color: var(--theme-accent);
}
.mobile-container {
padding-top: 68px;
background:
radial-gradient(circle at 84% 0%, color-mix(in srgb, var(--theme-primary) 26%, transparent), transparent 32%),
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 76%, transparent), var(--theme-page-bg));
}
.header {
height: 64px;
padding: 12px 18px 10px;
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
}
.header h1 {
font-size: 17px;
font-weight: 820;
}
.back-btn {
border-radius: 999px;
background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent);
}
.group-tabs {
padding: 16px 18px 0;
}
.group-tab {
height: 34px;
border-radius: 999px;
background: color-mix(in srgb, var(--theme-card-bg) 84%, transparent);
}
.group-tab--active {
border-color: color-mix(in srgb, var(--theme-primary) 40%, var(--theme-border));
background: color-mix(in srgb, var(--theme-primary) 20%, var(--theme-card-bg));
color: var(--theme-primary-action);
}
.wishlist-items {
padding: 18px;
}
.wishlist-item {
border-radius: 24px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 18px 42px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
.item-image {
width: 92px;
height: 92px;
border-radius: 18px;
}
.item-name {
font-weight: 820;
}
.item-group {
border-radius: 999px;
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 18%, var(--theme-card-bg));
}
.item-price {
color: var(--theme-primary-action);
}
.empty-wishlist {
border-radius: 24px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 18px 42px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
:deep(.el-button--primary) {
--el-button-bg-color: var(--theme-primary-action);
--el-button-border-color: var(--theme-primary-action);
--el-button-hover-bg-color: var(--theme-secondary);
--el-button-hover-border-color: var(--theme-secondary);
}
</style>
@@ -1,312 +0,0 @@
<template>
<div class="campaigns">
<a-page-header v-if="!isMobile" title="活动管理" sub-title="维护营销活动、推荐位和关联资源" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">活动</span>
<h1 class="admin-page-intro__title">活动管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">活动 {{ pagination.total }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">活动列表</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-button type="primary" @click="openCreateModal">
<template #icon>
<PlusOutlined />
</template>
新增活动
</a-button>
</div>
</template>
<AdminFilterPanel :active-count="activeFilterCount">
<a-select
v-model:value="statusFilter"
:options="statusOptions"
style="width: 160px"
@change="reload"
/>
<a-button @click="resetFilters">重置筛选</a-button>
</AdminFilterPanel>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="campaigns"
:loading="loading"
:pagination="pagination"
row-key="id"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 0 ? 'red' : 'green'">{{ campaignStatusText(record.status) }}</a-tag>
</template>
<template v-else-if="column.key === 'time'">
{{ record.startTime || '-' }} 至 {{ record.endTime || '-' }}
</template>
<template v-else-if="column.key === 'actions'">
<a-button type="link" size="small" @click="openEditModal(record as CampaignVO)">编辑</a-button>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="campaigns" empty-description="暂无活动数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.title }}</div>
<div class="admin-mobile-card__subtitle">{{ item.scene || 'GENERAL' }} · 排序 {{ item.sortOrder ?? 0 }}</div>
</div>
<a-tag :color="item.status === 0 ? 'red' : 'green'">{{ campaignStatusText(item.status) }}</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>时间</span>
<strong>{{ item.startTime || '-' }} 至 {{ item.endTime || '-' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>作品ID</span>
<strong>{{ item.productIds || '-' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>优惠券ID</span>
<strong>{{ item.couponIds || '-' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button size="small" @click="openEditModal(item)">编辑</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalOpen"
:title="editingCampaign ? '编辑活动' : '新增活动'"
:desktop-width="760"
:confirm-loading="saving"
@ok="saveCampaign"
@cancel="closeModal"
>
<a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="活动标题" name="title">
<a-input v-model:value="formState.title" placeholder="请输入活动标题" />
</a-form-item>
<a-form-item label="活动场景">
<a-input v-model:value="formState.scene" placeholder="HOME / DETAIL / POPUP" />
</a-form-item>
<a-form-item label="活动说明">
<a-textarea v-model:value="formState.description" :rows="3" :maxlength="500" />
</a-form-item>
<a-form-item label="关联作品ID">
<a-input v-model:value="formState.productIds" placeholder="多个 ID 用英文逗号分隔" />
</a-form-item>
<a-form-item label="关联券ID">
<a-input v-model:value="formState.couponIds" placeholder="多个 ID 用英文逗号分隔" />
</a-form-item>
<a-form-item label="开始时间">
<a-date-picker
v-model:value="formState.startTime"
show-time
value-format="YYYY-MM-DDTHH:mm:ss"
format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="结束时间">
<a-date-picker
v-model:value="formState.endTime"
show-time
value-format="YYYY-MM-DDTHH:mm:ss"
format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="排序">
<a-input-number v-model:value="formState.sortOrder" :min="0" style="width: 100%" />
</a-form-item>
<a-form-item label="状态">
<a-select v-model:value="formState.status">
<a-select-option :value="1">启用</a-select-option>
<a-select-option :value="0">停用</a-select-option>
</a-select>
</a-form-item>
</a-form>
</AdminResponsiveModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { adminCampaignApi, type CampaignRequest, type CampaignVO } from '@/api/admin'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminFilterPanel from '@/components/admin/AdminFilterPanel.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { isMobile } = useAdminViewport()
const loading = ref(false)
const saving = ref(false)
const statusFilter = ref<'all' | number>('all')
const campaigns = ref<CampaignVO[]>([])
const modalOpen = ref(false)
const editingCampaign = ref<CampaignVO | null>(null)
const formRef = ref<FormInstance>()
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive<CampaignRequest>({
title: '',
description: '',
scene: 'HOME',
productIds: '',
couponIds: '',
status: 1,
startTime: undefined,
endTime: undefined,
sortOrder: 0
})
const rules = {
title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }]
} as any
const statusOptions = [
{ label: '全部状态', value: 'all' },
{ label: '启用', value: 1 },
{ label: '停用', value: 0 }
]
const activeFilterCount = computed(() => statusFilter.value === 'all' ? 0 : 1)
const columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '场景', dataIndex: 'scene', key: 'scene', width: 120 },
{ title: '活动时间', key: 'time', width: 280 },
{ title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 90 },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 90 }
]
const campaignStatusText = (status?: number) => status === 0 ? '停用' : '启用'
const resetForm = () => {
Object.assign(formState, {
title: '',
description: '',
scene: 'HOME',
productIds: '',
couponIds: '',
status: 1,
startTime: undefined,
endTime: undefined,
sortOrder: 0
})
}
const loadCampaigns = async () => {
loading.value = true
try {
const result = await adminCampaignApi.listCampaigns({
status: statusFilter.value === 'all' ? undefined : Number(statusFilter.value),
page: pagination.current,
size: pagination.pageSize
})
campaigns.value = result.list || []
pagination.total = result.total || 0
} catch (error) {
console.error('加载活动失败:', error)
message.error('加载活动失败')
} finally {
loading.value = false
}
}
const reload = () => {
pagination.current = 1
void loadCampaigns()
}
const resetFilters = () => {
statusFilter.value = 'all'
reload()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
void loadCampaigns()
}
const openCreateModal = () => {
editingCampaign.value = null
resetForm()
modalOpen.value = true
}
const openEditModal = (record: CampaignVO) => {
editingCampaign.value = record
Object.assign(formState, {
title: record.title || '',
description: record.description || '',
scene: record.scene || 'HOME',
productIds: record.productIds || '',
couponIds: record.couponIds || '',
status: record.status ?? 1,
startTime: record.startTime,
endTime: record.endTime,
sortOrder: record.sortOrder ?? 0
})
modalOpen.value = true
}
const closeModal = () => {
modalOpen.value = false
formRef.value?.resetFields()
}
const saveCampaign = async () => {
try {
await formRef.value?.validate()
saving.value = true
await runWithGlobalLoading(async () => {
await adminCampaignApi.saveCampaign({ ...formState })
await loadCampaigns()
})
message.success('活动已保存')
closeModal()
} catch (error: any) {
if (error?.errorFields) return
console.error('保存活动失败:', error)
message.error(error?.message || '保存活动失败')
} finally {
saving.value = false
}
}
onMounted(loadCampaigns)
</script>
<style scoped>
.campaigns {
padding: 0;
}
</style>
@@ -1,987 +0,0 @@
<template>
<div class="coupons">
<a-page-header v-if="!isMobile" title="优惠券管理" sub-title="管理系统优惠券" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">优惠券管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">优惠券 {{ couponList.length }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">
优惠券列表
</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-input-search
v-model:value="searchText"
placeholder="搜索优惠券名称"
:style="isMobile ? { width: '100%' } : { width: '260px' }"
@search="handleSearch"
/>
<a-button v-if="!isMobile && hasPermission('coupon:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增优惠券
</a-button>
</div>
</template>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="couponList"
:loading="loading"
:pagination="pagination"
row-key="id"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'shop'">
{{ record.shopName || '未指定店铺' }}
</template>
<template v-else-if="column.key === 'couponType'">
<a-tag :color="record.couponType === 1 ? 'blue' : 'green'">
{{ record.couponTypeName || (record.couponType === 1 ? '折扣券' : '满减券') }}
</a-tag>
</template>
<template v-else-if="column.key === 'couponScene'">
<a-tag :color="record.couponScene === 'VIP_AUTO' ? 'gold' : 'default'">
{{ getCouponSceneText(record.couponScene) }}
</a-tag>
</template>
<template v-else-if="column.key === 'requiredVipLevel'">
{{ record.requiredVipLevel || '-' }}
</template>
<template v-else-if="column.key === 'value'">
<template v-if="record.couponType === 1">
{{ record.discountValue }} 折
</template>
<template v-else>
满 {{ record.minAmount }} 减 {{ record.reduceAmount }}
</template>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="getStatusColor(record.status || 1)">
{{ record.statusName || '未知' }}
</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-space wrap>
<a-button v-if="hasPermission('coupon:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('coupon:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
<a-button
v-if="hasPermission('coupon:assign') && !isVipAutoCoupon(record) && record.status === 1"
type="link"
size="small"
@click="showDistributeModal(record)"
>
发放
</a-button>
<a-button
v-if="hasPermission('coupon:delete') && record.status !== 2"
type="link"
size="small"
danger
@click="handleDelete(record)"
>
删除
</a-button>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="couponList" empty-description="暂无优惠券数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.couponName }}</div>
<div class="admin-mobile-card__subtitle">{{ item.shopName || '未指定店铺' }}</div>
</div>
<a-tag :color="getStatusColor(item.status || 1)">
{{ item.statusName || '未知' }}
</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>类型</span>
<strong>{{ item.couponType === 1 ? '折扣券' : '满减券' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>场景</span>
<strong>{{ getCouponSceneText(item.couponScene) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>优惠值</span>
<strong>{{ getCouponValueText(item) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>剩余数量</span>
<strong>{{ item.remainingCount ?? '-' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button v-if="hasPermission('coupon:view')" size="small" @click="showViewModal(item)">查看</a-button>
<a-button v-if="hasPermission('coupon:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
<a-button
v-if="hasPermission('coupon:assign') && !isVipAutoCoupon(item) && item.status === 1"
size="small"
@click="showDistributeModal(item)"
>
发放
</a-button>
<a-button
v-if="hasPermission('coupon:delete') && item.status !== 2"
size="small"
danger
@click="handleDelete(item)"
>
删除
</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalVisible"
:title="isEdit ? '编辑优惠券' : '新增优惠券'"
:desktop-width="820"
:confirm-loading="modalLoading"
@ok="handleModalOk"
@cancel="handleModalCancel"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券名称" name="couponName">
<a-input v-model:value="formState.couponName" placeholder="请输入优惠券名称" />
</a-form-item>
<a-form-item label="所属店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
placeholder="请选择所属店铺"
:loading="loadingShops"
:disabled="currentUserInfo?.type === 2"
>
<a-select-option v-for="shop in shops" :key="shop.id" :value="shop.id">
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="优惠券类型" name="couponType">
<a-select v-model:value="formState.couponType" placeholder="请选择优惠券类型">
<a-select-option :value="1">折扣券</a-select-option>
<a-select-option :value="2">满减券</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="优惠场景" name="couponScene">
<a-select v-model:value="formState.couponScene" placeholder="请选择优惠场景">
<a-select-option value="GENERAL">普通券</a-select-option>
<a-select-option value="VIP_AUTO">VIP 自动券</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="自动匹配">
<a-switch :checked="formState.autoMatch === 1" @change="(checked: any) => handleAutoMatchChange(checked === true)" />
</a-form-item>
<a-form-item v-if="isVipAutoForm" label="所需 VIP 等级" name="requiredVipLevel">
<a-select v-model:value="formState.requiredVipLevel" placeholder="请选择 VIP 等级">
<a-select-option v-for="level in vipLevelOptions" :key="level" :value="level">{{ level }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="formState.couponType === 1" label="折扣值" name="discountValue">
<a-input-number v-model:value="formState.discountValue" :min="0.1" :max="9.9" :step="0.1" style="width: 100%" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="最低消费" name="minAmount">
<a-input-number v-model:value="formState.minAmount" :min="0" :step="0.01" style="width: 100%" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="减免金额" name="reduceAmount">
<a-input-number v-model:value="formState.reduceAmount" :min="0" :step="0.01" style="width: 100%" />
</a-form-item>
<a-form-item label="总数量" name="totalCount">
<a-input-number v-model:value="formState.totalCount" :min="1" style="width: 100%" />
</a-form-item>
<a-form-item label="开始时间" name="startTime">
<a-date-picker v-model:value="formState.startTime" show-time format="YYYY-MM-DD HH:mm:ss" popup-class-name="jayucloud-salon-date-picker-panel jayucloud-salon-date-time-panel" style="width: 100%" />
</a-form-item>
<a-form-item label="结束时间" name="endTime">
<a-date-picker v-model:value="formState.endTime" show-time format="YYYY-MM-DD HH:mm:ss" popup-class-name="jayucloud-salon-date-picker-panel jayucloud-salon-date-time-panel" style="width: 100%" />
</a-form-item>
<a-form-item label="可用标签" name="availableTagIds">
<a-select v-model:value="formState.availableTagIds" mode="multiple" placeholder="请选择可用标签">
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id" :disabled="formState.unavailableTagIds.includes(Number(tag.id))">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="不可用标签" name="unavailableTagIds">
<a-select v-model:value="formState.unavailableTagIds" mode="multiple" placeholder="请选择不可用标签">
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id" :disabled="formState.availableTagIds.includes(Number(tag.id))">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="viewModalVisible"
title="查看优惠券详情"
:footer="null"
:desktop-width="760"
@cancel="viewModalVisible = false"
>
<a-descriptions bordered :column="1" size="small">
<a-descriptions-item label="优惠券名称">{{ currentCoupon?.couponName || '-' }}</a-descriptions-item>
<a-descriptions-item label="所属店铺">{{ currentCoupon?.shopName || '-' }}</a-descriptions-item>
<a-descriptions-item label="优惠券类型">{{ currentCoupon?.couponType === 1 ? '折扣券' : '满减券' }}</a-descriptions-item>
<a-descriptions-item label="优惠场景">{{ getCouponSceneText(currentCoupon?.couponScene) }}</a-descriptions-item>
<a-descriptions-item label="所需 VIP 等级">{{ currentCoupon?.requiredVipLevel || '-' }}</a-descriptions-item>
<a-descriptions-item label="自动匹配">{{ currentCoupon?.autoMatch === 1 ? '是' : '否' }}</a-descriptions-item>
<a-descriptions-item label="优惠信息">{{ getCouponValueText(currentCoupon) }}</a-descriptions-item>
<a-descriptions-item label="总数量">{{ currentCoupon?.totalCount ?? '-' }}</a-descriptions-item>
<a-descriptions-item label="已使用">{{ currentCoupon?.usedCount ?? '-' }}</a-descriptions-item>
<a-descriptions-item label="开始时间">{{ currentCoupon?.startTime || '-' }}</a-descriptions-item>
<a-descriptions-item label="结束时间">{{ currentCoupon?.endTime || '-' }}</a-descriptions-item>
</a-descriptions>
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="distributeModalVisible"
title="发放优惠券"
:desktop-width="760"
:confirm-loading="distributeLoading"
@ok="handleDistributeOk"
@cancel="handleDistributeCancel"
>
<a-form
ref="distributeFormRef"
:model="distributeFormState"
:rules="distributeFormRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券">
<a-input v-model:value="distributeFormState.couponName" disabled />
</a-form-item>
<a-form-item label="选择用户" name="userIds">
<a-select
v-model:value="distributeFormState.userIds"
mode="multiple"
placeholder="请选择要发放的用户"
>
<a-select-option v-for="user in userList" :key="user.id" :value="user.id">
{{ user.nickname }}({{ user.account }})
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="发放数量" name="quantity">
<a-input-number v-model:value="distributeFormState.quantity" :min="1" style="width: 100%" />
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && hasPermission('coupon:create') && !modalVisible && !viewModalVisible && !distributeModalVisible"
label="新增优惠券"
@click="showAddModal"
/>
</div>
</template>
<script setup lang="ts">
/**
* CouponsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
/**
* Purpose: Dayjs supports CouponsView.vue by holding or executing the dayjs page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import dayjs, { type Dayjs } from 'dayjs'
import {
adminCouponApi,
adminVipRechargePlanApi,
adminShopApi,
adminTagApi,
adminUserApi,
type Coupon,
type Shop,
type Tag,
type UserVO
} from '@/api/admin'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** currentUserInfo is a local helper used by this page script. */
const currentUserInfo = (() => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
return userInfoStr ? JSON.parse(userInfoStr) : null
} catch (error) {
console.error('获取当前用户信息失败', error)
return null
}
})()
/**
* Purpose: CouponFormState supports CouponsView.vue by holding or executing the coupon form state page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface CouponFormState {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime?: Dayjs
endTime?: Dayjs
availableTagIds: number[]
unavailableTagIds: number[]
shopId?: number
couponScene: string
requiredVipLevel?: string
autoMatch: number
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
/**
* Purpose: formRef supports CouponsView.vue by holding or executing the form ref page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formRef = ref<FormInstance>()
/**
* Purpose: distributeFormRef supports CouponsView.vue by holding or executing the distribute form ref page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const distributeFormRef = ref<FormInstance>()
/**
* Purpose: currentCoupon supports CouponsView.vue by holding or executing the current coupon page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const currentCoupon = ref<Coupon | null>(null)
/**
* Purpose: draftSavedAt supports CouponsView.vue by holding or executing the draft saved at page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const draftSavedAt = ref<number | null>(null)
/**
* Purpose: couponList supports CouponsView.vue by holding or executing the coupon list page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const couponList = ref<Coupon[]>([])
/**
* Purpose: tagList supports CouponsView.vue by holding or executing the tag list page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const tagList = ref<Tag[]>([])
/**
* Purpose: userList supports CouponsView.vue by holding or executing the user list page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const userList = ref<UserVO[]>([])
/**
* Purpose: shops supports CouponsView.vue by holding or executing the shops page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shops = ref<Shop[]>([])
/**
* Purpose: vipLevelOptions supports CouponsView.vue by holding or executing the vip level options page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const vipLevelOptions = ref<string[]>(['普通', '青铜', '白银', '黄金'])
/** distributeModalVisible is a reactive state variable used by the template and event handlers. */
const distributeModalVisible = ref(false)
/** distributeLoading is a reactive state variable used by the template and event handlers. */
const distributeLoading = ref(false)
/**
* Purpose: currentDistributeCoupon supports CouponsView.vue by holding or executing the current distribute coupon page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const currentDistributeCoupon = ref<Coupon | null>(null)
/**
* Purpose: pagination supports CouponsView.vue by holding or executing the pagination page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/**
* Purpose: formState supports CouponsView.vue by holding or executing the form state page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formState = reactive<CouponFormState>({
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: dayjs(),
endTime: dayjs().add(30, 'day'),
availableTagIds: [],
unavailableTagIds: [],
shopId: undefined,
couponScene: 'GENERAL',
requiredVipLevel: undefined,
autoMatch: 0
})
/**
* Purpose: distributeFormState supports CouponsView.vue by holding or executing the distribute form state page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const distributeFormState = reactive({
couponName: '',
userIds: [] as number[],
quantity: 1
})
/**
* Purpose: formRules supports CouponsView.vue by holding or executing the form rules page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formRules = {
couponName: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
couponType: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
couponScene: [{ required: true, message: '请选择优惠场景', trigger: 'change' }],
requiredVipLevel: [{ required: true, message: '请选择所需 VIP 等级', trigger: 'change' }],
totalCount: [{ required: true, message: '请输入优惠券总数量', trigger: 'blur' }],
startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
shopId: [{ required: true, message: '请选择所属店铺', trigger: 'change' }]
} as any
/**
* Purpose: distributeFormRules supports CouponsView.vue by holding or executing the distribute form rules page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const distributeFormRules = {
userIds: [{ required: true, message: '请选择要发放的用户', trigger: 'change' }],
quantity: [{ required: true, message: '请输入发放数量', trigger: 'blur' }]
} as any
/**
* Purpose: columns supports CouponsView.vue by holding or executing the columns page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const columns = [
{ title: '优惠券名称', dataIndex: 'couponName', key: 'couponName' },
{ title: '所属店铺', key: 'shop', width: 140 },
{ title: '类型', key: 'couponType', width: 100 },
{ title: '场景', key: 'couponScene', width: 120 },
{ title: '所需 VIP', key: 'requiredVipLevel', width: 110 },
{ title: '优惠信息', key: 'value', width: 170 },
{ title: '总数量', dataIndex: 'totalCount', key: 'totalCount', width: 90 },
{ title: '已使用', dataIndex: 'usedCount', key: 'usedCount', width: 90 },
{ title: '剩余', dataIndex: 'remainingCount', key: 'remainingCount', width: 90 },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 180, fixed: 'right' as const }
]
/** isVipAutoForm is a reactive state variable used by the template and event handlers. */
const isVipAutoForm = computed(() => formState.couponScene === 'VIP_AUTO' || formState.autoMatch === 1)
/** getStatusColor is a local helper used by this page script. */
const getStatusColor = (status: number) => {
switch (status) {
case 1:
return 'green'
case 2:
return 'red'
case 3:
return 'orange'
default:
return 'default'
}
}
/** getCouponSceneText is a local helper used by this page script. */
const getCouponSceneText = (scene?: string) => {
if (scene === 'VIP_AUTO') {
return 'VIP 自动券'
}
return '普通券'
}
/** isVipAutoCoupon is a local helper used by this page script. */
const isVipAutoCoupon = (coupon: any) => coupon?.couponScene === 'VIP_AUTO' || coupon?.autoMatch === 1
/** getCouponValueText is a local helper used by this page script. */
const getCouponValueText = (coupon: Coupon | null) => {
if (!coupon) {
return '-'
}
return coupon.couponType === 1
? `${coupon.discountValue} 折`
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
/** resetFormState is a local helper used by this page script. */
const resetFormState = () => {
Object.assign(formState, {
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: dayjs(),
endTime: dayjs().add(30, 'day'),
availableTagIds: [],
unavailableTagIds: [],
shopId: currentUserInfo?.shopId || undefined,
couponScene: 'GENERAL',
requiredVipLevel: undefined,
autoMatch: 0
})
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-coupons', isEdit.value ? 'edit' : 'create', currentCoupon.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
couponType: formState.couponType,
discountValue: formState.discountValue,
minAmount: formState.minAmount,
reduceAmount: formState.reduceAmount,
totalCount: formState.totalCount,
startTime: formState.startTime?.format('YYYY-MM-DDTHH:mm:ss'),
endTime: formState.endTime?.format('YYYY-MM-DDTHH:mm:ss'),
availableTagIds: [...formState.availableTagIds],
unavailableTagIds: [...formState.unavailableTagIds],
shopId: formState.shopId,
couponScene: formState.couponScene,
requiredVipLevel: formState.requiredVipLevel,
autoMatch: formState.autoMatch
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, {
...draft.payload,
startTime: draft.payload.startTime ? dayjs(draft.payload.startTime) : undefined,
endTime: draft.payload.endTime ? dayjs(draft.payload.endTime) : undefined
})
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/**
* Purpose: isSameTagSelection supports CouponsView.vue by holding or executing the is same tag selection page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const isSameTagSelection = (left: number[], right: number[]) =>
left.length === right.length && left.every((id, index) => Number(id) === Number(right[index]))
/**
* Purpose: removeSelectedTags supports CouponsView.vue by holding or executing the remove selected tags page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const removeSelectedTags = (target: number[], selected: number[]) => {
const selectedIds = new Set(selected.map(Number))
return target.filter(id => !selectedIds.has(Number(id)))
}
watch(
() => formState.couponScene,
value => {
if (value === 'VIP_AUTO') {
formState.autoMatch = 1
if (!formState.requiredVipLevel) {
formState.requiredVipLevel = vipLevelOptions.value.find(level => level !== '普通') || vipLevelOptions.value[0]
}
} else {
formState.autoMatch = 0
formState.requiredVipLevel = undefined
}
}
)
watch(
() => formState.availableTagIds.slice(),
value => {
const nextUnavailableTagIds = removeSelectedTags(formState.unavailableTagIds, value)
if (!isSameTagSelection(formState.unavailableTagIds, nextUnavailableTagIds)) {
formState.unavailableTagIds = nextUnavailableTagIds
}
}
)
watch(
() => formState.unavailableTagIds.slice(),
value => {
const nextAvailableTagIds = removeSelectedTags(formState.availableTagIds, value)
if (!isSameTagSelection(formState.availableTagIds, nextAvailableTagIds)) {
formState.availableTagIds = nextAvailableTagIds
}
}
)
/** handleAutoMatchChange is a local helper used by this page script. */
const handleAutoMatchChange = (checked: boolean) => {
formState.autoMatch = checked ? 1 : 0
formState.couponScene = checked ? 'VIP_AUTO' : 'GENERAL'
}
/** fetchCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCoupons = async () => {
loading.value = true
try {
const shopId = currentUserInfo?.shopId || undefined
const coupons = await adminCouponApi.listAllCoupons(shopId) as unknown as Coupon[]
const list = Array.isArray(coupons) ? coupons : []
const keyword = searchText.value.trim()
couponList.value = keyword
? list.filter(item => (item.couponName || '').includes(keyword))
: list
pagination.total = couponList.value.length
} catch (error) {
console.error('获取优惠券列表失败:', error)
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTags = async () => {
try {
const tags = await adminTagApi.listAllTags() as unknown as Tag[]
tagList.value = tags || []
} catch (error) {
console.error('获取标签列表失败:', error)
}
}
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
loadingShops.value = true
try {
const shopList = await adminShopApi.listAllShops() as unknown as Shop[]
shops.value = shopList || []
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
loadingShops.value = false
}
}
/** fetchUsers is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUsers = async () => {
try {
const params: Record<string, unknown> = { page: 1, size: 200 }
if (currentUserInfo?.shopId) {
params.shopId = currentUserInfo.shopId
}
const result = await adminUserApi.listUsers(params as any)
userList.value = result.list || []
} catch (error) {
console.error('获取用户列表失败:', error)
userList.value = []
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchCoupons())
}
/** handleTableChange is a local helper used by this page script. */
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
}
/** showAddModal is a local helper used by this page script. */
const showAddModal = () => {
isEdit.value = false
currentCoupon.value = null
resetFormState()
restoreDraft()
modalVisible.value = true
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: any) => {
isEdit.value = true
currentCoupon.value = record
Object.assign(formState, {
couponCode: record.couponCode || '',
couponName: record.couponName || '',
couponType: record.couponType || 1,
discountValue: record.discountValue ? Number(record.discountValue) : 9.5,
minAmount: record.minAmount ? Number(record.minAmount) : 100,
reduceAmount: record.reduceAmount ? Number(record.reduceAmount) : 20,
totalCount: record.totalCount || 100,
startTime: record.startTime ? dayjs(record.startTime) : undefined,
endTime: record.endTime ? dayjs(record.endTime) : undefined,
availableTagIds: record.availableTags?.map((tag: Tag) => tag.id) || [],
unavailableTagIds: record.unavailableTags?.map((tag: Tag) => tag.id) || [],
shopId: record.shopId,
couponScene: record.couponScene || 'GENERAL',
requiredVipLevel: record.requiredVipLevel || undefined,
autoMatch: record.autoMatch || 0
})
restoreDraft()
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: any) => {
currentCoupon.value = record
viewModalVisible.value = true
}
/** buildCouponPayload is a local helper used by this page script. */
const buildCouponPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
couponType: formState.couponType,
discountValue: formState.couponType === 1 ? formState.discountValue : undefined,
minAmount: formState.couponType === 2 ? formState.minAmount : undefined,
reduceAmount: formState.couponType === 2 ? formState.reduceAmount : undefined,
totalCount: formState.totalCount,
startTime: formState.startTime?.format('YYYY-MM-DDTHH:mm:ss'),
endTime: formState.endTime?.format('YYYY-MM-DDTHH:mm:ss'),
availableTagIds: formState.availableTagIds,
unavailableTagIds: formState.unavailableTagIds,
shopId: formState.shopId,
couponScene: formState.couponScene,
requiredVipLevel: isVipAutoForm.value ? formState.requiredVipLevel : undefined,
autoMatch: isVipAutoForm.value ? 1 : 0
})
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
await runWithGlobalLoading(async () => {
const payload = buildCouponPayload()
if (isEdit.value && currentCoupon.value) {
await adminCouponApi.updateCoupon(currentCoupon.value.id, payload)
message.success('更新成功')
} else {
await adminCouponApi.createCoupon(payload)
message.success('创建成功')
}
handleClearDraft(false)
modalVisible.value = false
formRef.value?.resetFields()
await fetchCoupons()
})
} catch (error: any) {
console.error('保存优惠券失败:', error)
message.error(error.message || '操作失败')
} finally {
modalLoading.value = false
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
resetFormState()
}
/** handleDelete is a local helper used by this page script. */
const handleDelete = (record: any) => {
Modal.confirm({
title: '确认删除',
content: `确定要删除优惠券 ${record.couponName} 吗?`,
async onOk() {
try {
await runWithGlobalLoading(async () => {
await adminCouponApi.deleteCoupon(record.id)
message.success('删除成功')
await fetchCoupons()
})
} catch (error) {
console.error('删除优惠券失败:', error)
message.error('删除失败')
}
}
})
}
/** showDistributeModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showDistributeModal = async (record: any) => {
currentDistributeCoupon.value = record
distributeFormState.couponName = record.couponName
distributeFormState.userIds = []
distributeFormState.quantity = 1
await runWithGlobalLoading(() => fetchUsers())
distributeModalVisible.value = true
}
/** handleDistributeOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDistributeOk = async () => {
if (!currentDistributeCoupon.value) {
return
}
const couponId = currentDistributeCoupon.value.id
if (isVipAutoCoupon(currentDistributeCoupon.value)) {
message.warning('VIP 自动券为系统模板券,不能手动发放')
return
}
try {
await distributeFormRef.value?.validate()
distributeLoading.value = true
await runWithGlobalLoading(async () => {
await adminCouponApi.distributeCoupon({
couponId,
userIds: distributeFormState.userIds,
quantity: distributeFormState.quantity
})
message.success('发放成功')
distributeModalVisible.value = false
})
} catch (error: any) {
console.error('发放优惠券失败:', error)
message.error(error.message || '发放失败')
} finally {
distributeLoading.value = false
}
}
/** handleDistributeCancel is a local helper used by this page script. */
const handleDistributeCancel = () => {
distributeModalVisible.value = false
distributeFormRef.value?.resetFields()
}
/**
* Purpose: fetchVipLevelOptions supports CouponsView.vue by holding or executing the fetch vip level options page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const fetchVipLevelOptions = async () => {
try {
const levels = await adminVipRechargePlanApi.listVipLevelOptions(currentUserInfo?.shopId)
if (Array.isArray(levels) && levels.length) {
vipLevelOptions.value = ['普通', ...levels.filter(level => level !== '普通')]
}
} catch (error) {
console.error('VIP 等级选项加载失败:', error)
}
}
onMounted(async () => {
await loadUserPermissions()
await Promise.all([fetchTags(), fetchShops(), fetchCoupons(), fetchVipLevelOptions()])
})
</script>
<style scoped>
.coupons {
padding: 0;
}
</style>
@@ -349,186 +349,6 @@
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="assetModalVisible"
title="余额 / VIP 管理"
:desktop-width="960"
:footer="null"
@cancel="handleAssetModalCancel"
>
<a-spin :spinning="assetLoading">
<div v-if="assetTargetUser" class="asset-modal">
<a-alert
:message="`${assetTargetUser.nickname}(${assetTargetUser.account})`"
:description="getShopDisplay(assetTargetUser) ? `所属店铺:${getShopDisplay(assetTargetUser)}` : '未绑定店铺'"
type="info"
show-icon
style="margin-bottom: 16px"
/>
<a-row :gutter="16" class="asset-summary">
<a-col :span="8">
<a-card size="small" title="当前余额">
<div class="summary-value">¥{{ formatMoney(assetData?.balance) }}</div>
<div class="summary-sub">累计充值:¥{{ formatMoney(assetData?.totalRechargeAmount) }}</div>
</a-card>
</a-col>
<a-col :span="8">
<a-card size="small" title="VIP 状态">
<div class="summary-value">{{ assetData?.vipLevel || '普通' }}</div>
<div class="summary-sub">
{{ assetData?.manualOverride ? '当前为手工指定' : '当前按累计充值自动判级' }}
</div>
</a-card>
</a-col>
<a-col :span="8">
<a-card size="small" title="最近充值">
<div class="summary-value">{{ formatDate(assetData?.lastRechargeTime) }}</div>
<div class="summary-sub">权益说明:{{ assetData?.benefitInfo || '-' }}</div>
</a-card>
</a-col>
</a-row>
<a-row :gutter="16" class="asset-actions">
<a-col :span="12">
<a-card size="small" title="余额变动">
<DraftActions
:saved-at="balanceDraftSavedAt"
@save="handleSaveBalanceDraft"
@clear="handleClearBalanceDraft"
/>
<a-form layout="vertical">
<a-form-item label="变动场景">
<a-select v-model:value="balanceForm.changeScene">
<a-select-option value="RECHARGE">充值</a-select-option>
<a-select-option value="MANUAL_ADD">手工增加余额</a-select-option>
<a-select-option value="MANUAL_DEDUCT">手工扣减余额</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="变动金额">
<a-input-number
v-model:value="balanceForm.amount"
:min="0.01"
:precision="2"
style="width: 100%"
placeholder="请输入金额"
/>
</a-form-item>
<a-form-item label="关联系统订单 ID(可选)">
<a-input-number
v-model:value="balanceForm.relatedOrderId"
:min="1"
:precision="0"
style="width: 100%"
placeholder="如有系统订单可填写"
/>
</a-form-item>
<a-form-item label="外部单号(扣减时二选一)">
<a-input
v-model:value="balanceForm.externalOrderNo"
placeholder="没有系统订单时请填写外部单号"
/>
</a-form-item>
<a-form-item label="备注">
<a-textarea
v-model:value="balanceForm.remark"
:rows="3"
placeholder="请输入备注"
/>
</a-form-item>
<a-button
v-if="hasPermission('user:balance:manage')"
type="primary"
:loading="assetSaving"
@click="handleBalanceChange"
>
提交余额变动
</a-button>
<a-typography-text v-else type="secondary">
当前账号只有查看权限,不能调整余额。
</a-typography-text>
</a-form>
</a-card>
</a-col>
<a-col :span="12">
<a-card size="small" title="VIP 管理">
<DraftActions
:saved-at="vipDraftSavedAt"
@save="handleSaveVipDraft"
@clear="handleClearVipDraft"
/>
<a-form layout="vertical">
<a-form-item label="目标等级">
<a-select v-model:value="vipForm.vipLevel">
<a-select-option v-for="level in vipLevelOptions" :key="level" :value="level">{{ level }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="备注">
<a-textarea
v-model:value="vipForm.remark"
:rows="3"
placeholder="可填写手工调整原因"
/>
</a-form-item>
<a-space>
<a-button
v-if="hasPermission('user:vip:manage')"
type="primary"
:loading="assetSaving"
@click="handleVipOverride"
>
手工设置 VIP
</a-button>
<a-button
v-if="hasPermission('user:vip:manage')"
:loading="assetSaving"
@click="handleVipRecalculate"
>
恢复自动判级
</a-button>
</a-space>
<div class="vip-note">
{{ assetData?.manualOverride ? '当前处于手工指定状态。' : '当前按累计充值自动判级。' }}
</div>
</a-form>
</a-card>
</a-col>
</a-row>
<a-card size="small" title="余额流水" class="history-card">
<a-table
:columns="historyColumns"
:data-source="balanceHistory"
:pagination="false"
size="small"
row-key="id"
:scroll="{ x: 'max-content', y: 320 }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'amount'">
<span :class="Number(record.amount) >= 0 ? 'amount-plus' : 'amount-minus'">
{{ Number(record.amount) >= 0 ? '+' : '' }}{{ formatMoney(record.amount) }}
</span>
</template>
<template v-else-if="column.key === 'changeScene'">
{{ getSceneText(record.changeScene) }}
</template>
<template v-else-if="column.key === 'balanceRange'">
{{ formatMoney(record.beforeBalance) }} -> {{ formatMoney(record.afterBalance) }}
</template>
<template v-else-if="column.key === 'relatedOrder'">
{{ record.relatedOrderNo || record.externalOrderNo || '-' }}
</template>
<template v-else-if="column.key === 'changeTime'">
{{ formatDate(record.changeTime) }}
</template>
</template>
</a-table>
</a-card>
</div>
</a-spin>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && canCreateUser && !modalVisible && !viewModalVisible && !assetModalVisible"
label="新增店长"
@@ -1,189 +0,0 @@
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>VIP 充值配置</h2>
<p>这里只配置展示档位,不会创建支付订单或修改余额。</p>
</div>
<a-button type="primary" @click="openCreate">新增档位</a-button>
</div>
<a-table :columns="columns" :data-source="plans" :loading="loading" row-key="id" :scroll="{ x: 'max-content' }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'amount'">
充 {{ money(record.rechargeAmount) }} 送 {{ money(record.giftAmount) }}
</template>
<template v-else-if="column.key === 'status'">
<a-switch :checked="record.status === 1" @change="(checked: any) => toggleStatus(record as VipRechargePlanVO, Boolean(checked))" />
</template>
<template v-else-if="column.key === 'action'">
<a-button size="small" @click="openEdit(record as VipRechargePlanVO)">编辑</a-button>
</template>
</template>
</a-table>
<a-modal v-model:open="formOpen" :title="editingId ? '编辑档位' : '新增档位'" :mask-closable="false" @ok="submit" :confirm-loading="saving">
<a-form layout="vertical">
<a-form-item label="所属店铺">
<a-select v-model:value="form.shopId" :options="shopOptions" allow-clear placeholder="店长默认当前店铺" />
</a-form-item>
<a-form-item label="标题">
<a-input v-model:value="form.title" />
</a-form-item>
<a-form-item label="充值金额">
<a-input-number v-model:value="form.rechargeAmount" :min="0" :precision="2" style="width: 100%" />
</a-form-item>
<a-form-item label="赠送金额">
<a-input-number v-model:value="form.giftAmount" :min="0" :precision="2" style="width: 100%" />
</a-form-item>
<a-form-item label="对应 VIP 等级">
<a-input v-model:value="form.vipLevel" placeholder="如 青铜 / 白银 / 黄金,也可以输入自定义等级" />
<div class="level-shortcuts">
<a-tag v-for="level in vipLevelOptions" :key="level" @click="form.vipLevel = level">{{ level }}</a-tag>
</div>
</a-form-item>
<a-form-item label="展示说明">
<a-textarea v-model:value="form.description" :rows="3" />
</a-form-item>
<a-form-item label="排序">
<a-input-number v-model:value="form.sortOrder" style="width: 100%" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* VipRechargePlansView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
/**
* Purpose: Shop supports VipRechargePlansView.vue by holding or executing the shop page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { adminShopApi, adminVipRechargePlanApi, type Shop, type VipRechargePlanVO } from '@/api/admin'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** formOpen is a reactive state variable used by the template and event handlers. */
const formOpen = ref(false)
/**
* Purpose: editingId supports VipRechargePlansView.vue by holding or executing the editing id page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const editingId = ref<any>()
/**
* Purpose: plans supports VipRechargePlansView.vue by holding or executing the plans page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const plans = ref<VipRechargePlanVO[]>([])
/**
* Purpose: shops supports VipRechargePlansView.vue by holding or executing the shops page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shops = ref<Shop[]>([])
/**
* Purpose: vipLevelOptions supports VipRechargePlansView.vue by holding or executing the vip level options page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const vipLevelOptions = ref<string[]>(['普通', '青铜', '白银', '黄金'])
/**
* Purpose: form supports VipRechargePlansView.vue by holding or executing the form page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const form = reactive<any>({ shopId: undefined, title: '', rechargeAmount: 0, giftAmount: 0, vipLevel: '', description: '', sortOrder: 0, status: 1 })
/**
* Purpose: columns supports VipRechargePlansView.vue by holding or executing the columns page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '店铺', dataIndex: 'shopName', key: 'shopName' },
{ title: '金额', key: 'amount' },
{ title: 'VIP 等级', dataIndex: 'vipLevel', key: 'vipLevel' },
{ title: '说明', dataIndex: 'description', key: 'description' },
{ title: '启用', key: 'status', width: 100 },
{ title: '操作', key: 'action', width: 100 }
]
/**
* Purpose: shopOptions supports VipRechargePlansView.vue by holding or executing the shop options page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shopOptions = ref<Array<{ label: string; value: any }>>([])
/** money is a local helper used by this page script. */
const money = (value: number | string) => Number(value || 0).toFixed(2)
/** load is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const load = async () => {
loading.value = true
try {
const [planList, shopList] = await Promise.all([
adminVipRechargePlanApi.listPlans(),
adminShopApi.listAllShops().catch(() => [])
])
plans.value = planList || []
const configuredLevels = Array.from(new Set(plans.value.map(item => item.vipLevel).filter(Boolean)))
vipLevelOptions.value = Array.from(new Set(['普通', '青铜', '白银', '黄金', ...configuredLevels]))
shops.value = shopList || []
shopOptions.value = shops.value.map(item => ({ label: item.shopName, value: item.id }))
} finally {
loading.value = false
}
}
/** resetForm is a local helper used by this page script. */
const resetForm = () => Object.assign(form, { shopId: undefined, title: '', rechargeAmount: 0, giftAmount: 0, vipLevel: '', description: '', sortOrder: 0, status: 1 })
/** openCreate is a local helper used by this page script. */
const openCreate = () => { editingId.value = undefined; resetForm(); formOpen.value = true }
/** openEdit is a local helper used by this page script. */
const openEdit = (record: VipRechargePlanVO) => {
editingId.value = record.id
Object.assign(form, record)
formOpen.value = true
}
/** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submit = async () => {
if (!form.title || !form.vipLevel || Number(form.rechargeAmount) <= 0) {
message.warning('请填写标题、充值金额和 VIP 等级')
return
}
saving.value = true
try {
if (editingId.value) {
await adminVipRechargePlanApi.updatePlan(editingId.value, form)
} else {
await adminVipRechargePlanApi.createPlan(form)
}
message.success('档位已保存')
formOpen.value = false
await load()
} finally {
saving.value = false
}
}
/** toggleStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const toggleStatus = async (record: VipRechargePlanVO, checked: boolean) => {
await adminVipRechargePlanApi.updateStatus(record.id, checked ? 1 : 0)
record.status = checked ? 1 : 0
}
onMounted(load)
</script>
<style scoped>
.admin-page { display: grid; gap: 18px; }
.page-head { display: flex; justify-content: space-between; gap: 16px; align-items: center; }
.page-head h2 { margin: 0 0 4px; }
.page-head p { margin: 0; color: var(--text-secondary); }
.level-shortcuts { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
.level-shortcuts :deep(.ant-tag) { cursor: pointer; }
</style>
@@ -6,7 +6,7 @@ import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
import java.util.List;
/**
* Gateway CORS 配置
@@ -17,11 +17,21 @@ import java.util.Arrays;
@Configuration
public class CorsConfig {
private final CorsProperties corsProperties;
public CorsConfig(CorsProperties corsProperties) {
this.corsProperties = corsProperties;
}
@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*");
List<String> allowedOrigins = corsProperties.getAllowedOrigins();
if (allowedOrigins == null || allowedOrigins.isEmpty()) {
throw new IllegalStateException("jayucloud-salon.security.cors.allowed-origins 未配置,拒绝启动以避免开放跨域");
}
allowedOrigins.forEach(config::addAllowedOrigin);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
@@ -0,0 +1,15 @@
package com.xiaowang.jayucloud.salon.gateway.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Data
@Configuration
@ConfigurationProperties(prefix = "jayucloud-salon.security.cors")
public class CorsProperties {
private List<String> allowedOrigins = new ArrayList<>();
}
@@ -4,6 +4,8 @@ import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* Gateway JWT 校验配置。
*/
@@ -12,9 +14,16 @@ import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "jayucloud-salon.security.jwt")
public class JwtProperties {
private String secret = "jayucloud-salon-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
private String secret;
private String issuer = "jayucloud-salon";
private long clockSkewSeconds = 30;
@PostConstruct
public void validate() {
if (secret == null || secret.trim().length() < 64) {
throw new IllegalStateException("jayucloud-salon.security.jwt.secret 未配置或长度不足 64 位");
}
}
}
@@ -14,8 +14,8 @@ spring:
# 注册到 Nacos 的服务名。
service: jc-salon-gateway
# Nacos 认证信息可由运行环境覆盖。
username: ${NACOS_USERNAME:jayucloud}
password: ${NACOS_PASSWORD:122503wcy....}
username: ${NACOS_USERNAME:}
password: ${NACOS_PASSWORD:}
config:
# Nacos 配置中心与服务发现使用同一运行环境参数。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848}
@@ -28,8 +28,8 @@ spring:
# 所有 Nacos 配置均使用 YAML。
file-extension: yaml
# Nacos 认证信息可由运行环境覆盖。
username: ${NACOS_USERNAME:jayucloud}
password: ${NACOS_PASSWORD:122503wcy....}
username: ${NACOS_USERNAME:}
password: ${NACOS_PASSWORD:}
# Core 与 Gateway 共享的公共配置文件。
shared-configs:
- data-id: infra.yaml
@@ -12,12 +12,6 @@ spring:
- Path=/api/product/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: product-like-route
uri: lb://jc-salon-core
predicates:
- Path=/api/product-like/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: shop-route
uri: lb://jc-salon-core
predicates:
@@ -36,12 +30,6 @@ spring:
- Path=/api/comment/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: balance-route
uri: lb://jc-salon-core
predicates:
- Path=/api/balance/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: tag-route
uri: lb://jc-salon-core
predicates:
@@ -60,30 +48,12 @@ spring:
- Path=/api/permission/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: coupon-route
uri: lb://jc-salon-core
predicates:
- Path=/api/coupon/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: cart-route
uri: lb://jc-salon-core
predicates:
- Path=/api/cart/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: order-route
uri: lb://jc-salon-core
predicates:
- Path=/api/order/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: wishlist-route
uri: lb://jc-salon-core
predicates:
- Path=/api/wishlist/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: nail-artist-route
uri: lb://jc-salon-core
predicates:
@@ -131,6 +101,12 @@ jayucloud-salon:
jwt:
issuer: jayucloud-salon
clock-skew-seconds: 30
cors:
allowed-origins:
- http://localhost:5173
- http://127.0.0.1:5173
- http://localhost:4173
- http://127.0.0.1:4173
gateway:
whitelist:
- /api/user/login
@@ -9,12 +9,6 @@ spring:
- Path=/api/product/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: product-like-route
uri: lb://jc-salon-core
predicates:
- Path=/api/product-like/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: shop-route
uri: lb://jc-salon-core
predicates:
@@ -33,12 +27,6 @@ spring:
- Path=/api/comment/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: balance-route
uri: lb://jc-salon-core
predicates:
- Path=/api/balance/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: tag-route
uri: lb://jc-salon-core
predicates:
@@ -57,30 +45,12 @@ spring:
- Path=/api/permission/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: coupon-route
uri: lb://jc-salon-core
predicates:
- Path=/api/coupon/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: cart-route
uri: lb://jc-salon-core
predicates:
- Path=/api/cart/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: order-route
uri: lb://jc-salon-core
predicates:
- Path=/api/order/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: wishlist-route
uri: lb://jc-salon-core
predicates:
- Path=/api/wishlist/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: nail-artist-route
uri: lb://jc-salon-core
predicates:
@@ -128,6 +98,9 @@ jayucloud-salon:
jwt:
issuer: jayucloud-salon
clock-skew-seconds: 30
cors:
allowed-origins:
- https://salon.yunail.art
gateway:
whitelist:
- /api/user/login
@@ -9,12 +9,6 @@ spring:
- Path=/api/product/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: product-like-route
uri: lb://jc-salon-core
predicates:
- Path=/api/product-like/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: shop-route
uri: lb://jc-salon-core
predicates:
@@ -33,12 +27,6 @@ spring:
- Path=/api/comment/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: balance-route
uri: lb://jc-salon-core
predicates:
- Path=/api/balance/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: tag-route
uri: lb://jc-salon-core
predicates:
@@ -57,30 +45,12 @@ spring:
- Path=/api/permission/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: coupon-route
uri: lb://jc-salon-core
predicates:
- Path=/api/coupon/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: cart-route
uri: lb://jc-salon-core
predicates:
- Path=/api/cart/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: order-route
uri: lb://jc-salon-core
predicates:
- Path=/api/order/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: wishlist-route
uri: lb://jc-salon-core
predicates:
- Path=/api/wishlist/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: nail-artist-route
uri: lb://jc-salon-core
predicates:
@@ -128,6 +98,9 @@ jayucloud-salon:
jwt:
issuer: jayucloud-salon
clock-skew-seconds: 30
cors:
allowed-origins:
- https://sit.salon.yunail.art
gateway:
whitelist:
- /api/user/login