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

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
+7
View File
@@ -1,6 +1,13 @@
const request = require('../utils/request')
module.exports = {
getProductPage(params) {
return request({
url: '/product/list/page',
params
})
},
getAllProducts() {
return request({
url: '/product/list/all'
+85
View File
@@ -1,4 +1,36 @@
const request = require('../utils/request')
const actionGuard = require('../utils/action-guard')
const { API_BASE_URL, REQUEST_TIMEOUT } = require('../utils/config')
function normalizeUploadResponse(response) {
if (!response) {
throw new Error('头像上传失败')
}
if (response.statusCode === 401) {
throw new Error('登录已过期,请重新登录')
}
if (response.statusCode >= 400) {
throw new Error('头像上传失败')
}
let payload = response.data
if (typeof payload === 'string') {
try {
payload = JSON.parse(payload)
} catch (error) {}
}
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
if (payload.code === 200) {
return payload.data
}
throw new Error(payload.message || '头像上传失败')
}
return payload
}
module.exports = {
getUserInfo() {
@@ -23,6 +55,59 @@ module.exports = {
})
},
bindPhone(data) {
return request({
url: '/user/bind-phone',
method: 'POST',
data
})
},
updatePhone(data) {
return request({
url: '/user/phone',
method: 'PUT',
data
})
},
deactivateAccount() {
return request({
url: '/user/deactivate',
method: 'DELETE'
})
},
uploadAvatar(filePath) {
const signedHeaders = request.buildSignatureHeaders({
url: '/user/upload-avatar',
method: 'POST',
formData: {}
})
return actionGuard.run(null, `POST:/user/upload-avatar:${filePath || ''}`, () => new Promise((resolve, reject) => {
wx.uploadFile({
url: `${API_BASE_URL}/user/upload-avatar`,
filePath,
name: 'file',
timeout: REQUEST_TIMEOUT,
header: signedHeaders,
success: response => {
try {
resolve(normalizeUploadResponse(response))
} catch (error) {
reject(error)
}
},
fail: error => {
reject(new Error(error.errMsg || '头像上传失败'))
}
})
}), {
message: '上传处理中,请勿重复操作'
})
},
checkAccountAvailability(account) {
return request({
url: `/user/check/account/${encodeURIComponent(account)}`
+47
View File
@@ -1,6 +1,9 @@
const authApi = require('./api/auth')
const cartApi = require('./api/cart')
const userApi = require('./api/user')
const auth = require('./utils/auth')
const idleSession = require('./utils/idle-session')
const { IDLE_TIMEOUT_MS, IDLE_WARNING_MS } = require('./utils/config')
App({
globalData: {
@@ -13,12 +16,26 @@ App({
},
onLaunch() {
idleSession.init({
timeoutMs: IDLE_TIMEOUT_MS,
warningMs: IDLE_WARNING_MS,
isLoggedIn: () => auth.isLoggedIn(),
onLogout: () => this.handleIdleLogout()
})
this.bootstrapSession()
if (!auth.isLoggedIn()) {
this.tryWechatMiniAutoLogin()
}
},
onShow() {
idleSession.onAppShow()
},
onHide() {
idleSession.onAppHide()
},
bootstrapSession() {
const userInfo = auth.getStoredUserInfo()
const isLoggedIn = auth.isLoggedIn()
@@ -30,6 +47,7 @@ App({
}
if (isLoggedIn) {
this.refreshSessionUserInfo()
this.updateCartBadge()
return
}
@@ -168,6 +186,35 @@ App({
this.clearCartBadge()
},
async refreshSessionUserInfo() {
if (!auth.isLoggedIn()) {
return
}
try {
const userInfo = await userApi.getUserInfo()
this.refreshUserInfo(userInfo)
} catch (error) {}
},
async handleIdleLogout() {
if (!auth.isLoggedIn()) {
return
}
try {
await authApi.logout()
} catch (error) {}
this.clearUserSession()
wx.showToast({
title: '长时间未操作,已退出登录',
icon: 'none'
})
setTimeout(() => {
wx.reLaunch({
url: '/pages/auth/index'
})
}, 260)
},
async updateCartBadge() {
if (!auth.isLoggedIn()) {
this.clearCartBadge()
@@ -11,12 +11,24 @@ Component({
showStats: {
type: Boolean,
value: false
},
showQuickAdd: {
type: Boolean,
value: false
},
inCart: {
type: Boolean,
value: false
}
},
methods: {
handleTap() {
this.triggerEvent('select', this.properties.item)
},
handleQuickAdd() {
this.triggerEvent('quickadd', this.properties.item)
}
}
})
@@ -1,6 +1,6 @@
<view class="product-card" bindtap="handleTap">
<view class="product-cover-wrap">
<image class="product-cover" src="{{item.coverUrl}}" mode="aspectFill"></image>
<image class="product-cover" src="{{item.coverUrl}}" mode="aspectFill" lazy-load="{{true}}"></image>
<view class="product-cover-shadow"></view>
<view wx:if="{{showMeta && item.metaText}}" class="product-meta-badge">{{item.metaText}}</view>
</view>
@@ -15,7 +15,19 @@
<text class="product-price">{{item.priceText}}</text>
<text wx:if="{{showStats}}" class="product-stats">{{item.statsText}}</text>
</view>
<view class="product-arrow">查看</view>
<view wx:if="{{showQuickAdd}}" class="product-actions">
<view wx:if="{{!inCart}}" class="product-quick-add" catchtap="handleQuickAdd">
<view class="product-quick-add-icon">
<view class="product-quick-add-handle"></view>
<view class="product-quick-add-basket"></view>
<view class="product-quick-add-wheel product-quick-add-wheel--left"></view>
<view class="product-quick-add-wheel product-quick-add-wheel--right"></view>
<view class="product-quick-add-plus product-quick-add-plus--horizontal"></view>
<view class="product-quick-add-plus product-quick-add-plus--vertical"></view>
</view>
</view>
<view wx:else class="product-in-cart">购物车已有</view>
</view>
</view>
</view>
</view>
@@ -1,8 +1,9 @@
.product-card {
display: flex;
flex-direction: column;
min-width: 0;
overflow: hidden;
border-radius: 30rpx;
border-radius: 28rpx;
background: #ffffff;
border: 1rpx solid rgba(239, 216, 224, 0.84);
box-shadow: 0 18rpx 42rpx rgba(122, 67, 88, 0.08);
@@ -14,7 +15,7 @@
.product-cover {
width: 100%;
height: 300rpx;
height: 288rpx;
background: #f7ecf0;
}
@@ -29,60 +30,72 @@
.product-meta-badge {
position: absolute;
left: 18rpx;
top: 18rpx;
max-width: calc(100% - 36rpx);
padding: 10rpx 16rpx;
left: 16rpx;
top: 16rpx;
max-width: calc(100% - 32rpx);
padding: 8rpx 14rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.92);
color: #7a5262;
font-size: 20rpx;
font-size: 19rpx;
font-weight: 700;
}
.product-body {
display: flex;
flex-direction: column;
gap: 12rpx;
padding: 22rpx 22rpx 24rpx;
gap: 10rpx;
min-height: 220rpx;
padding: 20rpx 20rpx 22rpx;
}
.product-title {
font-size: 28rpx;
min-height: 74rpx;
font-size: 27rpx;
font-weight: 700;
line-height: 1.5;
line-height: 1.38;
color: #2d2430;
word-break: break-all;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.product-meta {
font-size: 24rpx;
font-size: 22rpx;
color: #8d7a84;
line-height: 1.5;
line-height: 1.4;
}
.product-tags {
display: flex;
flex-wrap: wrap;
gap: 10rpx;
gap: 8rpx;
}
.tag-item {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 8rpx 16rpx;
max-width: 100%;
padding: 6rpx 14rpx;
border-radius: 999rpx;
background: #fbecf1;
color: #c6597d;
font-size: 20rpx;
font-size: 18rpx;
line-height: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.product-footer {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16rpx;
margin-top: 4rpx;
gap: 14rpx;
margin-top: auto;
}
.product-price-wrap {
@@ -90,30 +103,115 @@
min-width: 0;
}
.product-actions {
display: flex;
align-items: center;
flex-shrink: 0;
}
.product-price {
display: block;
font-size: 30rpx;
font-weight: 700;
font-size: 34rpx;
line-height: 1.12;
font-weight: 800;
color: #d5536f;
}
.product-stats {
display: block;
margin-top: 8rpx;
font-size: 22rpx;
margin-top: 6rpx;
font-size: 20rpx;
line-height: 1.4;
color: #9d8a92;
}
.product-arrow {
.product-quick-add {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 96rpx;
height: 52rpx;
width: 64rpx;
height: 64rpx;
border-radius: 22rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
box-shadow: 0 14rpx 30rpx rgba(198, 89, 125, 0.22);
}
.product-quick-add-icon {
position: relative;
width: 32rpx;
height: 28rpx;
}
.product-quick-add-handle {
position: absolute;
left: 2rpx;
top: 2rpx;
width: 12rpx;
height: 4rpx;
border-radius: 999rpx;
background: #ffffff;
transform: rotate(20deg);
transform-origin: left center;
}
.product-quick-add-basket {
position: absolute;
left: 6rpx;
top: 8rpx;
width: 18rpx;
height: 11rpx;
border: 3rpx solid #ffffff;
border-top: 0;
border-radius: 0 0 6rpx 6rpx;
}
.product-quick-add-wheel {
position: absolute;
top: 22rpx;
width: 6rpx;
height: 6rpx;
border-radius: 50%;
background: #ffffff;
}
.product-quick-add-wheel--left {
left: 10rpx;
}
.product-quick-add-wheel--right {
left: 22rpx;
}
.product-quick-add-plus {
position: absolute;
border-radius: 999rpx;
background: #ffffff;
}
.product-quick-add-plus--horizontal {
top: 2rpx;
right: 0;
width: 10rpx;
height: 3rpx;
}
.product-quick-add-plus--vertical {
top: -1rpx;
right: 4rpx;
width: 3rpx;
height: 10rpx;
}
.product-in-cart {
display: inline-flex;
align-items: center;
justify-content: center;
height: 56rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #c6597d;
font-size: 22rpx;
background: #f8eef1;
color: #8f6e7a;
font-size: 20rpx;
font-weight: 700;
white-space: nowrap;
}
+8 -7
View File
@@ -2,6 +2,7 @@ const authApi = require('../../api/auth')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
const authStore = require('../../utils/auth')
const actionGuard = require('../../utils/action-guard')
const navigation = require('../../utils/navigation')
const { runWithLoading } = require('../../utils/loading')
@@ -86,14 +87,14 @@ Page({
const systemInfo = wx.getSystemInfoSync()
if (systemInfo && systemInfo.platform === 'devtools') {
supported = false
disabledReason = '开发者工具暂不支持微信手机号一键登录,请使用真机调试或传统登录。'
disabledReason = '开发者工具暂不支持一键登录,请用真机或其他方式登录'
}
} catch (error) {
supported = false
}
if (!supported && !disabledReason) {
disabledReason = '当前微信环境暂不支持手机号一键登录,请使用账号密码或验证码登录。'
disabledReason = '当前环境暂不支持一键登录,请使用其他方式登录'
}
this.setData({
@@ -385,7 +386,7 @@ Page({
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前暂无法预加载可登录门店,可直接尝试登录。',
message: '暂时无法加载门店,可直接登录',
shops: []
})
}
@@ -398,7 +399,7 @@ Page({
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前暂无法预加载可登录门店,可直接尝试登录。',
message: '暂时无法加载门店,可直接登录',
shops: []
})
}
@@ -907,11 +908,11 @@ Page({
buildAuthHelperText(activeTab, loginType) {
if (activeTab === 'register') {
return '注册前会检查账号和手机号是否可用,并要求先选择门店。'
return '注册前请先选门店'
}
if (loginType === 'phone') {
return '验证码登录时,若手机号未注册,会先选择门店后自动注册。'
return '未注册手机号会先选门店'
}
return '若账号绑定了多家门店,登录前需要先选择本次门店。'
return '多门店账号需先选门店'
}
})
+9 -9
View File
@@ -12,7 +12,7 @@
<view class="wechat-login-panel">
<view class="wechat-login-copy">
<text class="wechat-login-title">微信手机号一键登录</text>
<text class="wechat-login-desc">最快的登录方式,首次授权也能自动注册。</text>
<text class="wechat-login-desc">更快登录</text>
</view>
<button
@@ -34,22 +34,22 @@
微信手机号一键登录
</button>
<text class="wechat-login-hint">{{wechatMiniSupported ? '若只绑定一家可用门店,会直接登录。' : wechatMiniDisabledReason}}</text>
<text class="wechat-login-hint">{{wechatMiniSupported ? '单门店可直接登录' : wechatMiniDisabledReason}}</text>
</view>
<view wx:if="{{miniShopTicket && !showMiniShopSelector}}" class="hint-card mini-login-resume">
<text class="mini-login-resume-text">微信身份已识别完成,还差一步门店确认即可登录。</text>
<text class="mini-login-resume-text">请选择登录门店</text>
<view class="ghost-btn mini-login-resume-btn" bindtap="handleResumeMiniShopSelector">继续选择门店</view>
</view>
<view wx:if="{{!traditionalLoginExpanded}}" class="traditional-entry">
<view class="secondary-btn traditional-entry-btn" bindtap="handleShowTraditionalLogin">使用账号密码或验证码登录</view>
<view class="secondary-btn traditional-entry-btn" bindtap="handleShowTraditionalLogin">其他登录方式</view>
</view>
<view wx:if="{{traditionalLoginExpanded}}" class="traditional-login-panel">
<view class="login-divider">
<view class="divider-line"></view>
<text class="login-divider-text">传统登录方式</text>
<text class="login-divider-text">其他方式</text>
<view class="divider-line"></view>
</view>
@@ -130,7 +130,7 @@
<view wx:if="{{showResetPanel}}" class="page-card reset-card">
<view class="section-title">重置密码</view>
<view class="section-subtitle">使用短信验证码设置新的登录密码。</view>
<view class="section-subtitle">短信验证后重置密码</view>
<view class="field-block">
<text class="field-label">手机号</text>
@@ -157,8 +157,8 @@
<view wx:if="{{showMiniShopSelector}}" class="mini-shop-mask" catchtouchmove="noop">
<view class="page-card mini-shop-modal">
<text class="mini-shop-kicker">{{miniShopNewUser ? '首次微信登录' : '确认本次登录门店'}}</text>
<text class="mini-shop-title">{{miniShopNewUser ? '先选一家门店,我们会自动注册并登录' : '该账号绑定了多家门店,请先选择本次登录门店'}}</text>
<text class="mini-shop-desc">{{miniShopMessage || '选择后将继续完成登录。'}}</text>
<text class="mini-shop-title">{{miniShopNewUser ? '先选门店' : '选择登录门店'}}</text>
<text class="mini-shop-desc">{{miniShopMessage || '选择后继续登录'}}</text>
<view class="field-block mini-shop-field">
<text class="field-label">登录门店</text>
@@ -167,7 +167,7 @@
</picker>
</view>
<view wx:if="{{miniShopNewUser}}" class="hint-card mini-shop-note">首次通过微信手机号登录时,会自动创建账号、绑定手机号,并将当前门店作为本次登录门店。</view>
<view wx:if="{{miniShopNewUser}}" class="hint-card mini-shop-note">首次登录会自动注册并绑定手机号。</view>
<view class="mini-shop-actions">
<view class="secondary-btn mini-shop-action" bindtap="handleCloseMiniShopSelector">稍后再选</view>
+8 -8
View File
@@ -4,7 +4,7 @@
<view class="page-content cart-content">
<view wx:if="{{!isLoggedIn}}" 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="handleOpenAuth">去登录</view>
</view>
@@ -12,23 +12,23 @@
<view class="page-hero cart-hero">
<text class="hero-kicker">结算准备</text>
<text class="hero-title">已选 {{selectedCount}} 个预约项目</text>
<text class="hero-desc">先确认美甲师和预约时间,再统一提交订单,避免来回修改。</text>
<text class="hero-desc">确认美甲师和时间后再下单。</text>
<view class="summary-strip">
<view class="summary-metric">
<text class="summary-label">选中项目</text>
<text class="summary-value">{{selectedCount}} 项</text>
<text class="summary-note">可分批勾选结算</text>
<text class="summary-note">可分批结算</text>
</view>
<view class="summary-metric">
<text class="summary-label">数量合计</text>
<text class="summary-value">{{totalQuantity}} 件</text>
<text class="summary-note">支持直接增减数量</text>
<text class="summary-note">可改数量</text>
</view>
<view class="summary-metric">
<text class="summary-label">待支付</text>
<text class="summary-value">{{totalAmountText}}</text>
<text class="summary-note">已自动计算优惠</text>
<text class="summary-note">已算优惠</text>
</view>
</view>
</view>
@@ -41,7 +41,7 @@
<view wx:for="{{cartItems}}" wx:key="id" class="page-card cart-item-card">
<view class="cart-item-top">
<view class="select-dot {{item.selected ? 'active' : ''}}" data-index="{{index}}" bindtap="handleToggleSelect"></view>
<image class="cart-thumb" src="{{item.productImageUrl}}" mode="aspectFill" data-product-id="{{item.productId}}" bindtap="handleOpenProduct"></image>
<image class="cart-thumb" src="{{item.productImageUrl}}" mode="aspectFill" data-product-id="{{item.productId}}" bindtap="handleOpenProduct" lazy-load="{{true}}"></image>
<view class="cart-main">
<view class="cart-title-row">
<view class="cart-title" data-product-id="{{item.productId}}" bindtap="handleOpenProduct">{{item.productTitle}}</view>
@@ -93,7 +93,7 @@
<view wx:if="{{selectedCount}}" class="page-card coupon-card">
<view class="section-title">优惠方式</view>
<view class="section-subtitle">系统会优先帮你匹配最合适的 VIP 自动折扣,普通优惠券仍可手动改选。</view>
<view class="section-subtitle">系统会优先匹配 VIP 优惠。</view>
<radio-group bindchange="handleCouponChange">
<label class="coupon-option">
@@ -144,7 +144,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="handleBrowseProducts">去逛作品</view>
</view>
</view>
+41 -2
View File
@@ -13,7 +13,15 @@ Page({
data: {
loading: false,
isLoggedIn: false,
coupons: []
coupons: [],
filteredCoupons: [],
activeFilter: 'all',
filterOptions: [
{ value: 'all', label: '全部' },
{ value: 'available', label: '未使用' },
{ value: 'used', label: '已使用' },
{ value: 'expired', label: '已过期' }
]
},
onShow() {
@@ -30,6 +38,8 @@ Page({
if (!isLoggedIn) {
this.setData({
coupons: [],
filteredCoupons: [],
activeFilter: 'all',
loading: false
})
return
@@ -47,9 +57,11 @@ Page({
this.setData({
coupons: list
})
this.applyFilter(this.data.activeFilter, list)
} catch (error) {
this.setData({
coupons: []
coupons: [],
filteredCoupons: []
})
wx.showToast({
title: error.message || '优惠券加载失败',
@@ -62,6 +74,33 @@ Page({
}
},
applyFilter(filterValue, sourceCoupons) {
const activeFilter = filterValue || 'all'
const coupons = Array.isArray(sourceCoupons) ? sourceCoupons : this.data.coupons
let filteredCoupons = coupons
if (activeFilter === 'available') {
filteredCoupons = coupons.filter(item => Number(item.status) === 1)
} else if (activeFilter === 'used') {
filteredCoupons = coupons.filter(item => Number(item.status) === 2)
} else if (activeFilter === 'expired') {
filteredCoupons = coupons.filter(item => Number(item.status) === 3)
}
this.setData({
activeFilter,
filteredCoupons
})
},
handleFilterChange(event) {
const value = event.currentTarget.dataset.value
if (!value || value === this.data.activeFilter) {
return
}
this.applyFilter(value)
},
handleOpenAuth() {
navigation.openAuth('/pages/coupons/index')
},
+32 -13
View File
@@ -4,27 +4,46 @@
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看优惠券</text>
<text class="empty-desc">可用优惠、VIP 自动折扣都会统一展示在这里。</text>
<text class="empty-desc">登录后查看可用优惠。</text>
<view class="ghost-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{coupons.length}}">
<view class="page-hero coupons-hero">
<text class="hero-kicker">优惠资产</text>
<text class="hero-title">当前有 {{coupons.length}} 张可查看</text>
<text class="hero-desc">普通优惠券和系统自动匹配的 VIP 折扣都会在结算前统一展示。</text>
<text class="hero-title">当前有 {{coupons.length}} 张</text>
<text class="hero-desc">下单前可查看可用优惠。</text>
</view>
<view wx:for="{{coupons}}" wx:key="id" class="page-card coupon-card">
<view class="coupon-top">
<view>
<view class="coupon-title">{{item.couponName}}</view>
<view class="coupon-source">{{item.sourceText}}</view>
</view>
<view class="coupon-status">{{item.statusName || '待使用'}}</view>
<view class="coupon-filter-row">
<view
wx:for="{{filterOptions}}"
wx:key="value"
class="coupon-filter-chip {{activeFilter === item.value ? 'active' : ''}}"
data-value="{{item.value}}"
bindtap="handleFilterChange"
>
{{item.label}}
</view>
<view class="coupon-benefit">{{item.benefitText}}</view>
<view class="coupon-period">{{item.periodText}}</view>
</view>
<block wx:if="{{filteredCoupons.length}}">
<view wx:for="{{filteredCoupons}}" wx:key="id" class="page-card coupon-card">
<view class="coupon-top">
<view>
<view class="coupon-title">{{item.couponName}}</view>
<view class="coupon-source">{{item.sourceText}}</view>
</view>
<view class="coupon-status">{{item.statusName || '待使用'}}</view>
</view>
<view class="coupon-benefit">{{item.benefitText}}</view>
<view class="coupon-period">{{item.periodText}}</view>
</view>
</block>
<view wx:else class="page-card empty-card">
<text class="empty-title">当前筛选下暂无优惠券</text>
<text class="empty-desc">换个筛选试试。</text>
</view>
</block>
@@ -34,7 +53,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>
</view>
</view>
+26
View File
@@ -2,6 +2,32 @@
margin-bottom: 20rpx;
}
.coupon-filter-row {
display: flex;
flex-wrap: wrap;
gap: 16rpx;
margin-bottom: 20rpx;
}
.coupon-filter-chip {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 120rpx;
height: 60rpx;
padding: 0 24rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.78);
color: #8d7a84;
font-size: 24rpx;
font-weight: 600;
}
.coupon-filter-chip.active {
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
color: #ffffff;
}
.coupon-card + .coupon-card {
margin-top: 20rpx;
}
+94 -62
View File
@@ -1,8 +1,9 @@
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const cache = require('../../utils/cache')
const { buildProductCards } = require('../../utils/product')
const { resolveImageList } = require('../../utils/file')
const { DEFAULT_SHOP_IMAGE } = require('../../utils/config')
const { DEFAULT_SHOP_IMAGE, CACHE_TTL } = require('../../utils/config')
const productApi = require('../../api/product')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
@@ -11,6 +12,7 @@ Page({
data: {
initialized: false,
loading: false,
loadingMore: false,
isLoggedIn: false,
userInfo: null,
greeting: '欢迎来到 Yumi Nail',
@@ -18,14 +20,15 @@ Page({
searchKeyword: '',
bannerImages: [],
featuredItems: [],
popularSource: [],
popularItems: [],
popularPage: 1,
pageSize: 6,
hasMore: false
hasMore: false,
popularTotal: 0
},
onLoad() {
this.homeRequestId = 0
this.loadHomeData()
},
@@ -37,22 +40,16 @@ Page({
},
async onPullDownRefresh() {
cache.removeByPrefix('home:')
await this.loadHomeData()
wx.stopPullDownRefresh()
},
onReachBottom() {
if (!this.data.hasMore) {
if (!this.data.hasMore || this.data.loadingMore) {
return
}
const nextPage = this.data.popularPage + 1
const nextItems = this.data.popularSource.slice(0, nextPage * this.data.pageSize)
this.setData({
popularPage: nextPage,
popularItems: nextItems,
hasMore: nextItems.length < this.data.popularSource.length
})
this.loadPopularProducts(false)
},
syncUserState() {
@@ -88,81 +85,116 @@ Page({
},
async loadHomeData() {
const requestId = ++this.homeRequestId
this.setData({ loading: true })
this.syncUserState()
try {
await Promise.all([
this.loadUserProfile(),
this.loadBannerImages(),
this.loadFeaturedProducts(),
this.loadPopularProducts()
this.loadBannerImages(requestId),
this.loadFeaturedProducts(requestId),
this.loadPopularProducts(true, requestId)
])
this.setData({
initialized: true
})
if (requestId === this.homeRequestId) {
this.setData({
initialized: true
})
}
} catch (error) {
wx.showToast({
title: error.message || '首页加载失败',
icon: 'none'
})
} finally {
this.setData({ loading: false })
if (requestId === this.homeRequestId) {
this.setData({ loading: false })
}
}
},
async loadBannerImages() {
const shops = await shopApi.getPublicShops()
const list = Array.isArray(shops) ? shops : []
const banners = []
for (let index = 0; index < list.length; index += 1) {
const shop = list[index]
const imageIds = shop.coverImageFileId || shop.imageFileIds
const urls = await resolveImageList(imageIds, DEFAULT_SHOP_IMAGE)
if (urls[0]) {
banners.push({
async loadBannerImages(requestId) {
const banners = await cache.remember('home:banners', CACHE_TTL.banner, async () => {
const shops = await shopApi.getPublicShops()
const list = Array.isArray(shops) ? shops : []
const resolved = await Promise.all(list.slice(0, 6).map(async (shop, index) => {
const imageIds = shop.coverImageFileId || shop.imageFileIds
const urls = await resolveImageList(imageIds, DEFAULT_SHOP_IMAGE)
return {
id: `${shop.id}-${index}`,
shopId: shop.id,
shopName: shop.shopName,
businessHours: shop.businessHours || '欢迎到店体验',
imageUrl: urls[0]
}
}))
return resolved.filter(item => item.imageUrl)
})
if (requestId === this.homeRequestId) {
this.setData({
bannerImages: Array.isArray(banners) ? banners : []
})
}
},
async loadFeaturedProducts(requestId) {
const items = await cache.remember('home:featured', CACHE_TTL.homeList, async () => {
const result = await productApi.getProductPage({
page: 1,
size: 6,
tag: '精选'
})
return buildProductCards(result && result.list ? result.list : [])
})
if (requestId === this.homeRequestId) {
this.setData({
featuredItems: Array.isArray(items) ? items : []
})
}
},
async loadPopularProducts(reset, requestId) {
const currentRequestId = requestId || this.homeRequestId
const nextPage = reset ? 1 : this.data.popularPage + 1
const loadingState = reset ? { loading: true } : { loadingMore: true }
this.setData(loadingState)
try {
const result = await productApi.getProductPage({
page: nextPage,
size: this.data.pageSize,
tag: '热门'
})
const cards = await buildProductCards(result && result.list ? result.list : [])
if (currentRequestId !== this.homeRequestId) {
return
}
const mergedItems = reset ? cards : this.data.popularItems.concat(cards)
const total = Number(result && result.total) || 0
this.setData({
popularItems: mergedItems,
popularPage: nextPage,
popularTotal: total,
hasMore: mergedItems.length < total
})
} catch (error) {
if (currentRequestId !== this.homeRequestId) {
return
}
wx.showToast({
title: error.message || '热门作品加载失败',
icon: 'none'
})
} finally {
if (currentRequestId === this.homeRequestId) {
this.setData({
loadingMore: false
})
}
}
this.setData({
bannerImages: banners.slice(0, 6)
})
},
async loadFeaturedProducts() {
let products = await productApi.getProductsByTag('精选')
if (!Array.isArray(products) || !products.length) {
products = await productApi.getAllProducts()
}
const cards = await buildProductCards((products || []).slice(0, 6))
this.setData({
featuredItems: cards
})
},
async loadPopularProducts() {
let products = await productApi.getProductsByTag('热门')
if (!Array.isArray(products) || !products.length) {
products = await productApi.getAllProducts()
}
const cards = await buildProductCards(products || [])
const initialItems = cards.slice(0, this.data.pageSize)
this.setData({
popularSource: cards,
popularItems: initialItems,
popularPage: 1,
hasMore: initialItems.length < cards.length
})
},
handleSearchInput(event) {
+15 -12
View File
@@ -7,7 +7,7 @@
<view class="page-hero home-hero">
<text class="hero-kicker">{{isLoggedIn ? greeting : 'YUMI NAIL 小程序'}}</text>
<text class="hero-title">{{displayName}}</text>
<text class="hero-desc">先看门店氛围,再挑喜欢的作品,最后一站式完成收藏、加购和预约。</text>
<text class="hero-desc">先选喜欢的作品。</text>
<view class="hero-action-row">
<view class="hero-action primary" bindtap="handleProfileTap">{{isLoggedIn ? '进入个人中心' : '立即登录'}}</view>
@@ -31,22 +31,22 @@
<view class="summary-metric">
<text class="summary-label">门店橱窗</text>
<text class="summary-value">{{bannerImages.length ? bannerImages.length : 0}} 家</text>
<text class="summary-note">先看环境,再决定去哪家</text>
<text class="summary-note">看环境</text>
</view>
<view class="summary-metric">
<text class="summary-label">精选作品</text>
<text class="summary-value">{{featuredItems.length ? featuredItems.length : 0}} 款</text>
<text class="summary-note">适合快速找到灵感</text>
<text class="summary-note">找灵感</text>
</view>
<view class="summary-metric">
<text class="summary-label">热门推荐</text>
<text class="summary-value">{{popularItems.length ? popularItems.length : 0}} 条</text>
<text class="summary-note">当前最受欢迎的预约款式</text>
<text class="summary-note">热门款</text>
</view>
</view>
<view wx:if="{{!isLoggedIn}}" class="guest-tip">
登录后可同步收藏、购物车和预约记录,切换设备也不会丢。
登录后可同步收藏和预约记录。
</view>
</view>
@@ -55,7 +55,7 @@
<view class="section-copy">
<text class="section-kicker">门店氛围</text>
<text class="section-title">先看看线下环境</text>
<text class="section-subtitle">轮播展示门店图片和营业时间,帮助你快速判断想去的店。</text>
<text class="section-subtitle">看店铺环境</text>
</view>
</view>
@@ -63,7 +63,7 @@
<swiper class="banner-swiper" indicator-dots autoplay circular interval="3200">
<swiper-item wx:for="{{bannerImages}}" wx:key="id">
<view class="banner-item" data-shop-id="{{item.shopId}}" bindtap="handleBannerTap">
<image class="banner-image" src="{{item.imageUrl}}" mode="aspectFill"></image>
<image class="banner-image" src="{{item.imageUrl}}" mode="aspectFill" lazy-load="{{true}}"></image>
<view class="banner-mask">
<view class="banner-badge">门店实拍</view>
<view class="banner-title">{{item.shopName}}</view>
@@ -76,7 +76,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>
</view>
@@ -85,7 +85,7 @@
<view class="section-copy">
<text class="section-kicker">快速入门</text>
<text class="section-title">精选作品</text>
<text class="section-subtitle">适合先快速逛一圈的热门款式,向右滑动查看更多。</text>
<text class="section-subtitle">先看热门款</text>
</view>
<view class="section-link" bindtap="handleSeeAllFeatured">查看全部</view>
</view>
@@ -102,7 +102,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>
</view>
@@ -111,7 +111,7 @@
<view class="section-copy">
<text class="section-kicker">热门预约</text>
<text class="section-title">最近大家都在看</text>
<text class="section-subtitle">结合点赞和收藏热度展示当前最受欢迎的款式。</text>
<text class="section-subtitle">热门款式</text>
</view>
<view class="section-link" bindtap="handleSeeAllPopular">查看全部</view>
</view>
@@ -121,6 +121,9 @@
<product-card item="{{item}}" show-stats="{{true}}" bindselect="handleProductSelect"></product-card>
</view>
</view>
<view wx:if="{{popularItems.length && (loadingMore || !hasMore)}}" class="section-load-state">
<text class="section-load-text">{{loadingMore ? '正在加载更多热门作品...' : '已经到底了'}}</text>
</view>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载首页内容</text>
@@ -128,7 +131,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>
</view>
</view>
+11
View File
@@ -148,3 +148,14 @@
.popular-card {
width: calc(50% - 9rpx);
}
.section-load-state {
display: flex;
justify-content: center;
padding-top: 18rpx;
}
.section-load-text {
font-size: 22rpx;
color: #8d7a84;
}
+1 -1
View File
@@ -2,6 +2,6 @@
<view class="redirect-page">
<view class="redirect-card">
<view class="redirect-title">正在进入首页</view>
<view class="redirect-desc">这个 `pages/index` 是初始化遗留页,当前实际首页是 `pages/home/index`。</view>
<view class="redirect-desc">即将进入首页</view>
</view>
</view>
+29 -21
View File
@@ -1,6 +1,7 @@
const orderApi = require('../../api/order')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const actionGuard = require('../../utils/action-guard')
const { resolveLegacyImage } = require('../../utils/file')
const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format')
const { runWithLoading } = require('../../utils/loading')
@@ -38,11 +39,11 @@ Page({
...order,
statusText: getOrderStatusText(order),
statusClass: getOrderStatusClass(order),
actualAmountText: `¥${formatPrice(order.actualAmount)}`,
actualAmountText: `\u00a5${formatPrice(order.actualAmount)}`,
items: await Promise.all((order.items || []).map(async item => ({
...item,
productImageUrl: await resolveLegacyImage(item.productImage),
priceText: `¥${formatPrice(item.price)}`,
priceText: `\u00a5${formatPrice(item.price)}`,
appointmentText: formatDateTime(item.appointmentTime)
})))
})))
@@ -55,7 +56,7 @@ Page({
orders: []
})
wx.showToast({
title: error.message || '订单列表加载失败',
title: error.message || '\u8ba2\u5355\u5217\u8868\u52a0\u8f7d\u5931\u8d25',
icon: 'none'
})
} finally {
@@ -79,28 +80,35 @@ Page({
return
}
const result = await new Promise(resolve => {
wx.showModal({
title: '取消订单',
content: '确认取消这笔订单吗?',
success: modalRes => resolve(Boolean(modalRes.confirm))
})
})
if (!result) {
return
}
try {
await runWithLoading(() => orderApi.cancelOrder(orderId))
wx.showToast({
title: '订单已取消',
icon: 'none'
await actionGuard.run(this, `order:cancel:${orderId}`, async () => {
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '\u53d6\u6d88\u8ba2\u5355',
content: '\u786e\u8ba4\u53d6\u6d88\u8fd9\u7b14\u8ba2\u5355\u5417\uff1f',
success: modalRes => resolve(Boolean(modalRes.confirm))
})
})
if (!confirmed) {
return
}
await runWithLoading(() => orderApi.cancelOrder(orderId))
wx.showToast({
title: '\u8ba2\u5355\u5df2\u53d6\u6d88',
icon: 'none'
})
await this.loadOrders()
}, {
message: '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
})
this.loadOrders()
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '取消订单失败',
title: error.message || '\u53d6\u6d88\u8ba2\u5355\u5931\u8d25',
icon: 'none'
})
}
+4 -4
View File
@@ -4,7 +4,7 @@
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" 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="handleOpenAuth">去登录</view>
</view>
@@ -12,7 +12,7 @@
<view class="page-hero orders-hero">
<text class="hero-kicker">预约记录</text>
<text class="hero-title">共 {{orders.length}} 笔订单</text>
<text class="hero-desc">这里展示每笔订单的状态、项目、预约时间以及取消入口。</text>
<text class="hero-desc">查看订单状态和预约时间。</text>
</view>
<view wx:for="{{orders}}" wx:key="id" class="page-card order-card">
@@ -25,7 +25,7 @@
</view>
<view wx:for="{{item.items}}" wx:key="id" wx:for-item="orderItem" class="order-item">
<image class="order-thumb" src="{{orderItem.productImageUrl}}" mode="aspectFill"></image>
<image class="order-thumb" src="{{orderItem.productImageUrl}}" mode="aspectFill" lazy-load="{{true}}"></image>
<view class="order-main">
<view class="order-title">{{orderItem.productTitle}}</view>
<view class="order-line">{{orderItem.priceText}} x {{orderItem.quantity}}</view>
@@ -47,7 +47,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>
</view>
</view>
+60 -35
View File
@@ -3,6 +3,7 @@ const productApi = require('../../api/product')
const productLikeApi = require('../../api/product-like')
const shopApi = require('../../api/shop')
const wishlistApi = require('../../api/wishlist')
const actionGuard = require('../../utils/action-guard')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { resolveImageList } = require('../../utils/file')
@@ -110,7 +111,7 @@ Page({
...product,
displayTitle: getProductTitle(product),
priceText: `¥${formatPrice(product.price)}`,
descriptionText: product.description || '店家还没有补充作品说明。'
descriptionText: product.description || '商家还没有补充作品说明。'
}
this.setData({
@@ -193,25 +194,32 @@ Page({
}
try {
const nextFavorite = !this.data.isFavorite
if (this.data.isFavorite) {
await runWithLoading(() => wishlistApi.removeFromWishlist(product.id))
product.collectCount = Math.max(0, Number(product.collectCount || 0) - 1)
} else {
await runWithLoading(() => wishlistApi.addToWishlist(product.id))
product.collectCount = Number(product.collectCount || 0) + 1
}
await actionGuard.run(this, `wishlist:toggle:${product.id}`, async () => {
const nextFavorite = !this.data.isFavorite
if (this.data.isFavorite) {
await runWithLoading(() => wishlistApi.removeFromWishlist(product.id))
product.collectCount = Math.max(0, Number(product.collectCount || 0) - 1)
} else {
await runWithLoading(() => wishlistApi.addToWishlist(product.id))
product.collectCount = Number(product.collectCount || 0) + 1
}
this.setData({
isFavorite: nextFavorite,
product
})
this.setData({
isFavorite: nextFavorite,
product
})
wx.showToast({
title: nextFavorite ? '已加入收藏' : '已取消收藏',
icon: 'none'
wx.showToast({
title: nextFavorite ? '已加入收藏' : '已取消收藏',
icon: 'none'
})
}, {
message: '操作进行中,请勿重复点击'
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '收藏操作失败',
icon: 'none'
@@ -226,25 +234,32 @@ Page({
}
try {
const nextLiked = !this.data.isLiked
if (this.data.isLiked) {
await runWithLoading(() => productLikeApi.unlikeProduct(product.id))
product.likeCount = Math.max(0, Number(product.likeCount || 0) - 1)
} else {
await runWithLoading(() => productLikeApi.likeProduct(product.id))
product.likeCount = Number(product.likeCount || 0) + 1
}
await actionGuard.run(this, `like:toggle:${product.id}`, async () => {
const nextLiked = !this.data.isLiked
if (this.data.isLiked) {
await runWithLoading(() => productLikeApi.unlikeProduct(product.id))
product.likeCount = Math.max(0, Number(product.likeCount || 0) - 1)
} else {
await runWithLoading(() => productLikeApi.likeProduct(product.id))
product.likeCount = Number(product.likeCount || 0) + 1
}
this.setData({
isLiked: nextLiked,
product
})
this.setData({
isLiked: nextLiked,
product
})
wx.showToast({
title: nextLiked ? '已点赞' : '已取消点赞',
icon: 'none'
wx.showToast({
title: nextLiked ? '已点赞' : '已取消点赞',
icon: 'none'
})
}, {
message: '操作进行中,请勿重复点击'
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '点赞操作失败',
icon: 'none'
@@ -259,16 +274,21 @@ Page({
}
try {
await runWithLoading(() => cartApi.addToCart({
await actionGuard.run(this, `cart:add:${product.id}`, () => runWithLoading(() => cartApi.addToCart({
productId: product.id,
quantity: 1
}))
})), {
message: '购物车处理中,请勿重复操作'
})
await getApp().updateCartBadge()
wx.showToast({
title: '已加入购物车',
icon: 'none'
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '加入购物车失败',
icon: 'none'
@@ -283,15 +303,20 @@ Page({
}
try {
await runWithLoading(() => cartApi.addToCart({
await actionGuard.run(this, `cart:buy-now:${product.id}`, () => runWithLoading(() => cartApi.addToCart({
productId: product.id,
quantity: 1
}))
})), {
message: '操作进行中,请勿重复点击'
})
await getApp().updateCartBadge()
wx.switchTab({
url: '/pages/cart/index'
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '操作失败',
icon: 'none'
@@ -13,7 +13,7 @@
<view class="media-box">
<swiper class="media-swiper" indicator-dots autoplay circular>
<swiper-item wx:for="{{productImages}}" wx:key="*this">
<image class="media-image" src="{{item}}" mode="aspectFill" data-url="{{item}}" bindtap="handlePreviewImage"></image>
<image class="media-image" src="{{item}}" mode="aspectFill" data-url="{{item}}" bindtap="handlePreviewImage" lazy-load="{{true}}"></image>
</swiper-item>
</swiper>
<view class="media-mask">
@@ -30,24 +30,24 @@
<text class="section-kicker">作品详情</text>
<view class="product-title">{{product.displayTitle}}</view>
<view class="product-price">{{product.priceText}}</view>
<view class="product-brief">适合先看作品风格、门店信息和可预约情况,再决定是否立即下单。</view>
<view class="product-brief">查看作品、门店和可预约信息。</view>
</view>
<view class="summary-strip detail-summary">
<view class="summary-metric" bindtap="handleOpenShop">
<text class="summary-label">所属门店</text>
<text class="summary-value detail-summary-value">{{shopInfo ? shopInfo.shopName : '待绑定'}}</text>
<text class="summary-note">点击查看门店详情</text>
<text class="summary-note">查看门店</text>
</view>
<view class="summary-metric">
<text class="summary-label">可约美甲师</text>
<text class="summary-value detail-summary-value">{{artistCountText}}</text>
<text class="summary-note">预约前可在购物车继续选择</text>
<text class="summary-note">可继续选择</text>
</view>
<view class="summary-metric">
<text class="summary-label">最早可约</text>
<text class="summary-value detail-summary-value">{{earliestBookableText}}</text>
<text class="summary-note">以门店营业时间为准</text>
<text class="summary-note">以营业时间为准</text>
</view>
</view>
+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;
}
+97 -44
View File
@@ -3,6 +3,7 @@ const couponApi = require('../../api/coupon')
const orderApi = require('../../api/order')
const userApi = require('../../api/user')
const wishlistApi = require('../../api/wishlist')
const actionGuard = require('../../utils/action-guard')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { DEFAULT_AVATAR } = require('../../utils/config')
@@ -25,6 +26,7 @@ Page({
},
async loadProfile() {
this._avatarReloadSource = ''
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
@@ -60,7 +62,7 @@ Page({
})
} catch (error) {
wx.showToast({
title: error.message || '个人中心加载失败',
title: error.message || '\u4e2a\u4eba\u4e2d\u5fc3\u52a0\u8f7d\u5931\u8d25',
icon: 'none'
})
} finally {
@@ -83,28 +85,28 @@ Page({
},
handleOpenOrders() {
if (!navigation.ensureLogin('查看订单')) {
if (!navigation.ensureLogin('\u67e5\u770b\u8ba2\u5355')) {
return
}
navigation.navigate('/pages/orders/index')
},
handleOpenWishlist() {
if (!navigation.ensureLogin('查看收藏')) {
if (!navigation.ensureLogin('\u67e5\u770b\u6536\u85cf')) {
return
}
navigation.navigate('/pages/wishlist/index')
},
handleOpenCoupons() {
if (!navigation.ensureLogin('查看优惠券')) {
if (!navigation.ensureLogin('\u67e5\u770b\u4f18\u60e0\u5238')) {
return
}
navigation.navigate('/pages/coupons/index')
},
async handleSwitchShop() {
if (!navigation.ensureLogin('切换门店')) {
if (!navigation.ensureLogin('\u5207\u6362\u95e8\u5e97')) {
return
}
@@ -114,7 +116,7 @@ Page({
if (!shopIds.length) {
wx.showToast({
title: '当前账号还没有可用门店',
title: '\u5f53\u524d\u8d26\u53f7\u8fd8\u6ca1\u6709\u53ef\u7528\u95e8\u5e97',
icon: 'none'
})
return
@@ -128,31 +130,38 @@ Page({
return
}
const selection = await new Promise(resolve => {
wx.showActionSheet({
itemList: shopNames.map((name, index) => name || `门店 ${shopIds[index]}`),
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
if (selection < 0 || selection >= shopIds.length) {
return
}
try {
const payload = await runWithLoading(() => authApi.switchShop({
shopId: shopIds[selection]
}))
getApp().setUserSession(payload)
wx.showToast({
title: '门店已切换',
icon: 'none'
await actionGuard.run(this, 'user:switch-shop', async () => {
const selection = await new Promise(resolve => {
wx.showActionSheet({
itemList: shopNames.map((name, index) => name || `\u95e8\u5e97 ${shopIds[index]}`),
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
if (selection < 0 || selection >= shopIds.length) {
return
}
const payload = await runWithLoading(() => authApi.switchShop({
shopId: shopIds[selection]
}))
getApp().setUserSession(payload)
wx.showToast({
title: '\u95e8\u5e97\u5df2\u5207\u6362',
icon: 'none'
})
await this.loadProfile()
}, {
message: '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
})
this.loadProfile()
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '门店切换失败',
title: error.message || '\u95e8\u5e97\u5207\u6362\u5931\u8d25',
icon: 'none'
})
}
@@ -164,27 +173,71 @@ Page({
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '退出登录',
content: '退出后需要重新登录才能查看订单和继续下单。',
success: res => resolve(Boolean(res.confirm))
})
})
try {
await actionGuard.run(this, 'auth:logout', async () => {
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '\u9000\u51fa\u767b\u5f55',
content: '\u9000\u51fa\u540e\u9700\u8981\u91cd\u65b0\u767b\u5f55\u624d\u80fd\u67e5\u770b\u8ba2\u5355\u548c\u7ee7\u7eed\u4e0b\u5355\u3002',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
if (!confirmed) {
return
}
try {
await runWithLoading(() => authApi.logout())
} catch (error) {}
getApp().clearUserSession()
await this.loadProfile()
wx.showToast({
title: '\u5df2\u9000\u51fa\u767b\u5f55',
icon: 'none'
})
}, {
message: '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
})
} catch (error) {
if (!actionGuard.isGuardError(error)) {
throw error
}
}
},
async handleAvatarError() {
const currentAvatar = this.data.userInfo && this.data.userInfo.avatar
if (!currentAvatar) {
return
}
try {
await runWithLoading(() => authApi.logout())
} catch (error) {}
if (this._avatarReloadSource === currentAvatar) {
this.setData({
'userInfo.avatar': ''
})
return
}
getApp().clearUserSession()
await this.loadProfile()
wx.showToast({
title: '已退出登录',
icon: 'none'
})
this._avatarReloadSource = currentAvatar
try {
const userInfo = await userApi.getUserInfo()
getApp().refreshUserInfo(userInfo)
if (!userInfo || !userInfo.avatar || userInfo.avatar === currentAvatar) {
this.setData({
'userInfo.avatar': ''
})
return
}
this.setData({
userInfo
})
} catch (error) {
this.setData({
'userInfo.avatar': ''
})
}
}
})
+5 -9
View File
@@ -6,16 +6,16 @@
<view class="page-shell profile-page">
<view class="page-content profile-content">
<view wx:if="{{!isLoggedIn}}" class="page-card guest-card">
<image class="guest-avatar" src="{{defaultAvatar}}" mode="aspectFill"></image>
<image class="guest-avatar" src="{{defaultAvatar}}" mode="aspectFill" lazy-load="{{true}}"></image>
<view class="guest-title">还没有登录账号</view>
<view class="guest-desc">登录后可以查看订单、收藏作品、领取和使用优惠。</view>
<view class="guest-desc">登录后查看订单、收藏和优惠券。</view>
<view class="primary-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{userInfo}}">
<view class="page-card profile-card">
<view class="profile-top">
<image class="avatar" src="{{userInfo.avatar || defaultAvatar}}" mode="aspectFill"></image>
<image class="avatar" src="{{userInfo.avatar || defaultAvatar}}" mode="aspectFill" lazy-load="{{true}}" binderror="handleAvatarError"></image>
<view class="profile-copy">
<view class="nickname">{{userInfo.nickname || 'Yumi 用户'}}</view>
<view class="account">{{userInfo.account}}</view>
@@ -27,17 +27,14 @@
<view class="summary-metric" bindtap="handleOpenOrders">
<text class="summary-label">订单</text>
<text class="summary-value">{{orderCount}}</text>
<text class="summary-note">查看预约记录</text>
</view>
<view class="summary-metric" bindtap="handleOpenWishlist">
<text class="summary-label">收藏</text>
<text class="summary-value">{{wishlistCount}}</text>
<text class="summary-note">回看喜欢的作品</text>
</view>
<view class="summary-metric" bindtap="handleOpenCoupons">
<text class="summary-label">优惠券</text>
<text class="summary-value">{{couponCount}}</text>
<text class="summary-note">结算前可直接使用</text>
</view>
</view>
@@ -50,15 +47,14 @@
</view>
<view wx:if="{{needSetPassword}}" class="password-tip">
建议尽快补充登录密码,之后切换设备会更方便。
建议尽快设置登录密码。
</view>
<view class="secondary-btn edit-btn" bindtap="handleOpenSettings">编辑资料与设置</view>
<view class="secondary-btn edit-btn" bindtap="handleOpenSettings">资料与设置</view>
</view>
<view class="page-card menu-card">
<view class="section-title">常用入口</view>
<view class="section-subtitle">订单、收藏、优惠券和账号设置都集中在这里。</view>
<view class="menu-item" bindtap="handleOpenOrders">
<text>我的订单</text>
<text class="menu-arrow">></text>
+601 -31
View File
@@ -3,24 +3,74 @@ const userApi = require('../../api/user')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { DEFAULT_AVATAR } = require('../../utils/config')
const { getDraftValue, clearDraft, scheduleDraftSave, clearDraftTimer } = require('../../utils/form-draft')
const { runWithLoading } = require('../../utils/loading')
const phoneRegex = /^1[3-9]\d{9}$/
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/
const SETTINGS_DRAFT_KEY = 'user-settings'
const placeholderEntries = [
{
key: 'notifications',
title: '消息通知'
},
{
key: 'message-push',
title: '消息推送'
},
{
key: 'theme',
title: '主题设置'
},
{
key: 'privacy',
title: '隐私政策'
},
{
key: 'about',
title: '关于我们'
},
{
key: 'help',
title: '帮助中心'
},
{
key: 'clear-cache',
title: '缓存清理'
}
]
Page({
data: {
isLoggedIn: false,
loading: false,
savingProfile: false,
uploadingAvatar: false,
updatingPhone: false,
updatingPassword: false,
deactivating: false,
countdown: 0,
needSetPassword: false,
activeSecurityPanel: '',
userInfo: null,
defaultAvatar: DEFAULT_AVATAR,
placeholderEntries,
form: {
nickname: '',
signature: ''
},
bindPhoneForm: {
phone: '',
verificationCode: ''
},
changePhoneForm: {
newPhone: '',
verificationCode: ''
},
passwordForm: {
verificationCode: '',
password: ''
password: '',
confirmPassword: ''
}
},
@@ -28,16 +78,107 @@ Page({
this.loadSettings()
},
onHide() {
this.clearCountdown()
clearDraftTimer(this)
},
onUnload() {
this.clearCountdown()
clearDraftTimer(this)
},
clearCountdown() {
if (this.countdownTimer) {
clearInterval(this.countdownTimer)
this.countdownTimer = null
}
},
resetSecurityForms() {
this.setData({
bindPhoneForm: {
phone: '',
verificationCode: ''
},
changePhoneForm: {
newPhone: '',
verificationCode: ''
},
passwordForm: {
verificationCode: '',
password: '',
confirmPassword: ''
}
})
},
restoreDraftValues() {
const draft = getDraftValue(SETTINGS_DRAFT_KEY, null)
if (!draft || typeof draft !== 'object') {
return
}
this.setData({
activeSecurityPanel: draft.activeSecurityPanel || '',
'form.nickname': draft.form && draft.form.nickname !== undefined ? draft.form.nickname : this.data.form.nickname,
'form.signature': draft.form && draft.form.signature !== undefined ? draft.form.signature : this.data.form.signature,
'bindPhoneForm.phone': draft.bindPhoneForm && draft.bindPhoneForm.phone ? draft.bindPhoneForm.phone : '',
'changePhoneForm.newPhone': draft.changePhoneForm && draft.changePhoneForm.newPhone ? draft.changePhoneForm.newPhone : ''
})
},
scheduleSettingsDraft() {
scheduleDraftSave(this, SETTINGS_DRAFT_KEY, () => ({
activeSecurityPanel: this.data.activeSecurityPanel,
form: {
nickname: this.data.form.nickname,
signature: this.data.form.signature
},
bindPhoneForm: {
phone: this.data.bindPhoneForm.phone
},
changePhoneForm: {
newPhone: this.data.changePhoneForm.newPhone
}
}))
},
startCountdown() {
this.clearCountdown()
this.setData({
countdown: 60
})
this.countdownTimer = setInterval(() => {
const next = this.data.countdown - 1
if (next <= 0) {
this.clearCountdown()
this.setData({
countdown: 0
})
return
}
this.setData({
countdown: next
})
}, 1000)
},
async loadSettings() {
this._avatarReloadSource = ''
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
needSetPassword: auth.getNeedSetPassword(),
loading: isLoggedIn
})
if (!isLoggedIn) {
this.clearCountdown()
this.setData({
userInfo: null,
activeSecurityPanel: '',
loading: false
})
return
@@ -49,8 +190,10 @@ Page({
this.setData({
userInfo,
'form.nickname': userInfo.nickname || '',
'form.signature': userInfo.signature || ''
'form.signature': userInfo.signature || '',
needSetPassword: auth.getNeedSetPassword()
})
this.restoreDraftValues()
} catch (error) {
wx.showToast({
title: error.message || '设置页加载失败',
@@ -76,6 +219,27 @@ Page({
this.setData({
[`form.${field}`]: event.detail.value
})
this.scheduleSettingsDraft()
},
handleBindPhoneInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`bindPhoneForm.${field}`]: event.detail.value
})
if (field === 'phone') {
this.scheduleSettingsDraft()
}
},
handleChangePhoneInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`changePhoneForm.${field}`]: event.detail.value
})
if (field === 'newPhone') {
this.scheduleSettingsDraft()
}
},
handlePasswordInput(event) {
@@ -85,6 +249,28 @@ Page({
})
},
handleToggleSecurityPanel(event) {
const panel = event.currentTarget.dataset.panel
const nextPanel = this.data.activeSecurityPanel === panel ? '' : panel
this.clearCountdown()
this.resetSecurityForms()
this.setData({
activeSecurityPanel: nextPanel,
countdown: 0
})
this.scheduleSettingsDraft()
},
handleCloseSecurityPanel() {
this.resetSecurityForms()
this.clearCountdown()
this.setData({
activeSecurityPanel: '',
countdown: 0
})
this.scheduleSettingsDraft()
},
async handleSaveProfile() {
if (!this.data.form.nickname.trim()) {
wx.showToast({
@@ -107,7 +293,8 @@ Page({
title: '资料已更新',
icon: 'none'
})
this.loadSettings()
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '资料更新失败',
@@ -120,20 +307,298 @@ Page({
}
},
startCountdown() {
this.setData({
countdown: 60
handleChooseAvatar() {
if (this.data.uploadingAvatar) {
return
}
wx.chooseImage({
count: 1,
sizeType: ['compressed', 'original'],
sourceType: ['album', 'camera'],
success: async res => {
const filePath = Array.isArray(res.tempFilePaths) ? res.tempFilePaths[0] : ''
if (!filePath) {
return
}
this.setData({
uploadingAvatar: true
})
try {
await runWithLoading(() => userApi.uploadAvatar(filePath))
wx.showToast({
title: '头像已更新',
icon: 'none'
})
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '头像上传失败',
icon: 'none'
})
} finally {
this.setData({
uploadingAvatar: false
})
}
}
})
},
async handleDeleteAvatar() {
if (!this.data.userInfo || !this.data.userInfo.avatar) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '删除头像',
content: '删除后会恢复为默认头像。',
success: res => resolve(Boolean(res.confirm))
})
})
const timer = setInterval(() => {
const next = this.data.countdown - 1
this.setData({
countdown: next
if (!confirmed) {
return
}
try {
await runWithLoading(() => userApi.updateUserInfo({
avatar: ''
}))
wx.showToast({
title: '头像已删除',
icon: 'none'
})
if (next <= 0) {
clearInterval(timer)
}
}, 1000)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '头像删除失败',
icon: 'none'
})
}
},
async handleSwitchShop() {
if (!navigation.ensureLogin('查看门店')) {
return
}
const userInfo = this.data.userInfo
const shopIds = userInfo && Array.isArray(userInfo.shopIds) ? userInfo.shopIds : []
const shopNames = userInfo && Array.isArray(userInfo.shopNames) ? userInfo.shopNames : []
if (!shopIds.length) {
wx.showToast({
title: '当前账号还没有可用门店',
icon: 'none'
})
return
}
if (shopIds.length === 1) {
navigation.navigate('/pages/shop-detail/index', {
id: shopIds[0],
returnTo: navigation.getCurrentPageUrl()
})
return
}
const selection = await new Promise(resolve => {
wx.showActionSheet({
itemList: shopNames.map((name, index) => name || `门店 ${shopIds[index]}`),
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
if (selection < 0 || selection >= shopIds.length) {
return
}
try {
const payload = await runWithLoading(() => authApi.switchShop({
shopId: shopIds[selection]
}))
getApp().setUserSession(payload)
wx.showToast({
title: '门店已切换',
icon: 'none'
})
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '门店切换失败',
icon: 'none'
})
}
},
async handleSendBindPhoneCode() {
if (this.data.countdown > 0) {
return
}
const phone = String(this.data.bindPhoneForm.phone || '').trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => userApi.sendVerificationCode({ phone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown()
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleBindPhoneSubmit() {
const phone = String(this.data.bindPhoneForm.phone || '').trim()
const verificationCode = String(this.data.bindPhoneForm.verificationCode || '').trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
if (!verificationCode) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
this.setData({
updatingPhone: true
})
try {
await runWithLoading(() => userApi.bindPhone({
phone,
verificationCode
}))
wx.showToast({
title: '手机号绑定成功',
icon: 'none'
})
this.handleCloseSecurityPanel()
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '手机号绑定失败',
icon: 'none'
})
} finally {
this.setData({
updatingPhone: false
})
}
},
async handleSendChangePhoneCode() {
if (this.data.countdown > 0) {
return
}
const newPhone = String(this.data.changePhoneForm.newPhone || '').trim()
if (!phoneRegex.test(newPhone)) {
wx.showToast({
title: '请输入正确的新手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => userApi.sendVerificationCode({ phone: newPhone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown()
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleChangePhoneSubmit() {
const userInfo = this.data.userInfo || {}
const oldPhone = String(userInfo.phone || '').trim()
const newPhone = String(this.data.changePhoneForm.newPhone || '').trim()
const verificationCode = String(this.data.changePhoneForm.verificationCode || '').trim()
if (!oldPhone) {
wx.showToast({
title: '请先绑定手机号',
icon: 'none'
})
return
}
if (!phoneRegex.test(newPhone)) {
wx.showToast({
title: '请输入正确的新手机号',
icon: 'none'
})
return
}
if (!verificationCode) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
this.setData({
updatingPhone: true
})
try {
await runWithLoading(() => userApi.updatePhone({
oldPhone,
newPhone,
verificationCode
}))
wx.showToast({
title: '手机号修改成功',
icon: 'none'
})
this.handleCloseSecurityPanel()
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '手机号修改失败',
icon: 'none'
})
} finally {
this.setData({
updatingPhone: false
})
}
},
async handleSendPasswordCode() {
@@ -141,19 +606,18 @@ Page({
return
}
const userInfo = this.data.userInfo
if (!userInfo || !userInfo.phone) {
const userInfo = this.data.userInfo || {}
const phone = String(userInfo.phone || '').trim()
if (!phone) {
wx.showToast({
title: '当前账号未绑定手机号',
title: '请先绑定手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => authApi.sendVerificationCode({
phone: userInfo.phone
}))
await runWithLoading(() => authApi.sendVerificationCode({ phone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
@@ -168,16 +632,38 @@ Page({
},
async handleUpdatePassword() {
if (!this.data.passwordForm.verificationCode.trim()) {
const verificationCode = String(this.data.passwordForm.verificationCode || '').trim()
const password = String(this.data.passwordForm.password || '')
const confirmPassword = String(this.data.passwordForm.confirmPassword || '')
const userInfo = this.data.userInfo || {}
if (!userInfo.phone) {
wx.showToast({
title: '请先绑定手机号',
icon: 'none'
})
return
}
if (!verificationCode) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
if (!this.data.passwordForm.password || this.data.passwordForm.password.length < 6) {
if (!passwordRegex.test(password)) {
wx.showToast({
title: '新密码至少 6 位',
title: '密码需至少8位且包含字母和数字',
icon: 'none'
})
return
}
if (password !== confirmPassword) {
wx.showToast({
title: '两次输入的密码不一致',
icon: 'none'
})
return
@@ -189,20 +675,17 @@ Page({
try {
await runWithLoading(() => userApi.updatePassword({
password: this.data.passwordForm.password,
verificationCode: this.data.passwordForm.verificationCode.trim()
password,
verificationCode
}))
auth.setNeedSetPassword(false)
wx.showToast({
title: '密码已更新',
icon: 'none'
})
this.setData({
passwordForm: {
verificationCode: '',
password: ''
}
})
this.handleCloseSecurityPanel()
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '密码更新失败',
@@ -215,6 +698,58 @@ Page({
}
},
handleComingSoon() {
wx.showToast({
title: '该功能暂未开放',
icon: 'none'
})
},
async handleDeactivateAccount() {
if (this.data.deactivating) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '注销账号',
content: '注销后当前账号将不可继续登录,请确认是否继续。',
confirmColor: '#d5536f',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
this.setData({
deactivating: true
})
try {
await runWithLoading(() => userApi.deactivateAccount())
clearDraft(SETTINGS_DRAFT_KEY)
getApp().clearUserSession()
wx.showToast({
title: '账号已注销',
icon: 'none'
})
wx.switchTab({
url: '/pages/home/index'
})
} catch (error) {
wx.showToast({
title: error.message || '账号注销失败',
icon: 'none'
})
} finally {
this.setData({
deactivating: false
})
}
},
async handleLogout() {
const confirmed = await new Promise(resolve => {
wx.showModal({
@@ -232,6 +767,7 @@ Page({
await runWithLoading(() => authApi.logout())
} catch (error) {}
clearDraft(SETTINGS_DRAFT_KEY)
getApp().clearUserSession()
wx.showToast({
title: '已退出登录',
@@ -240,5 +776,39 @@ Page({
wx.switchTab({
url: '/pages/home/index'
})
},
async handleAvatarError() {
const currentAvatar = this.data.userInfo && this.data.userInfo.avatar
if (!currentAvatar) {
return
}
if (this._avatarReloadSource === currentAvatar) {
this.setData({
'userInfo.avatar': ''
})
return
}
this._avatarReloadSource = currentAvatar
try {
const userInfo = await userApi.getUserInfo()
getApp().refreshUserInfo(userInfo)
if (!userInfo || !userInfo.avatar || userInfo.avatar === currentAvatar) {
this.setData({
'userInfo.avatar': ''
})
return
}
this.setData({
userInfo
})
} catch (error) {
this.setData({
'userInfo.avatar': ''
})
}
}
})
+131 -18
View File
@@ -6,27 +6,37 @@
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" 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="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{userInfo}}">
<view class="page-hero settings-hero">
<text class="hero-kicker">个人设置</text>
<text class="hero-title">维护你的资料与登录信息</text>
<text class="hero-desc">资料会同步到小程序端展示区域,密码更新后下次登录立即生效。</text>
<text class="hero-kicker">账号设置</text>
<text class="hero-title">资料与安全</text>
<text class="hero-desc">常用设置都在这里</text>
</view>
<view class="page-card settings-card">
<view class="section-title">个人资料</view>
<view class="profile-preview">
<image class="avatar" src="{{userInfo.avatar || defaultAvatar}}" mode="aspectFill"></image>
<image class="avatar" src="{{userInfo.avatar || defaultAvatar}}" mode="aspectFill" lazy-load="{{true}}" binderror="handleAvatarError"></image>
<view class="profile-preview-copy">
<view class="preview-name">{{userInfo.nickname || 'Yumi 用户'}}</view>
<view class="preview-account">{{userInfo.account}}</view>
<view class="preview-phone">{{userInfo.phone || '未绑定手机号'}}</view>
</view>
</view>
<view class="avatar-actions">
<view class="ghost-btn avatar-action" bindtap="handleChooseAvatar">{{uploadingAvatar ? '头像上传中...' : '更换头像'}}</view>
<view wx:if="{{userInfo.avatar}}" class="text-action" bindtap="handleDeleteAvatar">删除头像</view>
</view>
<view wx:if="{{needSetPassword}}" class="hint-card password-hint">
当前账号未设置登录密码。
</view>
<view class="field-block">
<text class="field-label">昵称</text>
<input class="field-input" placeholder="请输入昵称" placeholder-class="field-placeholder" value="{{form.nickname}}" data-field="nickname" bindinput="handleFormInput"></input>
@@ -34,30 +44,133 @@
<view class="field-block">
<text class="field-label">个性签名</text>
<textarea class="field-textarea" placeholder="写一句想让客人认识你的话" placeholder-class="field-placeholder" value="{{form.signature}}" data-field="signature" bindinput="handleFormInput"></textarea>
<textarea class="field-textarea" placeholder="请输入个性签名" placeholder-class="field-placeholder" value="{{form.signature}}" data-field="signature" bindinput="handleFormInput"></textarea>
</view>
<view class="primary-btn save-btn" bindtap="handleSaveProfile">{{savingProfile ? '保存中...' : '保存资料'}}</view>
</view>
<view class="page-card settings-card password-card">
<view class="section-title">登录密码</view>
<view class="section-subtitle">向已绑定手机号发送验证码后更新登录密码。</view>
<view class="page-card settings-card security-card">
<view class="section-title">账号与安全</view>
<view class="field-block">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="field-input code-input" type="number" placeholder="请输入验证码" placeholder-class="field-placeholder" value="{{passwordForm.verificationCode}}" data-field="verificationCode" bindinput="handlePasswordInput"></input>
<view class="code-btn {{countdown > 0 ? 'disabled' : ''}}" bindtap="handleSendPasswordCode">{{countdown > 0 ? countdown + 's' : '发送验证码'}}</view>
<view class="setting-row" bindtap="handleSwitchShop">
<view class="setting-main">
<view class="setting-name">当前登录门店</view>
<view class="setting-desc">{{userInfo.shopName || '当前暂无可用门店'}}</view>
</view>
<view class="setting-action">{{(userInfo.shopIds && userInfo.shopIds.length > 1) ? '切换' : '查看'}}</view>
</view>
<view wx:if="{{!userInfo.phone}}" class="setting-row" data-panel="bindPhone" bindtap="handleToggleSecurityPanel">
<view class="setting-main">
<view class="setting-name">绑定手机号</view>
<view class="setting-desc">绑定后可设置密码</view>
</view>
<view class="setting-action">{{activeSecurityPanel === 'bindPhone' ? '收起' : '去绑定'}}</view>
</view>
<view wx:if="{{userInfo.phone}}" class="setting-row" data-panel="changePhone" bindtap="handleToggleSecurityPanel">
<view class="setting-main">
<view class="setting-name">修改手机号</view>
<view class="setting-desc">{{userInfo.phone}}</view>
</view>
<view class="setting-action">{{activeSecurityPanel === 'changePhone' ? '收起' : '修改'}}</view>
</view>
<view class="setting-row" data-panel="password" bindtap="handleToggleSecurityPanel">
<view class="setting-main">
<view class="setting-name">{{needSetPassword ? '设置登录密码' : '修改登录密码'}}</view>
<view class="setting-desc">{{userInfo.phone ? '短信验证后修改' : '请先绑定手机号'}}</view>
</view>
<view class="setting-action">{{activeSecurityPanel === 'password' ? '收起' : (needSetPassword ? '去设置' : '修改')}}</view>
</view>
<view wx:if="{{activeSecurityPanel === 'bindPhone'}}" class="security-panel">
<view class="section-subtitle">输入后完成绑定</view>
<view class="field-block">
<text class="field-label">手机号</text>
<input class="field-input" type="number" placeholder="请输入手机号" placeholder-class="field-placeholder" value="{{bindPhoneForm.phone}}" data-field="phone" bindinput="handleBindPhoneInput"></input>
</view>
<view class="field-block">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="field-input code-input" type="number" placeholder="请输入验证码" placeholder-class="field-placeholder" value="{{bindPhoneForm.verificationCode}}" data-field="verificationCode" bindinput="handleBindPhoneInput"></input>
<view class="code-btn {{countdown > 0 ? 'disabled' : ''}}" bindtap="handleSendBindPhoneCode">{{countdown > 0 ? countdown + 's' : '发送验证码'}}</view>
</view>
</view>
<view class="panel-actions">
<view class="secondary-btn panel-btn" bindtap="handleCloseSecurityPanel">取消</view>
<view class="primary-btn panel-btn" bindtap="handleBindPhoneSubmit">{{updatingPhone ? '绑定中...' : '确认绑定'}}</view>
</view>
</view>
<view class="field-block">
<text class="field-label">新密码</text>
<input class="field-input" password placeholder="请输入新密码" placeholder-class="field-placeholder" value="{{passwordForm.password}}" data-field="password" bindinput="handlePasswordInput"></input>
<view wx:if="{{activeSecurityPanel === 'changePhone'}}" class="security-panel">
<view class="section-subtitle">验证后更新手机号</view>
<view class="field-block">
<text class="field-label">当前手机号</text>
<view class="field-static">{{userInfo.phone}}</view>
</view>
<view class="field-block">
<text class="field-label">新手机号</text>
<input class="field-input" type="number" placeholder="请输入新的手机号" placeholder-class="field-placeholder" value="{{changePhoneForm.newPhone}}" data-field="newPhone" bindinput="handleChangePhoneInput"></input>
</view>
<view class="field-block">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="field-input code-input" type="number" placeholder="请输入验证码" placeholder-class="field-placeholder" value="{{changePhoneForm.verificationCode}}" data-field="verificationCode" bindinput="handleChangePhoneInput"></input>
<view class="code-btn {{countdown > 0 ? 'disabled' : ''}}" bindtap="handleSendChangePhoneCode">{{countdown > 0 ? countdown + 's' : '发送验证码'}}</view>
</view>
</view>
<view class="panel-actions">
<view class="secondary-btn panel-btn" bindtap="handleCloseSecurityPanel">取消</view>
<view class="primary-btn panel-btn" bindtap="handleChangePhoneSubmit">{{updatingPhone ? '提交中...' : '确认修改'}}</view>
</view>
</view>
<view class="secondary-btn save-btn" bindtap="handleUpdatePassword">{{updatingPassword ? '更新中...' : '更新密码'}}</view>
<view wx:if="{{activeSecurityPanel === 'password'}}" class="security-panel">
<view wx:if="{{!userInfo.phone}}" class="hint-card password-hint">请先绑定手机号,再通过验证码设置或修改登录密码。</view>
<block wx:else>
<view class="section-subtitle">密码需包含字母和数字</view>
<view class="field-block">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="field-input code-input" type="number" placeholder="请输入验证码" placeholder-class="field-placeholder" value="{{passwordForm.verificationCode}}" data-field="verificationCode" bindinput="handlePasswordInput"></input>
<view class="code-btn {{countdown > 0 ? 'disabled' : ''}}" bindtap="handleSendPasswordCode">{{countdown > 0 ? countdown + 's' : '发送验证码'}}</view>
</view>
</view>
<view class="field-block">
<text class="field-label">新密码</text>
<input class="field-input" password placeholder="请输入新密码" placeholder-class="field-placeholder" value="{{passwordForm.password}}" data-field="password" bindinput="handlePasswordInput"></input>
</view>
<view class="field-block">
<text class="field-label">确认密码</text>
<input class="field-input" password placeholder="请再次输入新密码" placeholder-class="field-placeholder" value="{{passwordForm.confirmPassword}}" data-field="confirmPassword" bindinput="handlePasswordInput"></input>
</view>
<view class="panel-actions">
<view class="secondary-btn panel-btn" bindtap="handleCloseSecurityPanel">取消</view>
<view class="primary-btn panel-btn" bindtap="handleUpdatePassword">{{updatingPassword ? '提交中...' : '确认保存'}}</view>
</view>
</block>
</view>
<view class="setting-row danger-row" bindtap="handleDeactivateAccount">
<view class="setting-main">
<view class="setting-name">注销账号</view>
<view class="setting-desc">注销后不可继续登录</view>
</view>
<view class="setting-action danger-text">{{deactivating ? '处理中' : '注销'}}</view>
</view>
</view>
<view class="page-card settings-card more-card">
<view class="section-title">更多功能</view>
<view wx:for="{{placeholderEntries}}" wx:key="key" class="setting-row" bindtap="handleComingSoon">
<view class="setting-main">
<view class="setting-name">{{item.title}}</view>
</view>
<view class="placeholder-tag">暂未开放</view>
</view>
</view>
<view class="logout-btn" bindtap="handleLogout">退出登录</view>
+118 -2
View File
@@ -29,7 +29,7 @@
.profile-preview {
display: flex;
align-items: center;
gap: 18rpx;
gap: 20rpx;
margin-top: 22rpx;
}
@@ -42,6 +42,7 @@
.profile-preview-copy {
flex: 1;
min-width: 0;
}
.preview-name {
@@ -50,10 +51,31 @@
color: #2d2430;
}
.preview-account,
.preview-phone {
margin-top: 10rpx;
font-size: 24rpx;
color: #8d7a84;
word-break: break-all;
}
.avatar-actions {
display: flex;
align-items: center;
gap: 18rpx;
margin-top: 22rpx;
}
.avatar-action {
width: auto;
min-width: 220rpx;
padding: 0 28rpx;
}
.text-action {
font-size: 24rpx;
font-weight: 600;
color: #c6597d;
}
.field-block {
@@ -64,10 +86,76 @@
margin-top: 26rpx;
}
.password-card {
.password-hint {
margin-top: 20rpx;
}
.security-card,
.more-card {
margin-top: 20rpx;
}
.setting-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18rpx;
padding: 24rpx 0;
border-bottom: 1rpx solid rgba(239, 216, 224, 0.92);
}
.setting-row:first-of-type {
margin-top: 8rpx;
}
.setting-row:last-child {
border-bottom: 0;
padding-bottom: 0;
}
.setting-main {
flex: 1;
min-width: 0;
}
.setting-name {
font-size: 28rpx;
font-weight: 700;
color: #2d2430;
}
.setting-desc {
margin-top: 10rpx;
font-size: 24rpx;
line-height: 1.7;
color: #8d7a84;
}
.setting-action {
flex-shrink: 0;
font-size: 24rpx;
font-weight: 700;
color: #c6597d;
}
.security-panel {
margin-top: 6rpx;
padding: 26rpx 24rpx;
border-radius: 28rpx;
background: #fff7f8;
}
.field-static {
display: flex;
align-items: center;
min-height: 92rpx;
padding: 0 28rpx;
border-radius: 24rpx;
background: #f5edf0;
color: #5d4b55;
font-size: 28rpx;
}
.code-row {
display: flex;
align-items: center;
@@ -97,6 +185,34 @@
color: #a998a0;
}
.panel-actions {
display: flex;
gap: 14rpx;
margin-top: 24rpx;
}
.panel-btn {
flex: 1;
}
.placeholder-tag {
flex-shrink: 0;
padding: 12rpx 18rpx;
border-radius: 999rpx;
background: #fdf0f4;
color: #c6597d;
font-size: 22rpx;
font-weight: 700;
}
.danger-row {
margin-top: 8rpx;
}
.danger-text {
color: #d5536f;
}
.logout-btn {
display: flex;
align-items: center;
+2 -1
View File
@@ -2,7 +2,7 @@
<view class="page-shell shop-page">
<view class="shop-hero">
<image wx:if="{{shopImages.length}}" class="shop-hero-image" src="{{shopImages[0]}}" mode="aspectFill"></image>
<image wx:if="{{shopImages.length}}" class="shop-hero-image" src="{{shopImages[0]}}" mode="aspectFill" lazy-load="{{true}}"></image>
<view class="shop-hero-mask"></view>
</view>
@@ -67,6 +67,7 @@
mode="aspectFill"
data-url="{{item}}"
bindtap="handlePreviewImage"
lazy-load="{{true}}"
></image>
</view>
</view>
+113 -6
View File
@@ -1,4 +1,6 @@
const wishlistApi = require('../../api/wishlist')
const cartApi = require('../../api/cart')
const actionGuard = require('../../utils/action-guard')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { buildProductCard } = require('../../utils/product')
@@ -23,6 +25,7 @@ Page({
})
if (!isLoggedIn) {
this.cartProductIdSet = new Set()
this.setData({
wishlist: [],
loading: false
@@ -33,10 +36,14 @@ Page({
try {
const wishlist = await wishlistApi.getWishlist()
const list = Array.isArray(wishlist) ? wishlist : []
const cartProductIdSet = await this.fetchCartProductIdSet()
const cards = await Promise.all(list.map(async item => ({
id: item.id,
productId: item.productId,
productCard: await buildProductCard(item.product || {})
productCard: this.markCardInCart(
await buildProductCard(item.product || {}),
cartProductIdSet
)
})))
this.setData({
wishlist: cards
@@ -46,7 +53,7 @@ Page({
wishlist: []
})
wx.showToast({
title: error.message || '收藏列表加载失败',
title: error.message || '\u6536\u85cf\u5217\u8868\u52a0\u8f7d\u5931\u8d25',
icon: 'none'
})
} finally {
@@ -56,6 +63,57 @@ Page({
}
},
normalizeId(value) {
return value === undefined || value === null ? '' : String(value)
},
async fetchCartProductIdSet() {
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
}
},
markCardInCart(card, idSet) {
return {
...card,
inCart: (idSet || new Set()).has(this.normalizeId(card && card.id))
}
},
markWishlistProductInCart(productId) {
const normalizedId = this.normalizeId(productId)
if (!normalizedId) {
return
}
this.cartProductIdSet = this.cartProductIdSet || new Set()
this.cartProductIdSet.add(normalizedId)
this.setData({
wishlist: this.data.wishlist.map(item => (
this.normalizeId(item && item.productId) === normalizedId
? {
...item,
productCard: {
...item.productCard,
inCart: true
}
}
: item
))
})
},
handleOpenAuth() {
navigation.openAuth('/pages/wishlist/index')
},
@@ -65,11 +123,55 @@ Page({
if (!product.id) {
return
}
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: '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
})
this.markWishlistProductInCart(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'
})
}
},
async handleRemove(event) {
const productId = event.currentTarget.dataset.productId
if (!productId) {
@@ -77,15 +179,20 @@ Page({
}
try {
await runWithLoading(() => wishlistApi.removeFromWishlist(productId))
await actionGuard.run(this, `wishlist:remove:${productId}`, () => runWithLoading(() => wishlistApi.removeFromWishlist(productId)), {
message: '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
})
wx.showToast({
title: '已取消收藏',
title: '\u5df2\u53d6\u6d88\u6536\u85cf',
icon: 'none'
})
this.loadWishlist()
await this.loadWishlist()
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '取消收藏失败',
title: error.message || '\u53d6\u6d88\u6536\u85cf\u5931\u8d25',
icon: 'none'
})
}
+13 -5
View File
@@ -4,7 +4,7 @@
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" 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="handleOpenAuth">去登录</view>
</view>
@@ -12,12 +12,20 @@
<view class="page-hero wishlist-hero">
<text class="hero-kicker">收藏夹</text>
<text class="hero-title">已收藏 {{wishlist.length}} 个作品</text>
<text class="hero-desc">遇到喜欢的款式先放进收藏,之后再决定是否预约会更从容。</text>
<text class="hero-desc">喜欢的款式先收藏。</text>
</view>
<view wx:for="{{wishlist}}" wx:key="id" class="wishlist-item">
<product-card item="{{item.productCard}}" bindselect="handleProductSelect"></product-card>
<view class="wishlist-action" data-product-id="{{item.productId}}" bindtap="handleRemove">取消收藏</view>
<product-card
item="{{item.productCard}}"
show-quick-add="{{true}}"
in-cart="{{item.productCard.inCart}}"
bindselect="handleProductSelect"
bindquickadd="handleQuickAdd"
></product-card>
<view class="wishlist-actions">
<view class="wishlist-action wishlist-action--secondary" data-product-id="{{item.productId}}" bindtap="handleRemove">取消收藏</view>
</view>
</view>
</block>
@@ -27,7 +35,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="handleBack">去逛作品</view>
</view>
</view>
+12 -1
View File
@@ -6,15 +6,26 @@
margin-top: 22rpx;
}
.wishlist-actions {
display: flex;
gap: 16rpx;
margin-top: 12rpx;
}
.wishlist-action {
display: flex;
align-items: center;
justify-content: center;
height: 74rpx;
margin-top: 12rpx;
flex: 1;
border-radius: 20rpx;
background: #fff1f5;
color: #c6597d;
font-size: 26rpx;
font-weight: 600;
}
.wishlist-action--secondary {
background: #fff1f5;
color: #c6597d;
}
+78
View File
@@ -0,0 +1,78 @@
const inflightScopes = new Map()
function resolveScopeId(scope) {
if (scope && typeof scope === 'string') {
return scope
}
if (scope && typeof scope.route === 'string' && scope.route) {
return scope.route
}
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
const current = pages[pages.length - 1]
if (current && current.route) {
return current.route
}
return 'global'
}
function getScopeMap(scopeId) {
if (!inflightScopes.has(scopeId)) {
inflightScopes.set(scopeId, new Map())
}
return inflightScopes.get(scopeId)
}
function createGuardError(message, scopeId, actionKey) {
const error = new Error(message || '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb')
error.isActionGuardError = true
error.scopeId = scopeId
error.actionKey = actionKey
return error
}
async function run(scope, actionKey, task, options) {
const scopeId = resolveScopeId(scope)
const normalizedKey = String(actionKey || 'default')
const scopeMap = getScopeMap(scopeId)
if (scopeMap.get(normalizedKey)) {
return Promise.reject(createGuardError((options && options.message) || '', scopeId, normalizedKey))
}
scopeMap.set(normalizedKey, true)
try {
return await Promise.resolve().then(() => task())
} finally {
scopeMap.delete(normalizedKey)
if (!scopeMap.size) {
inflightScopes.delete(scopeId)
}
}
}
function isRunning(scope, actionKey) {
const scopeId = resolveScopeId(scope)
const scopeMap = inflightScopes.get(scopeId)
if (!scopeMap) {
return false
}
return Boolean(scopeMap.get(String(actionKey || 'default')))
}
function clearScope(scope) {
inflightScopes.delete(resolveScopeId(scope))
}
function isGuardError(error) {
return Boolean(error && error.isActionGuardError)
}
module.exports = {
run,
isRunning,
clearScope,
isGuardError,
createGuardError
}
+66 -4
View File
@@ -1,4 +1,61 @@
const { STORAGE_KEYS, getStorage, removeStorage, setStorage } = require('./storage')
const SIGNED_URL_SAFE_BUFFER_MS = 60 * 1000
function parseSignedUrlExpireAt(url) {
const rawUrl = String(url || '').trim()
if (!rawUrl || rawUrl.indexOf('?') < 0) {
return 0
}
const queryString = rawUrl.slice(rawUrl.indexOf('?') + 1)
const params = {}
queryString.split('&').forEach(segment => {
if (!segment) {
return
}
const dividerIndex = segment.indexOf('=')
const key = dividerIndex >= 0 ? segment.slice(0, dividerIndex) : segment
const value = dividerIndex >= 0 ? segment.slice(dividerIndex + 1) : ''
params[decodeURIComponent(key)] = decodeURIComponent(value)
})
const awsDate = params['X-Amz-Date']
const awsExpireSeconds = Number(params['X-Amz-Expires'] || 0)
if (awsDate && awsExpireSeconds > 0 && awsDate.length >= 16) {
const year = Number(awsDate.slice(0, 4))
const month = Number(awsDate.slice(4, 6)) - 1
const day = Number(awsDate.slice(6, 8))
const hour = Number(awsDate.slice(9, 11))
const minute = Number(awsDate.slice(11, 13))
const second = Number(awsDate.slice(13, 15))
const baseTimestamp = Date.UTC(year, month, day, hour, minute, second)
if (!Number.isNaN(baseTimestamp)) {
return baseTimestamp + awsExpireSeconds * 1000
}
}
const expires = Number(params.Expires || 0)
if (expires > 0) {
return expires * 1000
}
return 0
}
function sanitizeStoredUserInfo(userInfo) {
if (!userInfo || typeof userInfo !== 'object') {
return userInfo
}
const nextUserInfo = {
...userInfo
}
const avatarExpireAt = parseSignedUrlExpireAt(nextUserInfo.avatar)
if (avatarExpireAt > 0 && avatarExpireAt <= Date.now() + SIGNED_URL_SAFE_BUFFER_MS) {
nextUserInfo.avatar = ''
}
return nextUserInfo
}
function getAccessToken() {
return getStorage(STORAGE_KEYS.ACCESS_TOKEN, '')
@@ -9,7 +66,11 @@ function getRefreshToken() {
}
function getStoredUserInfo() {
return getStorage(STORAGE_KEYS.USER_INFO, null)
const userInfo = sanitizeStoredUserInfo(getStorage(STORAGE_KEYS.USER_INFO, null))
if (userInfo) {
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
}
return userInfo
}
function getNeedSetPassword() {
@@ -33,7 +94,7 @@ function setSession(payload) {
setStorage(STORAGE_KEYS.REFRESH_TOKEN, payload.refreshToken)
if (payload.userInfo) {
setStorage(STORAGE_KEYS.USER_INFO, payload.userInfo)
setStorage(STORAGE_KEYS.USER_INFO, sanitizeStoredUserInfo(payload.userInfo))
}
if (payload.needSetPassword) {
@@ -49,7 +110,7 @@ function updateStoredUserInfo(userInfo) {
return
}
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
setStorage(STORAGE_KEYS.USER_INFO, sanitizeStoredUserInfo(userInfo))
}
function setNeedSetPassword(value) {
@@ -88,5 +149,6 @@ module.exports = {
updateStoredUserInfo,
setNeedSetPassword,
setPreferredMiniLoginShopId,
clearSession
clearSession,
sanitizeStoredUserInfo
}
+108
View File
@@ -0,0 +1,108 @@
const CACHE_PREFIX = 'miniCache:'
const memoryCache = {}
const inflightCache = {}
function now() {
return Date.now()
}
function buildKey(key) {
return `${CACHE_PREFIX}${key}`
}
function clearExpiredEntry(key, entry) {
if (!entry) {
return
}
if (entry.expireAt && entry.expireAt <= now()) {
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
}
function getCache(key, defaultValue) {
if (!key) {
return defaultValue
}
const localEntry = memoryCache[key]
if (localEntry && (!localEntry.expireAt || localEntry.expireAt > now())) {
return localEntry.value
}
clearExpiredEntry(key, localEntry)
try {
const storedEntry = wx.getStorageSync(buildKey(key))
if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) {
memoryCache[key] = storedEntry
return storedEntry.value
}
clearExpiredEntry(key, storedEntry)
} catch (error) {}
return defaultValue
}
function setCache(key, value, ttlMs) {
if (!key) {
return value
}
const expireAt = ttlMs && ttlMs > 0 ? now() + ttlMs : 0
const entry = {
value,
expireAt
}
memoryCache[key] = entry
try {
wx.setStorageSync(buildKey(key), entry)
} catch (error) {}
return value
}
function removeCache(key) {
if (!key) {
return
}
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
function removeByPrefix(prefix) {
Object.keys(memoryCache).forEach(key => {
if (key.startsWith(prefix)) {
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
})
}
function remember(key, ttlMs, loader) {
const cached = getCache(key, undefined)
if (cached !== undefined) {
return Promise.resolve(cached)
}
if (inflightCache[key]) {
return inflightCache[key]
}
inflightCache[key] = Promise.resolve()
.then(() => loader())
.then(value => setCache(key, value, ttlMs))
.finally(() => {
delete inflightCache[key]
})
return inflightCache[key]
}
module.exports = {
getCache,
setCache,
removeCache,
removeByPrefix,
remember
}
+60 -6
View File
@@ -1,3 +1,11 @@
function safeRequire(modulePath) {
try {
return require(modulePath)
} catch (error) {
return {}
}
}
function getEnvVersion() {
if (typeof wx === 'undefined') {
return 'develop'
@@ -48,24 +56,70 @@ function getRuntimePlatform() {
return 'unknown'
}
function normalizeDomain(value, fallbackValue) {
const target = String(value || fallbackValue || '').trim()
if (!target) {
return ''
}
return target.replace(/\/+$/, '')
}
function ensureHttps(value, envVersion) {
if (!value) {
throw new Error(`Missing API domain for ${envVersion}`)
}
if (envVersion !== 'develop' && !value.startsWith('https://')) {
throw new Error(`${envVersion} environment must use HTTPS`)
}
return value
}
const localOverride = safeRequire('./config.local')
const ENV_VERSION = getEnvVersion()
const RUNTIME_PLATFORM = getRuntimePlatform()
const IS_DEVTOOLS = RUNTIME_PLATFORM === 'devtools'
const LOCAL_API_DOMAIN = 'http://127.0.0.1:80'
const REMOTE_API_DOMAIN = 'https://yunail.art'
const USE_LOCAL_API = ENV_VERSION === 'develop' && IS_DEVTOOLS
const API_DOMAIN = USE_LOCAL_API ? LOCAL_API_DOMAIN : REMOTE_API_DOMAIN
const DEFAULT_DOMAINS = {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
const DOMAIN_MAP = {
...DEFAULT_DOMAINS,
...(localOverride.domains || {})
}
const DEFAULT_DEVELOP_TARGET = IS_DEVTOOLS ? 'local' : 'dev-remote'
const DEVELOP_TARGET = String(localOverride.developTarget || DEFAULT_DEVELOP_TARGET)
const API_DOMAIN = ensureHttps(
ENV_VERSION === 'develop'
? normalizeDomain(DOMAIN_MAP[DEVELOP_TARGET], DOMAIN_MAP['dev-remote'])
: normalizeDomain(DOMAIN_MAP[ENV_VERSION], DOMAIN_MAP.release),
ENV_VERSION
)
module.exports = {
ENV_VERSION,
RUNTIME_PLATFORM,
IS_DEVTOOLS,
USE_LOCAL_API,
DEVELOP_TARGET,
API_DOMAIN,
API_BASE_URL: `${API_DOMAIN}/api`,
IS_DEV_ENV: ENV_VERSION === 'develop',
REQUEST_TIMEOUT: 10000,
REQUEST_TIMEOUT: Number(localOverride.requestTimeout || 10000),
ENABLE_REQUEST_SIGNING: localOverride.enableRequestSigning !== false,
IDLE_TIMEOUT_MS: 60 * 60 * 1000,
IDLE_WARNING_MS: 2 * 60 * 1000,
CACHE_TTL: {
banner: 5 * 60 * 1000,
publicShops: 5 * 60 * 1000,
tags: 10 * 60 * 1000,
homeList: 2 * 60 * 1000,
signedUrl: 50 * 60 * 1000
},
DEFAULT_AVATAR: 'https://api.dicebear.com/7.x/avataaars/svg?seed=default',
DEFAULT_PRODUCT_IMAGE: 'https://via.placeholder.com/200x200?text=Product',
DEFAULT_SHOP_IMAGE: 'https://via.placeholder.com/200x200?text=Shop',
@@ -0,0 +1,12 @@
module.exports = {
developTarget: 'local',
requestTimeout: 10000,
enableRequestSigning: true,
domains: {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
}
+177
View File
@@ -0,0 +1,177 @@
function utf8ToBytes(text) {
const encoded = unescape(encodeURIComponent(String(text || '')))
const bytes = []
for (let index = 0; index < encoded.length; index += 1) {
bytes.push(encoded.charCodeAt(index))
}
return bytes
}
function bytesToHex(bytes) {
return (Array.isArray(bytes) ? bytes : []).map(item => item.toString(16).padStart(2, '0')).join('')
}
function rightRotate(value, amount) {
return (value >>> amount) | (value << (32 - amount))
}
function sha256Bytes(messageBytes) {
const k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
const h = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
]
const bytes = Array.isArray(messageBytes) ? messageBytes.slice() : []
const bitLength = BigInt(bytes.length) * 8n
bytes.push(0x80)
while ((bytes.length % 64) !== 56) {
bytes.push(0)
}
for (let index = 7; index >= 0; index -= 1) {
bytes.push(Number((bitLength >> BigInt(index * 8)) & 0xffn))
}
const words = new Array(64)
for (let offset = 0; offset < bytes.length; offset += 64) {
for (let index = 0; index < 16; index += 1) {
const start = offset + index * 4
words[index] = (
(bytes[start] << 24) |
(bytes[start + 1] << 16) |
(bytes[start + 2] << 8) |
bytes[start + 3]
) >>> 0
}
for (let index = 16; index < 64; index += 1) {
const s0 = (rightRotate(words[index - 15], 7) ^ rightRotate(words[index - 15], 18) ^ (words[index - 15] >>> 3)) >>> 0
const s1 = (rightRotate(words[index - 2], 17) ^ rightRotate(words[index - 2], 19) ^ (words[index - 2] >>> 10)) >>> 0
words[index] = (words[index - 16] + s0 + words[index - 7] + s1) >>> 0
}
let a = h[0]
let b = h[1]
let c = h[2]
let d = h[3]
let e = h[4]
let f = h[5]
let g = h[6]
let innerH = h[7]
for (let index = 0; index < 64; index += 1) {
const s1 = (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) >>> 0
const choice = ((e & f) ^ ((~e) & g)) >>> 0
const temp1 = (innerH + s1 + choice + k[index] + words[index]) >>> 0
const s0 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) >>> 0
const majority = ((a & b) ^ (a & c) ^ (b & c)) >>> 0
const temp2 = (s0 + majority) >>> 0
innerH = g
g = f
f = e
e = (d + temp1) >>> 0
d = c
c = b
b = a
a = (temp1 + temp2) >>> 0
}
h[0] = (h[0] + a) >>> 0
h[1] = (h[1] + b) >>> 0
h[2] = (h[2] + c) >>> 0
h[3] = (h[3] + d) >>> 0
h[4] = (h[4] + e) >>> 0
h[5] = (h[5] + f) >>> 0
h[6] = (h[6] + g) >>> 0
h[7] = (h[7] + innerH) >>> 0
}
const output = []
h.forEach(value => {
output.push((value >>> 24) & 0xff)
output.push((value >>> 16) & 0xff)
output.push((value >>> 8) & 0xff)
output.push(value & 0xff)
})
return output
}
function sha256Hex(text) {
return bytesToHex(sha256Bytes(utf8ToBytes(text)))
}
function hmacSha256Hex(secret, message) {
let keyBytes = utf8ToBytes(secret)
if (keyBytes.length > 64) {
keyBytes = sha256Bytes(keyBytes)
}
while (keyBytes.length < 64) {
keyBytes.push(0)
}
const outer = []
const inner = []
for (let index = 0; index < 64; index += 1) {
outer[index] = keyBytes[index] ^ 0x5c
inner[index] = keyBytes[index] ^ 0x36
}
const innerDigest = sha256Bytes(inner.concat(utf8ToBytes(message)))
return bytesToHex(sha256Bytes(outer.concat(innerDigest)))
}
function buildCanonicalParams(input) {
const source = input || {}
const keys = Object.keys(source)
.filter(key => source[key] !== undefined && source[key] !== null && source[key] !== '')
.sort()
return keys.map(key => {
const rawValue = source[key]
const values = Array.isArray(rawValue) ? rawValue.slice() : [rawValue]
const normalized = values
.map(item => String(item))
.sort()
.join(',')
return `${key}=${normalized}`
}).join('&')
}
function buildJsonPayload(data) {
if (data === undefined || data === null || data === '') {
return ''
}
if (typeof data === 'string') {
return data
}
return JSON.stringify(data)
}
function randomNonce() {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
module.exports = {
sha256Hex,
hmacSha256Hex,
buildCanonicalParams,
buildJsonPayload,
randomNonce
}
+20
View File
@@ -0,0 +1,20 @@
const { STORAGE_KEYS, getStorage, setStorage } = require('./storage')
function createDeviceId() {
const randomText = Math.random().toString(36).slice(2, 10)
return `mini-device-${Date.now()}-${randomText}`
}
function getDeviceId() {
let value = getStorage(STORAGE_KEYS.DEVICE_ID, '')
if (value) {
return value
}
value = createDeviceId()
setStorage(STORAGE_KEYS.DEVICE_ID, value)
return value
}
module.exports = {
getDeviceId
}
+24 -13
View File
@@ -1,5 +1,6 @@
const fileApi = require('../api/file')
const { DEFAULT_PRODUCT_IMAGE } = require('./config')
const { CACHE_TTL } = require('./config')
const { splitCsv } = require('./format')
const urlCache = {}
@@ -10,11 +11,17 @@ async function getSignedUrl(fileId) {
return ''
}
if (!urlCache[key]) {
urlCache[key] = await fileApi.getSignedUrl(key)
const cached = urlCache[key]
if (cached && cached.expireAt > Date.now()) {
return cached.value || ''
}
return urlCache[key] || ''
const value = await fileApi.getSignedUrl(key)
urlCache[key] = {
value: value || '',
expireAt: Date.now() + (CACHE_TTL.signedUrl || 50 * 60 * 1000)
}
return urlCache[key].value
}
function extractLegacyFileId(value) {
@@ -31,16 +38,13 @@ async function resolveImageList(fileIds, fallbackImage) {
return [fallbackImage || DEFAULT_PRODUCT_IMAGE]
}
const urls = []
for (let index = 0; index < ids.length; index += 1) {
const fileId = ids[index]
const urls = (await Promise.all(ids.map(async fileId => {
try {
const url = await getSignedUrl(fileId)
if (url) {
urls.push(url)
}
} catch (error) {}
}
return await getSignedUrl(fileId)
} catch (error) {
return ''
}
}))).filter(Boolean)
return urls.length ? urls : [fallbackImage || DEFAULT_PRODUCT_IMAGE]
}
@@ -63,5 +67,12 @@ module.exports = {
getSignedUrl,
extractLegacyFileId,
resolveImageList,
resolveLegacyImage
resolveLegacyImage,
clearSignedUrlCache(fileId) {
if (fileId === undefined || fileId === null || fileId === '') {
Object.keys(urlCache).forEach(key => delete urlCache[key])
return
}
delete urlCache[String(fileId)]
}
}
+73
View File
@@ -0,0 +1,73 @@
const DRAFT_PREFIX = 'miniDraft:'
function buildDraftKey(key) {
return `${DRAFT_PREFIX}${key}`
}
function loadDraft(key, defaultValue) {
if (!key) {
return defaultValue
}
try {
const value = wx.getStorageSync(buildDraftKey(key))
return value === undefined || value === '' ? defaultValue : value
} catch (error) {
return defaultValue
}
}
function saveDraft(key, value) {
if (!key) {
return
}
try {
wx.setStorageSync(buildDraftKey(key), {
savedAt: Date.now(),
value
})
} catch (error) {}
}
function clearDraft(key) {
if (!key) {
return
}
try {
wx.removeStorageSync(buildDraftKey(key))
} catch (error) {}
}
function getDraftValue(key, defaultValue) {
const record = loadDraft(key, null)
if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) {
return defaultValue
}
return record.value
}
function scheduleDraftSave(context, key, buildValue, delay) {
if (!context) {
return
}
if (context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
}
context.__draftSaveTimer = setTimeout(() => {
saveDraft(key, buildValue())
}, delay || 300)
}
function clearDraftTimer(context) {
if (context && context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
context.__draftSaveTimer = null
}
}
module.exports = {
getDraftValue,
saveDraft,
clearDraft,
scheduleDraftSave,
clearDraftTimer
}
+165
View File
@@ -0,0 +1,165 @@
let options = null
let timer = null
let warningShown = false
let loggingOut = false
let hiddenAt = 0
let lastActiveAt = Date.now()
let pagePatched = false
function shouldTrackMethod(name) {
return ![
'onHide',
'onUnload',
'onShareAppMessage',
'onShareTimeline'
].includes(name)
}
function ensurePagePatched() {
if (pagePatched || typeof Page !== 'function') {
return
}
const originalPage = Page
Page = function wrappedPage(definition) {
const nextDefinition = {}
Object.keys(definition || {}).forEach(key => {
const value = definition[key]
if (typeof value !== 'function') {
nextDefinition[key] = value
return
}
nextDefinition[key] = function wrappedHandler(...args) {
if (shouldTrackMethod(key)) {
markActive()
}
return value.apply(this, args)
}
})
return originalPage(nextDefinition)
}
pagePatched = true
}
function start() {
stop()
if (!options) {
return
}
timer = setInterval(check, 15000)
}
function stop() {
if (timer) {
clearInterval(timer)
timer = null
}
}
function isLoggedIn() {
return options && typeof options.isLoggedIn === 'function' ? Boolean(options.isLoggedIn()) : false
}
function markActive() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
lastActiveAt = Date.now()
warningShown = false
}
function onAppShow() {
if (!options) {
return
}
if (hiddenAt > 0 && isLoggedIn()) {
const hiddenDuration = Date.now() - hiddenAt
if (hiddenDuration >= options.timeoutMs) {
forceLogout()
return
}
}
hiddenAt = 0
markActive()
start()
}
function onAppHide() {
hiddenAt = Date.now()
stop()
}
function check() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
const idleMs = Date.now() - lastActiveAt
if (idleMs >= options.timeoutMs) {
forceLogout()
return
}
if (idleMs >= options.timeoutMs - options.warningMs && !warningShown) {
showWarning()
}
}
function showWarning() {
if (!options || warningShown || loggingOut) {
return
}
warningShown = true
wx.showModal({
title: options.warningTitle || '登录即将过期',
content: options.warningContent || '长时间未操作,即将退出登录。',
confirmText: options.confirmText || '继续使用',
cancelText: options.cancelText || '退出登录',
success: result => {
warningShown = false
if (result.confirm) {
markActive()
if (typeof options.onContinue === 'function') {
options.onContinue()
}
return
}
forceLogout()
},
fail: () => {
warningShown = false
}
})
}
function forceLogout() {
if (!options || loggingOut) {
return
}
loggingOut = true
Promise.resolve()
.then(() => (typeof options.onLogout === 'function' ? options.onLogout() : undefined))
.catch(() => undefined)
.finally(() => {
loggingOut = false
warningShown = false
hiddenAt = 0
lastActiveAt = Date.now()
})
}
function init(nextOptions) {
options = nextOptions || null
lastActiveAt = Date.now()
warningShown = false
loggingOut = false
hiddenAt = 0
ensurePagePatched()
start()
}
module.exports = {
init,
start,
stop,
markActive,
onAppShow,
onAppHide
}
+2 -2
View File
@@ -18,12 +18,12 @@ async function buildProductCard(product) {
return {
...product,
displayTitle: getProductTitle(product),
priceText: `¥${formatPrice(product && product.price)}`,
priceText: `¥${formatPrice(product && product.price)}`,
metaText: (product && (product.approximateDuration || product.shopName)) || '支持预约',
coverUrl: images[0],
imageUrls: images,
tagsPreview: getProductTags(product),
statsText: `${Number(product && product.likeCount || 0)}赞 · ${Number(product && product.collectCount || 0)}藏`
statsText: `${Number((product && product.likeCount) || 0)}赞 · ${Number((product && product.collectCount) || 0)}藏`
}
}
+168 -21
View File
@@ -1,9 +1,20 @@
const auth = require('./auth')
const { API_BASE_URL, REQUEST_TIMEOUT } = require('./config')
const actionGuard = require('./action-guard')
const idleSession = require('./idle-session')
const { API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
const HEADER_TIMESTAMP = 'X-Timestamp'
const HEADER_NONCE = 'X-Nonce'
const HEADER_SIGNATURE = 'X-Signature'
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
const DEVICE_ID_HEADER = 'X-Device-Id'
let isRefreshing = false
let requestQueue = []
let redirectingToAuth = false
const inflightRequests = {}
function buildRequestUrl(url, params) {
const query = Object.keys(params || {})
@@ -36,13 +47,14 @@ function isWhitelistedPath(url) {
}
function normalizeError(message, statusCode, raw) {
const error = new Error(message || '请求失败')
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
error.statusCode = statusCode
error.raw = raw
return error
}
function rawRequest(options) {
idleSession.markActive()
return new Promise((resolve, reject) => {
wx.request({
...options,
@@ -71,7 +83,6 @@ function flushQueue(error) {
item.reject(error)
return
}
item.retry().then(item.resolve).catch(item.reject)
})
}
@@ -92,7 +103,7 @@ function redirectToAuth() {
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
wx.showToast({
title: '登录已过期,请重新登录',
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
icon: 'none'
})
@@ -106,10 +117,45 @@ function redirectToAuth() {
}, 300)
}
function buildSignatureHeaders(options) {
const headers = {
[DEVICE_ID_HEADER]: getDeviceId()
}
const method = String(options.method || 'GET').toUpperCase()
const accessToken = auth.getAccessToken()
if (accessToken && !isWhitelistedPath(options.url)) {
headers.Authorization = `Bearer ${accessToken}`
}
if (!ENABLE_REQUEST_SIGNING || !accessToken || isWhitelistedPath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) {
return headers
}
const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase()
const payload = contentType.includes('application/json')
? buildJsonPayload(options.data)
: buildCanonicalParams(options.formData || options.data || options.params)
const timestamp = String(Date.now())
const nonce = randomNonce()
const canonical = [
method,
options.url,
timestamp,
nonce,
sha256Hex(payload)
].join('\n')
headers[HEADER_TIMESTAMP] = timestamp
headers[HEADER_NONCE] = nonce
headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical)
headers[HEADER_SIGNATURE_VERSION] = 'v1'
return headers
}
async function refreshToken() {
const refreshTokenValue = auth.getRefreshToken()
if (!refreshTokenValue) {
throw normalizeError('缺少刷新令牌', 401)
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
}
const response = await rawRequest({
@@ -117,7 +163,8 @@ async function refreshToken() {
method: 'POST',
timeout: REQUEST_TIMEOUT,
header: {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
[DEVICE_ID_HEADER]: getDeviceId()
},
data: {
refreshToken: refreshTokenValue
@@ -134,7 +181,7 @@ async function refreshToken() {
}
throw normalizeError(
(response.data && response.data.message) || '刷新登录态失败',
(response.data && response.data.message) || '\u5237\u65b0\u767b\u5f55\u6001\u5931\u8d25',
response.statusCode,
response
)
@@ -148,7 +195,7 @@ async function handleUnauthorized(options) {
app.clearUserSession()
}
redirectToAuth()
throw normalizeError('登录已过期,请重新登录', 401)
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
}
if (isRefreshing) {
@@ -180,14 +227,16 @@ async function handleUnauthorized(options) {
}
}
function unwrapResponse(res, options) {
async function unwrapResponse(res, options) {
idleSession.markActive()
if (res.statusCode === 401) {
return handleUnauthorized(options)
}
if (res.statusCode >= 400) {
throw normalizeError(
(res.data && res.data.message) || '网络请求失败',
(res.data && res.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
res.statusCode,
res
)
@@ -198,32 +247,110 @@ function unwrapResponse(res, options) {
if (payload.code === 200) {
return payload.data
}
throw normalizeError(payload.message || '请求失败', payload.code, payload)
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
}
return payload
}
function buildDedupeKey(options, method) {
if (options.skipDedupe) {
return ''
}
if (options.dedupeKey) {
return `${method}:${options.dedupeKey}`
}
if (method === 'GET') {
return `${method}:${options.url}:${buildCanonicalParams(options.params)}`
}
return ''
}
function isSafeMethod(method) {
return ['GET', 'HEAD', 'OPTIONS'].includes(method)
}
function buildActionFingerprint(options, method) {
const paramsText = buildCanonicalParams(options.params)
const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data)
return sha256Hex([
options.url || '',
paramsText,
payloadText
].join('\n'))
}
function resolveRepeatMessage(url) {
const path = String(url || '')
if (
path.includes('/user/login')
|| path.includes('/user/phone-login')
|| path.includes('/user/register')
|| path.includes('/user/reset-password-by-phone')
|| path.includes('/user/wechat-mini/')
) {
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/send-verification-code')) {
return '\u9a8c\u8bc1\u7801\u53d1\u9001\u5904\u7406\u4e2d\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5'
}
if (path.includes('/switch-shop')) {
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/order/create')) {
return '\u8ba2\u5355\u6b63\u5728\u63d0\u4ea4\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
if (path.includes('/upload')) {
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/logout')) {
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/cart/')) {
return '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
function buildActionGuardConfig(options, method) {
if (options.skipActionGuard || isSafeMethod(method)) {
return null
}
return {
scope: options.guardScope,
key: options.actionKey || `${method}:${options.url}:${buildActionFingerprint(options, method)}`,
message: options.repeatMessage || resolveRepeatMessage(options.url)
}
}
function request(options) {
const method = (options.method || 'GET').toUpperCase()
const method = String(options.method || 'GET').toUpperCase()
const dedupeKey = buildDedupeKey(options, method)
if (dedupeKey && inflightRequests[dedupeKey]) {
return inflightRequests[dedupeKey]
}
const signatureHeaders = buildSignatureHeaders({
url: options.url,
method,
data: options.data,
params: options.params,
header: options.header
})
const header = {
'Content-Type': 'application/json',
...signatureHeaders,
...(options.header || {})
}
const accessToken = auth.getAccessToken()
if (accessToken) {
header.Authorization = `Bearer ${accessToken}`
}
const requestOptions = {
...options,
method,
header
}
const actionGuardConfig = buildActionGuardConfig(options, method)
return new Promise((resolve, reject) => {
const executeRequest = () => new Promise((resolve, reject) => {
wx.request({
url: buildRequestUrl(options.url, method === 'GET' ? options.params : undefined),
method,
@@ -239,10 +366,30 @@ function request(options) {
}
},
fail: error => {
reject(normalizeError(error.errMsg || '网络异常,请稍后重试', 0, error))
reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error))
}
})
})
const task = (actionGuardConfig
? actionGuard.run(actionGuardConfig.scope, actionGuardConfig.key, executeRequest, {
message: actionGuardConfig.message
})
: executeRequest()
).finally(() => {
if (dedupeKey) {
delete inflightRequests[dedupeKey]
}
})
if (dedupeKey) {
inflightRequests[dedupeKey] = task
}
return task
}
request.buildSignatureHeaders = buildSignatureHeaders
request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER
module.exports = request
+2 -1
View File
@@ -3,7 +3,8 @@ const STORAGE_KEYS = {
REFRESH_TOKEN: 'refreshToken',
USER_INFO: 'userInfo',
NEED_SET_PASSWORD: 'needSetPassword',
PREFERRED_MINI_LOGIN_SHOP_ID: 'preferredMiniLoginShopId'
PREFERRED_MINI_LOGIN_SHOP_ID: 'preferredMiniLoginShopId',
DEVICE_ID: 'miniDeviceId'
}
function getStorage(key, defaultValue) {