988 lines
39 KiB
Vue
988 lines
39 KiB
Vue
<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="fingertip-designer-date-picker-panel fingertip-designer-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="fingertip-designer-date-picker-panel fingertip-designer-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>
|