clue.service.ts
7.22 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
// import { Inject, Injectable, OnModuleInit, Logger } from '@nestjs/common'
import { Command, Events, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums'
// import { PrismaService } from 'nestjs-prisma'
import { Injectable } from '@nestjs/common';
import { InjectRepository} from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { DB1_Table1Entity } from './db1/entities/table1.entity';
import { DB1_Table2Entity } from './db1/entities/table2.entity'
import { DB2_Table3Entity } from './db2/entities/table3.entity';
import { DB1_Table4Entity } from './db1/entities/table4.entity';
type TableKey = 'script_record_browse_log' | 'dj_car_life_customer_dynamic_record' | 'clue_burial_point_record'
interface DailyStat {
date: string; // 日期
count: number; // 当日数据量
}
@Injectable()
export class ClueService {
constructor(
@InjectRepository(DB1_Table1Entity, 'db1')
private readonly table1Repo: Repository<DB1_Table1Entity>,
@InjectRepository(DB1_Table2Entity, 'db1')
private readonly table2Repo: Repository<DB1_Table2Entity>,
@InjectRepository(DB2_Table3Entity, 'db2')
private readonly table3Repo: Repository<DB2_Table3Entity>,
@InjectRepository(DB1_Table4Entity, 'db1')
private readonly table4Repo: Repository<DB1_Table4Entity>,
) {}
private getRepo(table: TableKey): Repository<any> {
switch (table) {
case 'script_record_browse_log': return this.table1Repo;
case 'dj_car_life_customer_dynamic_record': return this.table2Repo;
case 'clue_burial_point_record': return this.table3Repo;
default: throw new Error(`Unknown table: ${table}`);
}
}
async querySingleTable(params: {
table: TableKey;
where?: Record<string, any>;
// page?: number;
// pageSize?: number;
}): Promise<{ data: any[]; total: number, code: Number, message: string }> { // 明确返回类型
let goodsIdList: number[] = []
if (params.where.show_channel) {
// 查子表
goodsIdList = await this.table4Repo.createQueryBuilder('material')
.select('material.id')
.where('material.show_channel = :show_channel', { show_channel: Number(params.where.show_channel) })
.andWhere('material.deleted_flag = :deletedFlag', { deletedFlag: 'N' })
.getRawMany()
.then(results => results.map(r => r.material_id || r.id)); // 根据返回字段调整
// 如果没查到,直接返回空结果,避免主查询无意义执行
if (goodsIdList.length === 0) {
return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', data: [], total: 0 };
}
}
const repo = this.getRepo(params.table);
// 构造主查询条件
const where = {
...params.where,
};
console.log(goodsIdList)
if (params.where.show_channel) {
// 用查到的id数组替换goods_id条件
where.goods_id = In(goodsIdList);
delete where.show_channel; // 去掉子表条件,避免冲突
}
const [data, total] = await repo.findAndCount({
where,
// skip: (params.page - 1) * (params.pageSize || 10),
// take: params.pageSize || 10,
order: { id: 'DESC' }
});
const event_code = params.where.event_code
const show_channel = params.where.show_channel
const eventTimeStart = params.where.event_time?.value?.[0] || params.where.created_time?.value?.[0] || params.where.created_date?.value?.[0]
const eventTimeEnd = params.where.event_time?.value?.[1] || params.where.created_time?.value?.[1] || params.where.created_date?.value?.[1]
const formattedStart = this.formatUtcToBeijingDate(eventTimeStart?.toISOString())
const formattedEnd = this.formatUtcToBeijingDate(eventTimeEnd?.toISOString())
if (event_code == 'mentorship_page') { // 带教管理
const uniqueAccounts = new Set(data.map(user => user.login_account))
const count = total
const dateMap = new Map<string, number>();
data.forEach(record => {
// 提取YYYY-MM-DD格式的日期
const dateStr = record.event_time.toISOString().split('T')[0];
dateMap.set(dateStr, (dateMap.get(dateStr) || 0) + 1);
});
// 3. 转换为数组并排序
const dailyStats = Array.from(dateMap.entries())
.map(([date, count]) => ({ date, count }))
.sort((a, b) => a.date.localeCompare(b.date));
// 4. 计算统计指标
let peakDay: DailyStat | null = null
let totalCount = 0
dailyStats.forEach(day => {
totalCount += day.count
if (!peakDay || day.count > peakDay.count) {
peakDay = day
}
})
return {
code: RESPONSE_CODE.SUCCESS,
message: '查询成功',
data: [{
uniqueAccounts: uniqueAccounts.size,
formattedStart,
formattedEnd,
count,
peakDay
}],
total
}
}
if (event_code == 'supervisor_daily_page') { // 日报管理
const uniqueAccounts = new Set(data.map(user => user.login_account))
const count = total
let equityCount = 0
let upgradeCount= 0
data.forEach(item => {
if (item.scene === 0) {
equityCount++;
} else if (item.scene === 1) {
upgradeCount++;
}
})
// return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', data, total }
return {
code: RESPONSE_CODE.SUCCESS,
message: '查询成功',
data: [{
uniqueAccounts: uniqueAccounts.size,
formattedStart,
formattedEnd,
equityCount: equityCount,
upgradeCount: upgradeCount,
count,
}],
total
}
}
if (params.table == 'script_record_browse_log') { // 话术萃取
const uniqueAccounts = new Set(data.map(user => user.staff_phone))
const uniqueDates = new Set(
data.map(user => {
const d = new Date(user.start_time);
// 格式化成 YYYY-MM-DD HH:mm:ss
const Y = d.getFullYear();
const M = String(d.getMonth() + 1).padStart(2, '0');
const D = String(d.getDate()).padStart(2, '0');
const h = String(d.getHours()).padStart(2, '0');
const m = String(d.getMinutes()).padStart(2, '0');
const s = String(d.getSeconds()).padStart(2, '0');
return `${Y}-${M}-${D} ${h}:${m}:${s}`;
})
)
return {
code: RESPONSE_CODE.SUCCESS,
message: '查询成功',
data: [{
count: total,
batchTotal: uniqueDates.size,
peopleTotal: uniqueAccounts.size,
formattedStart,
formattedEnd,
}],
total
}
}
if (show_channel) {
// 培训资料、营销素材、场景集市
const uniqueAccounts = new Set(data.map(user => user.customer_account_name))
const nameMap = new Map<string, number>();
data.forEach(record => {
const name = record.customer_account_name;
if (name) {
nameMap.set(name, (nameMap.get(name) || 0) + 1);
}
});
console.log(nameMap, data)
return {
code: RESPONSE_CODE.SUCCESS,
message: '查询成功',
data: [{
count: total,
uniqueAccounts: uniqueAccounts.size,
remark: Array.from(nameMap.entries()).map(([name, count]) => ({ name, count })),
formattedStart,
formattedEnd,
}],
total
}
}
}
formatUtcToBeijingDate(utcStr: string): string {
if (!utcStr) return '';
const date = new Date(utcStr);
if (isNaN(date.getTime())) return '';
const datePlus8 = new Date(date.getTime());
const year = datePlus8.getUTCFullYear();
const month = (datePlus8.getUTCMonth() + 1).toString().padStart(2, '0');
const day = datePlus8.getUTCDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
}