refactor: 模块化小程序配置与请求逻辑
This commit is contained in:
1 parent
5b5ba9f7da
commit
34ec893369
11 files changed
+67
-20
No files matched your search
@@ -54,6 +54,8 @@ export class PublicController {
|
||||
hours: true,
|
||||
address: true,
|
||||
deliveryNote: true,
|
||||
contactPhone: true,
|
||||
contactWechat: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
App({
|
||||
onLaunch() {
|
||||
this.globalData = { apiBaseUrl: 'http://192.168.88.29:3001' };
|
||||
this.globalData = { apiBaseUrl: 'http://192.168.88.29:3001', brand: {} };
|
||||
},
|
||||
globalData: {},
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
"type": "module",
|
||||
"dependencies": { "@personal-brand/api-client": "workspace:*", "@personal-brand/types": "workspace:*" },
|
||||
"scripts": {
|
||||
"lint": "eslint . --ext .ts",
|
||||
"lint": "eslint src --ext .ts",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"clean": "rimraf dist"
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const API = getApp().globalData.apiBaseUrl;
|
||||
const { request, customerRequest } = require('../../utils/request');
|
||||
Page({
|
||||
data: { service: {}, form: {}, serviceId: '', quantity: 1, fulfillment: 'pickup', submitting: false },
|
||||
onLoad(query) { wx.request({ url: API + '/public/services', success: (res) => { const services = Array.isArray(res.data) ? res.data : []; const service = services.find((item) => item.id === query.serviceId) || services.find((item) => item.priceAmount !== null) || {}; this.setData({ service, serviceId: service.id || '' }); }, fail: () => wx.showToast({ title: '服务加载失败', icon: 'none' }) }); },
|
||||
onLoad(query) { request('/public/services').then((services) => { const list = Array.isArray(services) ? services : []; const service = list.find((item) => item.id === query.serviceId) || list.find((item) => item.priceAmount !== null) || {}; this.setData({ service, serviceId: service.id || '' }); }).catch(() => wx.showToast({ title: '服务加载失败', icon: 'none' })); },
|
||||
input(event) { this.setData({ ['form.' + event.currentTarget.dataset.key]: event.detail.value }); },
|
||||
chooseFulfillment(event) { this.setData({ fulfillment: event.currentTarget.dataset.value }); },
|
||||
increase() { if (this.data.quantity < 50) this.setData({ quantity: this.data.quantity + 1 }); },
|
||||
@@ -12,9 +12,9 @@ Page({
|
||||
if (!form.customerName || !form.wechatId) return wx.showToast({ title: '请填写称呼和联系方式', icon: 'none' });
|
||||
if (this.data.fulfillment === 'delivery' && !form.deliveryAddress) return wx.showToast({ title: '请填写配送地址', icon: 'none' });
|
||||
this.setData({ submitting: true });
|
||||
const send = (token) => wx.request({ url: API + '/customer/bookings', method: 'POST', header: { Authorization: 'Bearer ' + token }, data: { requestType: 'package', customerName: form.customerName, wechatId: form.wechatId, contactPreference: 'wechat', fulfillmentType: this.data.fulfillment, deliveryAddress: form.deliveryAddress, requestedTime: form.requestedTime, note: form.note, items: [{ serviceId: this.data.serviceId, quantity: this.data.quantity }] }, success: (res) => { this.setData({ submitting: false }); if (res.statusCode < 300) { wx.showToast({ title: '预约已提交' }); setTimeout(() => wx.navigateTo({ url: '/pages/bookings/index' }), 500); } else wx.showToast({ title: res.data?.error?.message || '提交失败', icon: 'none' }); }, fail: (error) => { this.setData({ submitting: false }); wx.showToast({ title: error.errMsg || '网络请求失败', icon: 'none' }); } });
|
||||
const send = () => customerRequest('/customer/bookings', { method: 'POST', data: { requestType: 'package', customerName: form.customerName, wechatId: form.wechatId, contactPreference: 'wechat', fulfillmentType: this.data.fulfillment, deliveryAddress: form.deliveryAddress, requestedTime: form.requestedTime, note: form.note, items: [{ serviceId: this.data.serviceId, quantity: this.data.quantity }] }).then(() => { this.setData({ submitting: false }); wx.showToast({ title: '预约已提交' }); setTimeout(() => wx.navigateTo({ url: '/pages/bookings/index' }), 500); }).catch((error) => { this.setData({ submitting: false }); wx.showToast({ title: error.message || '提交失败', icon: 'none' }); });
|
||||
const token = wx.getStorageSync('customerToken');
|
||||
if (token) return send(token);
|
||||
wx.login({ success: (login) => wx.request({ url: API + '/customer/session/wechat', method: 'POST', data: { code: login.code }, success: (res) => { if (res.statusCode < 300) { wx.setStorageSync('customerToken', res.data.token); send(res.data.token); } else { this.setData({ submitting: false }); wx.showToast({ title: res.data?.error?.message || '微信登录失败', icon: 'none' }); } }, fail: (error) => { this.setData({ submitting: false }); wx.showToast({ title: error.errMsg || '微信登录请求失败', icon: 'none' }); } }), fail: (error) => { this.setData({ submitting: false }); wx.showToast({ title: error.errMsg || '微信登录失败', icon: 'none' }); } });
|
||||
if (token) return send();
|
||||
wx.login({ success: (login) => request('/customer/session/wechat', { method: 'POST', data: { code: login.code } }).then((result) => { wx.setStorageSync('customerToken', result.token); send(); }).catch((error) => { this.setData({ submitting: false }); wx.showToast({ title: error.message || '微信登录失败', icon: 'none' }); }), fail: (error) => { this.setData({ submitting: false }); wx.showToast({ title: error.errMsg || '微信登录失败', icon: 'none' }); } });
|
||||
},
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
const API = getApp().globalData.apiBaseUrl;
|
||||
const STATUS_LABELS = { received: '待确认', contacting: '沟通中', confirmed: '已确认', completed: '已完成', cancelled: '已取消' };
|
||||
const FULFILLMENT_LABELS = { pickup: '自取', delivery: '配送' };
|
||||
const { customerRequest } = require('../../utils/request');
|
||||
const { bookingViewModel } = require('../../utils/labels');
|
||||
Page({
|
||||
data: { loading: true, error: '', bookings: [], cancellingId: '' },
|
||||
onLoad() { this.load(); }, onShow() { this.load(); },
|
||||
load() { const token = wx.getStorageSync('customerToken'); if (!token) return this.setData({ loading: false, bookings: [], error: '' }); this.setData({ loading: true, error: '' }); wx.request({ url: API + '/customer/bookings', header: { Authorization: 'Bearer ' + token }, success: (res) => { if (res.statusCode >= 300) return this.setData({ loading: false, error: res.data?.error?.message || '订单加载失败' }); const bookings = (Array.isArray(res.data) ? res.data : []).map((item) => ({ ...item, statusLabel: STATUS_LABELS[item.status] || '未知状态', fulfillmentLabel: FULFILLMENT_LABELS[item.fulfillmentType] || '待确认', serviceName: item.service?.name || item.items?.[0]?.serviceName || '红烧肉家常套餐', quantityLabel: `${item.items?.[0]?.quantity || 1} 份` })); this.setData({ bookings, loading: false }); }, fail: (error) => this.setData({ loading: false, error: error.errMsg || '网络请求失败' }) }); },
|
||||
load() { const token = wx.getStorageSync('customerToken'); if (!token) return this.setData({ loading: false, bookings: [], error: '' }); this.setData({ loading: true, error: '' }); customerRequest('/customer/bookings').then((items) => this.setData({ bookings: (Array.isArray(items) ? items : []).map(bookingViewModel), loading: false })).catch((error) => this.setData({ loading: false, error: error.message || '网络请求失败' })); },
|
||||
retry() { this.load(); }, contact() { wx.showToast({ title: '暂未配置联系方式', icon: 'none' }); },
|
||||
cancel(e) { const id = e.currentTarget.dataset.id; if (this.data.cancellingId) return; wx.showModal({ title: '取消预约', content: '确定取消这笔预约吗?', success: (result) => { if (!result.confirm) return; this.setData({ cancellingId: id }); wx.request({ url: API + '/customer/bookings/' + id + '/cancel', method: 'POST', header: { Authorization: 'Bearer ' + wx.getStorageSync('customerToken'), 'content-type': 'application/json' }, data: {}, success: (res) => { this.setData({ cancellingId: '' }); if (res.statusCode < 300) { wx.showToast({ title: '已取消预约', icon: 'success' }); this.load(); } else wx.showToast({ title: res.data?.error?.message || '取消失败', icon: 'none' }); }, fail: (error) => { this.setData({ cancellingId: '' }); wx.showToast({ title: error.errMsg || '网络请求失败', icon: 'none' }); } }); } }); }
|
||||
cancel(e) { const id = e.currentTarget.dataset.id; if (this.data.cancellingId) return; wx.showModal({ title: '取消预约', content: '确定取消这笔预约吗?', success: (result) => { if (!result.confirm) return; this.setData({ cancellingId: id }); customerRequest('/customer/bookings/' + id + '/cancel', { method: 'POST', data: {} }).then(() => { this.setData({ cancellingId: '' }); wx.showToast({ title: '已取消预约', icon: 'success' }); this.load(); }).catch((error) => { this.setData({ cancellingId: '' }); wx.showToast({ title: error.message || '取消失败', icon: 'none' }); }); } }); }
|
||||
});
|
||||
@@ -1,18 +1,17 @@
|
||||
const API_BASE_URL = getApp().globalData.apiBaseUrl;
|
||||
const { request } = require('../../utils/request');
|
||||
const config = require('../../utils/config');
|
||||
|
||||
Page({
|
||||
data: { loading: true, error: '', brand: {}, services: [] },
|
||||
onLoad() { this.load(); },
|
||||
load() {
|
||||
this.setData({ loading: true, error: '' });
|
||||
Promise.all([this.request('/public/brand'), this.request('/public/services')]).then(([brand, services]) => {
|
||||
wx.setNavigationBarTitle({ title: brand.name || '阿桂的家常小灶' });
|
||||
Promise.all([request('/public/brand'), request('/public/services')]).then(([brand, services]) => {
|
||||
getApp().globalData.brand = brand;
|
||||
wx.setNavigationBarTitle({ title: brand.name || '个人品牌' });
|
||||
this.setData({ brand, services, loading: false });
|
||||
}).catch(() => this.setData({ loading: false, error: '暂时无法加载内容' }));
|
||||
},
|
||||
request(path) {
|
||||
return new Promise((resolve, reject) => wx.request({ url: API_BASE_URL + path, success: (res) => res.statusCode < 400 ? resolve(res.data) : reject(res), fail: reject }));
|
||||
},
|
||||
selectService(event) { wx.navigateTo({ url: '/pages/booking/index?serviceId=' + encodeURIComponent(event.currentTarget.dataset.id) }); },
|
||||
goServices() { wx.navigateTo({ url: '/pages/services/index' }); },
|
||||
goPrivateChef() { wx.navigateTo({ url: '/pages/booking/index?type=private_chef' }); },
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
const API = getApp().globalData.apiBaseUrl;
|
||||
Page({data:{loading:true,services:[],filtered:[],category:'package'},onLoad(){wx.request({url:API+'/public/services',success:res=>this.setData({services:res.data,filtered:res.data.filter(x=>x.priceAmount!==null),loading:false}),fail:()=>this.setData({loading:false})})},switchCategory(e){const category=e.currentTarget.dataset.category;const filtered=category==='package'?this.data.services.filter(x=>x.priceAmount!==null):this.data.services.filter(x=>x.priceAmount===null);this.setData({category,filtered})},book(e){wx.navigateTo({url:'/pages/booking/index?serviceId='+e.currentTarget.dataset.id})}});
|
||||
const { request } = require('../../utils/request');
|
||||
Page({ data: { loading: true, error: '', services: [], filtered: [], category: 'package' }, onLoad() { request('/public/services').then((services) => this.setData({ services, filtered: services.filter((item) => item.priceAmount !== null), loading: false })).catch(() => this.setData({ loading: false, error: '服务加载失败' })); }, switchCategory(e) { const category = e.currentTarget.dataset.category; const filtered = category === 'package' ? this.data.services.filter((item) => item.priceAmount !== null) : this.data.services.filter((item) => item.priceAmount === null); this.setData({ category, filtered }); }, book(e) { wx.navigateTo({ url: '/pages/booking/index?serviceId=' + encodeURIComponent(e.currentTarget.dataset.id) }); } });
|
||||
@@ -0,0 +1,6 @@
|
||||
const app = getApp();
|
||||
|
||||
module.exports = {
|
||||
get apiBaseUrl() { return app.globalData.apiBaseUrl; },
|
||||
get brand() { return app.globalData.brand || {}; },
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
const STATUS_LABELS = { received: '待确认', contacting: '沟通中', confirmed: '已确认', completed: '已完成', cancelled: '已取消' };
|
||||
const FULFILLMENT_LABELS = { pickup: '自取', delivery: '配送' };
|
||||
|
||||
function bookingViewModel(item) {
|
||||
return {
|
||||
...item,
|
||||
statusLabel: STATUS_LABELS[item.status] || '未知状态',
|
||||
fulfillmentLabel: FULFILLMENT_LABELS[item.fulfillmentType] || '待确认',
|
||||
serviceName: item.service?.name || item.items?.[0]?.serviceNameSnapshot || '未命名服务',
|
||||
quantityLabel: `${item.items?.[0]?.quantity || 1} 份`,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { STATUS_LABELS, FULFILLMENT_LABELS, bookingViewModel };
|
||||
@@ -0,0 +1,25 @@
|
||||
const config = require('./config');
|
||||
|
||||
function request(path, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.request({
|
||||
url: config.apiBaseUrl + path,
|
||||
method: options.method || 'GET',
|
||||
header: { accept: 'application/json', ...(options.header || {}) },
|
||||
...(options.data === undefined ? {} : { data: options.data }),
|
||||
success: (response) => {
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) return resolve(response.data);
|
||||
const error = response.data?.error?.message || '请求失败';
|
||||
reject(Object.assign(new Error(error), { statusCode: response.statusCode, response }));
|
||||
},
|
||||
fail: reject,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function customerRequest(path, options = {}) {
|
||||
const token = wx.getStorageSync('customerToken');
|
||||
return request(path, { ...options, header: { ...(options.header || {}), Authorization: 'Bearer ' + token } });
|
||||
}
|
||||
|
||||
module.exports = { request, customerRequest };
|
||||
Reference in new issue
Block a user