168 lines
7.3 KiB
TypeScript
168 lines
7.3 KiB
TypeScript
import { provideZonelessChangeDetection } from '@angular/core';
|
|
import { TestBed } from '@angular/core/testing';
|
|
import { provideHttpClient, HttpEventType } from '@angular/common/http';
|
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
|
import { provideRouter } from '@angular/router';
|
|
import { provideAnimations } from '@angular/platform-browser/animations';
|
|
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
|
|
import { DocumentsService } from './documents.service';
|
|
import { AuthService } from '../auth/auth.service';
|
|
|
|
describe('DocumentsService (backend handoff contract)', () => {
|
|
let service: DocumentsService;
|
|
let httpMock: HttpTestingController;
|
|
|
|
beforeEach(() => {
|
|
TestBed.configureTestingModule({
|
|
providers: [
|
|
provideZonelessChangeDetection(),
|
|
provideHttpClient(),
|
|
provideHttpClientTesting(),
|
|
provideRouter([]),
|
|
provideAnimations(),
|
|
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
|
|
{ provide: AuthService, useValue: { getCsrfToken: () => 'csrf-abc' } },
|
|
],
|
|
});
|
|
service = TestBed.inject(DocumentsService);
|
|
httpMock = TestBed.inject(HttpTestingController);
|
|
});
|
|
|
|
afterEach(() => {
|
|
httpMock.verify();
|
|
});
|
|
|
|
it('uses same-origin /api/v1 paths for every MVP endpoint', () => {
|
|
service.getConfiguration().subscribe();
|
|
const req = httpMock.expectOne('/api/v1/configuration');
|
|
expect(req.request.method).toBe('GET');
|
|
req.flush({});
|
|
|
|
service.getDocuments({ status: 'ready', is_active: true }).subscribe();
|
|
const list = httpMock.expectOne('/api/v1/documents?status=ready&is_active=true');
|
|
list.flush({ items: [], next_cursor: null, knowledge_revision: 1 });
|
|
|
|
service.getKnowledgeSelection().subscribe();
|
|
const selection = httpMock.expectOne('/api/v1/knowledge-selection');
|
|
selection.flush({ active_document_ids: [], revision: 1 });
|
|
});
|
|
|
|
it('sends the caller idempotency key for uploads and reuses FormData without manual Content-Type', () => {
|
|
const file = new File([new Uint8Array([1, 2, 3])], 'faq.pdf', { type: 'application/pdf' });
|
|
const progress: number[] = [];
|
|
|
|
service.uploadDocument(file, 'عنوان', (percent) => progress.push(percent), undefined, 'key-upload-1').subscribe();
|
|
|
|
const req = httpMock.expectOne('/api/v1/documents');
|
|
expect(req.request.method).toBe('POST');
|
|
expect(req.request.headers.get('Idempotency-Key')).toBe('key-upload-1');
|
|
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
|
|
// The browser must own the multipart boundary.
|
|
expect(req.request.headers.get('Content-Type')).toBeNull();
|
|
expect((req.request.body as FormData).get('title')).toBe('عنوان');
|
|
req.event({ type: HttpEventType.UploadProgress, loaded: 3, total: 3 });
|
|
req.flush(
|
|
{ document_id: 'doc-1', job_id: 'job-1' },
|
|
{ status: 202, statusText: 'Accepted' },
|
|
);
|
|
expect(progress).toEqual([100]);
|
|
});
|
|
|
|
it('sends the same decision key on replay and forbids an empty note payload shape', () => {
|
|
service
|
|
.submitReviewDecision('doc-1', {
|
|
evidence_sha256: 'sha-1',
|
|
decision: 'approve',
|
|
checked: ['check-a'],
|
|
note: 'تأیید شد',
|
|
excluded_group_ids: [],
|
|
}, 'key-decision-1')
|
|
.subscribe();
|
|
|
|
const req = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
|
|
expect(req.request.method).toBe('POST');
|
|
expect(req.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
|
|
expect(req.request.body).toEqual({
|
|
evidence_sha256: 'sha-1',
|
|
decision: 'approve',
|
|
checked: ['check-a'],
|
|
note: 'تأیید شد',
|
|
excluded_group_ids: [],
|
|
});
|
|
req.flush({ decision_id: 'dec-1', review_state: 'pending' });
|
|
|
|
// Replaying the SAME key must hit the same URL with the same payload — the server
|
|
// deduplicates it (Idempotency-Replayed: true) instead of creating a second decision.
|
|
service
|
|
.submitReviewDecision(
|
|
'doc-1',
|
|
{
|
|
evidence_sha256: 'sha-1',
|
|
decision: 'approve',
|
|
checked: ['check-a'],
|
|
note: 'تأیید شد',
|
|
excluded_group_ids: [],
|
|
},
|
|
'key-decision-1',
|
|
)
|
|
.subscribe();
|
|
const replay = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
|
|
expect(replay.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
|
|
replay.flush({ decision_id: 'dec-1', review_state: 'pending' }, {
|
|
status: 200,
|
|
statusText: 'OK',
|
|
headers: { 'Idempotency-Replayed': 'true' },
|
|
} as never);
|
|
});
|
|
|
|
it('retries the same job through D04 with an explicit idempotency key', () => {
|
|
service.retryDocument('doc-1', 'key-retry-1').subscribe();
|
|
|
|
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
|
expect(req.request.method).toBe('POST');
|
|
expect(req.request.serializeBody()).toBeNull();
|
|
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
|
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
|
});
|
|
|
|
it('replaces the whole selection with a revision guard and no idempotency key (K02)', () => {
|
|
service.updateKnowledgeSelection({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] }).subscribe();
|
|
|
|
const req = httpMock.expectOne('/api/v1/knowledge-selection');
|
|
expect(req.request.method).toBe('PATCH');
|
|
expect(req.request.body).toEqual({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] });
|
|
// K02 is revision-controlled: no Idempotency-Key header.
|
|
expect(req.request.headers.get('Idempotency-Key')).toBeNull();
|
|
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
|
|
req.flush({ revision: 4, active_document_ids: ['doc-1', 'doc-2'], conversations_invalidated: true });
|
|
});
|
|
|
|
it('surfaces the error envelope code and request id for correlation', () => {
|
|
let captured: { code: string; message: string; requestId?: string } = { code: '', message: '' };
|
|
service.updateKnowledgeSelection({ expected_revision: 9, document_ids: [] }).subscribe({
|
|
error: (err) => {
|
|
captured = DocumentsService.getErrorInfo(err);
|
|
},
|
|
});
|
|
|
|
httpMock.expectOne('/api/v1/knowledge-selection').flush(
|
|
{ error: { code: 'REVISION_CONFLICT', message: 'Request could not be completed.', request_id: 'corr-1', retryable: false } },
|
|
{ status: 409, statusText: 'Conflict', headers: { 'X-Request-ID': 'corr-1' } },
|
|
);
|
|
|
|
expect(captured.code).toBe('REVISION_CONFLICT');
|
|
expect(captured.requestId).toBe('corr-1');
|
|
expect(DocumentsService.statusForError(captured.code, captured.message)).toContain('همزمان');
|
|
});
|
|
|
|
it('maps contract error codes to Persian guidance', () => {
|
|
expect(DocumentsService.statusForError('DOCUMENT_NOT_READY', '')).toContain('آماده');
|
|
expect(DocumentsService.statusForError('EXTRACTION_REVIEW_PENDING', '')).toContain('بازبینی');
|
|
expect(DocumentsService.statusForError('REVIEW_STALE', '')).toContain('شواهد');
|
|
expect(DocumentsService.statusForError('CONTEXT_REVOKED', '')).toContain('باطل');
|
|
expect(DocumentsService.statusForError('RATE_LIMITED', '')).toContain('حد مجاز');
|
|
expect(DocumentsService.isPolling('processing')).toBe(true);
|
|
expect(DocumentsService.isPolling('ready')).toBe(false);
|
|
});
|
|
});
|