From 942718b8d9d83d17f0e060c068eda522f41e6eb0 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Thu, 5 Nov 2026 10:51:40 +0800 Subject: [PATCH] =?UTF-8?q?fix(wechat):=20=E5=8D=8F=E8=AE=AE=E6=8C=82?= =?UTF-8?q?=E8=B5=B7=E8=AF=B7=E6=B1=82=E4=BB=85=E5=9C=A8=E7=A6=BB=E5=BC=80?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2=E6=97=B6=E7=BB=93=E7=AE=97=E5=B9=B6=E9=9B=86?= =?UTF-8?q?=E4=B8=AD=E6=98=A0=E5=B0=84=E9=94=99=E8=AF=AF=E6=96=87=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pages/account-settings/index.js | 15 ++++--- .../pages/appointment-detail/index.js | 5 ++- .../pages/appointment-form/index.js | 13 +++--- .../pages/artist-transfer/index.js | 3 +- JC-Salon-WeChat/pages/backfill-order/index.js | 5 ++- JC-Salon-WeChat/pages/customers/index.js | 5 ++- .../pages/employee-create/index.js | 7 +-- JC-Salon-WeChat/pages/employees/index.js | 3 +- JC-Salon-WeChat/pages/legal/index.js | 15 +++---- JC-Salon-WeChat/pages/legal/index.test.js | 13 ++++-- JC-Salon-WeChat/pages/login/index.js | 3 +- JC-Salon-WeChat/pages/planning/index.js | 9 ++-- JC-Salon-WeChat/pages/profile-edit/index.js | 9 ++-- JC-Salon-WeChat/pages/profile/index.js | 5 ++- JC-Salon-WeChat/pages/register/index.js | 5 ++- .../pages/schedule-setting/index.js | 3 +- JC-Salon-WeChat/pages/shop-settings/index.js | 5 ++- JC-Salon-WeChat/utils/request.js | 28 ++++++++++-- JC-Salon-WeChat/utils/request.test.js | 43 +++++++++++++------ JC-Salon-WeChat/utils/toast.js | 17 ++++++++ 20 files changed, 141 insertions(+), 70 deletions(-) create mode 100644 JC-Salon-WeChat/utils/toast.js diff --git a/JC-Salon-WeChat/pages/account-settings/index.js b/JC-Salon-WeChat/pages/account-settings/index.js index 4ccbd5a6..c787c85e 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.js +++ b/JC-Salon-WeChat/pages/account-settings/index.js @@ -1,6 +1,7 @@ const userApi = require('../../api/user') const auth = require('../../utils/auth') const profileCache = require('../../utils/profile-cache') +const { showErrorToast } = require('../../utils/toast') Page({ data: { @@ -46,7 +47,7 @@ Page({ this.setData({ closureRequest }) wx.showToast({ title: '注销申请已提交' }) } catch (error) { - wx.showToast({ title: error.message || '申请提交失败', icon: 'none' }) + showErrorToast(error, '申请提交失败') } }, @@ -58,7 +59,7 @@ Page({ await this.loadClosureRequest() wx.showToast({ title: '申请已撤回' }) } catch (error) { - wx.showToast({ title: error.message || '撤回失败', icon: 'none' }) + showErrorToast(error, '撤回失败') } }, @@ -71,7 +72,7 @@ Page({ const session = auth.getSession() app.setSession({ ...session, userInfo: { ...(session.userInfo || {}), ...profile } }) } catch (error) { - wx.showToast({ title: error.message || '账号信息加载失败', icon: 'none' }) + showErrorToast(error, '账号信息加载失败') } finally { this.setData({ loading: false }) } @@ -103,7 +104,7 @@ Page({ await this.loadProfile({ force: true }) wx.showToast({ title: '手机号已绑定' }) } catch (error) { - wx.showToast({ title: error.message || '绑定失败', icon: 'none' }) + showErrorToast(error, '绑定失败') } finally { this.setData({ binding: false }) } @@ -122,7 +123,7 @@ Page({ this.startCountdown() wx.showToast({ title: '验证码已发送' }) } catch (error) { - wx.showToast({ title: error.message || '验证码发送失败', icon: 'none' }) + showErrorToast(error, '验证码发送失败') } finally { this.setData({ codeLoading: false }) } @@ -151,7 +152,7 @@ Page({ await this.loadProfile({ force: true }) wx.showToast({ title: '手机号已绑定' }) } catch (error) { - wx.showToast({ title: error.message || '绑定失败', icon: 'none' }) + showErrorToast(error, '绑定失败') } finally { this.setData({ binding: false }) } @@ -178,7 +179,7 @@ Page({ await this.loadProfile({ force: true }) wx.showToast({ title: '手机号已解绑' }) } catch (error) { - wx.showToast({ title: error.message || '解绑失败', icon: 'none' }) + showErrorToast(error, '解绑失败') } finally { this.setData({ binding: false }) } diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index 04104d50..513f0cdf 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -1,6 +1,7 @@ const planningApi = require('../../api/planning') const customersApi = require('../../api/customers') const { markPlanningRefresh } = require('../../utils/planning-refresh') +const { showErrorToast } = require('../../utils/toast') function displayValue(value, fallback) { if (value === null || value === undefined) return fallback @@ -99,7 +100,7 @@ Page({ wx.showToast({ title: '已更新' }) this.loadDetail() } catch (error) { - wx.showToast({ title: error.message || '操作失败', icon: 'none' }) + showErrorToast(error, '操作失败') } finally { this.setData({ updating: false }) } @@ -151,7 +152,7 @@ Page({ } wx.makePhoneCall({ phoneNumber: result.dialNumber }) } catch (error) { - wx.showToast({ title: error.message || '取号失败', icon: 'none' }) + showErrorToast(error, '取号失败') } finally { this.setData({ dialing: false }) } diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index ae28ef55..deef35e8 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -4,6 +4,7 @@ const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') const { uploadObjectFile } = require('../../utils/upload') +const { showErrorToast } = require('../../utils/toast') const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft' const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000 @@ -665,7 +666,7 @@ Page({ try { draft = readDraft() } catch (error) { - wx.showToast({ title: error.message || '预约草稿读取失败', icon: 'none' }) + showErrorToast(error, '预约草稿读取失败') } } const draftForm = draft && draft.form ? draft.form : {} @@ -1121,7 +1122,7 @@ Page({ return true } catch (error) { this.setData({ draftSavedAtText: '草稿保存失败,请点击保存草稿重试' }) - if (showToast) wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' }) + if (showToast) showErrorToast(error, '草稿保存失败') return false } }, @@ -1148,7 +1149,7 @@ Page({ try { removeDraftForm() } catch (error) { - wx.showToast({ title: error.message || '草稿清理失败,请稍后重试', icon: 'none' }) + showErrorToast(error, '草稿清理失败,请稍后重试') return } const defaults = this._entryDefaults || {} @@ -1417,7 +1418,7 @@ Page({ wx.showToast({ title: `已添加${filePaths.length}张图片`, icon: 'success' }) } } catch (error) { - wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) + showErrorToast(error, '图片上传失败') } finally { this.setData({ manualImageUploading: false }) } @@ -1962,7 +1963,7 @@ Page({ this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) }) return true } catch (error) { - wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) + showErrorToast(error, '客户校验失败,请稍后重试') return false } finally { this.setData({ loading: false }) @@ -2080,7 +2081,7 @@ Page({ if ((error.message || '').includes('有效期') || (error.message || '').includes('到期')) { await showBusinessExpiryNotice() } else { - wx.showToast({ title: error.message || '提交失败', icon: 'none' }) + showErrorToast(error, '提交失败') } } finally { this.setData({ loading: false }) diff --git a/JC-Salon-WeChat/pages/artist-transfer/index.js b/JC-Salon-WeChat/pages/artist-transfer/index.js index 51d28295..c7d3767c 100644 --- a/JC-Salon-WeChat/pages/artist-transfer/index.js +++ b/JC-Salon-WeChat/pages/artist-transfer/index.js @@ -1,6 +1,7 @@ const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') +const { showErrorToast } = require('../../utils/toast') Page({ data: { @@ -154,7 +155,7 @@ Page({ wx.showToast({ title: this.data.isUnassigned ? '已分配' : '已改派' }) setTimeout(() => wx.navigateBack(), 500) } catch (error) { - wx.showToast({ title: error.message || '改派失败', icon: 'none' }) + showErrorToast(error, '改派失败') } finally { this.setData({ loading: false }) } diff --git a/JC-Salon-WeChat/pages/backfill-order/index.js b/JC-Salon-WeChat/pages/backfill-order/index.js index 2ad1fe72..b770157f 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.js +++ b/JC-Salon-WeChat/pages/backfill-order/index.js @@ -4,6 +4,7 @@ const productsApi = require('../../api/products') const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { uploadObjectFile } = require('../../utils/upload') +const { showErrorToast } = require('../../utils/toast') function normalizeProduct(product, artists) { const artistIds = String(product.bookableArtists || '').split(',').map(id => id.trim()).filter(Boolean) @@ -118,7 +119,7 @@ Page({ useWalkIn() { this.setData({ 'form.customerUserId': '', 'form.customerName': '', 'form.wechatId': '', 'form.phone': '', customerSelectorVisible: false }) }, onCustomerInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value, 'form.customerUserId': '' }) }, useManualProduct() { const title = String(this.data.manualProductDraft.title || '').trim(); const priceText = String(this.data.manualProductDraft.price || this.data.form.amount || '').trim(); const price = Number(priceText); const images = this.data.form.manualProductImages || []; if (this.data.form.productId) { if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } this.setData({ 'form.amount': priceText, 'form.durationMinutes': String(this.data.manualProductDraft.durationMinutes || '60'), manualProductSheetVisible: false }); return } if (!title && !images.length) { wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' }); return } if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } const duration = String(this.data.manualProductDraft.durationMinutes || '60'); this.setData({ 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductDescription': this.data.manualProductDraft.description || '', 'form.manualProductPrice': priceText, 'form.amount': priceText, 'form.durationMinutes': duration, 'manualProductDraft.price': priceText, selectedProduct: {}, selectedProductTitle: title, selectedProductPriceText: `¥${price}`, productSelectorVisible: false, manualProductSheetVisible: false }) }, - async chooseManualProductImage() { if (this.data.manualImageUploading) return; const remaining = 9 - (this.data.form.manualProductImages || []).length; if (remaining <= 0) { wx.showToast({ title: '最多添加9张图片', icon: 'none' }); return } try { this.setData({ manualImageUploading: true }); const paths = await chooseImages(remaining); for (const filePath of paths) { const result = await uploadObjectFile(filePath); const fileId = result.id || result.fileId; if (!fileId) throw new Error('图片上传成功但未返回文件ID'); this.setData(imagePatch((this.data.form.manualProductImages || []).concat({ fileId: String(fileId), fileUrl: result.fileUrl || result.primaryUrl || '', previewUrl: filePath }))) } } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { this.setData({ manualImageUploading: false }) } }, + async chooseManualProductImage() { if (this.data.manualImageUploading) return; const remaining = 9 - (this.data.form.manualProductImages || []).length; if (remaining <= 0) { wx.showToast({ title: '最多添加9张图片', icon: 'none' }); return } try { this.setData({ manualImageUploading: true }); const paths = await chooseImages(remaining); for (const filePath of paths) { const result = await uploadObjectFile(filePath); const fileId = result.id || result.fileId; if (!fileId) throw new Error('图片上传成功但未返回文件ID'); this.setData(imagePatch((this.data.form.manualProductImages || []).concat({ fileId: String(fileId), fileUrl: result.fileUrl || result.primaryUrl || '', previewUrl: filePath }))) } } catch (error) { showErrorToast(error, '图片上传失败') } finally { this.setData({ manualImageUploading: false }) } }, removeManualProductImage(event) { const index = Number(event.currentTarget.dataset.index); this.setData(imagePatch((this.data.form.manualProductImages || []).filter((item, itemIndex) => itemIndex !== index))) }, onManualProductImageError(event) { const index = Number(event.currentTarget.dataset.index); const images = this.data.form.manualProductImages || []; if (!images[index] || !images[index].fileUrl) return; const fallback = images.slice(); fallback[index] = { ...fallback[index], previewUrl: fallback[index].fileUrl }; this.setData(imagePatch(fallback)) }, onSelectedProductImageError() { this.setData({ 'selectedProduct.coverImage': '' }) }, @@ -126,5 +127,5 @@ Page({ onDateChange(event) { this.setData({ 'form.serviceDate': event.detail.value }) }, onTimeChange(event) { this.setData({ 'form.serviceTime': event.detail.value }) }, selectStatus(event) { this.setData({ 'form.status': Number(event.currentTarget.dataset.status) }) }, - async submit() { const form = this.data.form; if (!form.serviceDate || (!form.productId && !String(form.manualProductTitle || '').trim() && !(form.manualProductImages || []).length) || !String(form.amount || '').trim() || !form.artistId) { wx.showToast({ title: '请补全款式、金额、日期和美甲师', icon: 'none' }); return } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }); return } this.setData({ submitting: true }); try { const payload = { ...form, amount: Number(form.amount), manualProductPrice: Number(form.manualProductPrice || form.amount), durationMinutes: Number(form.durationMinutes) || 60, manualProductImageFileIds: String(form.manualProductImageFileIds || '').trim() || undefined, customerName: String(form.customerName || '').trim() || undefined, wechatId: String(form.wechatId || '').trim() || undefined, phone: String(form.phone || '').trim() || undefined, serviceTime: String(form.serviceTime || '').trim() || undefined }; if (!payload.manualProductTitle && payload.manualProductImageFileIds) payload.manualProductTitle = String(form.customerName || '').trim() || '散客款式'; await planningApi.createBackfillOrder(payload); wx.showToast({ title: '历史补单已保存', icon: 'success' }); const app = getApp(); app.globalData.planningNeedRefresh = true; setTimeout(() => wx.navigateBack(), 500) } catch (error) { wx.showToast({ title: error.message || '保存失败', icon: 'none' }) } finally { this.setData({ submitting: false }) } } + async submit() { const form = this.data.form; if (!form.serviceDate || (!form.productId && !String(form.manualProductTitle || '').trim() && !(form.manualProductImages || []).length) || !String(form.amount || '').trim() || !form.artistId) { wx.showToast({ title: '请补全款式、金额、日期和美甲师', icon: 'none' }); return } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }); return } this.setData({ submitting: true }); try { const payload = { ...form, amount: Number(form.amount), manualProductPrice: Number(form.manualProductPrice || form.amount), durationMinutes: Number(form.durationMinutes) || 60, manualProductImageFileIds: String(form.manualProductImageFileIds || '').trim() || undefined, customerName: String(form.customerName || '').trim() || undefined, wechatId: String(form.wechatId || '').trim() || undefined, phone: String(form.phone || '').trim() || undefined, serviceTime: String(form.serviceTime || '').trim() || undefined }; if (!payload.manualProductTitle && payload.manualProductImageFileIds) payload.manualProductTitle = String(form.customerName || '').trim() || '散客款式'; await planningApi.createBackfillOrder(payload); wx.showToast({ title: '历史补单已保存', icon: 'success' }); const app = getApp(); app.globalData.planningNeedRefresh = true; setTimeout(() => wx.navigateBack(), 500) } catch (error) { showErrorToast(error, '保存失败') } finally { this.setData({ submitting: false }) } } }) diff --git a/JC-Salon-WeChat/pages/customers/index.js b/JC-Salon-WeChat/pages/customers/index.js index 87a88a3e..bdcaa728 100644 --- a/JC-Salon-WeChat/pages/customers/index.js +++ b/JC-Salon-WeChat/pages/customers/index.js @@ -1,4 +1,5 @@ const customersApi = require('../../api/customers') +const { showErrorToast } = require('../../utils/toast') Page({ data: { @@ -134,11 +135,11 @@ Page({ return } } catch (lookupError) { - wx.showToast({ title: lookupError.message || '客户重复,请重新查询已有客户', icon: 'none' }) + showErrorToast(lookupError, '客户重复,请重新查询已有客户') return } } - wx.showToast({ title: error.message || '新增失败', icon: 'none' }) + showErrorToast(error, '新增失败') } finally { this.setData({ creating: false }) } diff --git a/JC-Salon-WeChat/pages/employee-create/index.js b/JC-Salon-WeChat/pages/employee-create/index.js index b712102c..6319090c 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.js +++ b/JC-Salon-WeChat/pages/employee-create/index.js @@ -1,5 +1,6 @@ const employeesApi = require('../../api/employees') const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload') +const { showErrorToast } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7BA7C7', '#8FB89A', '#A894C7', '#D7A86E', '#D98DA5', '#79A6A3', '#B9A16B', '#9BA9C8'] @@ -66,7 +67,7 @@ Page({ 'form.avatarUrl': filePath }) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } finally { this.setData({ avatarUploading: false }) } @@ -122,7 +123,7 @@ Page({ } await this.offerPendingAssociation() } catch (error) { - wx.showToast({ title: error.message || '新增失败', icon: 'none' }) + showErrorToast(error, '新增失败') } finally { this.setData({ creating: false }) } @@ -207,7 +208,7 @@ Page({ this.setData({ associationSheetVisible: false, onboardingVisible: true }) wx.showToast({ title: '已预关联申请', icon: 'success' }) } catch (error) { - wx.showToast({ title: error.message || '关联失败,请重新选择', icon: 'none' }) + showErrorToast(error, '关联失败,请重新选择') this.setData({ associationSelectedId: '' }) } finally { this.setData({ associationLoading: false }) diff --git a/JC-Salon-WeChat/pages/employees/index.js b/JC-Salon-WeChat/pages/employees/index.js index a926a20f..8aece3ec 100644 --- a/JC-Salon-WeChat/pages/employees/index.js +++ b/JC-Salon-WeChat/pages/employees/index.js @@ -1,6 +1,7 @@ const employeesApi = require('../../api/employees') const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') +const { showErrorToast } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D'] @@ -248,7 +249,7 @@ Page({ wx.showToast({ title: successMessage, icon: 'success' }) await Promise.all([this.loadReviewApplications(), this.loadEmployees()]) } catch (error) { - wx.showToast({ title: error.message || '申请状态已变化,请刷新重试', icon: 'none' }) + showErrorToast(error, '申请状态已变化,请刷新重试') await this.loadReviewApplications() } finally { this.setData({ reviewingId: '' }) diff --git a/JC-Salon-WeChat/pages/legal/index.js b/JC-Salon-WeChat/pages/legal/index.js index fd7473b8..6e3894bc 100644 --- a/JC-Salon-WeChat/pages/legal/index.js +++ b/JC-Salon-WeChat/pages/legal/index.js @@ -1,6 +1,7 @@ const authApi = require('../../api/auth') const auth = require('../../utils/auth') const request = require('../../utils/request') +const { showErrorToast } = require('../../utils/toast') Page({ data: { loading: true, agreement: null, mode: '', agreements: [], accepted: false, accepting: false }, @@ -23,7 +24,7 @@ Page({ const agreement = (Array.isArray(agreements) ? agreements : []).find(item => item.agreementType === agreementType) this.setData({ agreement: agreement || null }) } catch (error) { - wx.showToast({ title: error.message || '协议加载失败', icon: 'none' }) + showErrorToast(error, '协议加载失败') } finally { this.setData({ loading: false }) } @@ -35,23 +36,19 @@ Page({ const agreements = await authApi.getCurrentAgreements() this.setData({ agreements: Array.isArray(agreements) ? agreements : [] }) } catch (error) { - wx.showToast({ title: error.message || '协议加载失败', icon: 'none' }) + showErrorToast(error, '协议加载失败') } finally { this.setData({ loading: false }) } }, - onHide() { - this.discardPendingIfNotAccepted() - }, - onUnload() { this.discardPendingIfNotAccepted() }, /** - * 用户未完成同意就离开协议页(返回/隐藏/卸载)时,立即结算被 4510 挂起的请求, - * 避免调用方 loading 永久卡住;同意成功后不再触发。 + * 只有真正离开协议页(返回导致页面卸载)才结算被 4510 挂起的请求,避免调用方 loading 永久卡住; + * 切后台(如来电、复制协议文本)只触发 onHide,不结算;同意成功后也不再触发。 */ discardPendingIfNotAccepted() { if (this.data.mode !== 'accept' || this.agreementAccepted) { @@ -86,7 +83,7 @@ Page({ } catch (error) { // accept 返回 401 时请求层已清会话并跳登录页,这里不再叠加提示。 if (auth.getAccessToken()) { - wx.showToast({ title: error.message || '同意失败,请重试', icon: 'none' }) + showErrorToast(error, '同意失败,请重试') } } finally { this.setData({ accepting: false }) diff --git a/JC-Salon-WeChat/pages/legal/index.test.js b/JC-Salon-WeChat/pages/legal/index.test.js index 35010d16..46710a42 100644 --- a/JC-Salon-WeChat/pages/legal/index.test.js +++ b/JC-Salon-WeChat/pages/legal/index.test.js @@ -40,16 +40,21 @@ const reader = createPage('') pageDefinition.onUnload.call(reader) assert.strictEqual(discardCalls, 0) +// 切后台(来电、复制协议文本)不应结算挂起请求:协议页不再提供 onHide 结算入口 +assert.strictEqual(typeof pageDefinition.onHide, 'undefined') const hiddenPage = createPage('accept') -pageDefinition.onHide.call(hiddenPage) -assert.strictEqual(discardCalls, 1) +if (pageDefinition.onHide) { + pageDefinition.onHide.call(hiddenPage) +} +assert.strictEqual(discardCalls, 0) +// 真正离开协议页(返回触发页面卸载)仍然结算 const unloadedPage = createPage('accept') pageDefinition.onUnload.call(unloadedPage) -assert.strictEqual(discardCalls, 2) +assert.strictEqual(discardCalls, 1) const acceptedPage = createPage('accept', true) pageDefinition.onUnload.call(acceptedPage) -assert.strictEqual(discardCalls, 2) +assert.strictEqual(discardCalls, 1) console.log('legal page agreement discard test passed') diff --git a/JC-Salon-WeChat/pages/login/index.js b/JC-Salon-WeChat/pages/login/index.js index fd0112d8..7592861c 100644 --- a/JC-Salon-WeChat/pages/login/index.js +++ b/JC-Salon-WeChat/pages/login/index.js @@ -3,6 +3,7 @@ const auth = require('../../utils/auth') const { BRAND_CONFIG } = require('../../utils/config') const loginFlow = require('../../utils/login-flow') const { requestSubscribeMessages } = require('../../utils/subscribe-message') +const { showErrorToast } = require('../../utils/toast') function wxLoginCode() { return new Promise((resolve, reject) => wx.login({ @@ -234,7 +235,7 @@ Page({ if (result.status !== 'SUCCESS' || !result.accessToken) throw new Error(result.message || '进入门店失败') await this.finishLogin(result, true) } catch (error) { - wx.showToast({ title: error.message || '进入门店失败', icon: 'none' }) + showErrorToast(error, '进入门店失败') } finally { this.setData({ switchingShop: false }) } diff --git a/JC-Salon-WeChat/pages/planning/index.js b/JC-Salon-WeChat/pages/planning/index.js index bd3e264e..7619ce79 100644 --- a/JC-Salon-WeChat/pages/planning/index.js +++ b/JC-Salon-WeChat/pages/planning/index.js @@ -6,6 +6,7 @@ const { uploadProfileImage } = require('../../utils/upload') const { normalizeAvatar } = require('../../utils/profile-card') const profileCache = require('../../utils/profile-cache') const employeesApi = require('../../api/employees') +const { showErrorToast } = require('../../utils/toast') function canCreateAppointment() { const app = getApp() @@ -287,7 +288,7 @@ Page({ 'profileForm.avatarFileId': uploaded && uploaded.fileId ? String(uploaded.fileId) : '' }) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } finally { this.setData({ profileSaving: false }) } @@ -313,7 +314,7 @@ Page({ this.setData({ profilePromptVisible: false }) wx.showToast({ title: '资料已保存', duration: 3000 }) } catch (error) { - wx.showToast({ title: error.message || '资料保存失败', icon: 'none', duration: 3000 }) + showErrorToast(error, '资料保存失败', { duration: 3000 }) } finally { this.setData({ profileSaving: false }) } @@ -872,7 +873,7 @@ Page({ wx.showToast({ title: Number(event.currentTarget.dataset.status) === 2 ? '补单已完成' : '预约已确认', icon: 'success' }) this.loadCalendar() } catch (error) { - wx.showToast({ title: error.message || '预约状态更新失败', icon: 'none' }) + showErrorToast(error, '预约状态更新失败') } }, @@ -903,7 +904,7 @@ Page({ wx.showToast({ title: '预约已取消', icon: 'success' }) this.loadCalendar() } catch (error) { - wx.showToast({ title: error.message || '预约取消失败', icon: 'none' }) + showErrorToast(error, '预约取消失败') } } }) diff --git a/JC-Salon-WeChat/pages/profile-edit/index.js b/JC-Salon-WeChat/pages/profile-edit/index.js index ad97a190..2dea052b 100644 --- a/JC-Salon-WeChat/pages/profile-edit/index.js +++ b/JC-Salon-WeChat/pages/profile-edit/index.js @@ -4,6 +4,7 @@ const { chooseImageFilePath, uploadProfileImage } = require('../../utils/upload' const { buildProfileCard, normalizeAvatar } = require('../../utils/profile-card') const { BRAND_CONFIG } = require('../../utils/config') const profileCache = require('../../utils/profile-cache') +const { showErrorToast } = require('../../utils/toast') function resolveRoleText(type) { const role = Number(type) @@ -65,7 +66,7 @@ Page({ const profile = await profileCache.getProfile(options) this.syncProfileToSession(profile) } catch (error) { - wx.showToast({ title: error.message || '个人信息加载失败', icon: 'none' }) + showErrorToast(error, '个人信息加载失败') } finally { this.setData({ loading: false }) } @@ -146,7 +147,7 @@ Page({ if (!filePath) return await this.uploadAvatar(filePath) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } }, @@ -159,7 +160,7 @@ Page({ try { await this.uploadAvatar(event.detail && event.detail.avatarUrl) } catch (error) { - wx.showToast({ title: error.message || '微信头像获取失败', icon: 'none' }) + showErrorToast(error, '微信头像获取失败') } }, @@ -190,7 +191,7 @@ Page({ wx.showToast({ title: '已保存', icon: 'success', duration: 3000 }) setTimeout(() => wx.navigateBack(), 350) } catch (error) { - wx.showToast({ title: error.message || '保存失败', icon: 'none', duration: 3000 }) + showErrorToast(error, '保存失败', { duration: 3000 }) } finally { this.setData({ saving: false }) } diff --git a/JC-Salon-WeChat/pages/profile/index.js b/JC-Salon-WeChat/pages/profile/index.js index c1dd3649..aea5edca 100644 --- a/JC-Salon-WeChat/pages/profile/index.js +++ b/JC-Salon-WeChat/pages/profile/index.js @@ -4,6 +4,7 @@ const planningApi = require('../../api/planning') const { buildProfileCard } = require('../../utils/profile-card') const profileCache = require('../../utils/profile-cache') const authApi = require('../../api/auth') +const { showErrorToast } = require('../../utils/toast') function resolveRoleText(type) { const role = Number(type) @@ -62,7 +63,7 @@ Page({ } }) } catch (error) { - wx.showToast({ title: error.message || '今日概览加载失败', icon: 'none' }) + showErrorToast(error, '今日概览加载失败') } finally { this.setData({ overviewLoading: false }) } @@ -113,7 +114,7 @@ Page({ const profile = await profileCache.getProfile() this.syncProfileToSession(profile) } catch (error) { - wx.showToast({ title: error.message || '个人信息加载失败', icon: 'none' }) + showErrorToast(error, '个人信息加载失败') } }, diff --git a/JC-Salon-WeChat/pages/register/index.js b/JC-Salon-WeChat/pages/register/index.js index 5ac24897..494fbbd9 100644 --- a/JC-Salon-WeChat/pages/register/index.js +++ b/JC-Salon-WeChat/pages/register/index.js @@ -1,4 +1,5 @@ const authApi = require('../../api/auth') +const { showErrorToast } = require('../../utils/toast') Page({ data: { @@ -94,7 +95,7 @@ Page({ const result = await authApi.uploadRegistrationAvatar(this.data.registrationTicket, filePath) this.setData({ 'form.applicantAvatarFileId': result.fileId || result.id, 'form.applicantAvatarUrl': filePath }) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } finally { this.setData({ avatarUploading: false }) } @@ -209,7 +210,7 @@ Page({ this.setData({ ticketInvalid: true }) return } - wx.showToast({ title: message, icon: 'none' }) + showErrorToast(error, '提交失败') } finally { this.setData({ loading: false }) } diff --git a/JC-Salon-WeChat/pages/schedule-setting/index.js b/JC-Salon-WeChat/pages/schedule-setting/index.js index e7e0ac04..fe0da4fc 100644 --- a/JC-Salon-WeChat/pages/schedule-setting/index.js +++ b/JC-Salon-WeChat/pages/schedule-setting/index.js @@ -1,6 +1,7 @@ const employeesApi = require('../../api/employees') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') +const { showErrorToast } = require('../../utils/toast') const PRESETS = [ { value: 'DOUBLE_REST', label: '双休', workDays: [1, 2, 3, 4, 5], startTime: '09:00', endTime: '17:00' }, @@ -137,7 +138,7 @@ Page({ })) }) } catch (error) { - wx.showToast({ title: error.message || '排班规则加载失败', icon: 'none' }) + showErrorToast(error, '排班规则加载失败') } finally { this.setData({ loading: false }) } diff --git a/JC-Salon-WeChat/pages/shop-settings/index.js b/JC-Salon-WeChat/pages/shop-settings/index.js index b89de91c..a9c03151 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.js +++ b/JC-Salon-WeChat/pages/shop-settings/index.js @@ -1,6 +1,7 @@ const { BRAND_CONFIG } = require('../../utils/config') const profileCache = require('../../utils/profile-cache') const shopApi = require('../../api/shop') +const { showErrorToast } = require('../../utils/toast') function resolveNameStatus(value) { const status = String(value || '').toUpperCase() @@ -139,7 +140,7 @@ Page({ this.setData({ businessHoursConfigured: normalizedHours.some(day => day.open) }) wx.showToast({ title: '预约设置已生效', icon: 'success' }) } catch (error) { - wx.showToast({ title: error.message || '保存失败,请重试', icon: 'none' }) + showErrorToast(error, '保存失败,请重试') } finally { this.setData({ settingsSaving: false }) } @@ -157,7 +158,7 @@ Page({ wx.showToast({ title: '店铺名称已提交审核', icon: 'success' }) await this.loadProfileAndSettings({ force: true }) } catch (error) { - wx.showToast({ title: error.message || '提交审核失败', icon: 'none' }) + showErrorToast(error, '提交审核失败') } finally { this.setData({ nameSaving: false }) } diff --git a/JC-Salon-WeChat/utils/request.js b/JC-Salon-WeChat/utils/request.js index 3d57472b..4f377ad9 100644 --- a/JC-Salon-WeChat/utils/request.js +++ b/JC-Salon-WeChat/utils/request.js @@ -14,8 +14,15 @@ const AGREEMENT_VERSION_REQUIRED_CODE = 4510 /** 挂起请求被放弃时的自定义错误码,调用方据此区分“未完成协议同意”与普通业务失败。 */ const AGREEMENT_NOT_ACCEPTED_CODE = 'AGREEMENT_NOT_ACCEPTED' const AGREEMENT_NOT_ACCEPTED_MESSAGE = '未完成协议同意' -/** 挂起请求最长等待时间,超时自动结算,避免页面 loading 永久卡住。 */ -const AGREEMENT_PENDING_TIMEOUT_MS = 30000 +/** 面向用户的友好文案:内部错误码与文案保持技术语义,展示层统一经 resolveUserMessage 转换。 */ +const AGREEMENT_NOT_ACCEPTED_USER_MESSAGE = '协议未确认,请稍后重试' +/** + * 挂起请求最长等待时间(3 分钟),只作为“避免页面 loading 永久卡死”的兜底。 + * 用户阅读两份协议可能耗时较久,不能因为超时提前判定操作失败; + * 超时结算后不再自动重放该请求,但用户稍后再同意协议仍会正常记录同意, + * 只是原请求需要用户重新发起。 + */ +const AGREEMENT_PENDING_TIMEOUT_MS = 180000 const AGREEMENT_PAGE_URL = '/pages/legal/index?mode=accept' /** * 一屏多个请求同时命中 4510 时只允许弹一次弹窗; @@ -103,7 +110,18 @@ function createAgreementNotAcceptedError(raw) { } /** - * 创建挂起请求容器:保证 resolve/reject 各只生效一次,并携带 30 秒兜底定时器。 + * 集中把内部错误文案映射成可直接展示给用户的文案,避免各页面自行硬编码。 + * AGREEMENT_NOT_ACCEPTED 的内部语义保持“未完成协议同意”,展示为“协议未确认,请稍后重试”。 + */ +function resolveUserMessage(error, fallbackMessage) { + if (error && error.code === AGREEMENT_NOT_ACCEPTED_CODE) { + return AGREEMENT_NOT_ACCEPTED_USER_MESSAGE + } + return (error && error.message) || fallbackMessage +} + +/** + * 创建挂起请求容器:保证 resolve/reject 各只生效一次,并携带 3 分钟兜底定时器。 * 结算或开始重放时统一清理引用与定时器,避免内存泄漏和后续误重放。 */ function createBlockedAgreementRequest(options, resolve, reject) { @@ -209,7 +227,8 @@ function handleAgreementVersionRequired(response, options, resolve, reject) { } /** - * 放弃当前挂起请求:用于“稍后”以及协议页返回/隐藏/卸载,统一按“未完成协议同意”结算。 + * 放弃当前挂起请求:用于“稍后”以及真正离开协议页(返回触发页面卸载), + * 统一按“未完成协议同意”结算;切后台(onHide)不触发结算。 */ function discardPendingAgreement() { const blocked = agreementBlockedRequest @@ -371,6 +390,7 @@ request.toBackendRequestPath = toBackendRequestPath request.handleUnauthorized = handleUnauthorized request.retryPendingAfterAgreement = retryPendingAfterAgreement request.discardPendingAgreement = discardPendingAgreement +request.resolveUserMessage = resolveUserMessage request.AGREEMENT_NOT_ACCEPTED_CODE = AGREEMENT_NOT_ACCEPTED_CODE module.exports = request diff --git a/JC-Salon-WeChat/utils/request.test.js b/JC-Salon-WeChat/utils/request.test.js index 656000b6..c7f2e267 100644 --- a/JC-Salon-WeChat/utils/request.test.js +++ b/JC-Salon-WeChat/utils/request.test.js @@ -118,26 +118,29 @@ async function run() { const originalNonce = requests[requests.length - 1].header['X-Nonce'] respondLatest(200, { code: 4510, message: agreementMessage }) - // 4510 不清会话、不跳登录页,只弹一次弹窗,并挂起 30 秒兜底定时器 + // 4510 不清会话、不跳登录页,只弹一次弹窗,并挂起 3 分钟兜底定时器(30 秒内不会因超时结算) assert.strictEqual(clearedSessions, 2) assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index']) assert.strictEqual(modals.length, 1) assert.strictEqual(modals[0].confirmText, '查看并同意') assert.strictEqual(modals[0].cancelText, '稍后') assert.strictEqual(modals[0].content, agreementMessage) - assert.strictEqual(pendingTimers(30000).length, 1) + assert.strictEqual(pendingTimers(180000).length, 1) + // 超时已放宽到 3 分钟,不再存在 30 秒定时器;切后台(onHide)不会额外结算, + // 因此 30 秒内无论用户是否切后台,挂起请求都保持 pending。 + assert.strictEqual(pendingTimers(30000).length, 0) // 查看并同意:进入协议页,挂起期间定时器仍在跑 modals[0].success({ confirm: true, cancel: false }) assert.deepStrictEqual(navigateToPages, ['/pages/legal/index?mode=accept']) assert.strictEqual(clearedSessions, 2) - assert.strictEqual(pendingTimers(30000).length, 1) + assert.strictEqual(pendingTimers(180000).length, 1) // 同意后自动重放首个被拦请求一次:取走时清定时器、重新生成 nonce,原调用方无感 const requestsBeforeRetry = requests.length request.retryPendingAfterAgreement() assert.strictEqual(requests.length, requestsBeforeRetry + 1) - assert.strictEqual(pendingTimers(30000).length, 0) + assert.strictEqual(pendingTimers(180000).length, 0) const retriedRequest = requests[requests.length - 1] assert.strictEqual(retriedRequest.url.includes('/manager/orders'), true) assert.deepStrictEqual(retriedRequest.data, { page: 1 }) @@ -160,14 +163,14 @@ async function run() { respondLatest(200, { code: 4510, message: agreementMessage }) assert.strictEqual(modals.length, 2) const oldErrorPromise = oldRequest.promise.catch(error => error) - assert.strictEqual(pendingTimers(30000).length, 1) + assert.strictEqual(pendingTimers(180000).length, 1) const newRequest = startRequest({ url: '/manager/customers', method: 'POST', data: { page: 3 } }) respondLatest(200, { code: 4510, message: agreementMessage }) assert.strictEqual(modals.length, 2) const oldError = await oldErrorPromise assertAgreementPendingError(oldError) - assert.strictEqual(pendingTimers(30000).length, 1) + assert.strictEqual(pendingTimers(180000).length, 1) modals[1].success({ confirm: true, cancel: false }) assert.strictEqual(navigateToPages.length, 2) @@ -188,26 +191,28 @@ async function run() { assert.strictEqual(modals.length, 3) const backErrorPromise = backRequest.promise.catch(error => error) modals[2].success({ confirm: true, cancel: false }) - assert.strictEqual(pendingTimers(30000).length, 1) + assert.strictEqual(pendingTimers(180000).length, 1) request.discardPendingAgreement() const backError = await backErrorPromise assertAgreementPendingError(backError) - assert.strictEqual(pendingTimers(30000).length, 0) + assert.strictEqual(pendingTimers(180000).length, 0) const requestsBeforeBackRetry = requests.length request.retryPendingAfterAgreement() assert.strictEqual(requests.length, requestsBeforeBackRetry) - // 30 秒超时:自动 reject,之后用户再同意也不会重放 + // 3 分钟超时兜底:只有真的超时才会 reject;超时后用户再同意只记录同意,不再自动重放 auth.setSession({ accessToken: 'timeout-token' }, true) const timedRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 5 } }) respondLatest(200, { code: 4510, message: agreementMessage }) assert.strictEqual(modals.length, 4) const timedErrorPromise = timedRequest.promise.catch(error => error) - assert.strictEqual(pendingTimers(30000).length, 1) - runTimer(30000) + assert.strictEqual(pendingTimers(180000).length, 1) + // 3 分钟以内不结算:模拟用户在协议页停留/切后台 30 秒,仍有 2 分 30 秒余量。 + assert.strictEqual(pendingTimers(30000).length, 0) + runTimer(180000) const timedError = await timedErrorPromise assertAgreementPendingError(timedError) - assert.strictEqual(pendingTimers(30000).length, 0) + assert.strictEqual(pendingTimers(180000).length, 0) modals[3].success({ confirm: true, cancel: false }) const requestsBeforeTimeoutConfirm = requests.length request.retryPendingAfterAgreement() @@ -223,7 +228,7 @@ async function run() { const laterError = await laterPromise assertAgreementPendingError(laterError) assert.strictEqual(toasts[toasts.length - 1].title, '请先同意最新协议后再操作') - assert.strictEqual(pendingTimers(30000).length, 0) + assert.strictEqual(pendingTimers(180000).length, 0) assert.strictEqual(clearedSessions, 2) assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index']) @@ -234,6 +239,18 @@ async function run() { assert.strictEqual(pendingTimers(700).length, 1) runTimer(700) assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index', '/pages/login/index']) + + // 文案映射:内部错误 message 保持技术语义,展示层由公共提示工具统一映射为用户友好文案 + const mappedError = new Error('x') + mappedError.code = AGREEMENT_NOT_ACCEPTED_CODE + assert.strictEqual(mappedError.code, 'AGREEMENT_NOT_ACCEPTED') + assert.strictEqual(request.resolveUserMessage(mappedError, '兜底文案'), '协议未确认,请稍后重试') + assert.strictEqual(request.resolveUserMessage(new Error('业务失败'), '兜底文案'), '业务失败') + assert.strictEqual(request.resolveUserMessage(null, '兜底文案'), '兜底文案') + const { showErrorToast } = require('./toast') + showErrorToast(mappedError, '兜底文案') + assert.strictEqual(toasts[toasts.length - 1].title, '协议未确认,请稍后重试') + assert.strictEqual(toasts[toasts.length - 1].icon, 'none') } run().catch(error => { diff --git a/JC-Salon-WeChat/utils/toast.js b/JC-Salon-WeChat/utils/toast.js new file mode 100644 index 00000000..cbcd00ff --- /dev/null +++ b/JC-Salon-WeChat/utils/toast.js @@ -0,0 +1,17 @@ +const request = require('./request') + +/** + * 统一的错误提示入口:页面只调用这里 toast 请求错误。 + * 内部技术文案(如 AGREEMENT_NOT_ACCEPTED)在此集中映射为用户可读文案, + * 避免各个页面各自硬编码一段映射逻辑。 + */ +function showErrorToast(error, fallbackMessage, options) { + wx.showToast(Object.assign({ + title: request.resolveUserMessage(error, fallbackMessage), + icon: 'none' + }, options || {})) +} + +module.exports = { + showErrorToast +}