feat(M08-A): 接入顾客端充值入口
This commit is contained in:
@@ -49,6 +49,7 @@ import {
|
||||
registerDeviceControlRoutes, type DeviceControlRouteOptions
|
||||
} from './routes/device-control.js';
|
||||
import { registerMemberRoutes, type MemberRouteOptions } from './routes/members.js';
|
||||
import { registerRechargeRoutes, type RechargeRouteOptions } from './routes/recharge.js';
|
||||
|
||||
export interface BuildAppOptions {
|
||||
config?: AppConfig;
|
||||
@@ -70,6 +71,7 @@ export interface BuildAppOptions {
|
||||
devices?: DeviceRouteOptions;
|
||||
deviceControl?: DeviceControlRouteOptions;
|
||||
members?: MemberRouteOptions;
|
||||
recharge?: RechargeRouteOptions;
|
||||
}
|
||||
|
||||
declare module 'fastify' {
|
||||
@@ -165,6 +167,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
||||
if (options.members) {
|
||||
await registerMemberRoutes(app, options.members);
|
||||
}
|
||||
if (options.recharge) {
|
||||
await registerRechargeRoutes(app, options.recharge);
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { FastifyInstance, FastifyReply } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import type { AuthRepository } from '../auth/auth-repository.js';
|
||||
import { authenticateAccessToken } from '../auth/authenticate.js';
|
||||
import type { AccessProfile } from '../auth/rbac-repository.js';
|
||||
import { RechargeError, type RechargeService } from '../wallets/recharge-service.js';
|
||||
|
||||
const listSchema = z.object({
|
||||
storeId: z.string().regex(/^[1-9]\d{0,19}$/).optional()
|
||||
});
|
||||
const createSchema = z.object({
|
||||
planId: z.string().regex(/^[1-9]\d{0,19}$/),
|
||||
storeId: z.string().regex(/^[1-9]\d{0,19}$/).nullable().optional(),
|
||||
clientRequestId: z.string().min(8).max(128)
|
||||
}).strict();
|
||||
|
||||
export interface RechargeRouteOptions {
|
||||
service: Pick<RechargeService, 'listAvailablePlans' | 'createRechargeOrder'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerRechargeRoutes(
|
||||
app: FastifyInstance,
|
||||
options: RechargeRouteOptions
|
||||
) {
|
||||
app.get('/app-api/recharge/plans', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const query = listSchema.safeParse(request.query);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!query.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.service.listAvailablePlans({
|
||||
tenantId: auth.tenantId,
|
||||
storeId: query.data.storeId ?? null
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/app-api/recharge/orders', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const body = createSchema.safeParse(request.body);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0,
|
||||
data: await options.service.createRechargeOrder({
|
||||
tenantId: auth.tenantId,
|
||||
userId: auth.userId,
|
||||
planId: body.data.planId,
|
||||
storeId: body.data.storeId ?? null,
|
||||
clientRequestId: body.data.clientRequestId,
|
||||
traceId: request.traceId
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function authenticate(
|
||||
authorization: string | undefined,
|
||||
options: RechargeRouteOptions
|
||||
) {
|
||||
const result = await authenticateAccessToken(
|
||||
authorization,
|
||||
options.authRepository,
|
||||
options.jwtSecret
|
||||
);
|
||||
if (!result) return null;
|
||||
const access = await options.accessControl.getAccessProfile(
|
||||
result.session.tenantId,
|
||||
result.session.user.id
|
||||
);
|
||||
if (!access.capabilities.includes('profile.read')) return null;
|
||||
return {
|
||||
tenantId: result.session.tenantId,
|
||||
userId: result.session.user.id
|
||||
};
|
||||
}
|
||||
|
||||
async function handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (!(error instanceof RechargeError)) throw error;
|
||||
const status = error.code === 'RECHARGE_PLAN_NOT_FOUND'
|
||||
|| error.code === 'RECHARGE_ORDER_NOT_FOUND'
|
||||
? 404
|
||||
: error.code === 'RECHARGE_LIMIT_REACHED' ? 409 : 400;
|
||||
return reply.status(status).send({
|
||||
code: error.code,
|
||||
message: 'The recharge request is not available.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function unauthorized(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(401).send({
|
||||
code: 'AUTH_SESSION_INVALID',
|
||||
message: 'Authentication required.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_RECHARGE_REQUEST',
|
||||
message: 'The recharge request is invalid.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
@@ -34,6 +34,8 @@ 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';
|
||||
import { RechargeService } from './wallets/recharge-service.js';
|
||||
import { WalletLedgerService } from './wallets/wallet-ledger-service.js';
|
||||
|
||||
const config = loadConfig();
|
||||
const pool = createMySqlPool(config);
|
||||
@@ -41,6 +43,7 @@ const authRepository = new AuthRepository(pool);
|
||||
const accessControl = new RbacRepository(pool);
|
||||
const orderManagementRepository = new OrderManagementRepository(pool);
|
||||
const paymentRepository = new PaymentRepository(pool);
|
||||
const walletLedgerService = new WalletLedgerService(pool);
|
||||
const wechatCredentials = parseWechatPayCredentials(config.payment.wechatCredentialsJson);
|
||||
const wechatPayClient = new WechatPayClient(new FetchWechatPayTransport());
|
||||
const thirdPartyCredentials = parseThirdPartyCredentials(config.thirdParty.credentialsJson);
|
||||
@@ -169,6 +172,12 @@ const app = await buildApp({
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
},
|
||||
recharge: {
|
||||
service: new RechargeService(pool, walletLedgerService),
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
}
|
||||
});
|
||||
app.addHook('onClose', async () => {
|
||||
|
||||
@@ -40,6 +40,43 @@ export class RechargeService {
|
||||
private readonly wallet: Pick<WalletLedgerService, 'credit'>
|
||||
) {}
|
||||
|
||||
async listAvailablePlans(input: {
|
||||
tenantId: string;
|
||||
storeId?: string | null;
|
||||
}) {
|
||||
const params: Array<string | null> = [input.tenantId];
|
||||
const storeFilter = input.storeId
|
||||
? 'AND (store_id IS NULL OR store_id = ?)'
|
||||
: '';
|
||||
if (input.storeId) params.push(input.storeId);
|
||||
const [rows] = await this.pool.execute<PlanRow[]>(
|
||||
`SELECT id, tenant_id AS tenantId, store_id AS storeId, name,
|
||||
pay_amount_cents AS payAmountCents,
|
||||
gift_amount_cents AS giftAmountCents,
|
||||
scope_type AS scopeType, starts_at AS startsAt, ends_at AS endsAt,
|
||||
purchase_limit_per_user AS purchaseLimitPerUser, status
|
||||
FROM qipai_recharge_plans
|
||||
WHERE tenant_id = ? AND deleted_at IS NULL AND status = 'ACTIVE'
|
||||
AND (starts_at IS NULL OR starts_at <= UTC_TIMESTAMP(3))
|
||||
AND (ends_at IS NULL OR ends_at > UTC_TIMESTAMP(3))
|
||||
${storeFilter}
|
||||
ORDER BY pay_amount_cents ASC, id ASC`,
|
||||
params
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
planId: String(row.id),
|
||||
storeId: row.storeId === null ? null : String(row.storeId),
|
||||
name: row.name,
|
||||
payAmountCents: Number(row.payAmountCents),
|
||||
giftAmountCents: Number(row.giftAmountCents),
|
||||
scopeType: row.scopeType,
|
||||
purchaseLimitPerUser: row.purchaseLimitPerUser === null
|
||||
? null : Number(row.purchaseLimitPerUser),
|
||||
startsAt: row.startsAt,
|
||||
endsAt: row.endsAt
|
||||
}));
|
||||
}
|
||||
|
||||
async createRechargeOrder(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
|
||||
Reference in New Issue
Block a user