Commit 5225a4c8 by 前端

Merge branch 'v1.0.1' into 'master'

上线合并

See merge request !1
2 parents 25351b75 84b167d8
...@@ -11,3 +11,8 @@ SOCKET_PORT= 8080 ...@@ -11,3 +11,8 @@ SOCKET_PORT= 8080
APP_PORT= 3000 APP_PORT= 3000
STATIC_PATH = "public" STATIC_PATH = "public"
JWT_SECRET = 'secretKey' JWT_SECRET = 'secretKey'
SMTP_HOST='smtphz.qiye.163.com'
SMTP_PORT='465'
SMTP_USER='qianduan01@didihu.com.cn'
SMTP_PASSWORD='Q9gr7VKwJEr73d8F'
SMTP_FROM='qianduan01@didihu.com.cn'
\ No newline at end of file \ No newline at end of file
1
\ No newline at end of file \ No newline at end of file
## 常见问题
### 配置新的模块未显示
需要在app.module.ts里面引入模块
This diff could not be displayed because it is too large.
...@@ -33,10 +33,11 @@ ...@@ -33,10 +33,11 @@
}, },
"dependencies": { "dependencies": {
"@nest-modules/mailer": "^1.3.22", "@nest-modules/mailer": "^1.3.22",
"@nestjs-modules/mailer": "^1.6.0", "@nestjs-modules/mailer": "^1.11.2",
"@nestjs/axios": "^3.0.3", "@nestjs/axios": "^3.0.3",
"@nestjs/bull": "^0.1.1", "@nestjs/bull": "^0.1.1",
"@nestjs/common": "^10.4.1", "@nestjs/common": "^10.4.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^10.4.1", "@nestjs/core": "^10.4.1",
"@nestjs/event-emitter": "^2.0.4", "@nestjs/event-emitter": "^2.0.4",
"@nestjs/jwt": "^10.2.0", "@nestjs/jwt": "^10.2.0",
...@@ -57,13 +58,14 @@ ...@@ -57,13 +58,14 @@
"class-validator": "^0.12.2", "class-validator": "^0.12.2",
"compressing": "^1.5.1", "compressing": "^1.5.1",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"ejs": "^3.1.10",
"global": "^4.4.0", "global": "^4.4.0",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"nest-status-monitor": "^0.1.3", "nest-status-monitor": "^0.1.3",
"nest-winston": "^1.9.7", "nest-winston": "^1.9.7",
"nestjs-config": "^1.4.6", "nestjs-config": "^1.4.6",
"nestjs-prisma": "^0.23.0", "nestjs-prisma": "^0.23.0",
"nodemailer": "^6.4.16", "nodemailer": "^6.10.1",
"passport": "^0.4.1", "passport": "^0.4.1",
"passport-jwt": "^4.0.0", "passport-jwt": "^4.0.0",
"passport-local": "^1.0.0", "passport-local": "^1.0.0",
......
...@@ -2,7 +2,7 @@ import { resolve } from 'path' ...@@ -2,7 +2,7 @@ import { resolve } from 'path'
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common' import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common'
import { ScheduleModule } from '@nestjs/schedule' import { ScheduleModule } from '@nestjs/schedule'
import { ConfigModule, ConfigService } from 'nestjs-config' import { ConfigModule, ConfigService } from 'nestjs-config'
// import { MailerModule } from '@nest-modules/mailer' import { MailerModule } from '@nest-modules/mailer'
// import { StatusMonitorModule } from 'nest-status-monitor' // import { StatusMonitorModule } from 'nest-status-monitor'
// import statusMonitorConfig from './config/statusMonitor' // import statusMonitorConfig from './config/statusMonitor'
import { LoggerMiddleware } from './common/middleware/logger.middleware' import { LoggerMiddleware } from './common/middleware/logger.middleware'
...@@ -20,6 +20,8 @@ import { WsModule } from './modules/ws/ws.module' ...@@ -20,6 +20,8 @@ import { WsModule } from './modules/ws/ws.module'
// import { SseModule } from './modules/sse/sse.module' // import { SseModule } from './modules/sse/sse.module'
import { BroadcastModule } from './modules/broadcast/broadcast.module' import { BroadcastModule } from './modules/broadcast/broadcast.module'
import { ClueModule } from './modules/clue/clue.module'; import { ClueModule } from './modules/clue/clue.module';
import { DialogueModule } from './modules/dialogue/dialogue.module';
import {EmailModule} from './email/email.module'
import { EventEmitterModule } from '@nestjs/event-emitter' import { EventEmitterModule } from '@nestjs/event-emitter'
import { HttpModule } from '@nestjs/axios' import { HttpModule } from '@nestjs/axios'
// import { FieldsModule } from './modules/fields/fields.module' // import { FieldsModule } from './modules/fields/fields.module'
...@@ -57,7 +59,9 @@ import winstonLogger from './initor/winstion.config' ...@@ -57,7 +59,9 @@ import winstonLogger from './initor/winstion.config'
WsModule, WsModule,
BroadcastModule, BroadcastModule,
// FieldsModule, // FieldsModule,
ClueModule ClueModule,
DialogueModule,
EmailModule
] ]
}) })
export class AppModule { export class AppModule {
......
...@@ -9,7 +9,7 @@ export class RedisIoAdapter extends IoAdapter { ...@@ -9,7 +9,7 @@ export class RedisIoAdapter extends IoAdapter {
async connectToRedis(): Promise<void> { async connectToRedis(): Promise<void> {
// redis://IP 强制用IPv4 // redis://IP 强制用IPv4
const pubClient = createClient({ url: `redis://127.0.0.1:6379` }); const pubClient = createClient({ url: `redis://192.168.5.16:6382` });
const subClient = pubClient.duplicate(); const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]); await Promise.all([pubClient.connect(), subClient.connect()]);
this.adapterConstructor = createAdapter(pubClient, subClient); this.adapterConstructor = createAdapter(pubClient, subClient);
......
...@@ -6,7 +6,7 @@ export default { ...@@ -6,7 +6,7 @@ export default {
port: 3306, port: 3306,
username: 'wechat_user', username: 'wechat_user',
password: 'b4WRTkl', password: 'b4WRTkl',
database: 'scrm_clue', database: 'dj_smartcarlife',
// entities: [join(__dirname, '../', '**/**.entity{.ts,.js}')], // entities: [join(__dirname, '../', '**/**.entity{.ts,.js}')],
entities: [join(__dirname, '../', 'modules/entities/**{.ts,.js}')], entities: [join(__dirname, '../', 'modules/entities/**{.ts,.js}')],
synchronize: true, synchronize: true,
......
import { ApiProperty } from '@nestjs/swagger'
// import { IsDateString, IsOptional } from 'class-validator';
export class StatisticsQueryDto {
@ApiProperty({
type: String,
description: '开始时间',
required: true
})
startDate?: string;
@ApiProperty({
type: String,
description: '结束时间',
required: true
})
endDate?: string;
}
\ No newline at end of file \ No newline at end of file
import { ApiProperty } from '@nestjs/swagger'
// import { IsDateString, IsOptional } from 'class-validator';
export class EmailQueryDto {
@ApiProperty({
type: String,
description: '收件人',
required: true
})
to?: string;
@ApiProperty({
type: String,
description: '标题',
required: true
})
subject?: string;
@ApiProperty({
type: String,
description: '内容',
required: true
})
mentorship_page?: string;
supervisor_daily_page?: string;
extraction?: string;
sales_content?: string;
training_materials?: string;
scene_market?: string;
reportData?: string;
template?: string;
aiAgentColumns?: string;
ai_agent?: string;
}
class MentorshipPage {
count: number;
peakDay: Array<PeakDay>;
uniqueAccounts: number;
queryTime: Object;
}
class PeakDay {
count: number;
date: string;
}
\ No newline at end of file \ No newline at end of file
export * from './response.dto' export * from './response.dto'
export * from './broadcast.dto' export * from './broadcast.dto'
export * from './clue.dto' export * from './clue.dto'
export * from './dialogue.dto'
\ No newline at end of file \ No newline at end of file
import { Body, Controller, Get, Post, Query, Render, Logger, UsePipes } from '@nestjs/common';
import { EmailService } from './email.service';
import { EmailQueryDto } from 'src/dto/email.dto';
import { PagesPipe, ValidationPipe } from '../common/pipes'
import { ApiOperation } from '@nestjs/swagger';
@Controller('email')
@UsePipes(new ValidationPipe()) // 使用管道验证
export class EmailController {
constructor(private readonly emailService: EmailService) {}
@Post('send')
@UsePipes(new PagesPipe())
@ApiOperation({ summary: '发送邮件' })
async sendEmail(@Body() query: EmailQueryDto) {
// const {to, subject} = query
Logger.log(query,'==========')
try {
await this.emailService.sendMail(query);
return 'Email sent successfully!';
} catch (error) {
return 'Email sending failed: ' + error;
}
}
@Post('preview')
@Render('template')
getIndex(@Body() query: EmailQueryDto) {
return { ...query };
}
}
\ No newline at end of file \ No newline at end of file
// mail/mail.module.ts
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { EjsAdapter } from '@nestjs-modules/mailer/dist/adapters/ejs.adapter';
import { EmailService } from './email.service';
import { EmailController } from './email.controller';
const path = require('path')
@Module({
imports: [
MailerModule.forRoot({
transport: {
host: process.env.SMTP_HOST,
port: +process.env.SMTP_PORT,
secure: true, // true for 465, false for other ports
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
},
preview: true,
defaults: {
from: `"Your App" <${process.env.SMTP_FROM}>`,
},
template: {
dir: path.join(process.cwd(), './src/email/templates'),
adapter: new EjsAdapter(),
options: {
strict: true,
},
},
}),
],
controllers: [EmailController], // 注册控制器
providers: [EmailService],
exports: [EmailService], // 导出服务以便其他模块使用
})
export class EmailModule {}
\ No newline at end of file \ No newline at end of file
// mail/mail.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
import * as nodemailer from 'nodemailer';
import { EmailQueryDto } from 'src/dto/email.dto';
@Injectable()
export class EmailService {
// private transporter;
constructor(private readonly mailerService: MailerService) {}
// constructor() {
// this.transporter = nodemailer.createTransport({
// host: process.env.SMTP_HOST,
// port: +process.env.SMTP_PORT,
// secure: true, // 如果是 SMTPS 连接,设置为 true
// auth: {
// user: process.env.SMTP_USER,
// pass: process.env.SMTP_PASSWORD,
// },
// });
// }
async sendMail(query: EmailQueryDto): Promise<void> {
const { to, subject, mentorship_page, supervisor_daily_page, extraction, reportData, template, sales_content, training_materials, scene_market, aiAgentColumns, ai_agent } = query
Logger.log(aiAgentColumns, 'aiAgentColumns')
const mailOptions = {
from: process.env.SMTP_FROM,
to,
subject,
template: './function.point.ejs',
context: {
code: 1, //验证码
date: '2025-05-28', //日期
sign: '系统邮件,回复无效。', //发送的签名,当然也可以不要
mentorship_page,
supervisor_daily_page,
extraction,
sales_content,
training_materials,
scene_market,
reportData,
template,
aiAgentColumns,
ai_agent
// mentorship_page: mentorship_page,
// supervisor_daily_page: JSON.parse(supervisor_daily_page),
// extraction: JSON.parse(extraction),
// sales_content: JSON.parse(sales_content),
// training_materials: JSON.parse(training_materials),
// scene_market: JSON.parse(scene_market)
}
};
await this.mailerService.sendMail(mailOptions);
}
}
\ No newline at end of file \ No newline at end of file
<div class="biu-nav-email"
style="max-width: 600px;min-width: 300px;margin: 40px auto;box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);font-size: 16px;padding: 20px;background-image: linear-gradient(to right, #9646de 0%, #cb03e4 100%);border-radius: 5px;color: #fff;">
<h3 style="margin-bottom: 40px;">
Hi! 亲爱的用户:
</h3>
<p style="padding-left: 20px;">
您正在进行邮箱验证,本次请求的验证码为:
</p>
<p style="color: #dde2e2;padding-left: 14px;">
<strong style="color: #3acbff;font-size: 24px;">
<%= locals.code %>
</strong>
<span>(为了保障您帐号的安全性,请在30分钟内完成验证,祝您生活愉快!)</span>
</p>
<p style="padding-left: 20px;">
<span>快速访问:</span>
<a href="https://www.biunav.com" style="color:#fff" target="_blank"
rel="noopener noreferrer">https://www.biunav.com</a>
</p>
<p style="margin-top: 40px;text-align: right;">
<%= locals.sign %>
</p>
<p style="text-align: right;">
<%= locals.date %>
</p>
</div>
\ No newline at end of file \ No newline at end of file
...@@ -2,9 +2,18 @@ import { NestFactory } from '@nestjs/core' ...@@ -2,9 +2,18 @@ import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module' import { AppModule } from './app.module'
import { NestExpressApplication } from '@nestjs/platform-express' import { NestExpressApplication } from '@nestjs/platform-express'
import Initializer from './initor' import Initializer from './initor'
import * as ejs from 'ejs';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule) const app = await NestFactory.create<NestExpressApplication>(AppModule)
app.useStaticAssets('public', {
prefix: "/static/" //设置虚拟路径
});
app.setBaseViewsDir('views');
app.setViewEngine('ejs');
app.engine('ejs', ejs.renderFile);
app.set('view engine', 'ejs');
await Initializer.use(app) await Initializer.use(app)
await app.listen(process.env.APP_PORT) await app.listen(process.env.APP_PORT)
} }
bootstrap() bootstrap()
...@@ -3,6 +3,7 @@ import { ClueService } from './clue.service' ...@@ -3,6 +3,7 @@ import { ClueService } from './clue.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { PagesPipe, ValidationPipe } from '../../common/pipes' import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
import { Between, MoreThanOrEqual, LessThanOrEqual } from 'typeorm'
import { ClueQueryDto } from '../../dto' import { ClueQueryDto } from '../../dto'
@ApiTags('埋点信息') @ApiTags('埋点信息')
...@@ -10,15 +11,89 @@ import { ClueQueryDto } from '../../dto' ...@@ -10,15 +11,89 @@ import { ClueQueryDto } from '../../dto'
@UseInterceptors(TransformInterceptor) @UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) // 使用管道验证 @UsePipes(new ValidationPipe()) // 使用管道验证
export class ClueController{ export class ClueController{
constructor( constructor(private readonly queryService: ClueService) {}
@Inject(ClueService)
private readonly ClueService: ClueService,
) {}
@Get() @Get()
@UsePipes(new PagesPipe()) async getData(
@ApiOperation({ summary: '获取所有埋点信息' }) // @Query('page') page: number = 1,
async findAll(@Query() params: ClueQueryDto): Promise<CommonTypes.IResData> { // @Query('pageSize') pageSize: number = 10,
return await this.ClueService.findAll(params) @Query('event_code') event_code: string,
@Query('event_time_start') event_time_start: string,
@Query('event_time_end') event_time_end: string
) {
const event_codes = event_code ? [event_code] : ['mentorship_page', 'supervisor_daily_page', 'sales_content', 'training_materials', 'scene_market', 'extraction']
const data = {}
const promises = event_codes.map(event_code => {
const where = {}
let tableName
// 带教管理&工作日报
if (['mentorship_page', 'supervisor_daily_page'].includes(event_code)) {
tableName = 'clue_burial_point_record'
if (event_code) {
where['event_code'] = event_code
}
if (event_time_start && event_time_end) {
where['event_time'] = Between(
new Date(event_time_start),
new Date(event_time_end),
)
}
} else if (event_code == 'extraction') {
tableName = 'script_record_browse_log'
if (event_time_start && event_time_end) {
where['created_time'] = Between(
new Date(event_time_start),
new Date(event_time_end),
)
}
} else if (['sales_content', 'training_materials', 'scene_market'].includes(event_code)) {
tableName = 'dj_car_life_customer_dynamic_record'
// show_channel这个 - (0-培训资料;1-营销素材;2-展业助手 3.场景集市)
if (event_code == 'training_materials') where['show_channel'] = '0'
if (event_code == 'sales_content') where['show_channel'] = '1'
if (event_code == 'scene_market') where['show_channel'] = '3'
if (event_time_start && event_time_end) {
where['created_date'] = Between(
new Date(event_time_start),
new Date(event_time_end),
)
}
}
return this.queryService.querySingleTable({ table: tableName, where });
});
const results = await Promise.all(promises);
event_codes?.forEach((item, index) => {
data[item] = results[index].data || []
})
return { data }
// return this.queryService.querySingleTable({
// table: tableName,
// // page: Number(page),
// // pageSize: Number(pageSize),
// where, // 仅传递字段相关条件
// });
}
@Get('callThirdPartyAPI')
async callThirdPartyAPI(
@Query('startDate') startDate: string,
@Query('endDate') endDate: string,
@Query('rspType') rspType: number,
) {
try {
let url = `http://192.168.5.30:8008/api/selectAgentData?startDate=${startDate}&endDate=${endDate}`;
if (rspType) url += url + `&rspType=${rspType}`
const response = await fetch(url, {
method: 'GET',
});
const data = await response.json();
console.log(data);
return {data};
} catch (error) {
console.error('Error calling third party API:', error);
throw error;
}
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -2,9 +2,46 @@ import { Module } from '@nestjs/common'; ...@@ -2,9 +2,46 @@ import { Module } from '@nestjs/common';
import { ClueController } from './clue.controller'; import { ClueController } from './clue.controller';
import { ClueService } from './clue.service'; import { ClueService } from './clue.service';
import { PrismaModule } from 'nestjs-prisma'; import { PrismaModule } from 'nestjs-prisma';
import { TypeOrmModule } from '@nestjs/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';
@Module({ @Module({
imports: [PrismaModule], imports: [
TypeOrmModule.forRoot({
name: 'db1', // 连接名称
type: 'mysql',
// host: '192.168.1.39',
// port: 3306,
// username: 'user_chenwq',
// password: 'IxQstO23',
host: '192.168.5.23',
port: 3306,
username: 'user_chenwq',
password: '5bL3Vk1x',
database: 'dj_smartcarlife',
entities: [DB1_Table1Entity, DB1_Table2Entity, DB1_Table4Entity],
synchronize: false,
}),
TypeOrmModule.forRoot({
name: 'db2', // 连接名称
type: 'mysql',
// host: '192.168.3.227',
// port: 3306,
// username: 'os_user',
// password: 'os#123',
host: '192.168.5.1',
port: 3310,
username: 'user_chenwq',
password: 'n41X5tbK',
database: 'scrm_clue',
entities: [DB2_Table3Entity],
synchronize: false,
}),
TypeOrmModule.forFeature([DB1_Table1Entity, DB1_Table2Entity, DB1_Table4Entity], 'db1'),
TypeOrmModule.forFeature([DB2_Table3Entity], 'db2'),
],
controllers: [ClueController], controllers: [ClueController],
providers: [ClueService], providers: [ClueService],
exports: [ClueService], exports: [ClueService],
......
import { Inject, Injectable, OnModuleInit, Logger } from '@nestjs/common' // import { Inject, Injectable, OnModuleInit, Logger } from '@nestjs/common'
import { Command, Events, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums' import { Command, Events, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums'
import { PrismaService } from 'nestjs-prisma' // 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() @Injectable()
export class ClueService implements OnModuleInit { export class ClueService {
constructor( constructor(
@Inject(PrismaService) @InjectRepository(DB1_Table1Entity, 'db1')
private readonly prisma: PrismaService, // private connection: Connection, 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>,
) {} ) {}
async onModuleInit() { private getRepo(table: TableKey): Repository<any> {
Logger.warn('埋点信息开始---') 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)); // 根据返回字段调整
async findAll({ event_code, scene, login_account, event_time, system_source, event_type }: ClueTypes.IQueryClue): Promise<CommonTypes.IResData<ClueTypes.IClue[]>> { // 如果没查到,直接返回空结果,避免主查询无意义执行
if (goodsIdList.length === 0) {
return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', data: [], total: 0 };
}
}
const repo = this.getRepo(params.table);
// 构造主查询条件
const where = { const where = {
// event_code: { ...params.where,
// event_code: event_code };
// }, console.log(goodsIdList)
// scene: { if (params.where.show_channel) {
// scene: scene // 用查到的id数组替换goods_id条件
// }, where.goods_id = In(goodsIdList);
// login_account: { delete where.show_channel; // 去掉子表条件,避免冲突
// contains: login_account }
// } const [data, total] = await repo.findAndCount({
} where,
const result: ClueTypes.IClue[] = await this.prisma.clue_burial_point_record.findMany({ // skip: (params.page - 1) * (params.pageSize || 10),
select: { // take: params.pageSize || 10,
id: true, order: { id: 'DESC' }
event_code: true, // 明确选择字段 });
scene: true, const event_code = params.where.event_code
login_account: true, const show_channel = params.where.show_channel
system_source: true, const eventTimeStart = params.where.event_time?.value?.[0] || params.where.created_time?.value?.[0] || params.where.created_date?.value?.[0]
event_type: true, const eventTimeEnd = params.where.event_time?.value?.[1] || params.where.created_time?.value?.[1] || params.where.created_date?.value?.[1]
event_time: true, 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
} }
}) })
const total = await this.prisma.clue_burial_point_record.count({ where }) return {
return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', total, data: result } 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}`;
} }
} }
\ No newline at end of file \ No newline at end of file
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('script_record_browse_log') // 话术萃取
export class DB1_Table1Entity {
@Column({ type: 'json' })
@PrimaryGeneratedColumn()
id: number
@Column({ name: 'staff_uuid' })
staff_uuid: string;
@Column({ name: 'staff_phone' })
staff_phone: string
@Column({ name: 'staff_name' })
staff_name: string
@Column({ name: 'merchant_id' })
merchant_id: string
@Column({ name: 'merchant_name' })
merchant_name: string
@Column({ name: 'created_by' })
created_by: string
@Column({ name: 'created_time' })
created_time: string
@Column({ name: 'start_time' })
start_time: string
@Column({ name: 'sustain_time' })
sustain_time: string
}
\ No newline at end of file \ No newline at end of file
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('dj_car_life_customer_dynamic_record') // 培训资料、营销素材、场景集市
export class DB1_Table2Entity {
@Column({ type: 'json' })
@PrimaryGeneratedColumn()
id: number
@Column({ name: 'customer_account_uuid' })
customer_account_uuid: string;
@Column({ name: 'customer_account_name' })
customer_account_name: string
@Column({ name: 'customer_mobile' })
customer_mobile: string
@Column({ name: 'goods_id' })
goods_id: string
@Column({ name: 'goods_type' })
goods_type: number
@Column({ name: 'enter_date' })
enter_date: string
@Column({ name: 'leave_date' })
leave_date: string
@Column({ name: 'browse_duration' })
browse_duration: string
@Column({ name: 'merchant_id' })
merchant_id: string
@Column({ name: 'created_by' })
created_by: string
@Column({ name: 'merchant_name' })
merchant_name: string
@Column({ name: 'created_date' })
created_date: string
@Column({ name: 'updated_date' })
updated_date: string
@Column({ name: 'deleted_flag' })
deleted_flag: string
}
\ No newline at end of file \ No newline at end of file
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('dj_car_life_material_info') // 培训资料、营销素材、场景集市子表
export class DB1_Table4Entity {
@Column({ type: 'json' })
@PrimaryGeneratedColumn()
id: number
@Column({ name: 'title' })
title: string;
@Column({ name: 'type' })
type: string
@Column({ name: 'cover' })
cover: string
@Column({ name: 'subtitle' })
subtitle: string
@Column({ name: 'scene' })
scene: number
@Column({ name: 'show_channel' })
show_channel: string
@Column({ name: 'show_merchant' })
show_merchant: string
@Column({ name: 'status' })
status: string
@Column({ name: 'created_by' })
created_by: string
@Column({ name: 'created_date' })
created_date: string
@Column({ name: 'updated_by' })
updated_by: string
@Column({ name: 'updated_date' })
updated_date: string
@Column({ name: 'deleted_flag' })
deleted_flag: string
}
\ No newline at end of file \ No newline at end of file
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('clue_burial_point_record') // 实际表名
export class DB2_Table3Entity {
@Column({ type: 'json' })
@PrimaryGeneratedColumn()
id: number
@Column({ name: 'event_code' })
event_code: string;
@Column({ name: 'scene' })
scene: string
@Column({ name: 'login_account' })
login_account: string
@Column({ name: 'event_time' })
event_time: string
@Column({ name: 'system_source' })
system_source: string
@Column({ name: 'event_type' })
event_type: string
}
\ No newline at end of file \ No newline at end of file
import { Controller, Get, UsePipes, Query, Logger } from '@nestjs/common';
import { DialogueService } from './dialogue.service';
import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
import { StatisticsQueryDto } from 'src/dto/dialogue.dto';
@ApiTags('话术萃取')
@Controller('dialogue')
@UsePipes(new ValidationPipe()) // 使用管道验证
export class DialogueController {
constructor(private readonly dialogueService: DialogueService) {}
@Get('statistics')
@UsePipes(new PagesPipe())
@ApiOperation({ summary: '总数统计' })
async getTotal(@Query() query: StatisticsQueryDto) {
const { startDate = '2025-05-12', endDate = '2025-05-18' } = query;
return this.dialogueService.getTotal(startDate, endDate);
}
}
\ No newline at end of file \ No newline at end of file
import { Module } from '@nestjs/common';
import { DialogueController } from './dialogue.controller';
import { DialogueService } from './dialogue.service';
import { PrismaModule } from 'nestjs-prisma';
@Module({
imports: [PrismaModule],
controllers: [DialogueController],
providers: [DialogueService],
exports: [DialogueService],
})
export class DialogueModule {}
\ No newline at end of file \ No newline at end of file
import { Inject, Injectable } from '@nestjs/common';
import { PrismaService } from 'nestjs-prisma'
@Injectable()
export class DialogueService {
constructor(@Inject(PrismaService) private prisma: PrismaService) { }
// 总浏览次数
async getTotal(startDate: string, endDate: string) {
return this.prisma.$queryRaw`SELECT SUM(总浏览次数) as total,SUM(总浏览批次数) as batchTotal,SUM(总浏览人数) as peopleTotal FROM (
-- 总浏览次数数
SELECT COUNT(1) 总浏览次数,0 总浏览批次数,0 总浏览人数 FROM script_record_browse_log
WHERE DATE_FORMAT(created_time,'%Y-%m-%d') BETWEEN ${startDate} AND ${endDate}
UNION ALL
-- 总浏览批
SELECT COUNT(1) 总浏览次数,COUNT(*) 总浏览批次数,0 总浏览人数 FROM (
SELECT start_time,COUNT(1) FROM script_record_browse_log
WHERE DATE_FORMAT(created_time,'%Y-%m-%d') BETWEEN ${startDate} AND ${endDate} GROUP BY start_time) t
UNION ALL
-- 总浏览人数
SELECT 0 总浏览次数,0 总浏览批次数,COUNT(*) 总浏览人数 FROM (
SELECT staff_phone,COUNT(1) FROM script_record_browse_log
WHERE DATE_FORMAT(created_time,'%Y-%m-%d') BETWEEN ${startDate} AND ${endDate} GROUP BY staff_phone) t) tab;`
}
}
\ No newline at end of file \ No newline at end of file
declare namespace ClueTypes { declare namespace ClueTypes {
interface IQueryClue { interface IQueryClue {
event_code?: String, event_code?: String,
scene?: Number, scene?: any,
login_account?: Number, login_account?: any,
event_time?: Date | string, system_source?: any,
system_source?: Number, event_type?: any,
event_type?: Number page?: any,
pageSize?: any,
event_time_start?: string | Date,
event_time_end?: string | Date
} }
interface IClue { interface IClue {
......
...@@ -10,7 +10,8 @@ ...@@ -10,7 +10,8 @@
"outDir": "./dist", "outDir": "./dist",
"baseUrl": "./", "baseUrl": "./",
"incremental": true, "incremental": true,
"resolveJsonModule": true "resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
}, },
"exclude": ["node_modules", "dist"] "exclude": ["node_modules", "dist"]
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!