Files
JayuCloud/YumiNail-Frontend/src/views/admin/OrdersView.vue
T

461 lines
18 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="orders">
<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>
<p class="admin-page-intro__subtitle">
手机端不再默认展示横向大表格,而是把筛选、状态和处理按钮压到单列卡片里。
</p>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">订单 {{ filteredOrders.length }}</span>
<span class="admin-page-chip">{{ canProcessOrders ? '可处理订单' : '查看模式' }}</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="keyword"
class="admin-toolbar__grow"
placeholder="搜索订单号、用户 ID 或优惠券"
@search="loadOrders"
/>
<a-select
v-model:value="statusFilter"
:options="statusOptions"
:style="isMobile ? { width: '100%' } : { width: '160px' }"
@change="loadOrders"
/>
</div>
</template>
<div class="admin-filter-bar">
<a-select
v-model:value="shopFilter"
:allow-clear="currentUserType === 4"
placeholder="所属店铺"
style="width: 180px"
:loading="shopLoading"
:disabled="currentUserType !== 4 && !!currentUserInfo?.shopId"
@change="loadOrders"
>
<a-select-option
v-for="shop in shopList"
:key="shop.id"
:value="getShopOptionValue(shop)"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
<a-input v-model:value="artistKeyword" allow-clear placeholder="美甲师" style="width: 160px" @pressEnter="noop" />
<a-input v-model:value="userKeyword" allow-clear placeholder="用户ID/客户" style="width: 160px" @pressEnter="noop" />
<a-range-picker v-model:value="createRange" value-format="YYYY-MM-DD HH:mm:ss" show-time />
<a-range-picker v-model:value="appointmentRange" value-format="YYYY-MM-DD HH:mm:ss" show-time />
<a-input-number v-model:value="minAmount" :min="0" placeholder="最低金额" style="width: 120px" />
<a-input-number v-model:value="maxAmount" :min="0" placeholder="最高金额" style="width: 120px" />
<a-button @click="resetFilters">重置筛选</a-button>
</div>
<a-table v-if="!isMobile" :columns="columns" :data-source="filteredOrders" :loading="loading" row-key="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="statusColor(record.status)">{{ record.statusText }}</a-tag>
</template>
<template v-else-if="column.key === 'totalAmount'">
¥{{ record.totalAmount.toFixed(2) }}
</template>
<template v-else-if="column.key === 'actualAmount'">
¥{{ record.actualAmount.toFixed(2) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="currentOrder = record">查看</a-button>
<a-button
v-if="record.status === 1 && canProcessOrders"
type="primary"
size="small"
@click="process(record.id, 2)"
>
确认完成
</a-button>
<a-button
v-if="record.status === 1 && canProcessOrders && !isArtist"
danger
size="small"
@click="process(record.id, 3)"
>
取消订单
</a-button>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="filteredOrders" 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.orderNo }}</div>
<div class="admin-mobile-card__subtitle">
用户 {{ item.userId }} · {{ item.createTime }}
</div>
</div>
<a-tag :color="statusColor(item.status)">{{ item.statusText }}</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>总金额</span>
<strong>¥{{ item.totalAmount.toFixed(2) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>实付金额</span>
<strong>¥{{ item.actualAmount.toFixed(2) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>优惠券</span>
<strong>{{ item.couponName || '无' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>预约项目</span>
<strong>{{ item.items?.length || 0 }} 个</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button size="small" @click="currentOrder = item">查看详情</a-button>
<a-button
v-if="item.status === 1 && canProcessOrders"
size="small"
type="primary"
@click="process(item.id, 2)"
>
完成
</a-button>
<a-button
v-if="item.status === 1 && canProcessOrders && !isArtist"
size="small"
danger
@click="process(item.id, 3)"
>
取消
</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="detailVisible"
title="订单详情"
:desktop-width="860"
@cancel="currentOrder = null"
>
<template v-if="currentOrder">
<a-descriptions :column="isMobile ? 1 : 2" bordered size="small">
<a-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</a-descriptions-item>
<a-descriptions-item label="用户ID">{{ currentOrder.userId }}</a-descriptions-item>
<a-descriptions-item label="订单总额">¥{{ currentOrder.totalAmount.toFixed(2) }}</a-descriptions-item>
<a-descriptions-item label="实付金额">¥{{ currentOrder.actualAmount.toFixed(2) }}</a-descriptions-item>
<a-descriptions-item label="优惠券">{{ currentOrder.couponName || '无' }}</a-descriptions-item>
<a-descriptions-item label="订单状态">{{ currentOrder.statusText }}</a-descriptions-item>
<a-descriptions-item label="创建时间" :span="isMobile ? 1 : 2">{{ currentOrder.createTime }}</a-descriptions-item>
</a-descriptions>
<a-divider>订单项目</a-divider>
<a-table
v-if="!isMobile"
:columns="itemColumns"
:data-source="currentOrder.items"
row-key="id"
:pagination="false"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'price'">¥{{ record.price.toFixed(2) }}</template>
<template v-else-if="column.key === 'totalPrice'">¥{{ (record.price * record.quantity).toFixed(2) }}</template>
</template>
</a-table>
<div v-else class="detail-items">
<article v-for="item in currentOrder.items" :key="item.id" class="admin-mobile-card">
<div class="admin-mobile-card__title">{{ item.productTitle }}</div>
<div class="admin-mobile-card__subtitle">{{ item.artistName || '未指定美甲师' }}</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>预约时间</span>
<strong>{{ item.appointmentTime || '--' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>单价</span>
<strong>¥{{ item.price.toFixed(2) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>数量</span>
<strong>{{ item.quantity }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>小计</span>
<strong>¥{{ (item.price * item.quantity).toFixed(2) }}</strong>
</div>
</div>
</article>
</div>
</template>
</AdminResponsiveModal>
</div>
</template>
<script setup lang="ts">
/**
* OrdersView 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, ref } from 'vue'
import { message } from 'ant-design-vue'
import { adminOrderApi, adminShopApi, type Shop } from '@/api/admin'
import { usePermission } from '@/utils/permission'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { isMobile } = useAdminViewport()
const orders = ref<any[]>([])
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
const shopLoading = ref(false)
const currentOrder = ref<any | null>(null)
const currentUserType = ref<number | null>(null)
const currentUserInfo = (() => {
try {
const cached = localStorage.getItem('adminUserInfo') || sessionStorage.getItem('adminUserInfo')
return cached ? JSON.parse(cached) : null
} catch (error) {
console.error('获取当前用户信息失败', error)
return null
}
})()
/** keyword is a reactive state variable used by the template and event handlers. */
const keyword = ref('')
const statusFilter = ref<'all' | string>('all')
const shopList = ref<Shop[]>([])
const shopFilter = ref<string | undefined>()
const artistKeyword = ref('')
const userKeyword = ref('')
const createRange = ref<[string, string] | undefined>()
const appointmentRange = ref<[string, string] | undefined>()
const minAmount = ref<number | undefined>()
const maxAmount = ref<number | undefined>()
const { hasPermission, loadUserPermissions } = usePermission()
/** detailVisible is a reactive state variable used by the template and event handlers. */
const detailVisible = computed({
get: () => !!currentOrder.value,
set: value => { if (!value) currentOrder.value = null }
})
/** canProcessOrders is a reactive state variable used by the template and event handlers. */
const canProcessOrders = computed(() => hasPermission('order:process'))
/** isArtist is a reactive state variable used by the template and event handlers. */
const isArtist = computed(() => currentUserType.value === 3)
const statusOptions = [
{ label: '全部状态', value: 'all' },
{ label: '待处理', value: '1' },
{ label: '已完成', value: '2' },
{ label: '已取消', value: '3' }
]
/** filteredOrders is a reactive state variable used by the template and event handlers. */
const filteredOrders = computed(() => {
const keywordValue = keyword.value.trim().toLowerCase()
return orders.value.filter(order => {
const matchStatus = statusFilter.value === 'all' || String(order.status) === String(statusFilter.value)
if (!matchStatus) {
return false
}
const actualAmount = Number(order.actualAmount ?? order.totalAmount ?? 0)
if (minAmount.value !== undefined && actualAmount < minAmount.value) return false
if (maxAmount.value !== undefined && actualAmount > maxAmount.value) return false
if (!matchText(userKeyword.value, [order.userId, order.userNickname, order.customerName, order.customerPhone])) return false
if (!matchText(artistKeyword.value, (order.items || []).map((item: any) => item.artistName || item.artistId))) return false
if (!matchRange(order.createTime, createRange.value)) return false
if (!matchRange((order.items || [])[0]?.appointmentTime, appointmentRange.value, (order.items || []).map((item: any) => item.appointmentTime))) return false
if (!keywordValue) {
return true
}
const haystack = [
order.orderNo,
order.userId,
order.couponName,
...(order.items || []).map((item: any) => `${item.productTitle || ''} ${item.artistName || ''}`)
].join(' ').toLowerCase()
return haystack.includes(keywordValue)
})
})
const matchText = (needle: string, values: any[]) => {
const normalized = needle.trim().toLowerCase()
if (!normalized) return true
return values.some(value => String(value ?? '').toLowerCase().includes(normalized))
}
const matchRange = (value: string | undefined, range?: [string, string], candidates?: string[]) => {
if (!range?.length) return true
const values = candidates?.length ? candidates : [value]
const start = new Date(range[0]).getTime()
const end = new Date(range[1]).getTime()
return values.some(item => {
if (!item) return false
const time = new Date(item).getTime()
return time >= start && time <= end
})
}
const resetFilters = () => {
keyword.value = ''
statusFilter.value = 'all'
shopFilter.value = currentUserType.value !== 4 ? normalizeShopId(currentUserInfo?.shopId) : undefined
artistKeyword.value = ''
userKeyword.value = ''
createRange.value = undefined
appointmentRange.value = undefined
minAmount.value = undefined
maxAmount.value = undefined
void loadOrders()
}
const columns = [
{ title: '订单编号', dataIndex: 'orderNo', key: 'orderNo' },
{ title: '用户ID', dataIndex: 'userId', key: 'userId', width: 100 },
{ title: '订单总额', key: 'totalAmount', width: 120 },
{ title: '实付金额', key: 'actualAmount', width: 120 },
{ title: '优惠券', dataIndex: 'couponName', key: 'couponName', width: 140 },
{ title: '状态', key: 'status', width: 100 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
{ title: '操作', key: 'actions', width: 180 }
]
const itemColumns = [
{ title: '商品ID', dataIndex: 'productId', key: 'productId', width: 100 },
{ title: '商品名称', dataIndex: 'productTitle', key: 'productTitle' },
{ title: '美甲师', dataIndex: 'artistName', key: 'artistName', width: 120 },
{ title: '预约时间', dataIndex: 'appointmentTime', key: 'appointmentTime', width: 180 },
{ title: '单价', key: 'price', width: 100 },
{ title: '数量', dataIndex: 'quantity', key: 'quantity', width: 80 },
{ title: '总价', key: 'totalPrice', width: 100 }
]
/** statusColor is a local helper used by this page script. */
const statusColor = (status: number) => {
if (status === 1) return 'orange'
if (status === 2) return 'green'
if (status === 3) return 'red'
return 'default'
}
const normalizeUserType = (value: unknown) => {
const type = Number(value)
return Number.isFinite(type) ? type : null
}
/** resolveCurrentUserType is a local helper used by this page script. */
const resolveCurrentUserType = () => {
currentUserType.value = normalizeUserType(currentUserInfo?.type)
}
const normalizeShopId = (value: unknown) => {
if (value === undefined || value === null || value === '') {
return undefined
}
return String(value)
}
const getShopOptionValue = (shop: Shop) => normalizeShopId((shop as any).id) || ''
const loadShopOptions = async () => {
shopLoading.value = true
try {
shopList.value = await adminShopApi.listAllShops() as unknown as Shop[]
if (currentUserType.value !== 4 && currentUserInfo?.shopId) {
shopFilter.value = normalizeShopId(currentUserInfo.shopId)
}
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
shopLoading.value = false
}
}
/** loadOrders is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadOrders = async () => {
loading.value = true
try {
const scopedShopId = shopFilter.value || (currentUserType.value !== 4 ? normalizeShopId(currentUserInfo?.shopId) : undefined)
const result = await adminOrderApi.listOrders({
page: 1,
size: 1000,
keyword: keyword.value || undefined,
status: statusFilter.value === 'all' ? undefined : Number(statusFilter.value),
shopId: scopedShopId
}) as unknown as { list?: any[] }
orders.value = result.list || []
} catch {
message.error('获取订单列表失败')
} finally {
loading.value = false
}
}
/** process is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const process = async (orderId: IdType, status: number) => {
try {
await runWithGlobalLoading(async () => {
await adminOrderApi.updateOrderStatus(orderId, status)
await loadOrders()
})
message.success('操作成功')
if (sameId(currentOrder.value?.id, orderId)) {
currentOrder.value = orders.value.find(order => sameId(order.id, orderId)) || null
}
} catch {
message.error('操作失败')
}
}
/** noop is a local helper used by this page script. */
const noop = () => {}
onMounted(async () => {
resolveCurrentUserType()
await loadUserPermissions()
await loadShopOptions()
await loadOrders()
})
</script>
<style scoped>
.orders {
padding: 0;
}
.detail-items {
display: grid;
gap: 12px;
}
.admin-filter-bar {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 16px;
}
</style>