feat(M08-A): 接入顾客端个人中心

This commit is contained in:
Codex
2026-06-25 11:43:25 +08:00
parent c7c869c18b
commit 7446852cca
14 changed files with 476 additions and 4 deletions
+1 -1
View File
@@ -17,7 +17,7 @@
"db:migrate:verify": "npm run build && node dist/db/migrate-cli.js verify",
"db:migrate:down": "npm run build && node dist/db/migrate-cli.js down",
"test:mysql:migration": "npm run build && node tests/mysql-migration-roundtrip.test.mjs",
"test": "npm run build && node tests/backend-contract.test.mjs && node tests/mqtt-service.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs && node tests/auth.test.mjs && node tests/rbac.test.mjs && node tests/user-management.test.mjs && node tests/store-room.test.mjs && node tests/content-management.test.mjs && node tests/store-discovery.test.mjs && node tests/store-access.test.mjs && node tests/pricing.test.mjs && node tests/order-state.test.mjs && node tests/order-query.test.mjs && node tests/order-management.test.mjs && node tests/order-share.test.mjs && node tests/payment.test.mjs && node tests/wechat-pay.test.mjs && node tests/third-party.test.mjs && node tests/profit-sharing.test.mjs && node tests/device.test.mjs && node tests/iot-protocol.test.mjs && node tests/device-control.test.mjs && node tests/order-device-automation.test.mjs && node tests/hardware-smoke-runner.test.mjs && node tests/wallet-ledger.test.mjs && node tests/recharge-service.test.mjs && node tests/marketing-benefit-service.test.mjs && node tests/member-profile-service.test.mjs"
"test": "npm run build && node tests/backend-contract.test.mjs && node tests/mqtt-service.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs && node tests/auth.test.mjs && node tests/rbac.test.mjs && node tests/user-management.test.mjs && node tests/store-room.test.mjs && node tests/content-management.test.mjs && node tests/store-discovery.test.mjs && node tests/store-access.test.mjs && node tests/pricing.test.mjs && node tests/order-state.test.mjs && node tests/order-query.test.mjs && node tests/order-management.test.mjs && node tests/order-share.test.mjs && node tests/payment.test.mjs && node tests/wechat-pay.test.mjs && node tests/third-party.test.mjs && node tests/profit-sharing.test.mjs && node tests/device.test.mjs && node tests/iot-protocol.test.mjs && node tests/device-control.test.mjs && node tests/order-device-automation.test.mjs && node tests/hardware-smoke-runner.test.mjs && node tests/wallet-ledger.test.mjs && node tests/recharge-service.test.mjs && node tests/marketing-benefit-service.test.mjs && node tests/member-profile-service.test.mjs && node tests/member-profile-route.test.mjs"
},
"dependencies": {
"@fastify/cors": "^11.2.0",
+32 -1
View File
@@ -18,7 +18,7 @@ const listSchema = z.object({
});
export interface MemberRouteOptions {
service: Pick<MemberProfileService, 'listMembers' | 'getMember'>;
service: Pick<MemberProfileService, 'listMembers' | 'getMember' | 'getMyProfile'>;
authRepository: Pick<AuthRepository, 'validateSession'>;
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
jwtSecret: string;
@@ -28,6 +28,37 @@ export async function registerMemberRoutes(
app: FastifyInstance,
options: MemberRouteOptions
): Promise<void> {
app.get('/app-api/profile', async (request, reply) => {
const auth = await authenticateAccessToken(
request.headers.authorization,
options.authRepository,
options.jwtSecret
);
if (!auth) {
return reply.status(401).send({
code: 'AUTH_SESSION_INVALID', message: 'Authentication required.', traceId: request.traceId
});
}
const access = await options.accessControl.getAccessProfile(
auth.session.tenantId,
auth.session.user.id
);
if (!access.capabilities.includes('profile.read')) {
return reply.status(403).send({
code: 'PROFILE_READ_FORBIDDEN', message: 'Profile read permission is required.',
traceId: request.traceId
});
}
return handle(reply, request.traceId, async () => ({
code: 0,
data: await options.service.getMyProfile({
tenantId: auth.session.tenantId,
userId: auth.session.user.id
}),
traceId: request.traceId
}));
});
app.get('/admin-api/members', async (request, reply) => {
const actor = await requireReader(request, reply, options);
if (!actor) return;
+7
View File
@@ -33,6 +33,7 @@ import { CustomerDeviceAccessRepository } from './devices/customer-device-access
import { IotMessageService } from './devices/iot-message-service.js';
import { DeviceCommandService } from './devices/device-command-service.js';
import { DeviceControlService } from './devices/device-control-service.js';
import { MemberProfileService } from './wallets/member-profile-service.js';
const config = loadConfig();
const pool = createMySqlPool(config);
@@ -162,6 +163,12 @@ const app = await buildApp({
authRepository,
accessControl,
jwtSecret: config.auth.jwtSecret
},
members: {
service: new MemberProfileService(pool),
authRepository,
accessControl,
jwtSecret: config.auth.jwtSecret
}
});
app.addHook('onClose', async () => {
@@ -137,6 +137,36 @@ export class MemberProfileService {
};
}
async getMyProfile(input: {
tenantId: string;
userId: string;
ledgerLimit?: number;
}) {
const [rows] = await this.pool.execute<MemberRow[]>(
`SELECT u.id, u.status, u.nickname, u.phone,
u.created_at AS createdAt, u.last_login_at AS lastLoginAt
FROM qipai_users u
WHERE u.tenant_id = ? AND u.id = ? AND u.user_type = 'CUSTOMER'
AND u.deleted_at IS NULL
LIMIT 1`,
[input.tenantId, input.userId]
);
if (!rows[0]) throw new MemberProfileError('MEMBER_NOT_FOUND');
const actor = {
tenantId: input.tenantId,
userId: input.userId,
access: { roles: ['CUSTOMER'], capabilities: ['profile.read'], storeIds: [] }
};
return {
...await this.memberCard(actor, rows[0]),
recentLedger: await this.recentLedger(
input.tenantId,
String(rows[0].id),
input.ledgerLimit ?? 10
)
};
}
private async memberCard(actor: MemberActor, row: MemberRow) {
const memberId = String(row.id);
const [walletRows] = await this.pool.execute<WalletSummaryRow[]>(
@@ -0,0 +1,88 @@
import assert from 'node:assert/strict';
import { buildApp } from '../dist/app.js';
import { signAccessToken } from '../dist/auth/jwt.js';
const secret = 'test-only-member-profile-route-secret';
const token = signAccessToken({
sub: '21', sid: '5c4d3af8-c63c-4edb-bf95-b84127bb3f6e',
tid: '7', aid: '9', rv: 1
}, secret, 900);
const forbiddenToken = signAccessToken({
sub: '22', sid: '6c4d3af8-c63c-4edb-bf95-b84127bb3f6e',
tid: '7', aid: '9', rv: 1
}, secret, 900);
let profileInput;
const app = await buildApp({
members: {
jwtSecret: secret,
authRepository: {
async validateSession(sessionId) {
return {
id: sessionId,
tenantId: '7',
platformAppId: '9',
expiresAt: new Date(Date.now() + 60000),
user: {
id: sessionId === '6c4d3af8-c63c-4edb-bf95-b84127bb3f6e' ? '22' : '21',
tenantId: '7',
userType: 'CUSTOMER',
status: 'ACTIVE',
roleVersion: 1,
nickname: '',
avatarUrl: '',
phone: ''
}
};
}
},
accessControl: {
async getAccessProfile(tenantId, userId) {
return userId === '21'
? { roles: ['CUSTOMER'], capabilities: ['profile.read', 'order.self.read'], storeIds: [] }
: { roles: ['CUSTOMER'], capabilities: ['order.self.read'], storeIds: [] };
}
},
service: {
async listMembers() { throw new Error('not called'); },
async getMember() { throw new Error('not called'); },
async getMyProfile(input) {
profileInput = input;
return {
memberId: input.userId,
nickname: 'Alice',
maskedPhone: '138****8000',
wallet: { cashBalanceCents: 1000, giftBalanceCents: 200, totalBalanceCents: 1200 },
benefits: { availableCoupons: 2, activePackages: 1, packageMinutes: 90 },
recentLedger: []
};
}
}
}
});
const profile = await app.inject({
method: 'GET',
url: '/app-api/profile',
headers: { authorization: `Bearer ${token}` }
});
assert.equal(profile.statusCode, 200);
assert.equal(profileInput.tenantId, '7');
assert.equal(profileInput.userId, '21');
assert.equal(profile.json().data.wallet.totalBalanceCents, 1200);
const unauthorized = await app.inject({
method: 'GET',
url: '/app-api/profile'
});
assert.equal(unauthorized.statusCode, 401);
const forbidden = await app.inject({
method: 'GET',
url: '/app-api/profile',
headers: { authorization: `Bearer ${forbiddenToken}` }
});
assert.equal(forbidden.statusCode, 403);
await app.close();
console.log('PASS: M08-A customer profile route exposes only the current member.');
+1
View File
@@ -5,6 +5,7 @@
"pages/room/detail",
"pages/orders/list",
"pages/orders/detail",
"pages/profile/index",
"pages/logs/logs"
],
"window": {
+4
View File
@@ -69,6 +69,10 @@ Page({
wx.navigateTo({ url: '/pages/orders/list' })
},
openProfile() {
wx.navigateTo({ url: '/pages/profile/index' })
},
async resolveScene(code, sourceType) {
this.setData({ loading: true, errorMessage: '' })
try {
+3
View File
@@ -1,7 +1,10 @@
<scroll-view class="scrollarea" scroll-y type="list">
<view class="container">
<view class="title">选择门店</view>
<view class="quick-actions">
<button bindtap="openOrders">我的订单</button>
<button bindtap="openProfile">个人中心</button>
</view>
<button loading="{{locating}}" bindtap="locateNearby">定位附近门店</button>
<view class="city-search">
<input value="{{city}}" placeholder="拒绝定位时输入城市" bindinput="onCityInput" />
+10
View File
@@ -13,6 +13,16 @@
font-weight: 600;
}
.quick-actions {
display: flex;
gap: 16rpx;
margin-bottom: 20rpx;
}
.quick-actions button {
flex: 1;
}
.city-search {
display: flex;
gap: 16rpx;
+82
View File
@@ -0,0 +1,82 @@
const { request, ensureLogin, cents } = require('../../utils/api.js')
Page({
data: {
loading: false,
errorMessage: '',
profile: null,
recentLedger: [],
},
onLoad() {
this.loadProfile()
},
async loadProfile() {
this.setData({ loading: true, errorMessage: '' })
try {
await ensureLogin()
const response = await request('/profile')
const profile = formatProfile(response.data)
this.setData({
profile,
recentLedger: (response.data.recentLedger || []).map(formatLedger),
})
} catch (error) {
this.setData({ errorMessage: error.message || '个人中心加载失败' })
} finally {
this.setData({ loading: false })
}
},
openOrders() {
wx.navigateTo({ url: '/pages/orders/list' })
},
})
function formatProfile(profile) {
return {
...profile,
registeredText: formatDate(profile.registeredAt),
lastLoginText: profile.lastLoginAt ? formatDate(profile.lastLoginAt) : '暂无',
wallet: {
...profile.wallet,
cashText: cents(profile.wallet.cashBalanceCents),
giftText: cents(profile.wallet.giftBalanceCents),
totalText: cents(profile.wallet.totalBalanceCents),
},
benefits: {
...profile.benefits,
packageAmountText: cents(profile.benefits.packageAmountCents),
},
recharge: {
...profile.recharge,
creditedText: cents(profile.recharge.creditedRechargeCents),
giftedText: cents(profile.recharge.giftedRechargeCents),
},
orders: {
...profile.orders,
paidAmountText: cents(profile.orders.paidAmountCents),
},
}
}
function formatLedger(item) {
return {
...item,
deltaText: `${signedCents(item.cashDeltaCents)} / ${signedCents(item.giftDeltaCents)}`,
balanceText: `${cents(item.cashBalanceAfterCents)} / ${cents(item.giftBalanceAfterCents)}`,
createdText: formatDate(item.createdAt),
}
}
function signedCents(value) {
const amount = Number(value || 0)
return `${amount >= 0 ? '+' : '-'}${cents(Math.abs(amount))}`
}
function formatDate(value) {
const date = new Date(value)
const pad = (input) => String(input).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
+3
View File
@@ -0,0 +1,3 @@
{
"navigationBarTitleText": "个人中心"
}
+88
View File
@@ -0,0 +1,88 @@
<scroll-view class="scrollarea" scroll-y type="list">
<view class="page">
<view class="title">个人中心</view>
<view wx:if="{{errorMessage}}" class="error">{{errorMessage}}</view>
<view wx:if="{{profile}}" class="card">
<view class="member-name">{{profile.nickname || '微信用户'}}</view>
<view class="muted">{{profile.maskedPhone || '未绑定手机号'}}</view>
<view class="muted">注册:{{profile.registeredText}}</view>
<view class="muted">最近登录:{{profile.lastLoginText}}</view>
</view>
<view wx:if="{{profile}}" class="balance-band">
<view>
<view class="label">总余额</view>
<view class="balance">{{profile.wallet.totalText}}</view>
</view>
<view class="balance-split">
<view>现金 {{profile.wallet.cashText}}</view>
<view>赠送 {{profile.wallet.giftText}}</view>
</view>
</view>
<view wx:if="{{profile}}" class="metric-grid">
<view class="metric">
<view class="metric-value">{{profile.benefits.availableCoupons}}</view>
<view class="metric-label">可用券</view>
</view>
<view class="metric">
<view class="metric-value">{{profile.benefits.activePackages}}</view>
<view class="metric-label">套餐</view>
</view>
<view class="metric">
<view class="metric-value">{{profile.benefits.packageMinutes}}</view>
<view class="metric-label">分钟</view>
</view>
<view class="metric">
<view class="metric-value">{{profile.orders.orderCount}}</view>
<view class="metric-label">订单</view>
</view>
</view>
<view wx:if="{{profile}}" class="card">
<view class="section-title">权益</view>
<view class="row">
<text>冻结券</text>
<text>{{profile.benefits.frozenCoupons}}</text>
</view>
<view class="row">
<text>冻结套餐</text>
<text>{{profile.benefits.frozenPackages}}</text>
</view>
<view class="row">
<text>套餐余额</text>
<text>{{profile.benefits.packageAmountText}}</text>
</view>
</view>
<view wx:if="{{profile}}" class="card">
<view class="section-title">充值与消费</view>
<view class="row">
<text>已充值</text>
<text>{{profile.recharge.creditedText}}</text>
</view>
<view class="row">
<text>已赠送</text>
<text>{{profile.recharge.giftedText}}</text>
</view>
<view class="row">
<text>已消费</text>
<text>{{profile.orders.paidAmountText}}</text>
</view>
<button bindtap="openOrders">查看订单</button>
</view>
<view class="section-title ledger-title">最近账单</view>
<view wx:if="{{!loading && recentLedger.length === 0}}" class="empty">暂无账单</view>
<view wx:for="{{recentLedger}}" wx:key="ledgerId" class="ledger-item">
<view class="row">
<text>{{item.entryType}}</text>
<text>{{item.deltaText}}</text>
</view>
<view class="muted">{{item.businessType}} {{item.businessId}}</view>
<view class="muted">余额 {{item.balanceText}}</view>
<view class="muted">{{item.createdText}}</view>
</view>
</view>
</scroll-view>
+112
View File
@@ -0,0 +1,112 @@
.scrollarea {
height: 100vh;
background: #f5f6f8;
}
.page {
padding: 32rpx;
}
.title {
margin-bottom: 24rpx;
font-size: 40rpx;
font-weight: 600;
}
.card,
.ledger-item {
margin-top: 20rpx;
padding: 28rpx;
border-radius: 16rpx;
background: #ffffff;
}
.member-name,
.section-title {
font-size: 32rpx;
font-weight: 600;
}
.muted {
margin-top: 8rpx;
color: #667085;
}
.balance-band {
display: flex;
justify-content: space-between;
gap: 24rpx;
margin-top: 20rpx;
padding: 32rpx;
border-radius: 16rpx;
background: #174a3f;
color: #ffffff;
}
.label,
.balance-split {
color: rgba(255, 255, 255, 0.76);
}
.balance {
margin-top: 8rpx;
font-size: 48rpx;
font-weight: 700;
}
.balance-split {
display: flex;
flex-direction: column;
justify-content: center;
gap: 8rpx;
text-align: right;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12rpx;
margin-top: 20rpx;
}
.metric {
min-height: 112rpx;
padding: 18rpx 8rpx;
border-radius: 12rpx;
background: #ffffff;
text-align: center;
}
.metric-value {
color: #1f6feb;
font-size: 32rpx;
font-weight: 700;
}
.metric-label {
margin-top: 6rpx;
color: #667085;
font-size: 24rpx;
}
.row {
display: flex;
justify-content: space-between;
gap: 24rpx;
margin-top: 16rpx;
}
.ledger-title {
margin-top: 28rpx;
}
.empty {
padding: 80rpx 0;
color: #888888;
text-align: center;
}
.error {
margin: 16rpx 0;
color: #c73535;
}
+14 -1
View File
@@ -11,7 +11,8 @@ for (const page of [
'pages/store/detail',
'pages/room/detail',
'pages/orders/list',
'pages/orders/detail'
'pages/orders/detail',
'pages/profile/index'
]) {
assert.ok(appJson.pages.includes(page), `${page} must be registered`);
}
@@ -59,4 +60,16 @@ for (const route of [
assert.match(orders, new RegExp(route.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
}
const profile = read('miniapp/pages/profile/index.js')
+ read('miniapp/pages/profile/index.wxml');
for (const pattern of [
'/profile',
'wallet.totalText',
'benefits.availableCoupons',
'benefits.activePackages',
'recentLedger'
]) {
assert.match(profile, new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
}
console.log('PASS: M08-A miniapp customer pages use fixed domain and real app-api calls.');