sop-material-preview.ts
2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { FastifyPluginAsync } from 'fastify';
import type {
SopMaterialPreviewApiError,
SopMaterialPreviewApiResponse,
} from '../../packages/contracts/src/index.js';
import { AppError, createErrorResponse } from '../lib/errors.js';
import {
createPrismaSopMaterialPreviewRepository,
loadSopMaterialPreview,
recordSopMaterialPreviewVisit,
type SopMaterialPreviewRepository,
} from '../features/sop-material-preview.js';
export interface RouteOptions {
createRepository?: (repository: SopMaterialPreviewRepository) => SopMaterialPreviewRepository;
}
export const sopMaterialPreviewRoute: FastifyPluginAsync<RouteOptions> = async (app, options) => {
const baseRepository = createPrismaSopMaterialPreviewRepository(app.prisma);
const repository = options?.createRepository ? options.createRepository(baseRepository) : baseRepository;
app.get('/api/sop-material-preview', async (request, reply) => {
const query = (request.query as {
actionId?: string;
strategyId?: string;
customerInstanceId?: string;
taskId?: string;
customerPhone?: string;
storeName?: string;
customerName?: string;
} | undefined) ?? {};
const actionIdRaw = query.actionId;
if (typeof actionIdRaw !== 'string' || actionIdRaw.trim().length === 0) {
const error = new AppError('SOP_MATERIAL_PREVIEW_ACTION_ID_INVALID', '素材 actionId 非法', 400, {
missingFields: ['actionId'],
});
const response: SopMaterialPreviewApiError = createErrorResponse(
error.code,
error.message,
request.id,
error.details,
);
reply.status(error.statusCode).send(response);
return;
}
try {
const result: SopMaterialPreviewApiResponse = await loadSopMaterialPreview(repository, actionIdRaw);
try {
await recordSopMaterialPreviewVisit(repository, {
actionId: actionIdRaw,
strategyId: query.strategyId,
customerInstanceId: query.customerInstanceId,
taskId: query.taskId,
customerPhone: query.customerPhone,
storeName: query.storeName,
customerName: query.customerName,
});
} catch (error) {
request.log.warn({ err: error }, 'sop material preview event log persistence failed');
}
reply.send(result);
} catch (error) {
if (error instanceof AppError) {
const response: SopMaterialPreviewApiError = createErrorResponse(
error.code,
error.message,
request.id,
error.details,
);
reply.status(error.statusCode).send(response);
return;
}
throw error;
}
});
};