From 23052b8afd5da7f9e91175b58b82cb5dda72cd7d Mon Sep 17 00:00:00 2001 From: william Date: Mon, 2 Nov 2026 10:32:18 +0100 Subject: [PATCH] feat(veille): implement l'Agent de veille autonome et le profil freelance - Nouveau module freelance-profile (GET/PATCH /profile, upsert implicite au premier acces) - Nouveau module veille : cron quotidien (@nestjs/schedule), frequence quotidienne/hebdomadaire par profil (explicite ou inferee par mots-cles de domaines volatils) - Garde-fous de generation de signal recalcules cote code : minimum 3 sources independantes, score de pertinence >= max(0.7, seuil du profil), exclusion blacklist, dedoublonnage 30 jours par (profil, competence, type) - GET /veille/signals (priorite obsolete > refresh > emerging puis pertinence), POST /veille/signals/:id/action avec train (demarre une session + Agent 1 avec un message synthetique)/snooze (resurgence codee dans action_taken, pas de colonne dediee)/dismiss (marque le signal et le profil) - Ajoute @nestjs/schedule en dependance (version 6.1.3, compatible CommonJS/Jest - la 12.x est ESM-only et casse Jest) Co-Authored-By: Claude Sonnet 5 --- Max API/package-lock.json | 46 +++ Max API/package.json | 1 + Max API/src/app.module.ts | 6 + .../dto/freelance-profile-response.dto.ts | 72 ++++ .../dto/update-freelance-profile.dto.ts | 97 +++++ .../freelance-profile.controller.spec.ts | 41 ++ .../freelance-profile.controller.ts | 43 ++ .../freelance-profile.module.ts | 10 + .../freelance-profile.service.spec.ts | 82 ++++ .../freelance-profile.service.ts | 66 +++ .../dto/veille-signal-action-result.dto.ts | 12 + .../veille/dto/veille-signal-action.dto.ts | 8 + .../veille/dto/veille-signal-response.dto.ts | 32 ++ Max API/src/veille/veille.controller.spec.ts | 40 ++ Max API/src/veille/veille.controller.ts | 56 +++ Max API/src/veille/veille.module.ts | 11 + Max API/src/veille/veille.prompt.ts | 39 ++ Max API/src/veille/veille.service.spec.ts | 376 ++++++++++++++++++ Max API/src/veille/veille.service.ts | 354 +++++++++++++++++ 19 files changed, 1392 insertions(+) create mode 100644 Max API/src/freelance-profile/dto/freelance-profile-response.dto.ts create mode 100644 Max API/src/freelance-profile/dto/update-freelance-profile.dto.ts create mode 100644 Max API/src/freelance-profile/freelance-profile.controller.spec.ts create mode 100644 Max API/src/freelance-profile/freelance-profile.controller.ts create mode 100644 Max API/src/freelance-profile/freelance-profile.module.ts create mode 100644 Max API/src/freelance-profile/freelance-profile.service.spec.ts create mode 100644 Max API/src/freelance-profile/freelance-profile.service.ts create mode 100644 Max API/src/veille/dto/veille-signal-action-result.dto.ts create mode 100644 Max API/src/veille/dto/veille-signal-action.dto.ts create mode 100644 Max API/src/veille/dto/veille-signal-response.dto.ts create mode 100644 Max API/src/veille/veille.controller.spec.ts create mode 100644 Max API/src/veille/veille.controller.ts create mode 100644 Max API/src/veille/veille.module.ts create mode 100644 Max API/src/veille/veille.prompt.ts create mode 100644 Max API/src/veille/veille.service.spec.ts create mode 100644 Max API/src/veille/veille.service.ts diff --git a/Max API/package-lock.json b/Max API/package-lock.json index 5ea86f0..f406b1b 100644 --- a/Max API/package-lock.json +++ b/Max API/package-lock.json @@ -15,6 +15,7 @@ "@nestjs/core": "^11.0.1", "@nestjs/jwt": "11.0.2", "@nestjs/platform-express": "^11.0.1", + "@nestjs/schedule": "^6.1.3", "@nestjs/swagger": "^11.4.7", "@prisma/client": "6.19.3", "bcrypt": "^6.0.0", @@ -2388,6 +2389,19 @@ "@nestjs/core": "^11.0.0" } }, + "node_modules/@nestjs/schedule": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@nestjs/schedule/-/schedule-6.1.3.tgz", + "integrity": "sha512-RflMFOpR16Dwd1jAUbeB4mfGTCh65fvEdL4mSjQPJChpkRGRjIXjb+6YQcK2faQrVT60c9DmLmoVR7/ONCtuYQ==", + "license": "MIT", + "dependencies": { + "cron": "4.4.0" + }, + "peerDependencies": { + "@nestjs/common": "^10.0.0 || ^11.0.0", + "@nestjs/core": "^10.0.0 || ^11.0.0" + } + }, "node_modules/@nestjs/schematics": { "version": "11.1.0", "resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.1.0.tgz", @@ -3321,6 +3335,12 @@ "@types/node": "*" } }, + "node_modules/@types/luxon": { + "version": "3.7.6", + "resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.7.6.tgz", + "integrity": "sha512-6KSjliQAXK8ZLgFQO4B7iE4Rpf/B3rItzCFuXezBY/XIAGxOdLd7vRNK9/StRPwiS/yJsVbB7HKpW46B8tcEuQ==", + "license": "MIT" + }, "node_modules/@types/methods": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", @@ -5359,6 +5379,23 @@ "dev": true, "license": "MIT" }, + "node_modules/cron": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/cron/-/cron-4.4.0.tgz", + "integrity": "sha512-fkdfq+b+AHI4cKdhZlppHveI/mgz2qpiYxcm+t5E5TsxX7QrLS1VE0+7GENEk9z0EeGPcpSciGv6ez24duWhwQ==", + "license": "MIT", + "dependencies": { + "@types/luxon": "~3.7.0", + "luxon": "~3.7.0" + }, + "engines": { + "node": ">=18.x" + }, + "funding": { + "type": "ko-fi", + "url": "https://ko-fi.com/intcreator" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -8035,6 +8072,15 @@ "yallist": "^3.0.2" } }, + "node_modules/luxon": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz", + "integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/magic-string": { "version": "0.30.17", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz", diff --git a/Max API/package.json b/Max API/package.json index 7dd567c..bb34e4f 100644 --- a/Max API/package.json +++ b/Max API/package.json @@ -37,6 +37,7 @@ "@nestjs/core": "^11.0.1", "@nestjs/jwt": "11.0.2", "@nestjs/platform-express": "^11.0.1", + "@nestjs/schedule": "^6.1.3", "@nestjs/swagger": "^11.4.7", "@prisma/client": "6.19.3", "bcrypt": "^6.0.0", diff --git a/Max API/src/app.module.ts b/Max API/src/app.module.ts index ba460de..ca7942d 100644 --- a/Max API/src/app.module.ts +++ b/Max API/src/app.module.ts @@ -1,22 +1,28 @@ import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; +import { ScheduleModule } from '@nestjs/schedule'; import { ApiKeysModule } from './api-keys/api-keys.module'; import { AppController } from './app.controller'; import { AuthModule } from './auth/auth.module'; import { CryptoModule } from './common/crypto/crypto.module'; +import { FreelanceProfileModule } from './freelance-profile/freelance-profile.module'; import { PrismaModule } from './prisma/prisma.module'; import { SessionsModule } from './sessions/sessions.module'; import { UsersModule } from './users/users.module'; +import { VeilleModule } from './veille/veille.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), + ScheduleModule.forRoot(), PrismaModule, CryptoModule, UsersModule, ApiKeysModule, AuthModule, SessionsModule, + FreelanceProfileModule, + VeilleModule, ], controllers: [AppController], }) diff --git a/Max API/src/freelance-profile/dto/freelance-profile-response.dto.ts b/Max API/src/freelance-profile/dto/freelance-profile-response.dto.ts new file mode 100644 index 0000000..f393693 --- /dev/null +++ b/Max API/src/freelance-profile/dto/freelance-profile-response.dto.ts @@ -0,0 +1,72 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; + +export class FreelanceProfileResponseDto { + @ApiProperty() + id!: number; + + @ApiPropertyOptional() + displayName!: string | null; + + @ApiPropertyOptional() + positioning!: string | null; + + @ApiProperty({ type: [String] }) + domains!: string[]; + + @ApiProperty({ type: [String] }) + stack!: string[]; + + @ApiProperty({ type: [String] }) + targetMissionTypes!: string[]; + + @ApiProperty({ type: [String] }) + targetSectors!: string[]; + + @ApiPropertyOptional() + seniorityLevel!: string | null; + + @ApiPropertyOptional() + tjm!: number | null; + + @ApiPropertyOptional() + experienceYears!: number | null; + + @ApiProperty({ type: [String] }) + certifications!: string[]; + + @ApiPropertyOptional() + workFormat!: string | null; + + @ApiPropertyOptional() + geographicZone!: string | null; + + @ApiProperty({ type: [String] }) + competencesAcquired!: string[]; + + @ApiProperty({ type: [String] }) + competencesInProgress!: string[]; + + @ApiProperty({ type: [String] }) + competencesDismissed!: string[]; + + @ApiPropertyOptional() + lastTrainingAt!: Date | null; + + @ApiPropertyOptional({ enum: ['daily', 'weekly'] }) + veilleFrequency!: string | null; + + @ApiProperty({ type: [String] }) + veilleExtraTopics!: string[]; + + @ApiProperty({ type: [String] }) + veilleBlacklist!: string[]; + + @ApiPropertyOptional() + veilleRelevanceThreshold!: number | null; + + @ApiProperty() + veilleNotificationsEnabled!: boolean; + + @ApiPropertyOptional() + lastVeilleAt!: Date | null; +} diff --git a/Max API/src/freelance-profile/dto/update-freelance-profile.dto.ts b/Max API/src/freelance-profile/dto/update-freelance-profile.dto.ts new file mode 100644 index 0000000..2f74925 --- /dev/null +++ b/Max API/src/freelance-profile/dto/update-freelance-profile.dto.ts @@ -0,0 +1,97 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { + IsArray, + IsBoolean, + IsNumber, + IsOptional, + IsString, +} from 'class-validator'; + +/** Champs renseignes manuellement par le freelance - jamais les champs geres par le pipeline + * (competencesAcquired/InProgress/Dismissed, lastTrainingAt, lastVeilleAt). */ +export class UpdateFreelanceProfileDto { + @ApiPropertyOptional() + @IsOptional() + @IsString() + displayName?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + positioning?: string; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + domains?: string[]; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + stack?: string[]; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + targetMissionTypes?: string[]; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + targetSectors?: string[]; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + seniorityLevel?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsNumber() + tjm?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsNumber() + experienceYears?: number; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + certifications?: string[]; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + workFormat?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + geographicZone?: string; + + @ApiPropertyOptional({ enum: ['daily', 'weekly'] }) + @IsOptional() + @IsString() + veilleFrequency?: string; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + veilleExtraTopics?: string[]; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + veilleBlacklist?: string[]; + + @ApiPropertyOptional() + @IsOptional() + @IsNumber() + veilleRelevanceThreshold?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsBoolean() + veilleNotificationsEnabled?: boolean; +} diff --git a/Max API/src/freelance-profile/freelance-profile.controller.spec.ts b/Max API/src/freelance-profile/freelance-profile.controller.spec.ts new file mode 100644 index 0000000..1c8c146 --- /dev/null +++ b/Max API/src/freelance-profile/freelance-profile.controller.spec.ts @@ -0,0 +1,41 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { FreelanceProfileController } from './freelance-profile.controller'; +import { FreelanceProfileService } from './freelance-profile.service'; + +describe('FreelanceProfileController', () => { + let controller: FreelanceProfileController; + const freelanceProfileService = { getOrCreate: jest.fn(), update: jest.fn() }; + const request = { + user: { sub: 7, email: 'w@example.com' }, + } as AuthenticatedRequest; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + controllers: [FreelanceProfileController], + providers: [ + { provide: FreelanceProfileService, useValue: freelanceProfileService }, + ], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ canActivate: () => true }) + .compile(); + + controller = module.get(FreelanceProfileController); + }); + + it('should fetch the profile of the authenticated user', async () => { + freelanceProfileService.getOrCreate.mockResolvedValueOnce({ id: 1 }); + await controller.getProfile(request); + expect(freelanceProfileService.getOrCreate).toHaveBeenCalledWith(7); + }); + + it('should forward a profile update to the service', async () => { + freelanceProfileService.update.mockResolvedValueOnce({ id: 1 }); + const dto = { displayName: 'William' }; + await controller.updateProfile(dto, request); + expect(freelanceProfileService.update).toHaveBeenCalledWith(7, dto); + }); +}); diff --git a/Max API/src/freelance-profile/freelance-profile.controller.ts b/Max API/src/freelance-profile/freelance-profile.controller.ts new file mode 100644 index 0000000..01305ec --- /dev/null +++ b/Max API/src/freelance-profile/freelance-profile.controller.ts @@ -0,0 +1,43 @@ +import { Body, Controller, Get, Patch, Req, UseGuards } from '@nestjs/common'; +import { + ApiBearerAuth, + ApiOperation, + ApiResponse, + ApiTags, +} from '@nestjs/swagger'; +import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { FreelanceProfileResponseDto } from './dto/freelance-profile-response.dto'; +import { UpdateFreelanceProfileDto } from './dto/update-freelance-profile.dto'; +import { FreelanceProfileService } from './freelance-profile.service'; + +@ApiTags('freelance-profile') +@ApiBearerAuth() +@UseGuards(JwtAuthGuard) +@Controller('profile') +export class FreelanceProfileController { + constructor( + private readonly freelanceProfileService: FreelanceProfileService, + ) {} + + @Get() + @ApiOperation({ + summary: "Recuperer le profil freelance de l'utilisateur authentifie", + }) + @ApiResponse({ status: 200, type: FreelanceProfileResponseDto }) + getProfile( + @Req() request: AuthenticatedRequest, + ): Promise { + return this.freelanceProfileService.getOrCreate(request.user.sub); + } + + @Patch() + @ApiOperation({ summary: 'Mettre a jour le profil freelance' }) + @ApiResponse({ status: 200, type: FreelanceProfileResponseDto }) + updateProfile( + @Body() dto: UpdateFreelanceProfileDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.freelanceProfileService.update(request.user.sub, dto); + } +} diff --git a/Max API/src/freelance-profile/freelance-profile.module.ts b/Max API/src/freelance-profile/freelance-profile.module.ts new file mode 100644 index 0000000..5f6ce4d --- /dev/null +++ b/Max API/src/freelance-profile/freelance-profile.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { FreelanceProfileController } from './freelance-profile.controller'; +import { FreelanceProfileService } from './freelance-profile.service'; + +@Module({ + controllers: [FreelanceProfileController], + providers: [FreelanceProfileService], + exports: [FreelanceProfileService], +}) +export class FreelanceProfileModule {} diff --git a/Max API/src/freelance-profile/freelance-profile.service.spec.ts b/Max API/src/freelance-profile/freelance-profile.service.spec.ts new file mode 100644 index 0000000..38b4203 --- /dev/null +++ b/Max API/src/freelance-profile/freelance-profile.service.spec.ts @@ -0,0 +1,82 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { PrismaService } from '../prisma/prisma.service'; +import { FreelanceProfileService } from './freelance-profile.service'; + +describe('FreelanceProfileService', () => { + let service: FreelanceProfileService; + const prisma = { freelanceProfile: { upsert: jest.fn() } }; + + const storedProfile = { + id: 1, + userId: 7, + displayName: null, + positioning: null, + domains: ['Facturation'], + stack: null, + targetMissionTypes: null, + targetSectors: null, + seniorityLevel: null, + tjm: null, + experienceYears: null, + certifications: null, + workFormat: null, + geographicZone: null, + competencesAcquired: null, + competencesInProgress: null, + competencesDismissed: null, + lastTrainingAt: null, + veilleFrequency: null, + veilleExtraTopics: null, + veilleBlacklist: null, + veilleRelevanceThreshold: null, + veilleNotificationsEnabled: true, + lastVeilleAt: null, + }; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + providers: [ + FreelanceProfileService, + { provide: PrismaService, useValue: prisma }, + ], + }).compile(); + + service = module.get(FreelanceProfileService); + }); + + describe('getOrCreate()', () => { + it('should upsert an empty profile and default every JSON array field to []', async () => { + prisma.freelanceProfile.upsert.mockResolvedValueOnce(storedProfile); + + const result = await service.getOrCreate(7); + + expect(prisma.freelanceProfile.upsert).toHaveBeenCalledWith({ + where: { userId: 7 }, + create: { userId: 7 }, + update: {}, + }); + expect(result.domains).toEqual(['Facturation']); + expect(result.stack).toEqual([]); + expect(result.competencesAcquired).toEqual([]); + }); + }); + + describe('update()', () => { + it('should upsert the provided fields', async () => { + prisma.freelanceProfile.upsert.mockResolvedValueOnce({ + ...storedProfile, + displayName: 'William', + }); + + const result = await service.update(7, { displayName: 'William' }); + + expect(prisma.freelanceProfile.upsert).toHaveBeenCalledWith({ + where: { userId: 7 }, + create: { userId: 7, displayName: 'William' }, + update: { displayName: 'William' }, + }); + expect(result.displayName).toBe('William'); + }); + }); +}); diff --git a/Max API/src/freelance-profile/freelance-profile.service.ts b/Max API/src/freelance-profile/freelance-profile.service.ts new file mode 100644 index 0000000..0919b64 --- /dev/null +++ b/Max API/src/freelance-profile/freelance-profile.service.ts @@ -0,0 +1,66 @@ +import { Injectable } from '@nestjs/common'; +import { FreelanceProfile } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; +import { FreelanceProfileResponseDto } from './dto/freelance-profile-response.dto'; +import { UpdateFreelanceProfileDto } from './dto/update-freelance-profile.dto'; + +@Injectable() +export class FreelanceProfileService { + constructor(private readonly prisma: PrismaService) {} + + /** Cree le profil au premier acces (aucun endpoint de creation dedie : un freelance a toujours + * un profil, vide par defaut, des sa premiere consultation). */ + async getOrCreate(userId: number): Promise { + const profile = await this.prisma.freelanceProfile.upsert({ + where: { userId }, + create: { userId }, + update: {}, + }); + return this.toResponse(profile); + } + + async update( + userId: number, + dto: UpdateFreelanceProfileDto, + ): Promise { + const profile = await this.prisma.freelanceProfile.upsert({ + where: { userId }, + create: { userId, ...dto }, + update: { ...dto }, + }); + return this.toResponse(profile); + } + + private toResponse(profile: FreelanceProfile): FreelanceProfileResponseDto { + return { + id: profile.id, + displayName: profile.displayName, + positioning: profile.positioning, + domains: (profile.domains as unknown as string[]) ?? [], + stack: (profile.stack as unknown as string[]) ?? [], + targetMissionTypes: + (profile.targetMissionTypes as unknown as string[]) ?? [], + targetSectors: (profile.targetSectors as unknown as string[]) ?? [], + seniorityLevel: profile.seniorityLevel, + tjm: profile.tjm, + experienceYears: profile.experienceYears, + certifications: (profile.certifications as unknown as string[]) ?? [], + workFormat: profile.workFormat, + geographicZone: profile.geographicZone, + competencesAcquired: + (profile.competencesAcquired as unknown as string[]) ?? [], + competencesInProgress: + (profile.competencesInProgress as unknown as string[]) ?? [], + competencesDismissed: + (profile.competencesDismissed as unknown as string[]) ?? [], + lastTrainingAt: profile.lastTrainingAt, + veilleFrequency: profile.veilleFrequency, + veilleExtraTopics: + (profile.veilleExtraTopics as unknown as string[]) ?? [], + veilleBlacklist: (profile.veilleBlacklist as unknown as string[]) ?? [], + veilleRelevanceThreshold: profile.veilleRelevanceThreshold, + veilleNotificationsEnabled: profile.veilleNotificationsEnabled, + lastVeilleAt: profile.lastVeilleAt, + }; + } +} diff --git a/Max API/src/veille/dto/veille-signal-action-result.dto.ts b/Max API/src/veille/dto/veille-signal-action-result.dto.ts new file mode 100644 index 0000000..c678161 --- /dev/null +++ b/Max API/src/veille/dto/veille-signal-action-result.dto.ts @@ -0,0 +1,12 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; + +/** "sessionId" n'est renseigne que pour l'action "train" - signal structure pour le frontend + * (voix uniquement, jamais de decision d'UI prise par un LLM) : sa seule presence suffit a savoir + * qu'une nouvelle session de formation vient d'etre demarree et doit etre ouverte. */ +export class VeilleSignalActionResultDto { + @ApiProperty() + actionTaken!: string; + + @ApiPropertyOptional() + sessionId?: number; +} diff --git a/Max API/src/veille/dto/veille-signal-action.dto.ts b/Max API/src/veille/dto/veille-signal-action.dto.ts new file mode 100644 index 0000000..9e23963 --- /dev/null +++ b/Max API/src/veille/dto/veille-signal-action.dto.ts @@ -0,0 +1,8 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsIn } from 'class-validator'; + +export class VeilleSignalActionDto { + @ApiProperty({ enum: ['train', 'snooze', 'dismiss'] }) + @IsIn(['train', 'snooze', 'dismiss']) + action!: 'train' | 'snooze' | 'dismiss'; +} diff --git a/Max API/src/veille/dto/veille-signal-response.dto.ts b/Max API/src/veille/dto/veille-signal-response.dto.ts new file mode 100644 index 0000000..b2ed9aa --- /dev/null +++ b/Max API/src/veille/dto/veille-signal-response.dto.ts @@ -0,0 +1,32 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; + +export class VeilleSignalSourceDto { + @ApiProperty() + title!: string; + + @ApiProperty() + url!: string; +} + +export class VeilleSignalResponseDto { + @ApiProperty() + id!: number; + + @ApiProperty({ enum: ['emerging', 'refresh', 'obsolete'] }) + type!: string; + + @ApiProperty() + competence!: string; + + @ApiProperty({ type: [VeilleSignalSourceDto] }) + sources!: VeilleSignalSourceDto[]; + + @ApiProperty() + relevanceScore!: number; + + @ApiPropertyOptional() + actionTaken!: string | null; + + @ApiProperty() + createdAt!: Date; +} diff --git a/Max API/src/veille/veille.controller.spec.ts b/Max API/src/veille/veille.controller.spec.ts new file mode 100644 index 0000000..91a118b --- /dev/null +++ b/Max API/src/veille/veille.controller.spec.ts @@ -0,0 +1,40 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { VeilleController } from './veille.controller'; +import { VeilleService } from './veille.service'; + +describe('VeilleController', () => { + let controller: VeilleController; + const veilleService = { getActiveSignals: jest.fn(), applyAction: jest.fn() }; + const request = { + user: { sub: 7, email: 'w@example.com' }, + } as AuthenticatedRequest; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + controllers: [VeilleController], + providers: [{ provide: VeilleService, useValue: veilleService }], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ canActivate: () => true }) + .compile(); + + controller = module.get(VeilleController); + }); + + it('should list the active signals for the authenticated user', async () => { + veilleService.getActiveSignals.mockResolvedValueOnce([]); + await controller.getSignals(request); + expect(veilleService.getActiveSignals).toHaveBeenCalledWith(7); + }); + + it('should forward a signal action to the service', async () => { + veilleService.applyAction.mockResolvedValueOnce({ + actionTaken: 'dismissed', + }); + await controller.applyAction(1, { action: 'dismiss' }, request); + expect(veilleService.applyAction).toHaveBeenCalledWith(1, 7, 'dismiss'); + }); +}); diff --git a/Max API/src/veille/veille.controller.ts b/Max API/src/veille/veille.controller.ts new file mode 100644 index 0000000..3742c4f --- /dev/null +++ b/Max API/src/veille/veille.controller.ts @@ -0,0 +1,56 @@ +import { + Body, + Controller, + Get, + Param, + ParseIntPipe, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import { + ApiBearerAuth, + ApiOperation, + ApiResponse, + ApiTags, +} from '@nestjs/swagger'; +import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { VeilleSignalActionDto } from './dto/veille-signal-action.dto'; +import { VeilleSignalActionResultDto } from './dto/veille-signal-action-result.dto'; +import { VeilleSignalResponseDto } from './dto/veille-signal-response.dto'; +import { VeilleService } from './veille.service'; + +@ApiTags('veille') +@ApiBearerAuth() +@UseGuards(JwtAuthGuard) +@Controller('veille') +export class VeilleController { + constructor(private readonly veilleService: VeilleService) {} + + @Get('signals') + @ApiOperation({ + summary: + 'Lister les signaux de veille actifs (priorite obsolete > refresh > emerging, puis pertinence)', + }) + @ApiResponse({ status: 200, type: [VeilleSignalResponseDto] }) + getSignals( + @Req() request: AuthenticatedRequest, + ): Promise { + return this.veilleService.getActiveSignals(request.user.sub); + } + + @Post('signals/:id/action') + @ApiOperation({ + summary: + "Agir sur un signal de veille : demarrer une formation (train), le repousser 14 jours (snooze) ou l'ecarter (dismiss)", + }) + @ApiResponse({ status: 201, type: VeilleSignalActionResultDto }) + applyAction( + @Param('id', ParseIntPipe) id: number, + @Body() dto: VeilleSignalActionDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.veilleService.applyAction(id, request.user.sub, dto.action); + } +} diff --git a/Max API/src/veille/veille.module.ts b/Max API/src/veille/veille.module.ts new file mode 100644 index 0000000..e404c75 --- /dev/null +++ b/Max API/src/veille/veille.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { SessionsModule } from '../sessions/sessions.module'; +import { VeilleController } from './veille.controller'; +import { VeilleService } from './veille.service'; + +@Module({ + imports: [SessionsModule], + controllers: [VeilleController], + providers: [VeilleService], +}) +export class VeilleModule {} diff --git a/Max API/src/veille/veille.prompt.ts b/Max API/src/veille/veille.prompt.ts new file mode 100644 index 0000000..e7b2516 --- /dev/null +++ b/Max API/src/veille/veille.prompt.ts @@ -0,0 +1,39 @@ +/** + * Prompt de l'Agent de Veille (docs/Max Refonte Coach Freelance.md, "veille autonome") - pas de + * personnalite Max ici, personne n'entend cet agent (meme principe que ResearchAgent). Un appel + * par sujet surveille (domaine du profil ou sujet additionnel), recherche web reelle (":online"). + */ +export function buildVeilleScanPrompt(topic: string): string { + return `## Ton role dans cet echange + +Tu es un veilleur technologique pour un freelance specialise dans : ${topic} + +## Ce que tu fais + +Tu recherches, sur le web reel, des signaux recents et concrets pertinents pour ce freelance : +- "emerging" : une competence/outil/pratique emergente dans ce domaine qu'il ne maitrise pas encore +- "refresh" : une evolution significative d'une competence existante (nouvelle version majeure, nouvelle norme) +- "obsolete" : une pratique ou un outil du domaine en train de devenir obsolete + +Minimum 3 sources independantes et fiables par signal (pas le meme site duplique), fraiches (moins de 6 mois sauf si clairement toujours d'actualite). + +Tu produis un JSON (tableau, 0 a 5 signaux, uniquement si vraiment pertinent) : +{ + "signals": [ + { + "type": "emerging" | "refresh" | "obsolete", + "competence": "nom precis de la competence concernee", + "relevance_score": 0.0 a 1.0, + "sources": [{ "title": "...", "url": "..." }] + } + ] +} + +## Ce que tu ne fais pas + +- Tu n'inventes pas de signal pour remplir le quota - un tableau vide est une reponse valide +- Tu ne generes pas depuis ta memoire seule, uniquement depuis une recherche web reelle +- Tu ne proposes jamais moins de 3 sources pour un signal que tu remontes + +Reponds UNIQUEMENT avec cet objet JSON strict, sans texte avant ni apres.`; +} diff --git a/Max API/src/veille/veille.service.spec.ts b/Max API/src/veille/veille.service.spec.ts new file mode 100644 index 0000000..58e2e6d --- /dev/null +++ b/Max API/src/veille/veille.service.spec.ts @@ -0,0 +1,376 @@ +import { ForbiddenException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { PrismaService } from '../prisma/prisma.service'; +import { OpenRouterService } from '../llm/openrouter.service'; +import { SessionsService } from '../sessions/sessions.service'; +import { VeilleService } from './veille.service'; + +function makeProfile(overrides: Record = {}) { + return { + id: 1, + userId: 7, + domains: ['Facturation freelance'], + stack: [], + veilleExtraTopics: [], + veilleBlacklist: [], + veilleRelevanceThreshold: null, + veilleFrequency: null, + veilleNotificationsEnabled: true, + lastVeilleAt: null, + competencesDismissed: [], + ...overrides, + }; +} + +function makeSignal( + type: string, + score: number, + overrides: Record = {}, +) { + return { + signals: [ + { + type, + competence: 'TVA intracommunautaire', + relevance_score: score, + sources: [ + { title: 'Source 1', url: 'https://a.example' }, + { title: 'Source 2', url: 'https://b.example' }, + { title: 'Source 3', url: 'https://c.example' }, + ], + ...overrides, + }, + ], + }; +} + +describe('VeilleService', () => { + let service: VeilleService; + const chat = jest.fn(); + const updateProfile = jest.fn< + Promise, + [{ where: { id: number }; data: Record }] + >(); + const createSignal = jest.fn< + Promise, + [{ data: { freelanceProfileId: number } }] + >(); + const updateSignal = jest.fn< + Promise, + [{ where: { id: number }; data: { actionTaken: string } }] + >(); + const prisma = { + freelanceProfile: { + findMany: jest.fn(), + findUnique: jest.fn(), + update: updateProfile, + }, + veilleSignal: { + create: createSignal, + findFirst: jest.fn(), + findMany: jest.fn(), + findUnique: jest.fn(), + update: updateSignal, + }, + }; + const sessionsService = { + create: jest.fn(), + sendObjectiveMessage: jest.fn(), + }; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + providers: [ + VeilleService, + { provide: PrismaService, useValue: prisma }, + { provide: OpenRouterService, useValue: { chat } }, + { provide: SessionsService, useValue: sessionsService }, + ], + }).compile(); + + service = module.get(VeilleService); + }); + + describe('isDueToday()', () => { + it('should always be due for a profile with daily frequency', () => { + const profile = makeProfile({ + veilleFrequency: 'daily', + lastVeilleAt: new Date(), + }); + expect(service.isDueToday(profile as never)).toBe(true); + }); + + it('should be due when a weekly profile has never run', () => { + const profile = makeProfile({ + veilleFrequency: 'weekly', + lastVeilleAt: null, + }); + expect(service.isDueToday(profile as never)).toBe(true); + }); + + it('should not be due for a weekly profile that ran 2 days ago', () => { + const twoDaysAgo = new Date(); + twoDaysAgo.setDate(twoDaysAgo.getDate() - 2); + const profile = makeProfile({ + veilleFrequency: 'weekly', + lastVeilleAt: twoDaysAgo, + }); + expect(service.isDueToday(profile as never)).toBe(false); + }); + + it('should infer a daily cadence for a volatile domain when no explicit frequency is set', () => { + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); + const profile = makeProfile({ + veilleFrequency: null, + domains: ['Intelligence artificielle generative'], + lastVeilleAt: yesterday, + }); + expect(service.isDueToday(profile as never)).toBe(true); + }); + }); + + describe('runCycleForProfile()', () => { + it('should persist a signal with >=3 sources and relevance above threshold', async () => { + const profile = makeProfile(); + chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.9))); + prisma.veilleSignal.findFirst.mockResolvedValueOnce(null); + + await service.runCycleForProfile(profile as never); + + expect(createSignal.mock.calls[0][0].data.freelanceProfileId).toBe(1); + const updateCall = updateProfile.mock.calls[0][0]; + expect(updateCall.where).toEqual({ id: 1 }); + expect(updateCall.data.lastVeilleAt).toBeInstanceOf(Date); + }); + + it('should reject a signal with fewer than 3 sources', async () => { + const profile = makeProfile(); + const payload = makeSignal('emerging', 0.9); + payload.signals[0].sources = payload.signals[0].sources.slice(0, 2); + chat.mockResolvedValueOnce(JSON.stringify(payload)); + + await service.runCycleForProfile(profile as never); + + expect(prisma.veilleSignal.create).not.toHaveBeenCalled(); + }); + + it('should reject a signal below the relevance threshold', async () => { + const profile = makeProfile(); + chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.5))); + + await service.runCycleForProfile(profile as never); + + expect(prisma.veilleSignal.create).not.toHaveBeenCalled(); + }); + + it('should honor a profile relevance threshold stricter than the default', async () => { + const profile = makeProfile({ veilleRelevanceThreshold: 0.95 }); + chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.8))); + + await service.runCycleForProfile(profile as never); + + expect(prisma.veilleSignal.create).not.toHaveBeenCalled(); + }); + + it('should reject a competence on the blacklist', async () => { + const profile = makeProfile({ + veilleBlacklist: ['tva intracommunautaire'], + }); + chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.9))); + + await service.runCycleForProfile(profile as never); + + expect(prisma.veilleSignal.create).not.toHaveBeenCalled(); + }); + + it('should not duplicate a signal already raised in the last 30 days', async () => { + const profile = makeProfile(); + chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.9))); + prisma.veilleSignal.findFirst.mockResolvedValueOnce({ id: 99 }); + + await service.runCycleForProfile(profile as never); + + expect(prisma.veilleSignal.create).not.toHaveBeenCalled(); + }); + + it('should do nothing but stamp lastVeilleAt when there is no topic to watch', async () => { + const profile = makeProfile({ domains: [], veilleExtraTopics: [] }); + + await service.runCycleForProfile(profile as never); + + expect(chat).not.toHaveBeenCalled(); + const updateCall = updateProfile.mock.calls[0][0]; + expect(updateCall.where).toEqual({ id: 1 }); + expect(updateCall.data.lastVeilleAt).toBeInstanceOf(Date); + }); + }); + + describe('getActiveSignals()', () => { + it('should return an empty list when the user has no profile yet', async () => { + prisma.freelanceProfile.findUnique.mockResolvedValueOnce(null); + const result = await service.getActiveSignals(7); + expect(result).toEqual([]); + }); + + it('should order by type priority (obsolete > refresh > emerging) then relevance desc', async () => { + prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 }); + prisma.veilleSignal.findMany.mockResolvedValueOnce([ + { + id: 1, + type: 'emerging', + competence: 'A', + sources: [], + relevanceScore: 0.9, + actionTaken: null, + createdAt: new Date(), + }, + { + id: 2, + type: 'obsolete', + competence: 'B', + sources: [], + relevanceScore: 0.8, + actionTaken: null, + createdAt: new Date(), + }, + { + id: 3, + type: 'refresh', + competence: 'C', + sources: [], + relevanceScore: 0.95, + actionTaken: null, + createdAt: new Date(), + }, + ]); + + const result = await service.getActiveSignals(7); + + expect(result.map((s) => s.id)).toEqual([2, 3, 1]); + }); + + it('should exclude a dismissed signal', async () => { + prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 }); + prisma.veilleSignal.findMany.mockResolvedValueOnce([ + { + id: 1, + type: 'emerging', + competence: 'A', + sources: [], + relevanceScore: 0.9, + actionTaken: 'dismissed', + createdAt: new Date(), + }, + ]); + + const result = await service.getActiveSignals(7); + + expect(result).toEqual([]); + }); + + it('should exclude a snoozed signal whose resurface date has not passed', async () => { + const future = new Date(); + future.setDate(future.getDate() + 10); + prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 }); + prisma.veilleSignal.findMany.mockResolvedValueOnce([ + { + id: 1, + type: 'emerging', + competence: 'A', + sources: [], + relevanceScore: 0.9, + actionTaken: `snoozed_until:${future.toISOString()}`, + createdAt: new Date(), + }, + ]); + + const result = await service.getActiveSignals(7); + + expect(result).toEqual([]); + }); + + it('should resurface a snoozed signal once its resurface date has passed', async () => { + const past = new Date(); + past.setDate(past.getDate() - 1); + prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 }); + prisma.veilleSignal.findMany.mockResolvedValueOnce([ + { + id: 1, + type: 'emerging', + competence: 'A', + sources: [], + relevanceScore: 0.9, + actionTaken: `snoozed_until:${past.toISOString()}`, + createdAt: new Date(), + }, + ]); + + const result = await service.getActiveSignals(7); + + expect(result).toHaveLength(1); + }); + }); + + describe('applyAction()', () => { + it('should throw ForbiddenException when the signal does not belong to the user', async () => { + prisma.veilleSignal.findUnique.mockResolvedValueOnce({ + id: 1, + freelanceProfile: { userId: 99, id: 1, competencesDismissed: [] }, + }); + + await expect(service.applyAction(1, 7, 'dismiss')).rejects.toThrow( + ForbiddenException, + ); + }); + + it('should mark the signal dismissed and add the competence to the profile', async () => { + prisma.veilleSignal.findUnique.mockResolvedValueOnce({ + id: 1, + competence: 'TVA', + freelanceProfile: { userId: 7, id: 1, competencesDismissed: [] }, + }); + + const result = await service.applyAction(1, 7, 'dismiss'); + + expect(result).toEqual({ actionTaken: 'dismissed' }); + expect(prisma.freelanceProfile.update).toHaveBeenCalledWith({ + where: { id: 1 }, + data: { competencesDismissed: ['TVA'] }, + }); + }); + + it('should snooze the signal with a resurface date 14 days out', async () => { + prisma.veilleSignal.findUnique.mockResolvedValueOnce({ + id: 1, + competence: 'TVA', + freelanceProfile: { userId: 7, id: 1, competencesDismissed: [] }, + }); + + const result = await service.applyAction(1, 7, 'snooze'); + + expect(result).toEqual({ actionTaken: 'snoozed' }); + const updateCall = updateSignal.mock.calls[0][0]; + expect(updateCall.data.actionTaken).toMatch(/^snoozed_until:/); + }); + + it('should start a new training session on train', async () => { + prisma.veilleSignal.findUnique.mockResolvedValueOnce({ + id: 1, + competence: 'TVA intracommunautaire', + freelanceProfile: { userId: 7, id: 1, competencesDismissed: [] }, + }); + sessionsService.create.mockResolvedValueOnce({ id: 42 }); + + const result = await service.applyAction(1, 7, 'train'); + + expect(result).toEqual({ actionTaken: 'trained', sessionId: 42 }); + expect(sessionsService.sendObjectiveMessage).toHaveBeenCalledWith( + 42, + 7, + 'Je veux me former sur TVA intracommunautaire.', + ); + }); + }); +}); diff --git a/Max API/src/veille/veille.service.ts b/Max API/src/veille/veille.service.ts new file mode 100644 index 0000000..43f6d8b --- /dev/null +++ b/Max API/src/veille/veille.service.ts @@ -0,0 +1,354 @@ +import { ForbiddenException, Injectable, Logger } from '@nestjs/common'; +import { Cron, CronExpression } from '@nestjs/schedule'; +import { FreelanceProfile, Prisma, VeilleSignal } from '@prisma/client'; +import { OpenRouterService } from '../llm/openrouter.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { SessionsService } from '../sessions/sessions.service'; +import { VeilleSignalActionResultDto } from './dto/veille-signal-action-result.dto'; +import { VeilleSignalResponseDto } from './dto/veille-signal-response.dto'; +import { buildVeilleScanPrompt } from './veille.prompt'; + +export interface VeilleSignalSource { + title: string; + url: string; +} + +interface RawVeilleSignal { + type?: unknown; + competence?: unknown; + relevance_score?: unknown; + sources?: unknown; +} + +const MIN_SOURCES = 3; +const DEFAULT_RELEVANCE_THRESHOLD = 0.7; +const DEDUP_WINDOW_DAYS = 30; +const SNOOZE_DAYS = 14; +const SNOOZE_PREFIX = 'snoozed_until:'; +const WEEKLY_STALENESS_DAYS = 7; +const TYPE_PRIORITY: Record = { + obsolete: 0, + refresh: 1, + emerging: 2, +}; + +/** Domaines qui evoluent vite : veille quotidienne plutot qu'hebdomadaire, sauf si le freelance a + * explicitement choisi une frequence (profile.veilleFrequency). Liste volontairement simple - + * un faux negatif se rattrape a la prochaine veille hebdomadaire, pas de consequence grave. */ +const VOLATILE_DOMAIN_KEYWORDS = [ + 'ia', + 'intelligence artificielle', + 'ai', + 'llm', + 'genai', + 'ia generative', + 'web3', + 'blockchain', + 'no-code', + 'low-code', +]; + +/** + * Agent de veille (docs/Max Refonte Coach Freelance.md, "veille autonome") : tourne en tache de + * fond (cron), jamais a la demande de l'utilisateur. Propose des signaux (competence emergente, a + * rafraichir, ou obsolete) que le freelance traite explicitement (train/snooze/dismiss) - ne + * modifie jamais le profil ou ne demarre jamais de session de son propre chef. + */ +@Injectable() +export class VeilleService { + private readonly logger = new Logger(VeilleService.name); + + constructor( + private readonly prisma: PrismaService, + private readonly llm: OpenRouterService, + private readonly sessionsService: SessionsService, + ) {} + + /** Un seul cron quotidien : la distinction quotidien/hebdomadaire se fait par profil (voir + * isDueToday), pas par decorateur separe - plus simple a tester et a faire evoluer. */ + @Cron(CronExpression.EVERY_DAY_AT_6AM) + async runDailyTick(): Promise { + const profiles = await this.prisma.freelanceProfile.findMany({ + where: { veilleNotificationsEnabled: true }, + }); + for (const profile of profiles) { + if (!this.isDueToday(profile)) continue; + try { + await this.runCycleForProfile(profile); + } catch (error) { + this.logger.warn( + `Veille du profil ${profile.id} echouee: ${String(error)}`, + ); + } + } + } + + isDueToday(profile: FreelanceProfile): boolean { + const frequency = profile.veilleFrequency ?? this.inferFrequency(profile); + if (frequency === 'daily') return true; + if (!profile.lastVeilleAt) return true; + const daysSinceLastRun = + (Date.now() - profile.lastVeilleAt.getTime()) / (1000 * 60 * 60 * 24); + return daysSinceLastRun >= WEEKLY_STALENESS_DAYS; + } + + private inferFrequency(profile: FreelanceProfile): 'daily' | 'weekly' { + const domains = (profile.domains as unknown as string[]) ?? []; + const isVolatile = domains.some((domain) => + VOLATILE_DOMAIN_KEYWORDS.some((keyword) => + domain.toLowerCase().includes(keyword), + ), + ); + return isVolatile ? 'daily' : 'weekly'; + } + + async runCycleForProfile(profile: FreelanceProfile): Promise { + const domains = (profile.domains as unknown as string[]) ?? []; + const extraTopics = + (profile.veilleExtraTopics as unknown as string[]) ?? []; + const topics = [...new Set([...domains, ...extraTopics])]; + if (topics.length === 0) { + await this.prisma.freelanceProfile.update({ + where: { id: profile.id }, + data: { lastVeilleAt: new Date() }, + }); + return; + } + + const blacklist = new Set( + ((profile.veilleBlacklist as unknown as string[]) ?? []).map((c) => + c.toLowerCase(), + ), + ); + const threshold = Math.max( + DEFAULT_RELEVANCE_THRESHOLD, + profile.veilleRelevanceThreshold ?? 0, + ); + + const outcomes = await Promise.all( + topics.map((topic) => this.scanTopic(profile.userId, topic)), + ); + const candidates = outcomes.flat(); + + for (const candidate of candidates) { + if (candidate.sources.length < MIN_SOURCES) continue; + if (candidate.relevanceScore < threshold) continue; + if (blacklist.has(candidate.competence.toLowerCase())) continue; + if ( + await this.isDuplicate(profile.id, candidate.competence, candidate.type) + ) { + continue; + } + + await this.prisma.veilleSignal.create({ + data: { + freelanceProfileId: profile.id, + type: candidate.type, + competence: candidate.competence, + sources: candidate.sources as unknown as Prisma.InputJsonValue, + relevanceScore: candidate.relevanceScore, + }, + }); + } + + await this.prisma.freelanceProfile.update({ + where: { id: profile.id }, + data: { lastVeilleAt: new Date() }, + }); + } + + private async isDuplicate( + freelanceProfileId: number, + competence: string, + type: string, + ): Promise { + const since = new Date(); + since.setDate(since.getDate() - DEDUP_WINDOW_DAYS); + const existing = await this.prisma.veilleSignal.findFirst({ + where: { + freelanceProfileId, + competence, + type, + createdAt: { gte: since }, + }, + }); + return existing !== null; + } + + private async scanTopic( + userId: number, + topic: string, + ): Promise< + { + type: string; + competence: string; + relevanceScore: number; + sources: VeilleSignalSource[]; + }[] + > { + try { + const raw = await this.llm.chat( + userId, + [{ role: 'system', content: buildVeilleScanPrompt(topic) }], + { jsonResponse: true, online: true }, + ); + return this.parseSignals(raw); + } catch (error) { + this.logger.warn(`Veille du sujet "${topic}" echouee: ${String(error)}`); + return []; + } + } + + private parseSignals(raw: string): { + type: string; + competence: string; + relevanceScore: number; + sources: VeilleSignalSource[]; + }[] { + try { + const data = JSON.parse(raw) as { signals?: unknown }; + if (!Array.isArray(data.signals)) return []; + + const results: { + type: string; + competence: string; + relevanceScore: number; + sources: VeilleSignalSource[]; + }[] = []; + for (const rawSignal of data.signals as RawVeilleSignal[]) { + if ( + !['emerging', 'refresh', 'obsolete'].includes( + String(rawSignal.type), + ) || + typeof rawSignal.competence !== 'string' || + !Array.isArray(rawSignal.sources) + ) { + continue; + } + const sources: VeilleSignalSource[] = []; + for (const rawSource of rawSignal.sources as { + title?: unknown; + url?: unknown; + }[]) { + if ( + typeof rawSource.title === 'string' && + typeof rawSource.url === 'string' + ) { + sources.push({ title: rawSource.title, url: rawSource.url }); + } + } + results.push({ + type: rawSignal.type as string, + competence: rawSignal.competence, + relevanceScore: Number(rawSignal.relevance_score) || 0, + sources, + }); + } + return results; + } catch { + this.logger.warn(`Reponse de veille non-JSON, rejetee: ${raw}`); + return []; + } + } + + async getActiveSignals(userId: number): Promise { + const profile = await this.prisma.freelanceProfile.findUnique({ + where: { userId }, + }); + if (!profile) return []; + + const signals = await this.prisma.veilleSignal.findMany({ + where: { freelanceProfileId: profile.id }, + orderBy: { createdAt: 'desc' }, + }); + + return signals + .filter((signal) => this.isActionable(signal)) + .sort( + (a, b) => + TYPE_PRIORITY[a.type] - TYPE_PRIORITY[b.type] || + b.relevanceScore - a.relevanceScore, + ) + .map((signal) => this.toResponse(signal)); + } + + /** Un signal sans action est actionnable. Un signal "snooze" le redevient automatiquement une + * fois sa date de resurgence passee (voir SNOOZE_PREFIX) - pas de colonne dediee en base. */ + private isActionable(signal: VeilleSignal): boolean { + if (!signal.actionTaken) return true; + if (signal.actionTaken.startsWith(SNOOZE_PREFIX)) { + const resurfaceAt = new Date( + signal.actionTaken.slice(SNOOZE_PREFIX.length), + ); + return resurfaceAt.getTime() <= Date.now(); + } + return false; + } + + async applyAction( + signalId: number, + userId: number, + action: 'train' | 'snooze' | 'dismiss', + ): Promise { + const signal = await this.prisma.veilleSignal.findUnique({ + where: { id: signalId }, + include: { freelanceProfile: true }, + }); + if (!signal || signal.freelanceProfile.userId !== userId) { + throw new ForbiddenException('Signal de veille introuvable.'); + } + + if (action === 'snooze') { + const resurfaceAt = new Date(); + resurfaceAt.setDate(resurfaceAt.getDate() + SNOOZE_DAYS); + await this.prisma.veilleSignal.update({ + where: { id: signalId }, + data: { actionTaken: `${SNOOZE_PREFIX}${resurfaceAt.toISOString()}` }, + }); + return { actionTaken: 'snoozed' }; + } + + if (action === 'dismiss') { + await this.prisma.veilleSignal.update({ + where: { id: signalId }, + data: { actionTaken: 'dismissed' }, + }); + const dismissed = new Set( + (signal.freelanceProfile.competencesDismissed as unknown as string[]) ?? + [], + ); + dismissed.add(signal.competence); + await this.prisma.freelanceProfile.update({ + where: { id: signal.freelanceProfile.id }, + data: { + competencesDismissed: [...dismissed], + }, + }); + return { actionTaken: 'dismissed' }; + } + + await this.prisma.veilleSignal.update({ + where: { id: signalId }, + data: { actionTaken: 'trained' }, + }); + const session = await this.sessionsService.create(userId); + await this.sessionsService.sendObjectiveMessage( + session.id, + userId, + `Je veux me former sur ${signal.competence}.`, + ); + return { actionTaken: 'trained', sessionId: session.id }; + } + + private toResponse(signal: VeilleSignal): VeilleSignalResponseDto { + return { + id: signal.id, + type: signal.type, + competence: signal.competence, + sources: signal.sources as unknown as VeilleSignalSource[], + relevanceScore: signal.relevanceScore, + actionTaken: signal.actionTaken, + createdAt: signal.createdAt, + }; + } +}