188 lines
7.6 KiB
TypeScript
188 lines
7.6 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 {
|
|
BusinessStatisticsError,
|
|
type BusinessStatisticsRepository
|
|
} from '../operations/business-statistics-repository.js';
|
|
import {
|
|
BusinessReportError,
|
|
type BusinessReportService
|
|
} from '../operations/business-report-service.js';
|
|
|
|
const querySchema = z.object({
|
|
storeId: z.string().regex(/^[1-9]\d{0,19}$/),
|
|
from: z.coerce.date().optional(),
|
|
to: z.coerce.date().optional()
|
|
}).strict();
|
|
|
|
const reportQuerySchema = z.object({
|
|
storeId: z.string().regex(/^[1-9]\d{0,19}$/).optional(),
|
|
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/)
|
|
}).strict();
|
|
|
|
export interface BusinessStatisticsRouteOptions {
|
|
repository: Pick<BusinessStatisticsRepository, 'overview'>;
|
|
reportService?: Pick<BusinessReportService, 'report' | 'enqueueRange'>;
|
|
authRepository: Pick<AuthRepository, 'validateSession'>;
|
|
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
|
jwtSecret: string;
|
|
}
|
|
|
|
export async function registerBusinessStatisticsRoutes(
|
|
app: FastifyInstance,
|
|
options: BusinessStatisticsRouteOptions
|
|
) {
|
|
for (const path of ['/app-api/management/statistics', '/admin-api/statistics']) {
|
|
app.get(path, async (request, reply) => {
|
|
const actor = await requireActor(request, reply, options);
|
|
if (!actor) return;
|
|
const query = querySchema.safeParse(request.query);
|
|
if (!query.success) return invalid(reply, request.traceId);
|
|
const to = query.data.to ?? new Date();
|
|
const from = query.data.from ?? new Date(to.getTime() - 30 * 86400000);
|
|
const duration = to.getTime() - from.getTime();
|
|
if (duration <= 0 || duration > 93 * 86400000) return invalid(reply, request.traceId);
|
|
try {
|
|
return {
|
|
code: 0,
|
|
data: await options.repository.overview(actor, {
|
|
storeId: query.data.storeId,
|
|
from,
|
|
to
|
|
}),
|
|
traceId: request.traceId
|
|
};
|
|
} catch (error) {
|
|
if (!(error instanceof BusinessStatisticsError)) throw error;
|
|
return reply.status(403).send({
|
|
code: error.code,
|
|
message: 'Business statistics permission is required.',
|
|
traceId: request.traceId
|
|
});
|
|
}
|
|
});
|
|
}
|
|
if (!options.reportService) return;
|
|
for (const path of ['/app-api/management/reports/business', '/admin-api/reports/business']) {
|
|
app.get(path, async (request, reply) => {
|
|
const actor = await requireActor(request, reply, options);
|
|
if (!actor) return;
|
|
const query = reportQuerySchema.safeParse(request.query);
|
|
if (!query.success) return invalidReport(reply, request.traceId);
|
|
try {
|
|
return { code: 0, data: await options.reportService!.report(actor, query.data), traceId: request.traceId };
|
|
} catch (error) {
|
|
return handleReportError(error, reply, request.traceId);
|
|
}
|
|
});
|
|
}
|
|
app.get('/admin-api/reports/business/export', async (request, reply) => {
|
|
const actor = await requireActor(request, reply, options);
|
|
if (!actor) return;
|
|
if (!actor.access.capabilities.includes('report.export')
|
|
&& !actor.access.capabilities.includes('tenant.manage')
|
|
&& !actor.access.roles.includes('PLATFORM_ADMIN')) {
|
|
return reply.status(403).send({ code: 'BUSINESS_REPORT_FORBIDDEN', message: 'Report export permission is required.', traceId: request.traceId });
|
|
}
|
|
const query = reportQuerySchema.safeParse(request.query);
|
|
if (!query.success) return invalidReport(reply, request.traceId);
|
|
try {
|
|
const report = await options.reportService!.report(actor, query.data);
|
|
const rows: Array<Array<string | number>> = [[
|
|
'日期', '门店', '时区', '订单数', '下单人数', '实际使用分钟', '可用分钟', '利用率(%)',
|
|
'房费实收(分)', '房费退款(分)', '房费净收入(分)', '商品实收(分)', '商品退款(分)',
|
|
'商品净收入(分)', '总净收入(分)', '保洁成本(分)', '贡献额(分)',
|
|
'微信净收入(分)', '余额净收入(分)', '套餐净收入(分)', '团购净收入(分)', '其他净收入(分)'
|
|
]];
|
|
for (const item of report.daily) rows.push([
|
|
item.date, item.storeName, item.timezone, item.orderCount, item.customerCount,
|
|
item.usedMinutes, item.capacityMinutes, (item.utilizationBasisPoints / 100).toFixed(2),
|
|
item.roomGrossCents, item.roomRefundCents, item.roomNetCents,
|
|
item.productGrossCents, item.productRefundCents, item.productNetCents,
|
|
item.totalNetCents, item.cleaningCostCents, item.contributionCents,
|
|
item.channels.WECHAT, item.channels.BALANCE, item.channels.PACKAGE,
|
|
item.channels.GROUP_BUY, item.channels.OTHER
|
|
]);
|
|
const csv = `\uFEFF${rows.map((row) => row.map(csvCell).join(',')).join('\r\n')}`;
|
|
return reply.header('content-type', 'text/csv; charset=utf-8')
|
|
.header('content-disposition', `attachment; filename="business-report-${query.data.from}-${query.data.to}.csv"`)
|
|
.send(csv);
|
|
} catch (error) {
|
|
return handleReportError(error, reply, request.traceId);
|
|
}
|
|
});
|
|
app.post('/admin-api/reports/business/rebuild', async (request, reply) => {
|
|
const actor = await requireActor(request, reply, options);
|
|
if (!actor) return;
|
|
const body = reportQuerySchema.safeParse(request.body);
|
|
if (!body.success) return invalidReport(reply, request.traceId);
|
|
try {
|
|
return { code: 0, data: await options.reportService!.enqueueRange(actor, body.data), traceId: request.traceId };
|
|
} catch (error) {
|
|
return handleReportError(error, reply, request.traceId);
|
|
}
|
|
});
|
|
}
|
|
|
|
async function requireActor(
|
|
request: FastifyRequest,
|
|
reply: FastifyReply,
|
|
options: BusinessStatisticsRouteOptions
|
|
): Promise<ManagementActor | null> {
|
|
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
|
|
);
|
|
return {
|
|
tenantId: auth.session.tenantId,
|
|
userId: auth.session.user.id,
|
|
access,
|
|
traceId: request.traceId,
|
|
ip: request.ip,
|
|
userAgent: request.headers['user-agent'] ?? ''
|
|
};
|
|
}
|
|
|
|
function invalid(reply: FastifyReply, traceId: string) {
|
|
return reply.status(400).send({
|
|
code: 'INVALID_BUSINESS_STATISTICS_REQUEST',
|
|
message: 'The statistics request is invalid.',
|
|
traceId
|
|
});
|
|
}
|
|
|
|
function invalidReport(reply: FastifyReply, traceId: string) {
|
|
return reply.status(400).send({
|
|
code: 'INVALID_BUSINESS_REPORT_REQUEST',
|
|
message: 'The business report request is invalid.',
|
|
traceId
|
|
});
|
|
}
|
|
|
|
function handleReportError(error: unknown, reply: FastifyReply, traceId: string) {
|
|
if (!(error instanceof BusinessReportError)) throw error;
|
|
const status = error.code.endsWith('_FORBIDDEN') ? 403
|
|
: error.code.endsWith('_NOT_FOUND') ? 404 : 400;
|
|
return reply.status(status).send({ code: error.code, message: 'Business report request failed.', traceId });
|
|
}
|
|
|
|
function csvCell(value: string | number) {
|
|
const text = String(value);
|
|
return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
}
|