优惠券相关管理功能实现

This commit is contained in:
xiaowang
2026-02-27 11:05:15 +08:00
parent 3e591b953b
commit 244e761fd2
22 changed files with 1831 additions and 27 deletions
+11 -2
View File
@@ -375,8 +375,17 @@ export const adminArtistApi = {
export const adminCouponApi = {
listAllCoupons: () => {
return adminApi.get<any[]>('/coupon/list/all')
return adminApi.get<any[]>('/coupon/list', { params: { page: 1, size: 100 } })
},
createCoupon: (data: any) => {
return adminApi.post('/coupon/create', data)
},
updateCoupon: (id: number, data: any) => {
return adminApi.put(`/coupon/update/${id}`, data)
},
deleteCoupon: (id: number) => {
return adminApi.delete(`/coupon/delete/${id}`)
}
}
export default adminApi
export default adminApi
+145
View File
@@ -0,0 +1,145 @@
import request from './index'
export interface Coupon {
id: number
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
availableTags: Tag[]
unavailableTags: Tag[]
}
export interface Tag {
id: number
tagName?: string
}
export interface UserCoupon {
id: number
couponId: number
couponName: string
couponType: number
couponTypeName: string
discountValue: string
minAmount: string
reduceAmount: string
startTime: string
endTime: string
status: number
statusName: string
obtainTime: string
useTime: string
}
export interface CreateCouponRequest {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime: string
endTime: string
availableTagIds: number[]
unavailableTagIds: number[]
}
export interface CouponListResponse {
list: Coupon[]
total: number
page: number
size: number
}
export const couponApi = {
// 创建优惠券
createCoupon: (data: CreateCouponRequest) => {
return request({
url: '/coupon/create',
method: 'post',
data
})
},
// 更新优惠券
updateCoupon: (id: number, data: CreateCouponRequest) => {
return request({
url: `/coupon/update/${id}`,
method: 'put',
data
})
},
// 删除优惠券
deleteCoupon: (id: number) => {
return request({
url: `/coupon/delete/${id}`,
method: 'delete'
})
},
// 获取优惠券详情
getCouponById: (id: number) => {
return request({
url: `/coupon/detail/${id}`,
method: 'get'
})
},
// 获取优惠券列表
listCoupons: (params: { page: number; size: number; shopId?: number }) => {
return request({
url: '/coupon/list',
method: 'get',
params
})
},
// 为用户分配优惠券
assignCouponToUser: (userId: number, couponId: number) => {
return request({
url: '/coupon/assign',
method: 'post',
params: { userId, couponId }
})
},
// 获取用户优惠券列表
listUserCoupons: (status?: number) => {
return request({
url: '/coupon/user/list',
method: 'get',
params: { status }
})
},
// 使用优惠券
useCoupon: (userCouponId: number) => {
return request({
url: '/coupon/use',
method: 'post',
params: { userCouponId }
})
},
// 获取商品可用的优惠券
getAvailableCoupons: (productTags: string, productPrice: number) => {
return request({
url: '/coupon/available',
method: 'get',
params: { productTags, productPrice }
})
}
}
+35 -15
View File
@@ -43,7 +43,7 @@ const router = createRouter({
path: '/shop/:id',
name: 'shop-detail',
component: () => import('../views/ShopDetailView.vue'),
meta: { requiresAuth: true, isAdmin: false }
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/wishlist',
@@ -148,15 +148,26 @@ router.beforeEach((to, _from, next) => {
const userPermissionsStr = localStorage.getItem('userPermissions')
console.log('User permissions:', userPermissionsStr)
if (userPermissionsStr) {
const userPermissions = JSON.parse(userPermissionsStr)
// 检查用户是否拥有该权限
if (userPermissions.includes(permissionCode)) {
console.log('User has required permission:', permissionCode)
next()
} else {
console.log('User missing required permission:', permissionCode)
// 权限不足,重定向到首页
next('/admin')
try {
const userPermissions = JSON.parse(userPermissionsStr)
// 检查用户是否拥有该权限
if (userPermissions.includes(permissionCode)) {
console.log('User has required permission:', permissionCode)
next()
} else {
console.log('User missing required permission:', permissionCode)
// 权限不足,重定向到首页
next('/admin')
}
} catch (parseError) {
console.error('Failed to parse user permissions:', parseError)
// 解析失败,允许访问首页临时,直到权限加载完成
if (to.path === '/admin') {
console.log('Allowing access to home due to parse error')
next()
} else {
next('/admin')
}
}
} else {
console.log('No user permissions found')
@@ -171,9 +182,13 @@ router.beforeEach((to, _from, next) => {
}
} catch (parseError) {
console.error('Failed to parse user info:', parseError)
// 解析失败,允许访问所有页面临时,直到权限加载完成
console.log('Allowing temporary access due to parse error')
next()
// 解析失败,允许访问首页临时,直到权限加载完成
if (to.path === '/admin') {
console.log('Allowing access to home due to parse error')
next()
} else {
next('/admin')
}
}
} else {
console.log('No user info found, redirecting to login')
@@ -182,8 +197,13 @@ router.beforeEach((to, _from, next) => {
}
} catch (error) {
console.error('解析用户信息失败:', error)
// 解析失败,重定向到登录页
next('/admin/login')
// 解析失败,允许访问首页临时,直到权限加载完成
if (to.path === '/admin') {
console.log('Allowing access to home due to error')
next()
} else {
next('/admin')
}
}
} else {
// 没有权限要求,直接通过
+4 -4
View File
@@ -242,15 +242,15 @@ const handleEditProfile = () => {
const beforeUploadAvatar: UploadProps['beforeUpload'] = (file) => {
const isImage = file.type.startsWith('image/')
const isLt2M = file.size / 1024 / 1024 < 2
const isLt20M = file.size / 1024 / 1024 < 20
if (!isImage) {
message.error('只能上传图片文件!')
}
if (!isLt2M) {
message.error('图片大小不能超过 2MB!')
if (!isLt20M) {
message.error('图片大小不能超过 20MB!')
}
return isImage && isLt2M
return isImage && isLt20M
}
const handleAvatarUpload = async (options: any) => {
+385
View File
@@ -0,0 +1,385 @@
<template>
<div class="coupons">
<a-page-header title="优惠券管理" sub-title="管理系统优惠券" />
<a-card :bordered="false">
<template #extra>
<a-space>
<a-input-search
v-model:value="searchText"
placeholder="搜索优惠券名称或编码"
style="width: 250px"
@search="handleSearch"
/>
<a-button v-if="hasPermission('coupon:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增优惠券
</a-button>
</a-space>
</template>
<a-table
:columns="columns"
:data-source="couponList"
:loading="loading"
:pagination="pagination"
@change="handleTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'couponType'">
<a-tag :color="record.couponType === 1 ? 'blue' : 'green'">
{{ record.couponTypeName }}
</a-tag>
</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)">
{{ record.statusName }}
</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('coupon:edit')" type="link" size="small" @click="showEditModal(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>
</a-card>
<a-modal
v-model:open="modalVisible"
:title="isEdit ? '编辑优惠券' : '新增优惠券'"
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
width="800px"
>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券编码" name="couponCode">
<a-input v-model:value="formState.couponCode" placeholder="请输入优惠券编码" />
</a-form-item>
<a-form-item label="优惠券名称" name="couponName">
<a-input v-model:value="formState.couponName" placeholder="请输入优惠券名称" />
</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 v-if="formState.couponType === 1" label="折扣值" name="discountValue">
<a-input-number v-model:value="formState.discountValue" placeholder="请输入折扣值(如9.5表示95折)" :min="0.1" :max="9.9" :step="0.1" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="最低消费" name="minAmount">
<a-input-number v-model:value="formState.minAmount" placeholder="请输入最低消费金额" :min="0" :step="0.01" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="减免金额" name="reduceAmount">
<a-input-number v-model:value="formState.reduceAmount" placeholder="请输入减免金额" :min="0" :step="0.01" />
</a-form-item>
<a-form-item label="总数量" name="totalCount">
<a-input-number v-model:value="formState.totalCount" placeholder="请输入优惠券总数量" :min="1" />
</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" 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" style="width: 100%" />
</a-form-item>
<a-form-item label="可用标签" name="availableTagIds">
<a-select
v-model:value="formState.availableTagIds"
mode="multiple"
placeholder="请选择可用标签"
style="width: 100%"
>
<a-select-option v-for="tag in tagList" :key="tag.id" :value="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="请选择不可用标签"
style="width: 100%"
>
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { adminCouponApi, adminTagApi } from '@/api/admin'
import type { Coupon } from '@/api/coupon'
interface CreateCouponRequest {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime: string
endTime: string
availableTagIds: number[]
unavailableTagIds: number[]
}
interface TagVO {
id: number
tagName: string
textColor: string
bgColor: string
borderColor: string
shopId: number
createTime: string
updateTime: string
}
import { usePermission } from '@/utils/permission'
const { hasPermission, loadUserPermissions } = usePermission()
const loading = ref(false)
const modalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const searchText = ref('')
const formRef = ref<FormInstance>()
const currentCoupon = ref<Coupon | null>(null)
const couponList = ref<Coupon[]>([])
const tagList = ref<TagVO[]>([])
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive({
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: new Date(),
endTime: new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000),
availableTagIds: [] as number[],
unavailableTagIds: [] as number[]
})
const formRules = {
couponCode: [{ required: true, message: '请输入优惠券编码', trigger: 'blur' }],
couponName: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
couponType: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
discountValue: [{ required: formState.couponType === 1, message: '请输入折扣值', trigger: 'blur' }],
minAmount: [{ required: formState.couponType === 2, message: '请输入最低消费金额', trigger: 'blur' }],
reduceAmount: [{ required: formState.couponType === 2, message: '请输入减免金额', trigger: 'blur' }],
totalCount: [{ required: true, message: '请输入优惠券总数量', trigger: 'blur' }],
startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}
const columns = [
{ title: '优惠券编码', dataIndex: 'couponCode', key: 'couponCode' },
{ title: '优惠券名称', dataIndex: 'couponName', key: 'couponName' },
{ title: '类型', key: 'couponType', width: 100 },
{ title: '优惠信息', key: 'value', width: 150 },
{ title: '总数量', dataIndex: 'totalCount', key: 'totalCount', width: 100 },
{ title: '已使用', dataIndex: 'usedCount', key: 'usedCount', width: 100 },
{ title: '剩余', dataIndex: 'remainingCount', key: 'remainingCount', width: 100 },
{ title: '开始时间', dataIndex: 'startTime', key: 'startTime' },
{ title: '结束时间', dataIndex: 'endTime', key: 'endTime' },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
const getStatusColor = (status: number) => {
switch (status) {
case 1:
return 'green'
case 2:
return 'red'
case 3:
return 'orange'
default:
return 'default'
}
}
const fetchCoupons = async () => {
loading.value = true
try {
const res = await adminCouponApi.listAllCoupons()
couponList.value = res || []
pagination.total = res.length || 0
} catch (error) {
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
const fetchTags = async () => {
try {
const res = await adminTagApi.listAllTags()
tagList.value = res || []
} catch (error) {
console.error('获取标签列表失败:', error)
}
}
const handleSearch = () => {
pagination.current = 1
fetchCoupons()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
fetchCoupons()
}
const showAddModal = () => {
isEdit.value = false
Object.assign(formState, {
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: undefined,
endTime: undefined,
availableTagIds: [],
unavailableTagIds: []
})
modalVisible.value = true
}
const showEditModal = (record: Coupon) => {
isEdit.value = true
currentCoupon.value = record
Object.assign(formState, {
couponCode: record.couponCode,
couponName: record.couponName,
couponType: record.couponType,
discountValue: record.discountValue,
minAmount: record.minAmount,
reduceAmount: record.reduceAmount,
totalCount: record.totalCount,
startTime: undefined,
endTime: undefined,
availableTagIds: record.availableTags.map(tag => tag.id),
unavailableTagIds: record.unavailableTags.map(tag => tag.id)
})
modalVisible.value = true
}
const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
const requestData: CreateCouponRequest = {
couponCode: formState.couponCode,
couponName: formState.couponName,
couponType: formState.couponType,
discountValue: formState.discountValue,
minAmount: formState.minAmount,
reduceAmount: formState.reduceAmount,
totalCount: formState.totalCount,
startTime: formState.startTime.toISOString(),
endTime: formState.endTime.toISOString(),
availableTagIds: formState.availableTagIds,
unavailableTagIds: formState.unavailableTagIds
}
if (isEdit.value && currentCoupon.value) {
await adminCouponApi.updateCoupon(currentCoupon.value.id, requestData)
message.success('更新成功')
} else {
await adminCouponApi.createCoupon(requestData)
message.success('创建成功')
}
modalVisible.value = false
fetchCoupons()
} catch (error) {
console.error(error)
} finally {
modalLoading.value = false
}
}
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
}
const handleDelete = (record: Coupon) => {
message.confirm({
title: '确认删除',
content: `确定要删除优惠券 ${record.couponName} 吗?`,
onOk: async () => {
try {
await adminCouponApi.deleteCoupon(record.id)
message.success('删除成功')
fetchCoupons()
} catch (error) {
message.error('删除失败')
}
}
})
}
onMounted(async () => {
await loadUserPermissions()
await fetchTags()
await fetchCoupons()
})
</script>
<style scoped>
.coupons {
padding: 0;
}
</style>
+3 -3
View File
@@ -227,10 +227,10 @@
</a-select-option>
<a-select-option
v-for="coupon in coupons"
:key="coupon.id"
:value="coupon.id.toString()"
:key="coupon?.id"
:value="coupon?.id?.toString()"
>
{{ coupon.couponName }}
{{ coupon?.couponName || '' }}
</a-select-option>
</a-select>
</a-form-item>
+19 -2
View File
@@ -274,9 +274,26 @@ const fetchUserList = async () => {
params.shopId = currentUserInfo.shopId
}
// 后端只支持单个type参数,所以这里不设置类型过滤
// 依赖前端的二次过滤来确保只显示级别比当前用户低的用户
const res = await userApi.listUsers(params)
userList.value = res.list || []
pagination.total = res.total || 0
// 前端再次过滤,确保只显示级别比当前用户低的用户
let filteredList = res.list || []
if (currentUserInfo && currentUserInfo.type !== 4) {
filteredList = filteredList.filter(user => {
if (currentUserInfo.type === 2) {
// 店长可以看到美甲师(3)和用户(0)
return user.type === 3 || user.type === 0
} else if (currentUserInfo.type === 3) {
// 美甲师只能看到用户(0)
return user.type === 0
}
return true
})
}
userList.value = filteredList
pagination.total = filteredList.length || 0
} catch (error) {
message.error('获取用户列表失败')
} finally {
@@ -0,0 +1,111 @@
package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.CouponDTO;
import com.xiaowang.yuminailcore.service.CouponService;
import com.xiaowang.yuminailcore.vo.CouponVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.UserCouponVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 优惠券控制器
*/
@RestController
@RequestMapping("/coupon")
@RequiredArgsConstructor
public class CouponController {
private final CouponService couponService;
/**
* 创建优惠券
*/
@PostMapping("/create")
@RequirePermission("coupon:create")
public Result<Long> createCoupon(@RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
Long couponId = couponService.createCoupon(couponDTO, shopId);
return Result.success(couponId);
}
/**
* 更新优惠券
*/
@PutMapping("/update/{id}")
@RequirePermission("coupon:edit")
public Result<Boolean> updateCoupon(@PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
return Result.success(success);
}
/**
* 删除优惠券
*/
@DeleteMapping("/delete/{id}")
@RequirePermission("coupon:delete")
public Result<Boolean> deleteCoupon(@PathVariable Long id, @RequestParam(required = false) Long shopId) {
boolean success = couponService.deleteCoupon(id, shopId);
return Result.success(success);
}
/**
* 获取优惠券详情
*/
@GetMapping("/detail/{id}")
@RequirePermission("coupon:view")
public Result<CouponVO> getCouponById(@PathVariable Long id) {
CouponVO couponVO = couponService.getCouponById(id);
return Result.success(couponVO);
}
/**
* 获取优惠券列表
*/
@GetMapping("/list")
@RequirePermission("coupon:view")
public Result<PageResultVO<CouponVO>> listCoupons(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
PageResultVO<CouponVO> pageResult = couponService.listCoupons(page, size, shopId);
return Result.success(pageResult);
}
/**
* 为用户分配优惠券
*/
@PostMapping("/assign")
@RequirePermission("coupon:assign")
public Result<Boolean> assignCouponToUser(@RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
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 String productTags, @RequestParam Double productPrice, @RequestAttribute("userId") Long userId) {
List<UserCouponVO> availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice);
return Result.success(availableCoupons);
}
}
@@ -17,7 +17,7 @@ import java.util.List;
* @date 2026-02-13
*/
@RestController
@RequestMapping("/api/tag")
@RequestMapping("/tag")
@RequiredArgsConstructor
public class TagController {
@@ -0,0 +1,69 @@
package com.xiaowang.yuminailcore.dto;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 优惠券DTO
*/
@Data
public class CouponDTO {
/**
* 优惠券编码
*/
private String couponCode;
/**
* 优惠券名称
*/
private String couponName;
/**
* 优惠券类型:1-折扣券,2-满减券
*/
private Integer couponType;
/**
* 折扣值(如9.5表示95折)
*/
private BigDecimal discountValue;
/**
* 满减券最低消费金额
*/
private BigDecimal minAmount;
/**
* 满减券减免金额
*/
private BigDecimal reduceAmount;
/**
* 优惠券总数量
*/
private Integer totalCount;
/**
* 开始时间
*/
private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime;
/**
* 可用标签ID列表
*/
private List<Long> availableTagIds;
/**
* 不可用标签ID列表
*/
private List<Long> unavailableTagIds;
}
@@ -0,0 +1,81 @@
package com.xiaowang.yuminailcore.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 优惠券信息表
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_coupon")
public class CouponDO extends BaseEntity {
/**
* 优惠券编码
*/
private String couponCode;
/**
* 优惠券名称
*/
private String couponName;
/**
* 优惠券类型:1-折扣券,2-满减券
*/
private Integer couponType;
/**
* 折扣值(如9.5表示95折)
*/
private BigDecimal discountValue;
/**
* 满减券最低消费金额
*/
private BigDecimal minAmount;
/**
* 满减券减免金额
*/
private BigDecimal reduceAmount;
/**
* 优惠券总数量
*/
private Integer totalCount;
/**
* 已使用数量
*/
private Integer usedCount;
/**
* 开始时间
*/
private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime;
/**
* 状态:1-可用,2-已过期,3-已用完
*/
private Integer status;
/**
* 逻辑删除:0-未删,1-已删
*/
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,38 @@
package com.xiaowang.yuminailcore.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 优惠券标签关联表
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_coupon_tag")
public class CouponTagDO extends BaseEntity {
/**
* 关联优惠券表主键
*/
private Long couponId;
/**
* 关联标签表主键
*/
private Long tagId;
/**
* 是否可用:1-可用,0-不可用
*/
private Integer isAvailable;
/**
* 逻辑删除:0-未删,1-已删
*/
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,50 @@
package com.xiaowang.yuminailcore.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 用户优惠券关联表
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_user_coupon")
public class UserCouponDO extends BaseEntity {
/**
* 关联用户表主键
*/
private Long userId;
/**
* 关联优惠券表主键
*/
private Long couponId;
/**
* 状态:1-未使用,2-已使用,3-已过期
*/
private Integer status;
/**
* 获取时间
*/
private LocalDateTime obtainTime;
/**
* 使用时间
*/
private LocalDateTime useTime;
/**
* 逻辑删除:0-未删,1-已删
*/
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,12 @@
package com.xiaowang.yuminailcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.entity.CouponDO;
import org.apache.ibatis.annotations.Mapper;
/**
* 优惠券Mapper
*/
@Mapper
public interface CouponMapper extends BaseMapper<CouponDO> {
}
@@ -0,0 +1,12 @@
package com.xiaowang.yuminailcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.entity.CouponTagDO;
import org.apache.ibatis.annotations.Mapper;
/**
* 优惠券标签关联Mapper
*/
@Mapper
public interface CouponTagMapper extends BaseMapper<CouponTagDO> {
}
@@ -0,0 +1,12 @@
package com.xiaowang.yuminailcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.entity.UserCouponDO;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户优惠券Mapper
*/
@Mapper
public interface UserCouponMapper extends BaseMapper<UserCouponDO> {
}
@@ -0,0 +1,91 @@
package com.xiaowang.yuminailcore.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaowang.yuminailcore.dto.CouponDTO;
import com.xiaowang.yuminailcore.entity.CouponDO;
import com.xiaowang.yuminailcore.vo.CouponVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.UserCouponVO;
import java.util.List;
/**
* 优惠券服务
*/
public interface CouponService extends IService<CouponDO> {
/**
* 创建优惠券
* @param couponDTO 优惠券DTO
* @param shopId 店铺ID
* @return 优惠券ID
*/
Long createCoupon(CouponDTO couponDTO, Long shopId);
/**
* 更新优惠券
* @param id 优惠券ID
* @param couponDTO 优惠券DTO
* @param shopId 店铺ID
* @return 是否成功
*/
boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId);
/**
* 删除优惠券
* @param id 优惠券ID
* @param shopId 店铺ID
* @return 是否成功
*/
boolean deleteCoupon(Long id, Long shopId);
/**
* 获取优惠券详情
* @param id 优惠券ID
* @return 优惠券VO
*/
CouponVO getCouponById(Long id);
/**
* 获取优惠券列表
* @param page 页码
* @param size 每页大小
* @param shopId 店铺ID
* @return 分页结果
*/
PageResultVO<CouponVO> listCoupons(Integer page, Integer size, Long shopId);
/**
* 为用户分配优惠券
* @param userId 用户ID
* @param couponId 优惠券ID
* @param shopId 店铺ID
* @return 是否成功
*/
boolean assignCouponToUser(Long userId, Long couponId, Long shopId);
/**
* 获取用户优惠券列表
* @param userId 用户ID
* @param status 状态
* @return 用户优惠券列表
*/
List<UserCouponVO> listUserCoupons(Long userId, Integer status);
/**
* 使用优惠券
* @param userCouponId 用户优惠券ID
* @param userId 用户ID
* @return 是否成功
*/
boolean useCoupon(Long userCouponId, Long userId);
/**
* 获取商品可用的优惠券
* @param userId 用户ID
* @param productTags 商品标签
* @param productPrice 商品价格
* @return 可用优惠券列表
*/
List<UserCouponVO> getAvailableCoupons(Long userId, String productTags, Double productPrice);
}
@@ -0,0 +1,452 @@
package com.xiaowang.yuminailcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcore.dto.CouponDTO;
import com.xiaowang.yuminailcore.entity.CouponDO;
import com.xiaowang.yuminailcore.entity.CouponTagDO;
import com.xiaowang.yuminailcore.entity.TagDO;
import com.xiaowang.yuminailcore.entity.UserCouponDO;
import com.xiaowang.yuminailcore.mapper.CouponMapper;
import com.xiaowang.yuminailcore.mapper.CouponTagMapper;
import com.xiaowang.yuminailcore.mapper.TagMapper;
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
import com.xiaowang.yuminailcore.service.CouponService;
import com.xiaowang.yuminailcore.vo.CouponVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.TagVO;
import com.xiaowang.yuminailcore.vo.UserCouponVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 优惠券服务实现
*/
@Service
@RequiredArgsConstructor
public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> implements CouponService {
private final CouponTagMapper couponTagMapper;
private final UserCouponMapper userCouponMapper;
private final TagMapper tagMapper;
@Override
@Transactional
public Long createCoupon(CouponDTO couponDTO, Long shopId) {
// 创建优惠券
CouponDO couponDO = new CouponDO();
couponDO.setCouponCode(couponDTO.getCouponCode());
couponDO.setCouponName(couponDTO.getCouponName());
couponDO.setCouponType(couponDTO.getCouponType());
couponDO.setDiscountValue(couponDTO.getDiscountValue());
couponDO.setMinAmount(couponDTO.getMinAmount());
couponDO.setReduceAmount(couponDTO.getReduceAmount());
couponDO.setTotalCount(couponDTO.getTotalCount());
couponDO.setUsedCount(0);
couponDO.setStartTime(couponDTO.getStartTime());
couponDO.setEndTime(couponDTO.getEndTime());
couponDO.setStatus(1);
save(couponDO);
// 处理标签关联
handleCouponTags(couponDO.getId(), couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds());
return couponDO.getId();
}
@Override
@Transactional
public boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId) {
// 更新优惠券
CouponDO couponDO = getById(id);
if (couponDO == null) {
return false;
}
couponDO.setCouponCode(couponDTO.getCouponCode());
couponDO.setCouponName(couponDTO.getCouponName());
couponDO.setCouponType(couponDTO.getCouponType());
couponDO.setDiscountValue(couponDTO.getDiscountValue());
couponDO.setMinAmount(couponDTO.getMinAmount());
couponDO.setReduceAmount(couponDTO.getReduceAmount());
couponDO.setTotalCount(couponDTO.getTotalCount());
couponDO.setStartTime(couponDTO.getStartTime());
couponDO.setEndTime(couponDTO.getEndTime());
updateById(couponDO);
// 处理标签关联
handleCouponTags(id, couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds());
return true;
}
@Override
@Transactional
public boolean deleteCoupon(Long id, Long shopId) {
// 删除优惠券
CouponDO couponDO = getById(id);
if (couponDO == null) {
return false;
}
couponDO.setIsDelete(1);
return updateById(couponDO);
}
@Override
public CouponVO getCouponById(Long id) {
CouponDO couponDO = getById(id);
if (couponDO == null || couponDO.getIsDelete() == 1) {
return null;
}
return convertToCouponVO(couponDO);
}
@Override
public PageResultVO<CouponVO> listCoupons(Integer page, Integer size, Long shopId) {
Page<CouponDO> pageInfo = new Page<>(page, size);
IPage<CouponDO> couponPage = page(pageInfo, new LambdaQueryWrapper<CouponDO>()
.eq(CouponDO::getIsDelete, 0)
.orderByDesc(CouponDO::getCreateTime)
);
List<CouponVO> couponVOs = couponPage.getRecords().stream()
.map(this::convertToCouponVO)
.collect(Collectors.toList());
PageResultVO<CouponVO> pageResult = new PageResultVO<>();
pageResult.setList(couponVOs);
pageResult.setTotal(couponPage.getTotal());
pageResult.setPage(page);
pageResult.setSize(size);
return pageResult;
}
@Override
@Transactional
public boolean assignCouponToUser(Long userId, Long couponId, Long shopId) {
// 检查优惠券是否存在
CouponDO couponDO = getById(couponId);
if (couponDO == null || couponDO.getIsDelete() == 1) {
return false;
}
// 检查优惠券是否可用
if (couponDO.getStatus() != 1) {
return false;
}
// 检查是否已经分配
UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper<UserCouponDO>()
.eq(UserCouponDO::getUserId, userId)
.eq(UserCouponDO::getCouponId, couponId)
.eq(UserCouponDO::getIsDelete, 0)
);
if (existing != null) {
return false;
}
// 分配优惠券
UserCouponDO userCouponDO = new UserCouponDO();
userCouponDO.setUserId(userId);
userCouponDO.setCouponId(couponId);
userCouponDO.setStatus(1);
userCouponDO.setObtainTime(LocalDateTime.now());
userCouponMapper.insert(userCouponDO);
return true;
}
@Override
public List<UserCouponVO> listUserCoupons(Long userId, Integer status) {
LambdaQueryWrapper<UserCouponDO> queryWrapper = new LambdaQueryWrapper<UserCouponDO>()
.eq(UserCouponDO::getUserId, userId)
.eq(UserCouponDO::getIsDelete, 0);
if (status != null) {
queryWrapper.eq(UserCouponDO::getStatus, status);
}
List<UserCouponDO> userCouponDOs = userCouponMapper.selectList(queryWrapper);
return userCouponDOs.stream()
.map(this::convertToUserCouponVO)
.collect(Collectors.toList());
}
@Override
@Transactional
public boolean useCoupon(Long userCouponId, Long userId) {
// 检查用户优惠券是否存在
UserCouponDO userCouponDO = userCouponMapper.selectById(userCouponId);
if (userCouponDO == null || userCouponDO.getIsDelete() == 1) {
return false;
}
// 检查是否属于当前用户
if (!userCouponDO.getUserId().equals(userId)) {
return false;
}
// 检查是否未使用
if (userCouponDO.getStatus() != 1) {
return false;
}
// 检查优惠券是否过期
CouponDO couponDO = getById(userCouponDO.getCouponId());
if (couponDO == null || couponDO.getEndTime().isBefore(LocalDateTime.now())) {
return false;
}
// 使用优惠券
userCouponDO.setStatus(2);
userCouponDO.setUseTime(LocalDateTime.now());
userCouponMapper.updateById(userCouponDO);
// 更新优惠券使用数量
couponDO.setUsedCount(couponDO.getUsedCount() + 1);
if (couponDO.getUsedCount() >= couponDO.getTotalCount()) {
couponDO.setStatus(3);
}
updateById(couponDO);
return true;
}
@Override
public List<UserCouponVO> getAvailableCoupons(Long userId, String productTags, Double productPrice) {
// 获取用户未使用的优惠券
List<UserCouponDO> userCouponDOs = userCouponMapper.selectList(new LambdaQueryWrapper<UserCouponDO>()
.eq(UserCouponDO::getUserId, userId)
.eq(UserCouponDO::getStatus, 1)
.eq(UserCouponDO::getIsDelete, 0)
);
List<UserCouponVO> availableCoupons = new ArrayList<>();
LocalDateTime now = LocalDateTime.now();
for (UserCouponDO userCouponDO : userCouponDOs) {
CouponDO couponDO = getById(userCouponDO.getCouponId());
if (couponDO == null || couponDO.getIsDelete() == 1) {
continue;
}
// 检查优惠券是否在有效期内
if (now.isBefore(couponDO.getStartTime()) || now.isAfter(couponDO.getEndTime())) {
continue;
}
// 检查优惠券是否可用
if (couponDO.getStatus() != 1) {
continue;
}
// 检查满减券的最低消费金额
if (couponDO.getCouponType() == 2) {
if (couponDO.getMinAmount().doubleValue() > productPrice) {
continue;
}
}
// 检查标签是否匹配
if (!checkTagMatch(couponDO.getId(), productTags)) {
continue;
}
availableCoupons.add(convertToUserCouponVO(userCouponDO));
}
return availableCoupons;
}
/**
* 处理优惠券标签关联
*/
private void handleCouponTags(Long couponId, List<Long> availableTagIds, List<Long> unavailableTagIds) {
// 删除原有标签关联
couponTagMapper.delete(new LambdaQueryWrapper<CouponTagDO>()
.eq(CouponTagDO::getCouponId, couponId)
);
// 添加可用标签
if (availableTagIds != null) {
for (Long tagId : availableTagIds) {
CouponTagDO couponTagDO = new CouponTagDO();
couponTagDO.setCouponId(couponId);
couponTagDO.setTagId(tagId);
couponTagDO.setIsAvailable(1);
couponTagMapper.insert(couponTagDO);
}
}
// 添加不可用标签
if (unavailableTagIds != null) {
for (Long tagId : unavailableTagIds) {
CouponTagDO couponTagDO = new CouponTagDO();
couponTagDO.setCouponId(couponId);
couponTagDO.setTagId(tagId);
couponTagDO.setIsAvailable(0);
couponTagMapper.insert(couponTagDO);
}
}
}
/**
* 检查标签是否匹配
*/
private boolean checkTagMatch(Long couponId, String productTags) {
if (productTags == null || productTags.isEmpty()) {
return true;
}
// 解析商品标签
String[] tagNames = productTags.split(",");
// 查询所有标签
List<TagDO> allTags = tagMapper.selectList(new LambdaQueryWrapper<>());
// 找到匹配的标签ID
List<Long> productTagIds = allTags.stream()
.filter(tag -> {
for (String tagName : tagNames) {
if (tag.getTagName() != null && tag.getTagName().equals(tagName.trim())) {
return true;
}
}
return false;
})
.map(tag -> tag.getId())
.collect(Collectors.toList());
if (productTagIds.isEmpty()) {
return true;
}
List<CouponTagDO> couponTagDOs = couponTagMapper.selectList(new LambdaQueryWrapper<CouponTagDO>()
.eq(CouponTagDO::getCouponId, couponId)
.in(CouponTagDO::getTagId, productTagIds)
);
// 如果有不可用标签,则返回false
for (CouponTagDO couponTagDO : couponTagDOs) {
if (couponTagDO.getIsAvailable() == 0) {
return false;
}
}
return true;
}
/**
* 转换为CouponVO
*/
private CouponVO convertToCouponVO(CouponDO couponDO) {
CouponVO couponVO = new CouponVO();
couponVO.setId(couponDO.getId());
couponVO.setCouponCode(couponDO.getCouponCode());
couponVO.setCouponName(couponDO.getCouponName());
couponVO.setCouponType(couponDO.getCouponType());
couponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券");
couponVO.setDiscountValue(couponDO.getDiscountValue());
couponVO.setMinAmount(couponDO.getMinAmount());
couponVO.setReduceAmount(couponDO.getReduceAmount());
couponVO.setTotalCount(couponDO.getTotalCount());
couponVO.setUsedCount(couponDO.getUsedCount());
couponVO.setRemainingCount(couponDO.getTotalCount() - couponDO.getUsedCount());
couponVO.setStartTime(couponDO.getStartTime());
couponVO.setEndTime(couponDO.getEndTime());
couponVO.setStatus(couponDO.getStatus());
switch (couponDO.getStatus()) {
case 1:
couponVO.setStatusName("可用");
break;
case 2:
couponVO.setStatusName("已过期");
break;
case 3:
couponVO.setStatusName("已用完");
break;
default:
couponVO.setStatusName("未知");
}
// 获取可用标签
List<TagVO> availableTags = couponTagMapper.selectList(new LambdaQueryWrapper<CouponTagDO>()
.eq(CouponTagDO::getCouponId, couponDO.getId())
.eq(CouponTagDO::getIsAvailable, 1)
).stream()
.map(couponTag -> {
TagVO tagVO = new TagVO();
tagVO.setId(couponTag.getTagId());
return tagVO;
})
.collect(Collectors.toList());
couponVO.setAvailableTags(availableTags);
// 获取不可用标签
List<TagVO> unavailableTags = couponTagMapper.selectList(new LambdaQueryWrapper<CouponTagDO>()
.eq(CouponTagDO::getCouponId, couponDO.getId())
.eq(CouponTagDO::getIsAvailable, 0)
).stream()
.map(couponTag -> {
TagVO tagVO = new TagVO();
tagVO.setId(couponTag.getTagId());
return tagVO;
})
.collect(Collectors.toList());
couponVO.setUnavailableTags(unavailableTags);
return couponVO;
}
/**
* 转换为UserCouponVO
*/
private UserCouponVO convertToUserCouponVO(UserCouponDO userCouponDO) {
UserCouponVO userCouponVO = new UserCouponVO();
userCouponVO.setId(userCouponDO.getId());
userCouponVO.setCouponId(userCouponDO.getCouponId());
CouponDO couponDO = getById(userCouponDO.getCouponId());
if (couponDO != null) {
userCouponVO.setCouponName(couponDO.getCouponName());
userCouponVO.setCouponType(couponDO.getCouponType());
userCouponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券");
userCouponVO.setDiscountValue(couponDO.getDiscountValue() != null ? couponDO.getDiscountValue().toString() : "");
userCouponVO.setMinAmount(couponDO.getMinAmount() != null ? couponDO.getMinAmount().toString() : "");
userCouponVO.setReduceAmount(couponDO.getReduceAmount() != null ? couponDO.getReduceAmount().toString() : "");
userCouponVO.setStartTime(couponDO.getStartTime());
userCouponVO.setEndTime(couponDO.getEndTime());
}
userCouponVO.setStatus(userCouponDO.getStatus());
switch (userCouponDO.getStatus()) {
case 1:
userCouponVO.setStatusName("未使用");
break;
case 2:
userCouponVO.setStatusName("已使用");
break;
case 3:
userCouponVO.setStatusName("已过期");
break;
default:
userCouponVO.setStatusName("未知");
}
userCouponVO.setObtainTime(userCouponDO.getObtainTime());
userCouponVO.setUseTime(userCouponDO.getUseTime());
return userCouponVO;
}
}
@@ -0,0 +1,99 @@
package com.xiaowang.yuminailcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 优惠券VO
*/
@Data
public class CouponVO {
/**
* 优惠券ID
*/
private Long id;
/**
* 优惠券编码
*/
private String couponCode;
/**
* 优惠券名称
*/
private String couponName;
/**
* 优惠券类型:1-折扣券,2-满减券
*/
private Integer couponType;
/**
* 优惠券类型名称
*/
private String couponTypeName;
/**
* 折扣值(如9.5表示95折)
*/
private BigDecimal discountValue;
/**
* 满减券最低消费金额
*/
private BigDecimal minAmount;
/**
* 满减券减免金额
*/
private BigDecimal reduceAmount;
/**
* 优惠券总数量
*/
private Integer totalCount;
/**
* 已使用数量
*/
private Integer usedCount;
/**
* 剩余数量
*/
private Integer remainingCount;
/**
* 开始时间
*/
private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime;
/**
* 状态:1-可用,2-已过期,3-已用完
*/
private Integer status;
/**
* 状态名称
*/
private String statusName;
/**
* 可用标签列表
*/
private List<TagVO> availableTags;
/**
* 不可用标签列表
*/
private List<TagVO> unavailableTags;
}
@@ -0,0 +1,82 @@
package com.xiaowang.yuminailcore.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户优惠券VO
*/
@Data
public class UserCouponVO {
/**
* 关联ID
*/
private Long id;
/**
* 优惠券ID
*/
private Long couponId;
/**
* 优惠券名称
*/
private String couponName;
/**
* 优惠券类型:1-折扣券,2-满减券
*/
private Integer couponType;
/**
* 优惠券类型名称
*/
private String couponTypeName;
/**
* 折扣值(如9.5表示95折)
*/
private String discountValue;
/**
* 满减券最低消费金额
*/
private String minAmount;
/**
* 满减券减免金额
*/
private String reduceAmount;
/**
* 开始时间
*/
private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime;
/**
* 状态:1-未使用,2-已使用,3-已过期
*/
private Integer status;
/**
* 状态名称
*/
private String statusName;
/**
* 获取时间
*/
private LocalDateTime obtainTime;
/**
* 使用时间
*/
private LocalDateTime useTime;
}
@@ -0,0 +1,115 @@
-- 优惠券信息表
create table t_coupon
(
id bigint unsigned auto_increment comment '优惠券唯一主键ID'
primary key comment '优惠券主键索引',
coupon_code varchar(50) not null comment '优惠券编码',
coupon_name varchar(100) not null comment '优惠券名称',
coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券',
discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)',
min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额',
reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额',
total_count int unsigned default 100 not null comment '优惠券总数量',
used_count int unsigned default 0 not null comment '已使用数量',
start_time datetime not null comment '开始时间',
end_time datetime not null comment '结束时间',
status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
constraint uk_coupon_code
unique (coupon_code) comment '优惠券编码唯一索引'
) comment '优惠券信息表';
create index idx_status
on t_coupon (status) comment '按状态查询优惠券的索引';
-- 用户优惠券关联表
create table t_user_coupon
(
id bigint unsigned auto_increment comment '用户优惠券关联唯一主键ID'
primary key comment '用户优惠券关联主键索引',
user_id bigint unsigned not null comment '关联用户表主键',
coupon_id bigint unsigned not null comment '关联优惠券表主键',
status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期',
obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间',
use_time datetime null comment '使用时间',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
constraint uk_user_coupon
unique (user_id, coupon_id) comment '用户-优惠券唯一索引'
) comment '用户优惠券关联表';
create index idx_status
on t_user_coupon (status) comment '按状态查询用户优惠券的索引';
create index idx_user_id
on t_user_coupon (user_id) comment '按用户查询优惠券的索引';
-- 优惠券标签关联表
create table t_coupon_tag
(
id bigint unsigned auto_increment comment '优惠券标签关联唯一主键ID'
primary key comment '优惠券标签关联主键索引',
coupon_id bigint unsigned not null comment '关联优惠券表主键',
tag_id bigint unsigned not null comment '关联标签表主键',
is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
constraint uk_coupon_tag
unique (coupon_id, tag_id) comment '优惠券-标签唯一索引'
) comment '优惠券标签关联表';
create index idx_coupon_id
on t_coupon_tag (coupon_id) comment '按优惠券查询标签的索引';
create index idx_tag_id
on t_coupon_tag (tag_id) comment '按标签查询优惠券的索引';
-- 插入优惠券管理相关权限
INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) VALUES
('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券列表和详情', NOW(), NOW(), 0),
('coupon:create', '新增优惠券', '优惠券管理', '新增优惠券', NOW(), NOW(), 0),
('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券信息', NOW(), NOW(), 0),
('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券', NOW(), NOW(), 0),
('coupon:assign', '分配优惠券', '优惠券管理', '为用户分配优惠券', NOW(), NOW(), 0);
-- 为管理员(type=4)分配优惠券管理权限
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time)
SELECT
u.id as user_id,
p.id as permission_id,
NOW() as create_time,
NOW() as update_time
FROM t_user u
CROSS JOIN t_permission p
WHERE u.type = 4
AND p.is_delete = 0
AND p.permission_code IN (
'coupon:view',
'coupon:create',
'coupon:edit',
'coupon:delete',
'coupon:assign'
);
-- 为店长(type=2)分配优惠券管理权限
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time)
SELECT
u.id as user_id,
p.id as permission_id,
NOW() as create_time,
NOW() as update_time
FROM t_user u
CROSS JOIN t_permission p
WHERE u.type = 2
AND p.is_delete = 0
AND p.permission_code IN (
'coupon:view',
'coupon:create',
'coupon:edit',
'coupon:delete',
'coupon:assign'
);
@@ -38,3 +38,7 @@ spring:
uri: lb://yumi-nail-core
predicates:
- Path=/api/admin/**
- id: coupon-route
uri: lb://yumi-nail-core
predicates:
- Path=/api/coupon/**