Files
qipai/backend/src/routes/franchise.ts
T
2026-08-10 13:17:19 +08:00

149 lines
8.7 KiB
TypeScript

import type { FastifyInstance, FastifyReply, FastifyRequest } 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 type { ManagementActor } from '../auth/user-management-repository.js';
import { FranchiseError, type FranchiseRepository } from '../franchise/franchise-repository.js';
import { AmbiguousAppTenantError } from '../tenancy/platform-config-repository.js';
import type { PlatformConfigResolver } from './platform-bootstrap.js';
const id = z.string().regex(/^[1-9]\d{0,19}$/);
const status = z.enum(['NEW', 'CONTACTED', 'QUALIFIED', 'REJECTED', 'CONVERTED']);
const contextHeaders = z.object({
'x-wechat-appid': z.string().trim().min(6).max(64),
'tenant-id': id.optional()
});
const applicationSchema = z.object({
city: z.string().trim().min(1).max(64),
contactName: z.string().trim().min(1).max(64),
contactPhone: z.string().trim().regex(/^\+?[0-9 -]{6,32}$/),
message: z.string().trim().max(1000).default(''),
clientRequestId: z.string().trim().min(8).max(128)
});
const listSchema = z.object({
tenantId: id.optional(), page: z.coerce.number().int().min(1).default(1),
pageSize: z.coerce.number().int().min(1).max(100).default(20), status: status.optional(),
assigneeUserId: id.optional(), search: z.string().trim().max(64).optional()
});
const tenantQuery = z.object({ tenantId: id.optional() });
const assignmentSchema = z.object({ tenantId: id.optional(), assigneeUserId: id.nullable() });
const followUpSchema = z.object({
tenantId: id.optional(), followUpType: z.enum(['CALL', 'WECHAT', 'MEETING', 'NOTE']),
note: z.string().trim().min(1).max(1000), nextFollowUpAt: z.coerce.date().nullable().optional(),
status: status.optional()
});
export interface FranchiseRouteOptions {
repository: Pick<FranchiseRepository, 'submitApplication' | 'listApplications'
| 'getApplication' | 'assignApplication' | 'addFollowUp'>;
platformConfig: PlatformConfigResolver;
authRepository: Pick<AuthRepository, 'validateSession'>;
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
jwtSecret: string;
}
export async function registerFranchiseRoutes(app: FastifyInstance, options: FranchiseRouteOptions) {
app.post('/app-api/franchise-applications', async (request, reply) => {
const headers = contextHeaders.safeParse(request.headers);
const body = applicationSchema.safeParse(request.body);
if (!headers.success || !body.success) return invalid(reply, request.traceId);
return handle(reply, request.traceId, async () => {
let bootstrap;
try {
bootstrap = await options.platformConfig.resolveBootstrap(
headers.data['x-wechat-appid'], headers.data['tenant-id']
);
} catch (error) {
if (error instanceof AmbiguousAppTenantError) throw new FranchiseError('FRANCHISE_TENANT_SELECTION_REQUIRED');
throw error;
}
if (!bootstrap) throw new FranchiseError('FRANCHISE_TENANT_NOT_FOUND');
const auth = request.headers.authorization
? await authenticateAccessToken(request.headers.authorization, options.authRepository, options.jwtSecret)
: null;
if (request.headers.authorization && !auth) throw new FranchiseError('FRANCHISE_SESSION_INVALID');
const submittedUserId = auth?.session.tenantId === bootstrap.tenantId ? auth.session.user.id : null;
return reply.status(201).send({ code: 0, data: await options.repository.submitApplication({
tenantId: bootstrap.tenantId, submittedUserId, ...body.data, source: 'MINIAPP',
traceId: request.traceId, ip: request.ip, userAgent: request.headers['user-agent'] ?? ''
}), traceId: request.traceId });
});
});
app.get('/admin-api/franchise-applications', async (request, reply) => {
const actor = await requireManager(request, reply, options);
const query = listSchema.safeParse(request.query);
if (!actor || !query.success) return actor ? invalid(reply, request.traceId) : undefined;
const targetTenantId = resolveTenant(actor, query.data.tenantId);
if (!targetTenantId) return forbidden(reply, request.traceId);
return handle(reply, request.traceId, async () => ({ code: 0,
data: await options.repository.listApplications({ ...query.data, tenantId: targetTenantId }),
traceId: request.traceId }));
});
app.get('/admin-api/franchise-applications/:id', async (request, reply) => {
const actor = await requireManager(request, reply, options);
const params = z.object({ id }).safeParse(request.params);
const query = tenantQuery.safeParse(request.query);
if (!actor || !params.success || !query.success) return actor ? invalid(reply, request.traceId) : undefined;
const targetTenantId = resolveTenant(actor, query.data.tenantId);
if (!targetTenantId) return forbidden(reply, request.traceId);
return handle(reply, request.traceId, async () => ({ code: 0,
data: await options.repository.getApplication(targetTenantId, params.data.id), traceId: request.traceId }));
});
app.patch('/admin-api/franchise-applications/:id/assignee', async (request, reply) => {
const actor = await requireManager(request, reply, options);
const params = z.object({ id }).safeParse(request.params);
const body = assignmentSchema.safeParse(request.body);
if (!actor || !params.success || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
const targetTenantId = resolveTenant(actor, body.data.tenantId);
if (!targetTenantId) return forbidden(reply, request.traceId);
return handle(reply, request.traceId, async () => ({ code: 0,
data: await options.repository.assignApplication(actor, targetTenantId, params.data.id,
body.data.assigneeUserId), traceId: request.traceId }));
});
app.post('/admin-api/franchise-applications/:id/follow-ups', async (request, reply) => {
const actor = await requireManager(request, reply, options);
const params = z.object({ id }).safeParse(request.params);
const body = followUpSchema.safeParse(request.body);
if (!actor || !params.success || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
const targetTenantId = resolveTenant(actor, body.data.tenantId);
if (!targetTenantId) return forbidden(reply, request.traceId);
return handle(reply, request.traceId, async () => reply.status(201).send({ code: 0,
data: await options.repository.addFollowUp(actor, targetTenantId, params.data.id, body.data),
traceId: request.traceId }));
});
}
async function requireManager(request: FastifyRequest, reply: FastifyReply, options: FranchiseRouteOptions) {
const auth = await authenticateAccessToken(request.headers.authorization, options.authRepository, options.jwtSecret);
if (!auth) { reply.status(401).send({ code: 'AUTH_SESSION_INVALID', message: 'Authentication required.', traceId: request.traceId }); return null; }
const access = await options.accessControl.getAccessProfile(auth.session.tenantId, auth.session.user.id);
if (!access.capabilities.includes('tenant.manage') && !isPlatform(access)) {
reply.status(403).send({ code: 'FRANCHISE_MANAGEMENT_FORBIDDEN', message: 'Franchise management permission is required.', traceId: request.traceId }); return null;
}
return { tenantId: auth.session.tenantId, userId: auth.session.user.id, access,
traceId: request.traceId, ip: request.ip, userAgent: request.headers['user-agent'] ?? '' };
}
function resolveTenant(actor: ManagementActor, requested?: string) {
if (!requested || requested === actor.tenantId) return actor.tenantId;
return isPlatform(actor.access) ? requested : null;
}
function isPlatform(access: AccessProfile) { return access.roles.includes('PLATFORM_ADMIN') || access.capabilities.includes('platform.manage'); }
async function handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
try { return await work(); } catch (error) {
if (!(error instanceof FranchiseError)) throw error;
const statusCode = error.code === 'FRANCHISE_SESSION_INVALID' ? 401
: error.code.endsWith('_NOT_FOUND') ? 404
: error.code.includes('FORBIDDEN') ? 403
: error.code.endsWith('_SELECTION_REQUIRED') ? 409 : 400;
return reply.status(statusCode).send({ code: error.code, message: 'The franchise request is invalid or not allowed.', traceId });
}
}
function invalid(reply: FastifyReply, traceId: string) { return reply.status(400).send({ code: 'INVALID_FRANCHISE_REQUEST', message: 'The franchise request is invalid.', traceId }); }
function forbidden(reply: FastifyReply, traceId: string) { return reply.status(403).send({ code: 'FRANCHISE_TENANT_FORBIDDEN', message: 'The tenant is outside the allowed scope.', traceId }); }