feat: 添加投标信息按日期范围更新功能及AI推荐持久化
添加按日期范围更新投标信息的功能,支持日期范围选择和数据更新 实现AI推荐结果的持久化存储和加载功能 优化日期范围选择器的本地存储功能
This commit is contained in:
@@ -43,6 +43,7 @@
|
||||
:loading="loading"
|
||||
:is-crawling="isCrawling"
|
||||
@refresh="fetchData"
|
||||
@update-bids="updateBidsByDateRange"
|
||||
/>
|
||||
|
||||
<DashboardAI
|
||||
@@ -73,6 +74,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { DataBoard, Document, Setting, MagicStick } from '@element-plus/icons-vue'
|
||||
import Dashboard from './components/Dashboard.vue'
|
||||
import DashboardAI from './components/Dashboard-AI.vue'
|
||||
@@ -142,6 +144,26 @@ const fetchData = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 根据日期范围更新投标信息
|
||||
const updateBidsByDateRange = async (startDate: string, endDate?: string) => {
|
||||
loading.value = true
|
||||
try {
|
||||
const params: any = { startDate }
|
||||
if (endDate) {
|
||||
params.endDate = endDate
|
||||
}
|
||||
|
||||
const response = await axios.get('/api/bids/by-date-range', { params })
|
||||
todayBids.value = response.data
|
||||
ElMessage.success(`更新成功,共 ${response.data.length} 条数据`)
|
||||
} catch (error) {
|
||||
console.error('Failed to update bids by date range:', error)
|
||||
ElMessage.error('更新失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchData()
|
||||
})
|
||||
|
||||
@@ -106,7 +106,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { MagicStick, Loading, InfoFilled, List } from '@element-plus/icons-vue'
|
||||
@@ -132,6 +132,37 @@ const showAllBids = ref(false)
|
||||
const bidsLoading = ref(false)
|
||||
const bidsByDateRange = ref<any[]>([])
|
||||
|
||||
// 从 localStorage 加载保存的日期范围
|
||||
const loadSavedDateRange = () => {
|
||||
const saved = localStorage.getItem('dashboardAI_dateRange')
|
||||
if (saved) {
|
||||
try {
|
||||
dateRange.value = JSON.parse(saved)
|
||||
} catch (e) {
|
||||
console.error('Failed to parse saved date range:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 监听日期范围变化并保存到 localStorage
|
||||
watch(dateRange, (newDateRange) => {
|
||||
localStorage.setItem('dashboardAI_dateRange', JSON.stringify(newDateRange))
|
||||
}, { deep: true })
|
||||
|
||||
// 从数据库加载最新的 AI 推荐
|
||||
const loadLatestRecommendations = async () => {
|
||||
try {
|
||||
const response = await axios.get('/api/ai/latest-recommendations')
|
||||
aiRecommendations.value = response.data
|
||||
} catch (error) {
|
||||
console.error('Failed to load latest recommendations:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化时加载保存的日期范围和最新的 AI 推荐
|
||||
loadSavedDateRange()
|
||||
loadLatestRecommendations()
|
||||
|
||||
// 设置日期范围为最近3天
|
||||
const setLast3Days = () => {
|
||||
const endDate = new Date()
|
||||
@@ -181,7 +212,7 @@ const fetchAIRecommendations = async () => {
|
||||
})
|
||||
|
||||
// 根据 title 从 bidsByDateRange 中更新 url 和 source
|
||||
aiRecommendations.value = response.data.map((rec: any) => {
|
||||
const recommendations = response.data.map((rec: any) => {
|
||||
const bid = bidsByDateRange.value.find(b => b.title === rec.title)
|
||||
return {
|
||||
title: rec.title,
|
||||
@@ -191,6 +222,13 @@ const fetchAIRecommendations = async () => {
|
||||
}
|
||||
})
|
||||
|
||||
aiRecommendations.value = recommendations
|
||||
|
||||
// 保存推荐结果到数据库
|
||||
await axios.post('/api/ai/save-recommendations', {
|
||||
recommendations
|
||||
})
|
||||
|
||||
ElMessage.success('AI 推荐获取成功')
|
||||
} catch (error: any) {
|
||||
ElMessage.error('获取 AI 推荐失败')
|
||||
@@ -247,9 +285,6 @@ const getConfidenceType = (confidence: number) => {
|
||||
if (confidence >= 70) return 'warning'
|
||||
return 'info'
|
||||
}
|
||||
|
||||
// 初始化时设置默认日期范围为最近3天
|
||||
setLast3Days()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -56,6 +56,10 @@
|
||||
/>
|
||||
<el-button type="primary" @click="setLast3Days">3天</el-button>
|
||||
<el-button type="primary" @click="setLast7Days">7天</el-button>
|
||||
<el-button type="success" :loading="updating" @click="updateBidsByDateRange">
|
||||
<el-icon style="margin-right: 5px"><Refresh /></el-icon>
|
||||
更新
|
||||
</el-button>
|
||||
<el-select
|
||||
v-model="selectedKeywords"
|
||||
multiple
|
||||
@@ -107,14 +111,33 @@ const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
crawl: []
|
||||
refresh: []
|
||||
updateBids: [startDate: string, endDate?: string]
|
||||
}>()
|
||||
|
||||
const selectedKeywords = ref<string[]>([])
|
||||
const dateRange = ref<[string, string] | null>(null)
|
||||
const crawling = ref(false)
|
||||
const updating = ref(false)
|
||||
const highPriorityCollapsed = ref(false)
|
||||
const isInitialized = ref(false)
|
||||
|
||||
// 从 localStorage 加载保存的日期范围
|
||||
const loadSavedDateRange = () => {
|
||||
const saved = localStorage.getItem('dashboard_dateRange')
|
||||
if (saved) {
|
||||
try {
|
||||
dateRange.value = JSON.parse(saved)
|
||||
} catch (e) {
|
||||
console.error('Failed to parse saved date range:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 监听日期范围变化并保存到 localStorage
|
||||
watch(dateRange, (newDateRange) => {
|
||||
localStorage.setItem('dashboard_dateRange', JSON.stringify(newDateRange))
|
||||
}, { deep: true })
|
||||
|
||||
// 切换 High Priority Bids 的折叠状态
|
||||
const toggleHighPriority = () => {
|
||||
highPriorityCollapsed.value = !highPriorityCollapsed.value
|
||||
@@ -274,6 +297,36 @@ const setLast7Days = () => {
|
||||
// 只在手动点击按钮时显示提示,初始化时不显示
|
||||
}
|
||||
|
||||
// 根据日期范围更新投标信息
|
||||
const updateBidsByDateRange = async () => {
|
||||
if (!dateRange.value || dateRange.value.length !== 2) {
|
||||
ElMessage.warning('请先选择日期范围')
|
||||
return
|
||||
}
|
||||
|
||||
updating.value = true
|
||||
try {
|
||||
const [startDate, endDate] = dateRange.value
|
||||
|
||||
// 检查 endDate 是否是今天
|
||||
const today = new Date()
|
||||
const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
|
||||
|
||||
// 如果 endDate 是今天,则不传递 endDate 参数(不限制截止时间)
|
||||
if (endDate === todayStr) {
|
||||
emit('updateBids', startDate)
|
||||
} else {
|
||||
emit('updateBids', startDate, endDate)
|
||||
}
|
||||
|
||||
ElMessage.success('更新成功')
|
||||
} catch (error) {
|
||||
ElMessage.error('更新失败')
|
||||
} finally {
|
||||
updating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleCrawl = async () => {
|
||||
if (props.isCrawling) {
|
||||
ElMessage.warning('Crawl is already running')
|
||||
@@ -291,11 +344,14 @@ const handleCrawl = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化时加载保存的关键字
|
||||
// 初始化时加载保存的关键字和日期范围
|
||||
loadSavedKeywords()
|
||||
loadSavedDateRange()
|
||||
|
||||
// 初始化时设置默认日期范围为最近3天
|
||||
// 如果没有保存的日期范围,则设置默认为最近3天
|
||||
if (!dateRange.value) {
|
||||
setLast3Days()
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Controller, Post, Body } from '@nestjs/common';
|
||||
import { AiService } from './ai.service';
|
||||
import { Controller, Post, Body, Get } from '@nestjs/common';
|
||||
import { AiService, AIRecommendation } from './ai.service';
|
||||
|
||||
export class BidDataDto {
|
||||
title: string;
|
||||
@@ -9,6 +9,10 @@ export class BidsRequestDto {
|
||||
bids: BidDataDto[];
|
||||
}
|
||||
|
||||
export class SaveRecommendationsDto {
|
||||
recommendations: AIRecommendation[];
|
||||
}
|
||||
|
||||
@Controller('api/ai')
|
||||
export class AiController {
|
||||
constructor(private readonly aiService: AiService) {}
|
||||
@@ -17,4 +21,15 @@ export class AiController {
|
||||
async getRecommendations(@Body() request: BidsRequestDto) {
|
||||
return this.aiService.getRecommendations(request.bids);
|
||||
}
|
||||
|
||||
@Post('save-recommendations')
|
||||
async saveRecommendations(@Body() request: SaveRecommendationsDto) {
|
||||
await this.aiService.saveRecommendations(request.recommendations);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Get('latest-recommendations')
|
||||
async getLatestRecommendations() {
|
||||
return this.aiService.getLatestRecommendations();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AiController } from './ai.controller';
|
||||
import { AiService } from './ai.service';
|
||||
import { AiRecommendation } from './entities/ai-recommendation.entity';
|
||||
import { BidItem } from '../bids/entities/bid-item.entity';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
TypeOrmModule.forFeature([AiRecommendation, BidItem]),
|
||||
],
|
||||
controllers: [AiController],
|
||||
providers: [AiService],
|
||||
exports: [AiService],
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import OpenAI from 'openai';
|
||||
import { PromptString } from './Prompt';
|
||||
import { AiRecommendation as AiRecommendationEntity } from './entities/ai-recommendation.entity';
|
||||
import { BidItem } from '../bids/entities/bid-item.entity';
|
||||
|
||||
export interface BidDataDto {
|
||||
title: string;
|
||||
@@ -19,7 +23,13 @@ export class AiService {
|
||||
private readonly logger = new Logger(AiService.name);
|
||||
private openai: OpenAI;
|
||||
|
||||
constructor(private readonly configService: ConfigService) {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
@InjectRepository(AiRecommendationEntity)
|
||||
private readonly aiRecommendationRepository: Repository<AiRecommendationEntity>,
|
||||
@InjectRepository(BidItem)
|
||||
private readonly bidItemRepository: Repository<BidItem>,
|
||||
) {
|
||||
const apiKey = this.configService.get<string>('ARK_API_KEY');
|
||||
this.openai = new OpenAI({
|
||||
apiKey: apiKey || '',
|
||||
@@ -80,4 +90,57 @@ ${JSON.stringify(bids.map(b => b.title), null, 2)}`;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async saveRecommendations(recommendations: AIRecommendation[]): Promise<void> {
|
||||
this.logger.log('开始保存 AI 推荐结果');
|
||||
|
||||
try {
|
||||
// 删除所有旧的推荐
|
||||
await this.aiRecommendationRepository.clear();
|
||||
|
||||
// 保存新的推荐结果(只保存 title 和 confidence)
|
||||
const entities = recommendations.map(rec => {
|
||||
const entity = new AiRecommendationEntity();
|
||||
entity.title = rec.title;
|
||||
entity.confidence = rec.confidence;
|
||||
return entity;
|
||||
});
|
||||
|
||||
await this.aiRecommendationRepository.save(entities);
|
||||
this.logger.log(`成功保存 ${entities.length} 条 AI 推荐结果`);
|
||||
} catch (error) {
|
||||
this.logger.error('保存 AI 推荐失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getLatestRecommendations(): Promise<AIRecommendation[]> {
|
||||
this.logger.log('获取最新的 AI 推荐结果');
|
||||
|
||||
try {
|
||||
const entities = await this.aiRecommendationRepository.find({
|
||||
order: { confidence: 'DESC' }
|
||||
});
|
||||
|
||||
// 从 bid-items 表获取 url 和 source
|
||||
const result: AIRecommendation[] = [];
|
||||
for (const entity of entities) {
|
||||
const bidItem = await this.bidItemRepository.findOne({
|
||||
where: { title: entity.title }
|
||||
});
|
||||
|
||||
result.push({
|
||||
title: entity.title,
|
||||
url: bidItem?.url || '',
|
||||
source: bidItem?.source || '',
|
||||
confidence: entity.confidence
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.logger.error('获取最新 AI 推荐失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
16
src/ai/entities/ai-recommendation.entity.ts
Normal file
16
src/ai/entities/ai-recommendation.entity.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';
|
||||
|
||||
@Entity('ai_recommendations')
|
||||
export class AiRecommendation {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
title: string;
|
||||
|
||||
@Column({ type: 'int' })
|
||||
confidence: number;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { BidItem } from '../bids/entities/bid-item.entity';
|
||||
import { Keyword } from '../keywords/keyword.entity';
|
||||
import { AiRecommendation } from '../ai/entities/ai-recommendation.entity';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -16,7 +17,7 @@ import { Keyword } from '../keywords/keyword.entity';
|
||||
username: configService.get<string>('DATABASE_USERNAME', 'root'),
|
||||
password: configService.get<string>('DATABASE_PASSWORD', 'root'),
|
||||
database: configService.get<string>('DATABASE_NAME', 'bidding'),
|
||||
entities: [BidItem, Keyword],
|
||||
entities: [BidItem, Keyword, AiRecommendation],
|
||||
synchronize: configService.get<boolean>('DATABASE_SYNCHRONIZE', true),
|
||||
}),
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user