From 385c4b06ec3b473b4f0a55b353ae7eaaffdf152e Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Thu, 5 Nov 2026 11:32:29 +0800 Subject: [PATCH] =?UTF-8?q?fix(wechat):=20=E5=8D=8F=E8=AE=AE=E9=A1=B5?= =?UTF-8?q?=E5=88=87=E5=90=8E=E5=8F=B0=E6=9A=82=E5=81=9C=E8=B6=85=E6=97=B6?= =?UTF-8?q?=E8=AE=A1=E6=97=B6=E5=B9=B6=E5=85=A8=E9=87=8F=E6=98=A0=E5=B0=84?= =?UTF-8?q?=E6=8A=80=E6=9C=AF=E6=96=87=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JC-Salon-WeChat/app.js | 3 +- .../pages/account-settings/index.js | 4 +- .../pages/appointment-detail/index.js | 4 +- .../pages/appointment-form/index.js | 18 ++--- .../pages/artist-transfer/index.js | 6 +- JC-Salon-WeChat/pages/backfill-order/index.js | 8 +- .../pages/customer-detail/index.js | 3 +- JC-Salon-WeChat/pages/customers/index.js | 4 +- .../pages/employee-create/index.js | 6 +- .../pages/employee-detail/index.js | 3 +- JC-Salon-WeChat/pages/employees/index.js | 8 +- JC-Salon-WeChat/pages/export/index.js | 3 +- JC-Salon-WeChat/pages/legal/index.js | 14 +++- JC-Salon-WeChat/pages/legal/index.test.js | 19 +++-- JC-Salon-WeChat/pages/login/index.js | 8 +- JC-Salon-WeChat/pages/planning/index.js | 4 +- JC-Salon-WeChat/pages/register/index.js | 4 +- .../pages/schedule-setting/index.js | 6 +- JC-Salon-WeChat/pages/shop-settings/index.js | 4 +- JC-Salon-WeChat/utils/request.js | 74 ++++++++++++++++++- JC-Salon-WeChat/utils/request.test.js | 60 ++++++++++++++- JC-Salon-WeChat/utils/toast.js | 10 ++- 22 files changed, 214 insertions(+), 59 deletions(-) diff --git a/JC-Salon-WeChat/app.js b/JC-Salon-WeChat/app.js index d06ab5c5..487c64e3 100644 --- a/JC-Salon-WeChat/app.js +++ b/JC-Salon-WeChat/app.js @@ -2,6 +2,7 @@ const auth = require('./utils/auth') const authApi = require('./api/auth') const { BRAND_CONFIG } = require('./utils/config') const profileCache = require('./utils/profile-cache') +const { toUserMessage } = require('./utils/toast') App({ globalData: { @@ -79,7 +80,7 @@ App({ this.globalData.userInfo = null this.publishWechatLoginState({ status: 'ERROR', - message: error.message || '自动登录失败,请点击重试' + message: toUserMessage(error, '自动登录失败,请点击重试') }) this.goLogin() } diff --git a/JC-Salon-WeChat/pages/account-settings/index.js b/JC-Salon-WeChat/pages/account-settings/index.js index c787c85e..62d7286f 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.js +++ b/JC-Salon-WeChat/pages/account-settings/index.js @@ -1,7 +1,7 @@ const userApi = require('../../api/user') const auth = require('../../utils/auth') const profileCache = require('../../utils/profile-cache') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -27,7 +27,7 @@ Page({ const closureRequest = await userApi.getAccountClosure() this.setData({ closureRequest: closureRequest || null }) } catch (error) { - this.setData({ closureError: error.message || '注销状态加载失败' }) + this.setData({ closureError: toUserMessage(error, '注销状态加载失败') }) } finally { this.setData({ closureLoading: false }) } diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index 513f0cdf..98947bf6 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -1,7 +1,7 @@ const planningApi = require('../../api/planning') const customersApi = require('../../api/customers') const { markPlanningRefresh } = require('../../utils/planning-refresh') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function displayValue(value, fallback) { if (value === null || value === undefined) return fallback @@ -44,7 +44,7 @@ Page({ appointment: {}, avatarText: '', timeText: '', - loadError: error.message || '预约详情加载失败' + loadError: toUserMessage(error, '预约详情加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index deef35e8..64577cff 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -4,7 +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 { showErrorToast, toUserMessage } = require('../../utils/toast') const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft' const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000 @@ -759,7 +759,7 @@ Page({ this.setData({ products: [], filteredProducts: [], - productError: error.message || '作品列表加载失败' + productError: toUserMessage(error, '作品列表加载失败') }) } finally { this.setData({ loadingProducts: false }) @@ -828,8 +828,8 @@ Page({ businessEndTime: '', selectedArtist: unassignedSelection, 'form.artistId': '', - artistError: error.message || '美甲师列表加载失败', - conflictTip: error.message || '美甲师列表加载失败', + artistError: toUserMessage(error, '美甲师列表加载失败'), + conflictTip: toUserMessage(error, '美甲师列表加载失败'), conflictLevel: 'danger' }) } @@ -862,7 +862,7 @@ Page({ }) this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone) } catch (error) { - this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' }) + this.setData({ customerDirectory: [], customerOptions: [], customerError: toUserMessage(error, '客户列表加载失败') }) } finally { this.setData({ customerLoading: false }) } @@ -1013,7 +1013,7 @@ Page({ customerError: '' }) } catch (error) { - this.setData({ customerOptions: [], customerError: error.message || '客户加载失败' }) + this.setData({ customerOptions: [], customerError: toUserMessage(error, '客户加载失败') }) } return } @@ -1624,7 +1624,7 @@ Page({ timePickerMinutes: [], selectedTimeCandidate: '', 'form.appointmentTime': '', - timeError: error.message || '营业时间加载失败', + timeError: toUserMessage(error, '营业时间加载失败'), businessHoursMissing: false, timeLoading: false, timeSelectTip: '营业时间加载失败' @@ -1699,7 +1699,7 @@ Page({ timePickerMinutes: [], selectedTimeCandidate: '', 'form.appointmentTime': '', - timeError: error.message || '可约时间加载失败', + timeError: toUserMessage(error, '可约时间加载失败'), businessHoursMissing: false, timeSelectTip: '可约时间加载失败' }) @@ -1869,7 +1869,7 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { - const tip = error.message || '排班校验失败,请稍后重试' + const tip = toUserMessage(error, '排班校验失败,请稍后重试') this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } diff --git a/JC-Salon-WeChat/pages/artist-transfer/index.js b/JC-Salon-WeChat/pages/artist-transfer/index.js index c7d3767c..d7e0b46b 100644 --- a/JC-Salon-WeChat/pages/artist-transfer/index.js +++ b/JC-Salon-WeChat/pages/artist-transfer/index.js @@ -1,7 +1,7 @@ const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -43,7 +43,7 @@ Page({ }) return true } catch (error) { - this.setData({ loadError: error.message || '预约详情加载失败' }) + this.setData({ loadError: toUserMessage(error, '预约详情加载失败') }) return false } }, @@ -77,7 +77,7 @@ Page({ artistItems: [], selectedArtistId: '', selectedArtist: {}, - loadError: error.message || '美甲师列表加载失败' + loadError: toUserMessage(error, '美甲师列表加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/backfill-order/index.js b/JC-Salon-WeChat/pages/backfill-order/index.js index b770157f..43b7da69 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.js +++ b/JC-Salon-WeChat/pages/backfill-order/index.js @@ -4,7 +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') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function normalizeProduct(product, artists) { const artistIds = String(product.bookableArtists || '').split(',').map(id => id.trim()).filter(Boolean) @@ -93,10 +93,10 @@ Page({ manualProductSheetVisible: false }) }, - async loadArtists(preferredArtistId) { this.setData({ loadingArtists: true }); try { const result = await employeesApi.list({ page: 1, size: 100 }); const list = result.list || result || []; const artists = list.map(item => ({ ...item, name: item.name || item.nickname || item.account || `美甲师${item.id}` })); const selected = artists.find(item => String(item.id) === String(preferredArtistId || this.data.form.artistId)); this.setData({ artists, artistOptions: artists.map(item => ({ id: item.id, title: item.name, subtitle: item.phone || '' })), selectedArtistName: selected ? selected.name : '', 'form.artistId': selected ? selected.id : '', artistError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ artists: [], artistOptions: [], artistError: error.message || '美甲师加载失败' }) } finally { this.setData({ loadingArtists: false }) } }, - async loadProducts() { this.setData({ loadingProducts: true }); try { const result = await productsApi.list({ page: 1, size: 100 }); this.setData({ products: result.list || result || [], productError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ products: [], productOptions: [], productError: error.message || '款式加载失败' }) } finally { this.setData({ loadingProducts: false }) } }, + async loadArtists(preferredArtistId) { this.setData({ loadingArtists: true }); try { const result = await employeesApi.list({ page: 1, size: 100 }); const list = result.list || result || []; const artists = list.map(item => ({ ...item, name: item.name || item.nickname || item.account || `美甲师${item.id}` })); const selected = artists.find(item => String(item.id) === String(preferredArtistId || this.data.form.artistId)); this.setData({ artists, artistOptions: artists.map(item => ({ id: item.id, title: item.name, subtitle: item.phone || '' })), selectedArtistName: selected ? selected.name : '', 'form.artistId': selected ? selected.id : '', artistError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ artists: [], artistOptions: [], artistError: toUserMessage(error, '美甲师加载失败') }) } finally { this.setData({ loadingArtists: false }) } }, + async loadProducts() { this.setData({ loadingProducts: true }); try { const result = await productsApi.list({ page: 1, size: 100 }); this.setData({ products: result.list || result || [], productError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ products: [], productOptions: [], productError: toUserMessage(error, '款式加载失败') }) } finally { this.setData({ loadingProducts: false }) } }, refreshProductOptions() { const keyword = String(this.data.productKeyword || '').trim().toLowerCase(); const all = (this.data.products || []).map(product => normalizeProduct(product, this.data.artists)); this.setData({ productOptions: all.filter(item => !keyword || `${item.title} ${item.artistText} ${item.durationText} ${item.tagList.join(' ')}`.toLowerCase().includes(keyword)) }) }, - async loadCustomers() { this.setData({ loadingCustomers: true }); try { const result = customersApi.listForAppointment ? await customersApi.listForAppointment({ page: 1, size: 100 }) : await customersApi.list({ page: 1, size: 100 }); const options = (result.list || result || []).map(normalizeCustomer); this.setData({ allCustomerOptions: options, customerOptions: options, customerError: '' }) } catch (error) { this.setData({ customerError: error.message || '客户加载失败' }) } finally { this.setData({ loadingCustomers: false }) } }, + async loadCustomers() { this.setData({ loadingCustomers: true }); try { const result = customersApi.listForAppointment ? await customersApi.listForAppointment({ page: 1, size: 100 }) : await customersApi.list({ page: 1, size: 100 }); const options = (result.list || result || []).map(normalizeCustomer); this.setData({ allCustomerOptions: options, customerOptions: options, customerError: '' }) } catch (error) { this.setData({ customerError: toUserMessage(error, '客户加载失败') }) } finally { this.setData({ loadingCustomers: false }) } }, openProductSelector() { this.setData({ manualProductSheetVisible: true, manualProductTitleLength: String(this.data.manualProductDraft.title || '').length }) }, openProductLibrary() { this.setData({ manualProductSheetVisible: false, productSelectorVisible: true }) }, closeProductSelector() { this.setData({ productSelectorVisible: false }) }, diff --git a/JC-Salon-WeChat/pages/customer-detail/index.js b/JC-Salon-WeChat/pages/customer-detail/index.js index 721f2dd8..de65293a 100644 --- a/JC-Salon-WeChat/pages/customer-detail/index.js +++ b/JC-Salon-WeChat/pages/customer-detail/index.js @@ -1,4 +1,5 @@ const customersApi = require('../../api/customers') +const { toUserMessage } = require('../../utils/toast') function canCreateAppointment() { const app = getApp() @@ -61,7 +62,7 @@ Page({ customer: {}, stats: { orderCount: 0, amount: 0, lastTime: '-' }, orders: [], - loadError: error.message || '客户详情加载失败' + loadError: toUserMessage(error, '客户详情加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/customers/index.js b/JC-Salon-WeChat/pages/customers/index.js index bdcaa728..a853da7d 100644 --- a/JC-Salon-WeChat/pages/customers/index.js +++ b/JC-Salon-WeChat/pages/customers/index.js @@ -1,5 +1,5 @@ const customersApi = require('../../api/customers') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -43,7 +43,7 @@ Page({ } catch (error) { this.setData({ customers: [], - loadError: error.message || '客户列表加载失败' + loadError: toUserMessage(error, '客户列表加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/employee-create/index.js b/JC-Salon-WeChat/pages/employee-create/index.js index 6319090c..3ccf5857 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.js +++ b/JC-Salon-WeChat/pages/employee-create/index.js @@ -1,6 +1,6 @@ const employeesApi = require('../../api/employees') const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7BA7C7', '#8FB89A', '#A894C7', '#D7A86E', '#D98DA5', '#79A6A3', '#B9A16B', '#9BA9C8'] @@ -145,7 +145,7 @@ Page({ this.setData({ associatingApplication: false }) wx.showModal({ title: '关联审核未完成', - content: error.message || '美甲师档案已创建,可重试关联申请。', + content: toUserMessage(error, '美甲师档案已创建,可重试关联申请。'), confirmText: '重试', cancelText: '稍后处理', success: result => { @@ -259,7 +259,7 @@ Page({ }).catch(error => { wx.showModal({ title: '默认排班设置失败', - content: error.message || '未设置排班前,该美甲师暂不可预约。请重试或返回排班设置。', + content: toUserMessage(error, '未设置排班前,该美甲师暂不可预约。请重试或返回排班设置。'), confirmText: '重试', cancelText: '稍后设置', success: result => { diff --git a/JC-Salon-WeChat/pages/employee-detail/index.js b/JC-Salon-WeChat/pages/employee-detail/index.js index aafcebdd..6c5a6147 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.js +++ b/JC-Salon-WeChat/pages/employee-detail/index.js @@ -1,4 +1,5 @@ const employeesApi = require('../../api/employees') +const { toUserMessage } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D'] @@ -35,7 +36,7 @@ Page({ } catch (error) { this.setData({ employee: {}, - loadError: error.message || '美甲师详情加载失败' + loadError: toUserMessage(error, '美甲师详情加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/employees/index.js b/JC-Salon-WeChat/pages/employees/index.js index 8aece3ec..bab67d5e 100644 --- a/JC-Salon-WeChat/pages/employees/index.js +++ b/JC-Salon-WeChat/pages/employees/index.js @@ -1,7 +1,7 @@ const employeesApi = require('../../api/employees') const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D'] @@ -94,7 +94,7 @@ Page({ })) this.setData({ reviewApplications: applications, reviewPendingCount: applications.length }) } catch (error) { - this.setData({ reviewError: error.message || '审核申请加载失败' }) + this.setData({ reviewError: toUserMessage(error, '审核申请加载失败') }) } finally { this.setData({ reviewLoading: false }) } @@ -143,7 +143,7 @@ Page({ if (result.confirm) this.createEmployeeForApplication(applicationId, application && application.applicationNo) } } catch (error) { - this.setData({ associationError: error.message || '未关联美甲师加载失败' }) + this.setData({ associationError: toUserMessage(error, '未关联美甲师加载失败') }) } finally { this.setData({ associationLoading: false }) } @@ -293,7 +293,7 @@ Page({ } catch (error) { this.setData({ employees: [], - loadError: error.message || '美甲师列表加载失败' + loadError: toUserMessage(error, '美甲师列表加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/export/index.js b/JC-Salon-WeChat/pages/export/index.js index dcf6be69..6d1fc727 100644 --- a/JC-Salon-WeChat/pages/export/index.js +++ b/JC-Salon-WeChat/pages/export/index.js @@ -2,6 +2,7 @@ const dateUtil = require('../../utils/date') const planningApi = require('../../api/planning') const customersApi = require('../../api/customers') const employeesApi = require('../../api/employees') +const { toUserMessage } = require('../../utils/toast') const PREVIEW_SIZE = 10 @@ -64,7 +65,7 @@ Page({ } catch (error) { this.setData({ previewRows: [], - previewError: error.message || '预览数据加载失败' + previewError: toUserMessage(error, '预览数据加载失败') }) } finally { this.setData({ previewLoading: false }) diff --git a/JC-Salon-WeChat/pages/legal/index.js b/JC-Salon-WeChat/pages/legal/index.js index 6e3894bc..5425e8c1 100644 --- a/JC-Salon-WeChat/pages/legal/index.js +++ b/JC-Salon-WeChat/pages/legal/index.js @@ -42,13 +42,25 @@ Page({ } }, + /** + * 切后台(来电、复制协议文本)只暂停挂起请求的超时计时,绝不结算; + * 回到前台后按剩余可见时长恢复,若挂起请求已不存在则恢复逻辑自动 no-op。 + */ + onHide() { + request.pausePendingAgreementTimeout() + }, + + onShow() { + request.resumePendingAgreementTimeout() + }, + onUnload() { this.discardPendingIfNotAccepted() }, /** * 只有真正离开协议页(返回导致页面卸载)才结算被 4510 挂起的请求,避免调用方 loading 永久卡住; - * 切后台(如来电、复制协议文本)只触发 onHide,不结算;同意成功后也不再触发。 + * 切后台只暂停计时、不结算;同意成功后也不再触发。 */ discardPendingIfNotAccepted() { if (this.data.mode !== 'accept' || this.agreementAccepted) { diff --git a/JC-Salon-WeChat/pages/legal/index.test.js b/JC-Salon-WeChat/pages/legal/index.test.js index 46710a42..213ed26d 100644 --- a/JC-Salon-WeChat/pages/legal/index.test.js +++ b/JC-Salon-WeChat/pages/legal/index.test.js @@ -22,7 +22,11 @@ global.Page = definition => { pageDefinition = definition } const requestUtil = require('../../utils/request') let discardCalls = 0 +let pauseCalls = 0 +let resumeCalls = 0 requestUtil.discardPendingAgreement = () => { discardCalls += 1 } +requestUtil.pausePendingAgreementTimeout = () => { pauseCalls += 1 } +requestUtil.resumePendingAgreementTimeout = () => { resumeCalls += 1 } require('./index') @@ -40,12 +44,15 @@ const reader = createPage('') pageDefinition.onUnload.call(reader) assert.strictEqual(discardCalls, 0) -// 切后台(来电、复制协议文本)不应结算挂起请求:协议页不再提供 onHide 结算入口 -assert.strictEqual(typeof pageDefinition.onHide, 'undefined') +// 切后台:只暂停超时计时,绝不结算 const hiddenPage = createPage('accept') -if (pageDefinition.onHide) { - pageDefinition.onHide.call(hiddenPage) -} +pageDefinition.onHide.call(hiddenPage) +assert.strictEqual(pauseCalls, 1) +assert.strictEqual(discardCalls, 0) + +// 回到前台:恢复计时(是否真的有挂起由请求层自行判断,页面不重复结算) +pageDefinition.onShow.call(hiddenPage) +assert.strictEqual(resumeCalls, 1) assert.strictEqual(discardCalls, 0) // 真正离开协议页(返回触发页面卸载)仍然结算 @@ -57,4 +64,4 @@ const acceptedPage = createPage('accept', true) pageDefinition.onUnload.call(acceptedPage) assert.strictEqual(discardCalls, 1) -console.log('legal page agreement discard test passed') +console.log('legal page agreement lifecycle test passed') diff --git a/JC-Salon-WeChat/pages/login/index.js b/JC-Salon-WeChat/pages/login/index.js index 7592861c..27a5b275 100644 --- a/JC-Salon-WeChat/pages/login/index.js +++ b/JC-Salon-WeChat/pages/login/index.js @@ -3,7 +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') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function wxLoginCode() { return new Promise((resolve, reject) => wx.login({ @@ -69,7 +69,7 @@ Page({ const agreements = await authApi.getCurrentAgreements() this.setData({ agreements: Array.isArray(agreements) ? agreements : [] }) } catch (error) { - this.setData({ agreementError: error.message || '协议加载失败' }) + this.setData({ agreementError: toUserMessage(error, '协议加载失败') }) } finally { this.setData({ agreementLoading: false }) } @@ -157,7 +157,7 @@ Page({ this.setData({ loginState: result }) await this.handleResult(result) } catch (error) { - const state = { status: 'ERROR', message: error.message || '快捷登录失败,请重试' } + const state = { status: 'ERROR', message: toUserMessage(error, '快捷登录失败,请重试') } this.setData({ loginState: state }) this.handleResult(state) } finally { @@ -194,7 +194,7 @@ Page({ : status === 'REJECTED' ? '申请需要修改' : status === 'DISABLED' ? '账号暂不可用' : status === 'NEED_MANUAL_LOGIN' ? '需要完成注册' : '登录失败' - const content = result.registrationRejectReason || result.message || '请稍后重试' + const content = result.registrationRejectReason || toUserMessage(result, '请稍后重试') const canRetry = status === 'ERROR' || status === 'NEED_MANUAL_LOGIN' || status === 'REJECTED' wx.showModal({ title, diff --git a/JC-Salon-WeChat/pages/planning/index.js b/JC-Salon-WeChat/pages/planning/index.js index 7619ce79..32baa04d 100644 --- a/JC-Salon-WeChat/pages/planning/index.js +++ b/JC-Salon-WeChat/pages/planning/index.js @@ -6,7 +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') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function canCreateAppointment() { const app = getApp() @@ -15,7 +15,7 @@ function canCreateAppointment() { } function resolveCalendarErrorMessage(error) { - return error && error.message ? error.message : '日程数据加载失败' + return toUserMessage(error, '日程数据加载失败') } function toLocalDate(value) { diff --git a/JC-Salon-WeChat/pages/register/index.js b/JC-Salon-WeChat/pages/register/index.js index 494fbbd9..679abe47 100644 --- a/JC-Salon-WeChat/pages/register/index.js +++ b/JC-Salon-WeChat/pages/register/index.js @@ -1,5 +1,5 @@ const authApi = require('../../api/auth') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -54,7 +54,7 @@ Page({ shopSelectorItems: this.filterShops(shopOptions, this.data.shopKeyword) }) } catch (error) { - this.setData({ shopOptions: [], shopSelectorItems: [], shopError: error.message || '门店列表加载失败' }) + this.setData({ shopOptions: [], shopSelectorItems: [], shopError: toUserMessage(error, '门店列表加载失败') }) } finally { this.setData({ shopLoading: false }) } diff --git a/JC-Salon-WeChat/pages/schedule-setting/index.js b/JC-Salon-WeChat/pages/schedule-setting/index.js index fe0da4fc..dd22a53b 100644 --- a/JC-Salon-WeChat/pages/schedule-setting/index.js +++ b/JC-Salon-WeChat/pages/schedule-setting/index.js @@ -1,7 +1,7 @@ const employeesApi = require('../../api/employees') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') const PRESETS = [ { value: 'DOUBLE_REST', label: '双休', workDays: [1, 2, 3, 4, 5], startTime: '09:00', endTime: '17:00' }, @@ -253,7 +253,7 @@ Page({ await this.loadRule() } } catch (error) { - const message = error.message || '保存失败' + const message = toUserMessage(error, '保存失败') wx.showModal({ title: '排班保存失败', content: message, showCancel: false, confirmText: '知道了' }) } finally { this.setData({ saving: false }) @@ -284,7 +284,7 @@ Page({ wx.showToast({ title: '例外已保存', icon: 'success' }) await this.loadRule() } catch (error) { - const message = error.message || '例外保存失败' + const message = toUserMessage(error, '例外保存失败') wx.showModal({ title: '特殊日期保存失败', content: message, showCancel: false, confirmText: '知道了' }) } finally { this.setData({ saving: false }) diff --git a/JC-Salon-WeChat/pages/shop-settings/index.js b/JC-Salon-WeChat/pages/shop-settings/index.js index a9c03151..9af58551 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.js +++ b/JC-Salon-WeChat/pages/shop-settings/index.js @@ -1,7 +1,7 @@ const { BRAND_CONFIG } = require('../../utils/config') const profileCache = require('../../utils/profile-cache') const shopApi = require('../../api/shop') -const { showErrorToast } = require('../../utils/toast') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function resolveNameStatus(value) { const status = String(value || '').toUpperCase() @@ -96,7 +96,7 @@ Page({ }) } catch (error) { this.setData({ - settingsError: error.message || '设置加载失败', + settingsError: toUserMessage(error, '设置加载失败'), businessHoursConfigured: false, 'form.weeklyHours': [] }) diff --git a/JC-Salon-WeChat/utils/request.js b/JC-Salon-WeChat/utils/request.js index 4f377ad9..2cc4ac43 100644 --- a/JC-Salon-WeChat/utils/request.js +++ b/JC-Salon-WeChat/utils/request.js @@ -129,17 +129,58 @@ function createBlockedAgreementRequest(options, resolve, reject) { options: cloneRequestOptions(options), settled: false, retrying: false, - timer: null + timer: null, + startedAt: null, + remainingMs: AGREEMENT_PENDING_TIMEOUT_MS } const cleanup = () => { if (entry.timer) { clearTimeout(entry.timer) entry.timer = null } + entry.startedAt = null if (agreementBlockedRequest === entry) { agreementBlockedRequest = null } } + /** + * 启动(或恢复)超时兜底计时;已结算、已开始重放或计时已在运行时为 no-op, + * 保证同一请求不会被重复计时或二次结算。 + */ + entry.startTimer = delay => { + if (entry.settled || entry.retrying || entry.timer) { + return + } + entry.remainingMs = delay + entry.startedAt = Date.now() + entry.timer = setTimeout(() => { + entry.timer = null + entry.startedAt = null + entry.rejectNotAccepted() + }, delay) + } + /** + * 切后台时暂停计时:清除定时器并记下剩余可见时长,后台期间不会触发结算。 + */ + entry.pauseTimer = () => { + if (!entry.timer) { + return + } + const elapsed = Date.now() - entry.startedAt + entry.remainingMs = Math.max(0, entry.remainingMs - elapsed) + clearTimeout(entry.timer) + entry.timer = null + entry.startedAt = null + } + /** + * 回到前台按剩余时间恢复计时;挂起请求已被结算/已取走重放时为 no-op。 + */ + entry.resumeTimer = () => { + if (entry.settled || entry.retrying || entry.timer) { + return + } + entry.startTimer(entry.remainingMs) + } entry.resolveOnce = value => { if (entry.settled) { return @@ -172,9 +213,7 @@ function createBlockedAgreementRequest(options, resolve, reject) { cleanup() return Object.assign(cloneRequestOptions(entry.options), { _agreementRetry: 1 }) } - entry.timer = setTimeout(() => { - entry.rejectNotAccepted() - }, AGREEMENT_PENDING_TIMEOUT_MS) + entry.startTimer(AGREEMENT_PENDING_TIMEOUT_MS) return entry } @@ -238,6 +277,31 @@ function discardPendingAgreement() { blocked.rejectNotAccepted() } +/** + * 协议页切后台时调用:暂停挂起请求的超时计时,后台期间不会触发结算。 + * 挂起请求已不存在(已结算/已取走重放)时为 no-op。 + */ +function pausePendingAgreementTimeout() { + const blocked = agreementBlockedRequest + if (!blocked) { + return + } + blocked.pauseTimer() +} + +/** + * 协议页回到前台时调用:按剩余可见时长恢复计时。 + * 挂起请求已不存在(例如后台期间已在别处完成同意、或被新的 4510 结算)时为 no-op, + * 不会重复计时或二次结算。 + */ +function resumePendingAgreementTimeout() { + const blocked = agreementBlockedRequest + if (!blocked) { + return + } + blocked.resumeTimer() +} + /** * 用户在协议页同意成功后调用:重放首个被 4510 拦下的原请求一次。 * 取走待重放请求时即清理定时器与挂起引用,后续返回/超时不会打断已开始的成功重放; @@ -390,6 +454,8 @@ request.toBackendRequestPath = toBackendRequestPath request.handleUnauthorized = handleUnauthorized request.retryPendingAfterAgreement = retryPendingAfterAgreement request.discardPendingAgreement = discardPendingAgreement +request.pausePendingAgreementTimeout = pausePendingAgreementTimeout +request.resumePendingAgreementTimeout = resumePendingAgreementTimeout request.resolveUserMessage = resolveUserMessage request.AGREEMENT_NOT_ACCEPTED_CODE = AGREEMENT_NOT_ACCEPTED_CODE diff --git a/JC-Salon-WeChat/utils/request.test.js b/JC-Salon-WeChat/utils/request.test.js index c7f2e267..f5a037ca 100644 --- a/JC-Salon-WeChat/utils/request.test.js +++ b/JC-Salon-WeChat/utils/request.test.js @@ -41,6 +41,9 @@ global.clearTimeout = entry => { entry.cleared = true } } +// 可控时钟:用于验证“切后台暂停 / 回前台按剩余时间恢复”的可见时长累计。 +const clock = { now: 1700000000000 } +Date.now = () => clock.now const auth = require('./auth') const request = require('./request') @@ -71,6 +74,12 @@ function startRequest(options) { return { promise: request(options) } } +function trackSettlement(promise) { + const state = { settled: false } + promise.then(() => { state.settled = true }, () => { state.settled = true }) + return state +} + async function rejectWithUnauthorized(options) { const pending = request(options).then( () => { throw new Error('Expected request to reject') }, @@ -247,10 +256,59 @@ async function run() { assert.strictEqual(request.resolveUserMessage(mappedError, '兜底文案'), '协议未确认,请稍后重试') assert.strictEqual(request.resolveUserMessage(new Error('业务失败'), '兜底文案'), '业务失败') assert.strictEqual(request.resolveUserMessage(null, '兜底文案'), '兜底文案') - const { showErrorToast } = require('./toast') + const { showErrorToast, toUserMessage } = require('./toast') showErrorToast(mappedError, '兜底文案') assert.strictEqual(toasts[toasts.length - 1].title, '协议未确认,请稍后重试') assert.strictEqual(toasts[toasts.length - 1].icon, 'none') + // 内联错误态 / 弹窗等非 toast 出口复用同一映射 + assert.strictEqual(toUserMessage(mappedError, '兜底文案'), '协议未确认,请稍后重试') + assert.strictEqual(toUserMessage(new Error('业务失败'), '兜底文案'), '业务失败') + + // 切后台暂停:后台 2 分钟不计入可见时长,后台期间到点也不结算 + auth.setSession({ accessToken: 'pause-token' }, true) + const pausedRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 6 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + const pausedState = trackSettlement(pausedRequest.promise) + assert.strictEqual(pendingTimers(180000).length, 1) + + clock.now += 120000 + request.pausePendingAgreementTimeout() + assert.strictEqual(pendingTimers(180000).length, 0) + // 后台再停留 2 分钟(累计后台 4 分钟):没有定时器,绝不会结算 + clock.now += 120000 + await Promise.resolve() + assert.strictEqual(pausedState.settled, false) + + // 回前台按剩余 1 分钟恢复;可见时长累计 2 分钟 + 59 秒仍未满 3 分钟,不结算 + request.resumePendingAgreementTimeout() + assert.strictEqual(pendingTimers(60000).length, 1) + clock.now += 59000 + await Promise.resolve() + assert.strictEqual(pausedState.settled, false) + // 可见时长走满 3 分钟后,兜底定时器触发结算 + runTimer(60000) + const pausedError = await pausedRequest.promise.catch(error => error) + assertAgreementPendingError(pausedError) + + // 回前台时挂起已不存在(已超时结算):恢复计时为 no-op,不报错、不新增定时器 + request.resumePendingAgreementTimeout() + assert.strictEqual(pendingTimers(60000).length, 0) + assert.strictEqual(pendingTimers(180000).length, 0) + + // 后台期间从别处完成同意:挂起已被取走重放,回前台的恢复计时同样为 no-op + auth.setSession({ accessToken: 'resume-after-agree-token' }, true) + const agreedRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 7 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + request.pausePendingAgreementTimeout() + assert.strictEqual(pendingTimers(180000).length, 0) + const requestsBeforeAgreeRetry = requests.length + request.retryPendingAfterAgreement() + assert.strictEqual(requests.length, requestsBeforeAgreeRetry + 1) + resolveWithData({ page: 7, items: [] }) + assert.deepStrictEqual(await agreedRequest.promise, { page: 7, items: [] }) + request.resumePendingAgreementTimeout() + assert.strictEqual(pendingTimers(180000).length, 0) + assert.strictEqual(pendingTimers(60000).length, 0) } run().catch(error => { diff --git a/JC-Salon-WeChat/utils/toast.js b/JC-Salon-WeChat/utils/toast.js index cbcd00ff..936ea620 100644 --- a/JC-Salon-WeChat/utils/toast.js +++ b/JC-Salon-WeChat/utils/toast.js @@ -12,6 +12,14 @@ function showErrorToast(error, fallbackMessage, options) { }, options || {})) } +/** + * 内联错误态、弹窗等非 toast 展示出口共用同一套映射,避免技术文案漏到用户眼前。 + */ +function toUserMessage(error, fallbackMessage) { + return request.resolveUserMessage(error, fallbackMessage) +} + module.exports = { - showErrorToast + showErrorToast, + toUserMessage }