sop-material-preview.ts
7.15 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import { Prisma } from '@prisma/client';
import { AppError } from '../lib/errors.js';
import type { PrismaClientLike } from '../plugins/prisma.js';
import type {
SopMaterialPreviewApiResponse,
SopMaterialPreviewModel,
} from '../../packages/contracts/src/index.js';
interface SopStrategyActionRow {
id: number;
content: string | null;
bgColor: string | null;
materialJson: string | null;
intervalPx: number | null;
}
interface SopStrategyEventLogPayload {
strategyId: number | null;
customerInstanceId: bigint | null;
taskId: number | null;
eventType: string;
eventCode: string;
eventData: string;
eventTime: string;
}
export interface SopMaterialPreviewRepository {
findActionById(actionId: number): Promise<SopStrategyActionRow | null>;
saveEventLog(payload: SopStrategyEventLogPayload): Promise<void>;
}
export interface SopMaterialPreviewVisitPayload {
actionId: string;
strategyId?: string;
customerInstanceId?: string;
taskId?: string;
customerPhone?: string;
storeName?: string;
customerName?: string;
}
function normalizeText(value: unknown, fallback = ''): string {
if (typeof value === 'string') {
return value.trim();
}
if (typeof value === 'number' && Number.isFinite(value)) {
return String(value);
}
return fallback;
}
function normalizeNullableInteger(value: unknown): number | null {
const text = normalizeText(value);
if (text.length === 0) {
return null;
}
const parsed = Number.parseInt(text, 10);
return Number.isFinite(parsed) ? parsed : null;
}
function normalizeNullableBigInt(value: unknown): bigint | null {
const text = normalizeText(value);
if (text.length === 0) {
return null;
}
try {
return BigInt(text);
} catch {
return null;
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function normalizeMaterialItems(value: unknown): { type: string; url: string }[] | null {
if (!Array.isArray(value)) {
return null;
}
const items = value.map((item) => {
if (!isRecord(item)) {
return null;
}
if (typeof item.type !== 'string' || typeof item.url !== 'string') {
return null;
}
return {
type: item.type.trim(),
url: item.url.trim(),
};
});
return items.includes(null) ? null : (items as { type: string; url: string }[]);
}
function normalizeBgColor(value: unknown): string {
const text = normalizeText(value);
return text.length > 0 ? text : '#ffffff';
}
function normalizeIntervalPx(value: unknown): number {
const parsed = typeof value === 'number' ? value : Number.parseFloat(normalizeText(value));
if (!Number.isFinite(parsed) || parsed < 0) {
return 0;
}
return Math.floor(parsed);
}
function normalizePreviewModel(row: SopStrategyActionRow): SopMaterialPreviewModel {
let parsed: unknown;
if (normalizeText(row.materialJson).length === 0) {
throw new AppError('SOP_MATERIAL_PREVIEW_MATERIAL_INVALID', '素材配置不能为空', 422, {
id: row.id,
});
}
try {
parsed = JSON.parse(row.materialJson ?? '');
} catch {
throw new AppError('SOP_MATERIAL_PREVIEW_MATERIAL_INVALID', '素材配置无法解析', 422, {
id: row.id,
});
}
const materials = normalizeMaterialItems(parsed);
if (!materials || materials.length === 0) {
throw new AppError('SOP_MATERIAL_PREVIEW_MATERIAL_INVALID', '素材配置不能为空', 422, {
id: row.id,
});
}
return {
id: row.id,
content: normalizeText(row.content, 'SOP 素材展示/预览') || 'SOP 素材展示/预览',
bgColor: normalizeBgColor(row.bgColor),
intervalPx: normalizeIntervalPx(row.intervalPx),
materials,
};
}
function buildEventData(payload: SopMaterialPreviewVisitPayload): string {
return JSON.stringify({
source: 'query_action_id',
actionId: normalizeText(payload.actionId),
customerPhone: normalizeText(payload.customerPhone),
storeName: normalizeText(payload.storeName),
customerName: normalizeText(payload.customerName),
});
}
function normalizeActionId(actionId: string): number {
const parsed = Number.parseInt(actionId, 10);
if (!Number.isFinite(parsed)) {
throw new AppError('SOP_MATERIAL_PREVIEW_ACTION_ID_INVALID', '素材 actionId 非法', 400, {
missingFields: ['actionId'],
});
}
return parsed;
}
function formatChinaDateTime(date = new Date()): string {
const chinaDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);
const pad = (value: number) => String(value).padStart(2, '0');
return [
`${chinaDate.getUTCFullYear()}-${pad(chinaDate.getUTCMonth() + 1)}-${pad(chinaDate.getUTCDate())}`,
`${pad(chinaDate.getUTCHours())}:${pad(chinaDate.getUTCMinutes())}:${pad(chinaDate.getUTCSeconds())}`,
].join(' ');
}
export function createPrismaSopMaterialPreviewRepository(prisma: PrismaClientLike): SopMaterialPreviewRepository {
return {
async findActionById(actionId) {
const rows = await prisma.$queryRaw<SopStrategyActionRow>(Prisma.sql`
SELECT
id,
content,
bg_color AS bgColor,
material_json AS materialJson,
interval_px AS intervalPx
FROM sop_strategy_action
WHERE id = ${actionId}
LIMIT 1
`);
return rows[0] ?? null;
},
async saveEventLog(payload) {
await prisma.$executeRaw(Prisma.sql`
INSERT INTO sop_strategy_event_log (
strategy_id,
customer_instance_id,
event_type,
event_code,
event_data,
event_time,
deleted_flag,
created_by,
created_date,
task_id
) VALUES (
${payload.strategyId},
${payload.customerInstanceId},
${payload.eventType},
${payload.eventCode},
${payload.eventData},
${payload.eventTime},
'N',
'SYSTEM',
NOW(),
${payload.taskId}
)
`);
},
};
}
export async function loadSopMaterialPreview(
repository: SopMaterialPreviewRepository,
actionId: string,
): Promise<SopMaterialPreviewApiResponse> {
const normalizedActionId = normalizeActionId(actionId);
const row = await repository.findActionById(normalizedActionId);
if (!row) {
throw new AppError('SOP_MATERIAL_PREVIEW_NOT_FOUND', '素材不存在', 404, {
id: normalizedActionId,
});
}
return {
...normalizePreviewModel(row),
id: row.id,
};
}
export async function recordSopMaterialPreviewVisit(
repository: SopMaterialPreviewRepository,
payload: SopMaterialPreviewVisitPayload,
): Promise<void> {
const taskIdRaw = normalizeText(payload.taskId);
if (taskIdRaw.length === 0) {
return;
}
const taskId = normalizeNullableInteger(taskIdRaw);
const strategyId = normalizeNullableInteger(payload.strategyId);
const customerInstanceId = normalizeNullableBigInt(payload.customerInstanceId);
await repository.saveEventLog({
strategyId,
customerInstanceId,
taskId,
eventType: 'page_view',
eventCode: 'sop_strategy_h5_marketing_page_view',
eventData: buildEventData(payload),
eventTime: formatChinaDateTime(),
});
}
export { formatChinaDateTime };