fix: 封装 SpuSelect SpuAndSkuList 为商品活动商品选择商品编辑通用组件

This commit is contained in:
puhui999 2023-06-25 16:43:49 +08:00
parent 76ccc54a35
commit 51e79f29cc
12 changed files with 229 additions and 177 deletions

View File

@ -47,17 +47,13 @@ export interface Spu {
recommendBest?: boolean // 是否精品
recommendNew?: boolean // 是否新品
recommendGood?: boolean // 是否优品
}
// TODO @puhui999: SpuRespVO 合并到 SPU 里?前端少点 VO 类哈;
export interface SpuRespVO extends Spu {
price: number
salesCount: number
marketPrice: number
costPrice: number
stock: number
createTime: Date
status: number
price?: number // 商品价格
salesCount?: number // 商品销量
marketPrice?: number // 市场价
costPrice?: number // 成本价
stock?: number // 商品库存
createTime?: Date // 商品创建时间
status?: number // 商品状态
}
// 获得 Spu 列表

View File

@ -1,5 +1,5 @@
import request from '@/config/axios'
import { Sku, SpuRespVO } from '@/api/mall/product/spu'
import { Sku, Spu } from '@/api/mall/product/spu'
export interface SeckillActivityVO {
id: number
@ -21,6 +21,7 @@ export interface SeckillActivityVO {
products: SeckillProductVO[]
}
// 秒杀活动所需属性
export interface SeckillProductVO {
spuId: number
skuId: number
@ -28,11 +29,12 @@ export interface SeckillProductVO {
stock: number
}
// 扩展 Sku 配置
type SkuExtension = Sku & {
productConfig: SeckillProductVO
}
export interface SpuExtension extends SpuRespVO {
export interface SpuExtension extends Spu {
skus: SkuExtension[] // 重写类型
}

View File

@ -274,10 +274,7 @@ watch(
const emit = defineEmits(['update:activeName'])
const validate = async () => {
// sku
if (!skuListRef.value.validateSku()) {
message.warning('商品相关价格不能低于 0.01 元!!')
throw new Error('商品相关价格不能低于 0.01 元!!')
}
skuListRef.value.validateSku()
//
if (!productSpuBasicInfoRef) return
return await unref(productSpuBasicInfoRef).validate((valid) => {

View File

@ -259,8 +259,10 @@ import { UploadImg } from '@/components/UploadFile'
import type { Property, Sku, Spu } from '@/api/mall/product/spu'
import { createImageViewer } from '@/components/ImageViewer'
import { RuleConfig } from '@/views/mall/product/spu/components/index'
import { Properties } from './index'
defineOptions({ name: 'SkuList' })
const message = useMessage() //
const props = defineProps({
propFormData: {
@ -268,7 +270,7 @@ const props = defineProps({
default: () => {}
},
propertyList: {
type: Array,
type: Array as PropType<Properties[]>,
default: () => []
},
ruleConfig: {
@ -323,26 +325,47 @@ const tableHeaders = ref<{ prop: string; label: string }[]>([]) // 多属性表
/**
* 保存时每个商品规格的表单要校验下例如说销售金额最低是 0.01 这种
*/
const validateSku = (): boolean => {
const validateSku = () => {
const checks = ['price', 'marketPrice', 'costPrice']
let warningInfo = '请检查商品各行相关属性配置,'
let validate = true //
for (const sku of formData.value!.skus) {
for (const sku of formData.value!.skus!) {
//
if (props.isActivityComponent) {
for (const rule of props.ruleConfig) {
if (sku[rule.name] < rule.geValue) {
const arg = getValue(sku, rule.name)
if (!rule.rule(arg)) {
validate = false //
warningInfo += rule.message
break
}
}
} else {
if (checks.some((check) => sku[check] < 0.01)) {
validate = false //
warningInfo = '商品相关价格不能低于 0.01 元!!'
break
}
}
//
if (!validate) {
message.warning(warningInfo)
throw new Error(warningInfo)
}
}
return validate
}
const getValue = (obj, arg) => {
const keys = arg.split('.')
let value = obj
for (const key of keys) {
if (value && typeof value === 'object' && key in value) {
value = value[key]
} else {
value = undefined
break
}
}
return value
}
const emit = defineEmits<{
@ -417,13 +440,13 @@ const generateTableData = (propertyList: any[]) => {
* 生成 skus 前置校验
*/
const validateData = (propertyList: any[]) => {
const skuPropertyIds = []
const skuPropertyIds: number[] = []
formData.value!.skus!.forEach((sku) =>
sku.properties
?.map((property) => property.propertyId)
.forEach((propertyId) => {
if (skuPropertyIds.indexOf(propertyId) === -1) {
skuPropertyIds.push(propertyId)
?.forEach((propertyId) => {
if (skuPropertyIds.indexOf(propertyId!) === -1) {
skuPropertyIds.push(propertyId!)
}
})
)
@ -457,7 +480,7 @@ const build = (propertyValuesList: Property[][]) => {
/** 监听属性列表,生成相关参数和表头 */
watch(
() => props.propertyList,
(propertyList) => {
(propertyList: Properties[]) => {
//
if (!formData.value!.specType) {
return
@ -497,7 +520,7 @@ watch(
return
}
//
if (propertyList.some((item) => item.values.length === 0)) {
if (propertyList.some((item) => item.values!.length === 0)) {
return
}
// table sku

View File

@ -14,8 +14,19 @@ interface Properties {
}
interface RuleConfig {
name: string // 需要校验的字段
geValue: number // TODO 暂定大于一个数字
// 需要校验的字段
// 例name: 'name' 则表示校验 sku.name 的值
// 例name: 'productConfig.stock' 则表示校验 sku.productConfig.name 的值,此处 productConfig 表示我在 Sku 上扩展的属性
name: string
// 校验规格为一个毁掉函数,其中 arg 为需要校验的字段的值。
// 例需要校验价格必须大于0.01
// {
// name:'price',
// rule:(arg) => arg > 0.01
// }
rule: (arg: any) => boolean
// 校验不通过时的消息提示
message: string
}
/**

View File

@ -1,5 +1,5 @@
<template>
<el-table :data="spuData">
<el-table :data="spuData" :default-expand-all="true">
<el-table-column type="expand" width="30">
<template #default="{ row }">
<SkuList
@ -46,90 +46,39 @@
<el-table-column align="center" label="库存" min-width="90" prop="stock" />
</el-table>
</template>
<script lang="ts" setup>
<script generic="T extends Spu" lang="ts" setup>
// TODO SPU
import { formatToFraction } from '@/utils'
import { createImageViewer } from '@/components/ImageViewer'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { SpuRespVO } from '@/api/mall/product/spu'
import {
getPropertyList,
Properties,
RuleConfig,
SkuList
} from '@/views/mall/product/spu/components'
import { SeckillProductVO, SpuExtension } from '@/api/mall/promotion/seckill/seckillActivity'
import { Spu } from '@/api/mall/product/spu'
import { RuleConfig, SkuList } from '@/views/mall/product/spu/components'
import { SeckillProductVO } from '@/api/mall/promotion/seckill/seckillActivity'
import { SpuProperty } from '@/views/mall/promotion/components/index'
defineOptions({ name: 'PromotionSpuAndSkuList' })
const message = useMessage() //
// TODO @puhui999 spu
const props = defineProps<{
spuList: T[]
ruleConfig: RuleConfig[]
spuPropertyListP: SpuProperty<T>[]
}>()
// TODO @puhui999 spu
const props = defineProps({
spuList: {
type: Array,
default: () => []
}
})
const spuData = ref<SpuRespVO[]>([]) // spu
const spuData = ref<Spu[]>([]) // spu
const skuListRef = ref() // Ref
interface spuProperty {
spuId: number
spuDetail: SpuExtension
propertyList: Properties[]
} // TODO @puhui999
const spuPropertyList = ref<spuProperty[]>([]) // spuId sku
/**
* 获取 SPU 详情
* @param spuIds
*/
const getSpuDetails = async (spuIds: number[]) => {
const spuProperties: spuProperty[] = []
// TODO puhui999: spuIds
for (const spuId of spuIds) {
// SPU
const res = (await ProductSpuApi.getSpu(spuId)) as SpuExtension
if (!res) {
continue
}
// sku
res.skus?.forEach((sku) => {
const config: SeckillProductVO = {
spuId,
skuId: sku.id!,
stock: 0,
seckillPrice: 0
}
sku.productConfig = config
})
spuProperties.push({ spuId, spuDetail: res, propertyList: getPropertyList(res) })
}
spuPropertyList.value = spuProperties
}
const ruleConfig: RuleConfig[] = [
{
name: 'stock',
geValue: 10
},
{
name: 'seckillPrice',
geValue: 0.01
}
]
const spuPropertyList = ref<SpuProperty<T>[]>([]) // spuId sku
/**
* 获取所有 sku 秒杀配置
* @param extendedAttribute sku 上扩展的属性秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
*/
const getSkuConfigs = (): SeckillProductVO[] => {
if (!skuListRef.value.validateSku()) {
// TODO
message.warning('请检查商品相关属性配置!!')
throw new Error('请检查商品相关属性配置!!')
}
const getSkuConfigs: <V>(extendedAttribute: string) => V[] = (extendedAttribute: string) => {
skuListRef.value.validateSku()
const seckillProducts: SeckillProductVO[] = []
spuPropertyList.value.forEach((item) => {
item.spuDetail.skus.forEach((sku) => {
seckillProducts.push(sku.productConfig)
seckillProducts.push(sku[extendedAttribute])
})
})
return seckillProducts
@ -152,8 +101,21 @@ watch(
() => props.spuList,
(data) => {
if (!data) return
spuData.value = data as SpuRespVO[]
getSpuDetails(spuData.value.map((spu) => spu.id!))
spuData.value = data as Spu[]
},
{
deep: true,
immediate: true
}
)
/**
* 将传进来的值赋值给 skuList
*/
watch(
() => props.spuPropertyListP,
(data) => {
if (!data) return
spuPropertyList.value = data as SpuProperty<T>[]
},
{
deep: true,

View File

@ -20,7 +20,6 @@
class="w-1/1"
node-key="id"
placeholder="请选择商品分类"
@change="nodeClick"
/>
</el-col>
<el-col :span="6">
@ -116,13 +115,13 @@ import { ElTable } from 'element-plus'
import { dateFormatter } from '@/utils/formatTime'
import { createImageViewer } from '@/components/ImageViewer'
import { formatToFraction } from '@/utils'
import { checkSelectedNode, defaultProps, handleTree } from '@/utils/tree'
import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductCategoryApi from '@/api/mall/product/category'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { propTypes } from '@/utils/propTypes'
defineOptions({ name: 'PromotionSpuAndSkuSelect' })
defineOptions({ name: 'PromotionSpuSelect' })
const props = defineProps({
// spu spu sku
@ -161,7 +160,7 @@ const expandChange = async (row: ProductSpuApi.Spu, expandedRows: ProductSpuApi.
return
}
// SPU
const res = (await ProductSpuApi.getSpu(row.id as number)) as ProductSpuApi.SpuRespVO
const res = (await ProductSpuApi.getSpu(row.id as number)) as ProductSpuApi.Spu
propertyList.value = getPropertyList(res)
spuData.value = res
isExpand.value = true
@ -169,53 +168,50 @@ const expandChange = async (row: ProductSpuApi.Spu, expandedRows: ProductSpuApi.
}
//============ ============
const selectedSpu = ref<ProductSpuApi.Spu>() // spu
const selectedSku = ref<ProductSpuApi.Sku[]>() // sku
const selectedSpuIds = ref<number[]>([]) // spuIds
const selectedSkuIds = ref<number[]>([]) // skuIds
const selectSku = (val: ProductSpuApi.Sku[]) => {
selectedSku.value = val
selectedSkuIds.value = val.map((sku) => sku.id!)
}
const selectSpu = (val: ProductSpuApi.Spu[]) => {
//
selectedSpu.value = val[0]
// 1
if (val.length > 1) {
//
spuListRef.value.clearSelection()
//
spuListRef.value.toggleRowSelection(val.pop(), true)
}
selectedSpuIds.value = val.map((spu) => spu.id!)
// //
// selectedSpu.value = val[0]
// // 1
// if (val.length > 1) {
// //
// spuListRef.value.clearSelection()
// //
// spuListRef.value.toggleRowSelection(val.pop(), true)
// }
}
//
const emits = defineEmits<{
(e: 'confirm', value: ProductSpuApi.Spu, value1?: ProductSpuApi.Sku[]): void
(e: 'confirm', spuIds: number[], skuIds?: number[]): void
}>()
/**
* 确认选择返回选中的 spu sku (如果需要选择sku的话)
*/
const confirm = () => {
if (typeof selectedSpu.value === 'undefined') {
if (selectedSpuIds.value.length === 0) {
message.warning('没有选择任何商品')
return
}
if (
(props.isSelectSku && typeof selectedSku.value === 'undefined') ||
selectedSku.value?.length === 0
) {
if (props.isSelectSku && selectedSkuIds.value.length === 0) {
message.warning('没有选择任何商品属性')
return
}
// TODO sku
// id
props.isSelectSku
? emits('confirm', selectedSpu.value!, selectedSku.value!)
: emits('confirm', selectedSpu.value!)
? emits('confirm', selectedSpuIds.value, selectedSkuIds.value)
: emits('confirm', selectedSpuIds.value)
//
dialogVisible.value = false
}
// TODO @puhui999
/** 打开弹窗 TODO 没做国际化 */
const open = (title: string) => {
dialogTitle.value = title
/** 打开弹窗 */
const open = () => {
dialogTitle.value = '商品选择'
dialogVisible.value = true
}
defineExpose({ open }) // open
@ -261,15 +257,6 @@ const imagePreview = (imgUrl: string) => {
const categoryList = ref() //
// TODO @puhui999
/**
* 校验所选是否为二级及以下节点
*/
const nodeClick = () => {
if (!checkSelectedNode(categoryList.value, queryParams.value.categoryId)) {
queryParams.value.categoryId = null
message.warning('必须选择二级及以下节点!!')
}
}
/** 初始化 **/
onMounted(async () => {
await getList()

View File

@ -0,0 +1,13 @@
import SpuSelect from './SpuSelect.vue'
import SpuAndSkuList from './SpuAndSkuList.vue'
import { Properties } from '@/views/mall/product/spu/components'
type SpuProperty<T> = {
spuId: number
spuDetail: T
propertyList: Properties[]
}
/**
*
*/
export { SpuSelect, SpuAndSkuList, SpuProperty }

View File

@ -8,10 +8,15 @@
:schema="allSchemas.formSchema"
>
<!-- 先选择 -->
<template #spuId>
<el-button @click="spuAndSkuSelectForm.open('秒杀商品选择')">选择商品</el-button>
<template #spuIds>
<el-button @click="spuSelectRef.open()">选择商品</el-button>
<!-- TODO @puhui999默认展开 SKU 毕竟 SKU 是主角SPU 是配角 -->
<SpuAndSkuList ref="spuAndSkuListRef" :spu-list="spuList" />
<SpuAndSkuList
ref="spuAndSkuListRef"
:rule-config="ruleConfig"
:spu-list="spuList"
:spu-property-list-p="spuPropertyList"
/>
</template>
</Form>
<template #footer>
@ -19,15 +24,15 @@
<el-button @click="dialogVisible = false"> </el-button>
</template>
</Dialog>
<!-- TODO @puhui999这个组件是不是 SpuSelect不需要带 sku 或者 Form -->
<SpuAndSkuSelectForm ref="spuAndSkuSelectForm" @confirm="selectSpu" />
<SpuSelect ref="spuSelectRef" :is-select-sku="true" @confirm="selectSpu" />
</template>
<script lang="ts" setup>
import { SpuAndSkuList, SpuAndSkuSelectForm } from './components'
import { SpuAndSkuList, SpuProperty, SpuSelect } from '../../components'
import { allSchemas, rules } from './seckillActivity.data'
import { Spu } from '@/api/mall/product/spu'
import * as SeckillActivityApi from '@/api/mall/promotion/seckill/seckillActivity'
import { getPropertyList, RuleConfig } from '@/views/mall/product/spu/components'
import * as ProductSpuApi from '@/api/mall/product/spu'
defineOptions({ name: 'PromotionSeckillActivityForm' })
@ -39,14 +44,26 @@ const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 12
const formType = ref('') // create - update -
const formRef = ref() // Ref
const spuAndSkuSelectForm = ref() // Ref
const spuSelectRef = ref() // Ref
const spuAndSkuListRef = ref() // sku Ref
const ruleConfig: RuleConfig[] = [
{
name: 'productConfig.stock',
rule: (arg) => arg > 1,
message: '商品秒杀库存必须大于 1 '
},
{
name: 'productConfig.seckillPrice',
rule: (arg) => arg > 0.01,
message: '商品秒杀价格必须大于 0.01 '
}
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
dialogVisible.value = true
dialogTitle.value = t('action.' + type)
formType.value = type
resetForm()
// TODO
if (id) {
formLoading.value = true
@ -60,12 +77,49 @@ const open = async (type: string, id?: number) => {
}
defineExpose({ open }) // open
const spuList = ref<Spu[]>([]) // spu
const selectSpu = (val: Spu) => {
formRef.value.setValues({ spuId: val.id })
spuList.value = [val]
const spuList = ref<SeckillActivityApi.SpuExtension[]>([]) // spu
const spuPropertyList = ref<SpuProperty<SeckillActivityApi.SpuExtension>[]>([])
const selectSpu = (spuIds: number[]) => {
formRef.value.setValues({ spuIds })
getSpuDetails(spuIds)
}
/**
* 获取 SPU 详情
* TODO 获取 SPU 详情放到各自活动表单来做 SpuAndSkuList 职责单一点
* @param spuIds
*/
const getSpuDetails = async (spuIds: number[]) => {
const spuProperties: SpuProperty<SeckillActivityApi.SpuExtension>[] = []
spuList.value = []
// TODO puhui999: spuIds
for (const spuId of spuIds) {
// SPU
const res = (await ProductSpuApi.getSpu(spuId)) as SeckillActivityApi.SpuExtension
if (!res) {
continue
}
spuList.value.push(res)
// sku
res.skus?.forEach((sku) => {
const config: SeckillActivityApi.SeckillProductVO = {
spuId,
skuId: sku.id!,
stock: 0,
seckillPrice: 0
}
sku.productConfig = config
})
spuProperties.push({ spuId, spuDetail: res, propertyList: getPropertyList(res) })
}
spuPropertyList.value = spuProperties
}
/** 重置表单 */
const resetForm = () => {
spuList.value = []
spuPropertyList.value = []
formRef.value.getElFormRef().resetFields()
}
/** 提交表单 */
const emit = defineEmits(['success']) // success
const submitForm = async () => {

View File

@ -1,4 +0,0 @@
import SpuAndSkuSelectForm from './SpuAndSkuSelectForm.vue'
import SpuAndSkuList from './SpuAndSkuList.vue'
export { SpuAndSkuSelectForm, SpuAndSkuList }

View File

@ -29,6 +29,11 @@
total: tableObject.total
}"
>
<template #configIds="{ row }">
<el-tag v-for="(name, index) in convertSeckillConfigNames(row)" :key="index" class="mr-5px">
{{ name }}
</el-tag>
</template>
<template #action="{ row }">
<el-button
v-hasPermi="['promotion:seckill-activity:update']"
@ -55,6 +60,7 @@
</template>
<script lang="ts" setup>
import { allSchemas } from './seckillActivity.data'
import { getListAllSimple } from '@/api/mall/promotion/seckill/seckillConfig'
import * as SeckillActivityApi from '@/api/mall/promotion/seckill/seckillActivity'
import SeckillActivityForm from './SeckillActivityForm.vue'
@ -80,9 +86,16 @@ const openForm = (type: string, id?: number) => {
const handleDelete = (id: number) => {
tableMethods.delList(id, false)
}
const seckillConfigAllSimple = ref([]) //
const convertSeckillConfigNames = computed(
() => (row) =>
seckillConfigAllSimple.value
?.filter((item) => row.configIds.includes(item.id))
?.map((config) => config.name)
)
/** 初始化 **/
onMounted(() => {
getList()
onMounted(async () => {
await getList()
seckillConfigAllSimple.value = await getListAllSimple()
})
</script>

View File

@ -40,8 +40,7 @@ const crudSchemas = reactive<CrudSchema[]>([
component: 'DatePicker',
componentProps: {
valueFormat: 'YYYY-MM-DD',
type: 'daterange',
defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')]
type: 'daterange'
}
},
form: {
@ -52,7 +51,7 @@ const crudSchemas = reactive<CrudSchema[]>([
}
},
table: {
width: 300
width: 120
}
},
{
@ -64,8 +63,7 @@ const crudSchemas = reactive<CrudSchema[]>([
component: 'DatePicker',
componentProps: {
valueFormat: 'YYYY-MM-DD',
type: 'daterange',
defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')]
type: 'daterange'
}
},
form: {
@ -76,11 +74,11 @@ const crudSchemas = reactive<CrudSchema[]>([
}
},
table: {
width: 300
width: 120
}
},
{
label: '秒杀时段', // todo @PUHUI999: 在列表界面,格式化不对
label: '秒杀时段',
field: 'configIds',
form: {
component: 'Select',
@ -106,7 +104,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@ -118,7 +116,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@ -130,7 +128,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@ -141,7 +139,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@ -152,7 +150,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@ -164,7 +162,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@ -175,12 +173,12 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
label: '秒杀活动商品', // TODO @puhui999格式化的商品不对
field: 'spuId',
field: 'spuIds',
form: {
colProps: {
span: 24
@ -204,7 +202,7 @@ const crudSchemas = reactive<CrudSchema[]>([
},
isForm: false,
table: {
width: 300
width: 120
}
},
{
@ -215,7 +213,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 80
}
},
{