mirror of
https://github.com/siop-spelev/siop2.git
synced 2026-08-08 12:41:54 +00:00
feat(r5.3): écrans IA — assistant web, corpus administrable, suggestions OT/mobile
- Contrat (76 opérations) : Document expose inCorpus/indexedAt/chunkCount,
PATCH /documents/{id}/corpus (ASSETS.edit), POST /assistant/reindex
(bilan chiffré) ; ci-contract vérifie désormais aussi le client mobile.
- Web : page /assistant (chat sourcé — extraits exacts cités, Ouvrir vers
PDF authentifié ou fiche OT, avertissement permanent ; refus honnête
chiffré avec action utile) ; Bibliothèque = corpus (bandeau 09-08,
statut d'indexation par document, interrupteur d'exclusion PDF,
Réindexer tout) ; fiche OT : « Décrire pour suggérer » (Appliquer =
geste humain, liseré « suggéré » retiré au choix manuel).
- Mobile : chips de suggestion dans la clôture (un appui = un champ
pré-rempli, « réseau requis » hors-ligne — la file R4 n'en dépend pas).
- apps/ai : seuils AI_SEUIL_* configurables par env (CI + calibrage).
- CI e2e : service siop2-ai (embeddeur déterministe, seuils calibrés sur
mesures : match 0,66 vs bruit 0,11) + parcours R5 Playwright (PDF généré
xref valide → réindexation → réponse sourcée → refus → suggestion).
- Vérifié : 16/16 Playwright, 78 tests API, 23 pytest, 17 jest-expo ;
chaîne réelle au vrai modèle ONNX (web 7/7, mobile Expo web 6/6).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,6 +21,14 @@ export class AssistantController {
|
||||
return this.assistant.ask(body);
|
||||
}
|
||||
|
||||
/** Réindexer le corpus — même droit que la gestion du référentiel (D3). */
|
||||
@Post('reindex')
|
||||
@HttpCode(200)
|
||||
@RequirePermission('ASSETS', 'edit')
|
||||
reindex() {
|
||||
return this.assistant.reindex();
|
||||
}
|
||||
|
||||
/** Suggérer des codes — réservé à qui remplit des bilans (D1). */
|
||||
@Post('suggest-bilan')
|
||||
@HttpCode(200)
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
AssistantAsk,
|
||||
BilanField,
|
||||
BilanSuggestionsResponse,
|
||||
ReindexResult,
|
||||
SuggestBilan,
|
||||
} from '@siop/shared';
|
||||
import { loadEnv } from '../config/env';
|
||||
@@ -81,6 +82,21 @@ export class AssistantService {
|
||||
};
|
||||
}
|
||||
|
||||
async reindex(): Promise<ReindexResult> {
|
||||
const brut = await this.appeler<{
|
||||
documents_indexes: number;
|
||||
documents_ignores: number;
|
||||
bilans_indexes: number;
|
||||
extraits: number;
|
||||
}>('/internal/reindex', {});
|
||||
return {
|
||||
documentsIndexed: brut.documents_indexes,
|
||||
documentsSkipped: brut.documents_ignores,
|
||||
reportsIndexed: brut.bilans_indexes,
|
||||
chunks: brut.extraits,
|
||||
};
|
||||
}
|
||||
|
||||
async suggestBilan(dto: SuggestBilan): Promise<BilanSuggestionsResponse> {
|
||||
const brut = await this.appeler<{
|
||||
suggestions: {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
StreamableFile,
|
||||
@@ -14,11 +15,17 @@ import {
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { DOCUMENT_MAX_BYTES } from '@siop/shared';
|
||||
import {
|
||||
DOCUMENT_MAX_BYTES,
|
||||
DocumentCorpusUpdateSchema,
|
||||
type DocumentCorpusUpdate,
|
||||
} from '@siop/shared';
|
||||
import {
|
||||
AuthenticatedUser,
|
||||
CurrentUser,
|
||||
} from '../auth/current-user.decorator';
|
||||
import { ZodValidationPipe } from '../common/zod-validation.pipe';
|
||||
import { RequirePermission } from '../permissions/require-permission.decorator';
|
||||
import { DocumentsService } from './documents.service';
|
||||
|
||||
@Controller('documents')
|
||||
@@ -69,6 +76,16 @@ export class DocumentsController {
|
||||
});
|
||||
}
|
||||
|
||||
/** Corpus IA (D3) : réservé aux gestionnaires du référentiel. */
|
||||
@Patch(':id/corpus')
|
||||
@RequirePermission('ASSETS', 'edit')
|
||||
setCorpus(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new ZodValidationPipe(DocumentCorpusUpdateSchema)) body: DocumentCorpusUpdate,
|
||||
) {
|
||||
return this.documents.setCorpus(id, body.inCorpus);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(204)
|
||||
remove(@Param('id', ParseUUIDPipe) id: string, @CurrentUser() user: AuthenticatedUser) {
|
||||
|
||||
@@ -155,6 +155,21 @@ export class DocumentsService {
|
||||
workOrderReference: row.workOrder?.reference ?? null,
|
||||
uploadedByName: row.uploadedBy?.displayName ?? null,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
inCorpus: row.inCorpus,
|
||||
indexedAt: row.indexedAt?.toISOString() ?? null,
|
||||
chunkCount: row.chunkCount,
|
||||
};
|
||||
}
|
||||
|
||||
/** Interrupteur corpus (D3) — effectif à la prochaine réindexation. */
|
||||
async setCorpus(id: string, inCorpus: boolean): Promise<DocumentDto> {
|
||||
const doc = await this.prisma.document.findUnique({ where: { id } });
|
||||
if (!doc) throw new NotFoundException('Document inconnu');
|
||||
const updated = await this.prisma.document.update({
|
||||
where: { id },
|
||||
data: { inCorpus },
|
||||
include: documentInclude,
|
||||
});
|
||||
return this.toDto(updated);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,20 @@ const REPONSE_SUGGEST = {
|
||||
],
|
||||
};
|
||||
|
||||
const REPONSE_REINDEX = {
|
||||
documents_indexes: 6,
|
||||
documents_ignores: 2,
|
||||
bilans_indexes: 214,
|
||||
extraits: 180,
|
||||
};
|
||||
|
||||
describe('Assistant (e2e — stub du service IA)', () => {
|
||||
let app: INestApplication;
|
||||
let stub: Server;
|
||||
let ahmed: string; // Technicien : view + edit sur WORK_ORDERS
|
||||
let ahmed: string; // Technicien : view + edit sur WORK_ORDERS, ASSETS en lecture
|
||||
let karim: string; // Demandeur : aucun droit WORK_ORDERS
|
||||
let rachid: string; // Vue seule : view sans edit
|
||||
let nadia: string; // Gestionnaire : ASSETS.edit — administre le corpus
|
||||
const requetesRecues: { url: string; jeton: string | undefined }[] = [];
|
||||
const http = () => request(app.getHttpServer());
|
||||
const auth = (t: string) => ({ Authorization: `Bearer ${t}` });
|
||||
@@ -62,6 +70,7 @@ describe('Assistant (e2e — stub du service IA)', () => {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
if (req.url === '/internal/ask') res.end(JSON.stringify(REPONSE_ASK));
|
||||
else if (req.url === '/internal/suggest') res.end(JSON.stringify(REPONSE_SUGGEST));
|
||||
else if (req.url === '/internal/reindex') res.end(JSON.stringify(REPONSE_REINDEX));
|
||||
else {
|
||||
res.statusCode = 404;
|
||||
res.end('{}');
|
||||
@@ -87,6 +96,7 @@ describe('Assistant (e2e — stub du service IA)', () => {
|
||||
ahmed = await login('Technicien');
|
||||
karim = await login('Demandeur');
|
||||
rachid = await login('Vue seule');
|
||||
nadia = await login('Gestionnaire');
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -146,6 +156,19 @@ describe('Assistant (e2e — stub du service IA)', () => {
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('reindex : traduit le bilan d’indexation, réservé à ASSETS.edit (D3)', async () => {
|
||||
const res = await http().post('/assistant/reindex').set(auth(nadia)).expect(200);
|
||||
expect(res.body).toEqual({
|
||||
documentsIndexed: 6,
|
||||
documentsSkipped: 2,
|
||||
reportsIndexed: 214,
|
||||
chunks: 180,
|
||||
});
|
||||
expect(requetesRecues.at(-1)!.url).toBe('/internal/reindex');
|
||||
// Ahmed (Technicien) lit le parc mais n'administre pas le corpus
|
||||
await http().post('/assistant/reindex').set(auth(ahmed)).expect(403);
|
||||
});
|
||||
|
||||
it('question trop courte : 400 avant tout appel au service IA', async () => {
|
||||
const avant = requetesRecues.length;
|
||||
await http().post('/assistant/ask').set(auth(ahmed)).send({ question: 'ab' }).expect(400);
|
||||
|
||||
@@ -87,6 +87,36 @@ describe('Bibliothèque & analytics (e2e)', () => {
|
||||
await http().get(`/documents/${envoye.body.id}/download`).set(auth(nadia)).expect(404);
|
||||
});
|
||||
|
||||
it('corpus (R5, D3) : nouveau document inclus par défaut, bascule réversible et gardée', async () => {
|
||||
const { body: assets } = await http().get('/assets').set(auth(nadia));
|
||||
const a1 = assets.assets.find((a: { reference: string }) => a.reference === 'A1');
|
||||
const envoye = await http()
|
||||
.post('/documents')
|
||||
.set(auth(nadia))
|
||||
.field('kind', 'NOTICE')
|
||||
.field('assetId', a1.id)
|
||||
.attach('file', PNG_1PX, { filename: `corpus-${suffix}.png`, contentType: 'image/png' })
|
||||
.expect(201);
|
||||
// le contrat expose l'état d'indexation — jamais indexé à la naissance
|
||||
expect(envoye.body).toMatchObject({ inCorpus: true, indexedAt: null, chunkCount: 0 });
|
||||
|
||||
const exclu = await http()
|
||||
.patch(`/documents/${envoye.body.id}/corpus`)
|
||||
.set(auth(nadia))
|
||||
.send({ inCorpus: false })
|
||||
.expect(200);
|
||||
expect(exclu.body.inCorpus).toBe(false);
|
||||
|
||||
// Karim (Demandeur) n'administre pas le corpus
|
||||
await http()
|
||||
.patch(`/documents/${envoye.body.id}/corpus`)
|
||||
.set(auth(karim))
|
||||
.send({ inCorpus: true })
|
||||
.expect(403);
|
||||
|
||||
await http().delete(`/documents/${envoye.body.id}`).set(auth(nadia)).expect(204);
|
||||
});
|
||||
|
||||
it('refus typés : format, rattachement manquant, cible inconnue, permission', async () => {
|
||||
const { body: assets } = await http().get('/assets').set(auth(nadia));
|
||||
const a1 = assets.assets.find((a: { reference: string }) => a.reference === 'A1');
|
||||
|
||||
Reference in New Issue
Block a user