功能:收口小程序前后台安全与防重复提交

This commit is contained in:
xiaowang
2026-04-20 16:02:57 +08:00
parent eb1c209d79
commit a3df262fae
237 changed files with 14068 additions and 728 deletions
+268 -54
View File
@@ -1,40 +1,68 @@
const auth = require('../../utils/auth')
const cache = require('../../utils/cache')
const tagApi = require('../../api/tag')
const productApi = require('../../api/product')
const cartApi = require('../../api/cart')
const actionGuard = require('../../utils/action-guard')
const { buildProductCards } = require('../../utils/product')
const navigation = require('../../utils/navigation')
const { runWithLoading } = require('../../utils/loading')
const { CACHE_TTL } = require('../../utils/config')
const ALL_CATEGORY = '\u5168\u90e8'
const FILTER_BUSY_MESSAGE = '\u7b5b\u9009\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
const CART_BUSY_MESSAGE = '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
Page({
data: {
initialized: false,
loading: false,
categories: ['全部'],
selectedCategory: '全部',
loadingMore: false,
categories: [ALL_CATEGORY],
selectedCategory: ALL_CATEGORY,
searchKeyword: '',
products: [],
activeBannerText: ''
filterSummaryText: '',
page: 1,
pageSize: 10,
total: 0,
hasMore: false
},
onLoad(options) {
this.filterRequestId = 0
this.bootstrapPage(options || {})
},
onShow() {
async onShow() {
const app = getApp()
const pendingFilter = app && app.globalData ? app.globalData.pendingProductFilter : null
if (this.data.initialized && pendingFilter && (pendingFilter.keyword || pendingFilter.tag)) {
if (app && app.globalData) {
app.globalData.pendingProductFilter = null
}
this.applyFilter(pendingFilter)
await this.applyFilter(pendingFilter)
return
}
if (this.data.initialized) {
await this.syncProductCartState()
}
},
async onPullDownRefresh() {
await this.loadProducts()
await this.loadProducts(true)
wx.stopPullDownRefresh()
},
onReachBottom() {
if (!this.data.hasMore || this.data.loadingMore) {
return
}
this.loadProducts(false)
},
async bootstrapPage(options) {
this.setData({
loading: true
@@ -48,7 +76,7 @@ Page({
})
} catch (error) {
wx.showToast({
title: error.message || '作品列表加载失败',
title: error.message || '\u4f5c\u54c1\u5217\u8868\u52a0\u8f7d\u5931\u8d25',
icon: 'none'
})
} finally {
@@ -59,10 +87,10 @@ Page({
},
async loadTags() {
const tags = await tagApi.getAllTags()
const tags = await cache.remember('tags:all', CACHE_TTL.tags, () => tagApi.getAllTags())
const names = Array.isArray(tags) ? tags.map(item => item.tagName).filter(Boolean) : []
this.setData({
categories: ['全部'].concat(names)
categories: [ALL_CATEGORY].concat(names)
})
},
@@ -81,56 +109,154 @@ Page({
},
async applyFilter(filter) {
const keyword = (filter.keyword || '').trim()
const tag = (filter.tag || '').trim()
const keyword = String(filter.keyword || '').trim()
const tag = String(filter.tag || '').trim()
this.setData({
searchKeyword: keyword,
selectedCategory: tag && this.data.categories.includes(tag) ? tag : '全部'
selectedCategory: tag && this.data.categories.includes(tag) ? tag : ALL_CATEGORY,
page: 1,
total: 0,
hasMore: false
})
await this.loadProducts()
await this.loadProducts(true)
},
async loadProducts() {
this.setData({
loading: true
})
async loadProducts(reset) {
const requestId = ++this.filterRequestId
const nextPage = reset ? 1 : this.data.page + 1
this.setData(reset ? { loading: true } : { loadingMore: true })
try {
let products = []
const keyword = this.data.searchKeyword.trim()
const tag = this.data.selectedCategory
if (keyword) {
products = await productApi.searchProducts(keyword)
} else if (tag !== '全部') {
products = await productApi.getProductsByTag(tag)
} else {
products = await productApi.getAllProducts()
const keyword = String(this.data.searchKeyword || '').trim()
const tag = this.data.selectedCategory === ALL_CATEGORY ? '' : this.data.selectedCategory
const result = await productApi.getProductPage({
page: nextPage,
size: this.data.pageSize,
keyword: keyword || undefined,
tag: tag || undefined
})
const cards = await buildProductCards(result && result.list ? result.list : [])
const displayCards = await this.attachCartState(cards)
if (requestId !== this.filterRequestId) {
return
}
const cards = await buildProductCards(products || [])
const merged = reset ? displayCards : this.data.products.concat(displayCards)
const total = Number(result && result.total) || 0
this.setData({
products: cards,
activeBannerText: keyword
? `正在显示“${keyword}”的搜索结果`
: (tag !== '全部' ? `当前按“${tag}”筛选` : '')
products: merged,
page: nextPage,
total,
hasMore: merged.length < total,
filterSummaryText: this.buildFilterSummary(keyword, tag, total)
})
} catch (error) {
this.setData({
products: [],
activeBannerText: ''
})
if (requestId !== this.filterRequestId) {
return
}
if (reset) {
this.setData({
products: [],
total: 0,
hasMore: false,
filterSummaryText: ''
})
}
wx.showToast({
title: error.message || '作品列表加载失败',
title: error.message || '\u4f5c\u54c1\u5217\u8868\u52a0\u8f7d\u5931\u8d25',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
if (requestId === this.filterRequestId) {
this.setData({
loading: false,
loadingMore: false
})
}
}
},
buildFilterSummary(keyword, tag, total) {
const chips = []
if (tag) {
chips.push(tag)
}
if (keyword) {
chips.push(`\u641c\u7d22\uff1a${keyword}`)
}
chips.push(`\u5171 ${Number(total || 0)} \u4e2a`)
return chips.join(' \u00b7 ')
},
normalizeId(value) {
return value === undefined || value === null ? '' : String(value)
},
async fetchCartProductIdSet() {
if (!auth.isLoggedIn()) {
this.cartProductIdSet = new Set()
return this.cartProductIdSet
}
try {
const cartList = await cartApi.getCartList()
const idSet = new Set(
(Array.isArray(cartList) ? cartList : [])
.map(item => this.normalizeId(item && item.productId))
.filter(Boolean)
)
this.cartProductIdSet = idSet
return idSet
} catch (error) {
this.cartProductIdSet = new Set()
return this.cartProductIdSet
}
},
async attachCartState(cards) {
const idSet = await this.fetchCartProductIdSet()
return this.markCardsInCart(cards, idSet)
},
markCardsInCart(cards, idSet) {
const productIdSet = idSet || new Set()
return (Array.isArray(cards) ? cards : []).map(item => ({
...item,
inCart: productIdSet.has(this.normalizeId(item && item.id))
}))
},
async syncProductCartState() {
const idSet = await this.fetchCartProductIdSet()
this.setData({
products: this.markCardsInCart(this.data.products, idSet)
})
},
markProductInCart(productId) {
const normalizedId = this.normalizeId(productId)
if (!normalizedId) {
return
}
this.cartProductIdSet = this.cartProductIdSet || new Set()
this.cartProductIdSet.add(normalizedId)
this.setData({
products: this.data.products.map(item => (
this.normalizeId(item && item.id) === normalizedId
? {
...item,
inCart: true
}
: item
))
})
},
handleSearchInput(event) {
this.setData({
searchKeyword: event.detail.value
@@ -138,27 +264,72 @@ Page({
},
async handleSearchConfirm() {
this.setData({
selectedCategory: '全部'
})
await runWithLoading(() => this.loadProducts())
try {
await actionGuard.run(this, 'products:search', async () => {
this.setData({
selectedCategory: ALL_CATEGORY,
page: 1
})
await runWithLoading(() => this.loadProducts(true))
}, {
message: FILTER_BUSY_MESSAGE
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '\u7b5b\u9009\u5931\u8d25',
icon: 'none'
})
}
},
async handleSelectCategory(event) {
const category = event.currentTarget.dataset.category
this.setData({
selectedCategory: category,
searchKeyword: ''
})
await runWithLoading(() => this.loadProducts())
try {
await actionGuard.run(this, `products:category:${category}`, async () => {
this.setData({
selectedCategory: category,
searchKeyword: '',
page: 1
})
await runWithLoading(() => this.loadProducts(true))
}, {
message: FILTER_BUSY_MESSAGE
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '\u7b5b\u9009\u5931\u8d25',
icon: 'none'
})
}
},
async handleResetFilters() {
this.setData({
selectedCategory: '全部',
searchKeyword: ''
})
await runWithLoading(() => this.loadProducts())
try {
await actionGuard.run(this, 'products:reset', async () => {
this.setData({
selectedCategory: ALL_CATEGORY,
searchKeyword: '',
page: 1
})
await runWithLoading(() => this.loadProducts(true))
}, {
message: FILTER_BUSY_MESSAGE
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '\u7b5b\u9009\u5931\u8d25',
icon: 'none'
})
}
},
handleProductSelect(event) {
@@ -170,5 +341,48 @@ Page({
navigation.navigate('/pages/product-detail/index', {
id: product.id
})
},
async handleQuickAdd(event) {
const product = event.detail || {}
const productId = this.normalizeId(product.id)
if (!productId) {
return
}
if (!navigation.ensureLogin('\u52a0\u5165\u8d2d\u7269\u8f66')) {
return
}
if (this.cartProductIdSet && this.cartProductIdSet.has(productId)) {
wx.showToast({
title: '\u8d2d\u7269\u8f66\u5df2\u6709',
icon: 'none'
})
return
}
try {
await actionGuard.run(this, `cart:add:${productId}`, () => runWithLoading(() => cartApi.addToCart({
productId,
quantity: 1
})), {
message: CART_BUSY_MESSAGE
})
this.markProductInCart(productId)
await getApp().updateCartBadge()
wx.showToast({
title: '\u5df2\u52a0\u5165\u8d2d\u7269\u8f66',
icon: 'none'
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '\u52a0\u5165\u8d2d\u7269\u8f66\u5931\u8d25',
icon: 'none'
})
}
}
})
+25 -18
View File
@@ -1,17 +1,13 @@
<navigation-bar title="作品库" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="page-shell product-page">
<view class="page-content">
<view class="page-hero product-hero">
<text class="hero-kicker">作品筛选</text>
<text class="hero-title">{{selectedCategory !== '全部' ? selectedCategory : '找到适合你的美甲款式'}}</text>
<text class="hero-desc">{{activeBannerText ? activeBannerText : '按标签筛选或输入关键词搜索,先缩小范围,再挑喜欢的作品。'}}</text>
<view class="search-card">
<view class="page-content product-page-content">
<view class="sticky-filter-bar">
<view class="filter-surface">
<view class="search-row">
<input
class="search-input"
placeholder="搜索作品名称或关键词"
placeholder="搜索标题、标签或描述"
placeholder-class="field-placeholder"
value="{{searchKeyword}}"
bindinput="handleSearchInput"
@@ -21,7 +17,7 @@
<view class="search-btn" bindtap="handleSearchConfirm">搜索</view>
</view>
<scroll-view class="category-scroll" scroll-x enable-flex>
<scroll-view class="category-scroll" scroll-x enable-flex show-scrollbar="false">
<view class="category-list">
<view
wx:for="{{categories}}"
@@ -34,21 +30,32 @@
</view>
</view>
</scroll-view>
<view class="results-head">
<view class="results-meta">
<view class="results-count">{{products.length ? products.length : 0}} 个</view>
<view wx:if="{{filterSummaryText}}" class="filter-summary-chip">{{filterSummaryText}}</view>
</view>
<view wx:if="{{searchKeyword || selectedCategory !== '全部'}}" class="ghost-btn results-reset" bindtap="handleResetFilters">重置</view>
</view>
</view>
</view>
<view class="results-head">
<view class="results-count">{{products.length ? products.length : 0}} 个结果</view>
<view wx:if="{{searchKeyword || selectedCategory !== '全部'}}" class="ghost-btn results-reset" bindtap="handleResetFilters">重置筛选</view>
</view>
<view wx:if="{{activeBannerText}}" class="filter-banner">{{activeBannerText}}</view>
<view wx:if="{{products.length}}" class="product-grid">
<view wx:for="{{products}}" wx:key="id" class="product-grid-item">
<product-card item="{{item}}" show-stats="{{true}}" bindselect="handleProductSelect"></product-card>
<product-card
item="{{item}}"
show-stats="{{true}}"
show-quick-add="{{true}}"
in-cart="{{item.inCart}}"
bindselect="handleProductSelect"
bindquickadd="handleQuickAdd"
></product-card>
</view>
</view>
<view wx:if="{{products.length && (loadingMore || !hasMore)}}" class="load-state">
<text class="load-state-text">{{loadingMore ? '正在加载更多作品...' : '已经到底了'}}</text>
</view>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载作品</text>
@@ -56,7 +63,7 @@
<view wx:else class="page-card empty-card">
<text class="empty-title">暂时没有匹配的作品</text>
<text class="empty-desc">可以换个关键词试试,或者先浏览全部作品。</text>
<text class="empty-desc">换个关键词试试。</text>
<view class="ghost-btn" bindtap="handleResetFilters">查看全部</view>
</view>
</view>
+82 -43
View File
@@ -4,64 +4,71 @@
linear-gradient(180deg, #fff8fa 0%, #fffdfc 100%);
}
.product-hero {
background:
radial-gradient(circle at top right, rgba(255, 194, 211, 0.42), transparent 34%),
linear-gradient(145deg, #fffdfd 0%, #fff3f7 56%, #ffe7ef 100%);
.product-page-content {
padding-top: 10rpx;
}
.search-card {
margin-top: 28rpx;
display: flex;
flex-direction: column;
gap: 24rpx;
padding: 22rpx 22rpx 24rpx;
border-radius: 28rpx;
background: rgba(255, 255, 255, 0.78);
.sticky-filter-bar {
position: sticky;
top: 0;
z-index: 12;
padding: 6rpx 0 16rpx;
background:
linear-gradient(180deg, rgba(255, 248, 250, 0.98) 0%, rgba(255, 252, 251, 0.94) 76%, rgba(255, 252, 251, 0) 100%);
}
.filter-surface {
padding: 16rpx 16rpx 14rpx;
border-radius: 24rpx;
border: 1rpx solid rgba(239, 216, 224, 0.86);
background: rgba(255, 255, 255, 0.92);
box-shadow: 0 18rpx 40rpx rgba(122, 67, 88, 0.08);
}
.search-row {
display: flex;
align-items: center;
gap: 14rpx;
gap: 12rpx;
}
.search-input {
flex: 1;
height: 76rpx;
padding: 0 24rpx;
height: 68rpx;
padding: 0 22rpx;
border-radius: 999rpx;
background: #fbf5f7;
color: #2d2430;
font-size: 28rpx;
font-size: 26rpx;
}
.search-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 132rpx;
height: 76rpx;
min-width: 112rpx;
height: 68rpx;
padding: 0 28rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
color: #ffffff;
font-size: 26rpx;
font-size: 24rpx;
font-weight: 700;
}
.category-scroll {
margin-top: 14rpx;
width: 100%;
height: 68rpx;
min-height: 68rpx;
height: 56rpx;
min-height: 56rpx;
white-space: nowrap;
}
.category-list {
display: inline-flex;
align-items: center;
gap: 16rpx;
min-height: 68rpx;
padding-right: 8rpx;
gap: 12rpx;
min-height: 56rpx;
padding-right: 4rpx;
}
.category-item {
@@ -69,13 +76,13 @@
align-items: center;
justify-content: center;
flex-shrink: 0;
min-width: 120rpx;
height: 60rpx;
padding: 0 22rpx;
min-width: 88rpx;
height: 50rpx;
padding: 0 20rpx;
border-radius: 999rpx;
background: #f7edf1;
color: #8d7a84;
font-size: 24rpx;
font-size: 22rpx;
font-weight: 600;
}
@@ -88,37 +95,69 @@
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
margin-top: 24rpx;
gap: 12rpx;
margin-top: 14rpx;
}
.results-meta {
display: flex;
align-items: center;
gap: 12rpx;
min-width: 0;
}
.results-count {
font-size: 26rpx;
flex-shrink: 0;
font-size: 24rpx;
font-weight: 700;
color: #5d4b55;
}
.results-reset {
.filter-summary-chip {
display: inline-flex;
align-items: center;
min-width: 0;
max-width: 360rpx;
height: 46rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: #fdeff4;
color: #c6597d;
font-size: 22rpx;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.filter-banner {
margin-top: 20rpx;
padding: 20rpx 24rpx;
border-radius: 22rpx;
background: #fff1f5;
color: #b45172;
font-size: 24rpx;
line-height: 1.7;
.results-reset {
flex-shrink: 0;
height: 52rpx;
padding: 0 20rpx;
min-width: 0;
font-size: 22rpx;
}
.product-grid {
display: flex;
flex-wrap: wrap;
gap: 18rpx;
margin-top: 24rpx;
gap: 14rpx;
margin-top: 18rpx;
}
.product-grid-item {
width: calc(50% - 9rpx);
min-width: 0;
width: calc(50% - 7rpx);
}
.load-state {
display: flex;
align-items: center;
justify-content: center;
padding: 20rpx 0 10rpx;
}
.load-state-text {
font-size: 22rpx;
color: #8d7a84;
}