feat(M10-B): 完成可复算经营报表与日汇总
This commit is contained in:
@@ -8,6 +8,10 @@ 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}$/),
|
||||
@@ -15,8 +19,15 @@ const querySchema = z.object({
|
||||
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;
|
||||
@@ -56,6 +67,66 @@ export async function registerBusinessStatisticsRoutes(
|
||||
}
|
||||
});
|
||||
}
|
||||
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(
|
||||
@@ -94,3 +165,23 @@ function invalid(reply: FastifyReply, traceId: string) {
|
||||
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user