clue.service.ts 7.22 KB
// 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}`;
	}
}