Implementar Endpoint V2 de Relatórios com Paginação Contada e Baseada em Token#388
Implementar Endpoint V2 de Relatórios com Paginação Contada e Baseada em Token#388mateusmrosa wants to merge 4 commits intohomolfrom
Conversation
WalkthroughA new versioned report listing API (/relatorios/v2) was added with enhanced filtering and page-number pagination. It introduces a FilterRelatorioV2Dto, a controller endpoint, and service logic that issues and validates JWT pagination tokens tied to filter criteria. Existing endpoints and offset-based pagination remain unchanged. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Controller as ReportsController
participant Service as ReportsService
participant DB as Database
Client->>Controller: GET /relatorios/v2?filters
Controller->>Service: findAllV2(filters, user)
Service->>Service: _getWhereClauseForFindAll(filters, user)
Service->>DB: Query reports with where clause, skip/take for page
DB-->>Service: Return paginated report results
Service->>Service: encodePageToken(filters, total_rows)
Service-->>Controller: PaginatedWithPagesDto (results, page info, token)
Controller-->>Client: PaginatedWithPagesDto (results, page info, token)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~35 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: CodeRabbit UI 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
backend/src/reports/relatorios/reports.controller.ts (1)
99-99: Consider using Portuguese for consistency in commentsThe comment uses English while the rest of the codebase uses Portuguese. Consider changing to maintain consistency:
- @ApiPaginatedWithPagesResponse(RelatorioDto) // New decorator for counted pagination + @ApiPaginatedWithPagesResponse(RelatorioDto) // Novo decorator para paginação contadabackend/src/reports/relatorios/reports.service.ts (1)
51-51: Use relative import path for consistencyThe import uses an absolute path starting with 'src/' while other imports in the file use relative paths starting with '../../'.
-import { Object2Hash } from 'src/common/object2hash'; +import { Object2Hash } from '../../common/object2hash';
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts(1 hunks)backend/src/reports/relatorios/reports.controller.ts(2 hunks)backend/src/reports/relatorios/reports.service.ts(4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: `filtroparapagina` atualiza `route.query` somente no `submit` do formulário; consequentemente, watch...
Learnt from: robsonsobral
PR: AppCivico/smae#348
File: frontend/src/views/parlamentares/ParlamentaresLista.vue:43-55
Timestamp: 2025-06-11T00:41:40.158Z
Learning: `FiltroParaPagina` atualiza `route.query` somente no `submit` do formulário; consequentemente, watchers sobre esses parâmetros disparam apenas por submissão, não por digitação.
Applied to files:
backend/src/reports/relatorios/reports.service.ts
🔇 Additional comments (3)
backend/src/reports/relatorios/reports.service.ts (1)
1008-1010: Good implementation of filter hash validationThe hash comparison ensures that pagination tokens become invalid when filter criteria change, preventing inconsistent pagination results. This is a robust approach to maintaining data consistency.
backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts (2)
1-4: LGTM!All necessary imports are present and correctly referenced throughout the class.
12-25: LGTM!The enum fields are well-implemented with proper validation, consistent API documentation, and type-safe Prisma enum references.
| @IsOptional() | ||
| @IsDateString() | ||
| criado_em_de?: string; | ||
|
|
||
| @IsOptional() | ||
| @IsDateString() | ||
| criado_em_ate?: string; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add API documentation for date fields.
The date fields are missing @ApiProperty decorators for consistency with other fields and proper API documentation.
Apply this diff to add API documentation:
@IsOptional()
+@ApiProperty({ description: 'Data de criação inicial (ISO string)', required: false })
@IsDateString()
criado_em_de?: string;
@IsOptional()
+@ApiProperty({ description: 'Data de criação final (ISO string)', required: false })
@IsDateString()
criado_em_ate?: string;Consider adding business logic validation to ensure criado_em_de <= criado_em_ate in the service layer.
🤖 Prompt for AI Agents
In backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts around lines 27
to 33, the date fields criado_em_de and criado_em_ate lack @ApiProperty
decorators, which are needed for consistent API documentation. Add @ApiProperty
decorators above each date field with appropriate descriptions and example
values. Additionally, implement business logic validation in the service layer
to ensure that criado_em_de is less than or equal to criado_em_ate.
| @IsOptional() | ||
| @IsString() | ||
| token_paginacao?: string; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add API documentation for pagination token.
The pagination token field is missing @ApiProperty decorator for consistency and proper API documentation.
Apply this diff to add API documentation:
@IsOptional()
+@ApiProperty({ description: 'Token de paginação JWT para continuação', required: false })
@IsString()
token_paginacao?: string;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @IsOptional() | |
| @IsString() | |
| token_paginacao?: string; | |
| @IsOptional() | |
| @ApiProperty({ description: 'Token de paginação JWT para continuação', required: false }) | |
| @IsString() | |
| token_paginacao?: string; |
🤖 Prompt for AI Agents
In backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts around lines 35
to 37, the token_paginacao field lacks the @ApiProperty decorator, which is
needed for consistent and complete API documentation. Add the @ApiProperty
decorator above the token_paginacao declaration, specifying that the field is
optional and describing its purpose as the pagination token.
| @IsOptional() | ||
| @IsInt() | ||
| @Min(1) | ||
| @Transform((a: TransformFnParams) => (a.value === '' ? 1 : +a.value)) | ||
| pagina?: number = 1; | ||
|
|
||
| @IsOptional() | ||
| @IsInt() | ||
| @Max(500) | ||
| @Min(1) | ||
| @Transform((a: TransformFnParams) => (a.value === '' ? 25 : +a.value)) | ||
| ipp?: number = 25; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add API documentation and clarify default value handling.
The pagination parameters need improvements:
- Missing API documentation: Add
@ApiPropertydecorators - Redundant default values: Property defaults (
= 1,= 25) are redundant since the transform functions handle defaults
Apply this diff to improve the implementation:
@IsOptional()
+@ApiProperty({ description: 'Número da página', minimum: 1, default: 1, required: false })
@IsInt()
@Min(1)
@Transform((a: TransformFnParams) => (a.value === '' ? 1 : +a.value))
-pagina?: number = 1;
+pagina?: number;
@IsOptional()
+@ApiProperty({ description: 'Itens por página', minimum: 1, maximum: 500, default: 25, required: false })
@IsInt()
@Max(500)
@Min(1)
@Transform((a: TransformFnParams) => (a.value === '' ? 25 : +a.value))
-ipp?: number = 25;
+ipp?: number;Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts lines 39 to 50,
add @ApiProperty decorators to the pagination parameters 'pagina' and 'ipp' to
provide API documentation. Remove the redundant default value assignments (= 1
and = 25) from these properties since the @Transform functions already handle
default values when the input is an empty string.
…gir a duplicação apontada pelo SonarCloud
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
backend/src/reports/relatorios/reports.service.ts (1)
843-899: Core pagination logic is sound, but consider token validation improvements.The implementation correctly handles page-based pagination, but consider these enhancements:
- Token consistency validation: Verify that the token's
ippmatches the requestedippto prevent inconsistencies.- Performance optimization: When a valid token exists, avoid the redundant count query since
total_rowsis already available.Consider this enhancement for token validation:
if (token_paginacao) { const decoded = this.decodePageToken(token_paginacao, filtersForHash); + if (decoded.ipp !== ipp) { + throw new HttpException('Items per page mismatch with pagination token', 400); + } total_registros = decoded.total_rows; } else {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
backend/src/reports/relatorios/reports.service.ts(6 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: `filtroparapagina` atualiza `route.query` somente no `submit` do formulário; consequentemente, watch...
Learnt from: robsonsobral
PR: AppCivico/smae#348
File: frontend/src/views/parlamentares/ParlamentaresLista.vue:43-55
Timestamp: 2025-06-11T00:41:40.158Z
Learning: `FiltroParaPagina` atualiza `route.query` somente no `submit` do formulário; consequentemente, watchers sobre esses parâmetros disparam apenas por submissão, não por digitação.
Applied to files:
backend/src/reports/relatorios/reports.service.ts
🔇 Additional comments (9)
backend/src/reports/relatorios/reports.service.ts (9)
24-24: LGTM! Necessary imports for the new pagination features.The new imports properly support the V2 API functionality with page-based pagination, filter DTOs, and hashing utilities.
Also applies to: 50-51
67-72: Well-designed JWT body structure for secure pagination.The class properly encapsulates all necessary data for page-based pagination with filter consistency validation through the search hash.
405-405: Good refactoring to eliminate code duplication.Using the extracted
_getPermissionClausemethod maintains consistency between the old and new API versions.
775-841: Excellent extraction of complex permission logic.The method properly handles all three visibility levels with correct Prisma JSON path operations for role and organization-based restrictions. The conditional logic for
orgao_idis properly implemented.
752-773: Clean implementation of filter-to-where-clause conversion.The method properly handles all filter types including optional date ranges and integrates well with the permission system.
901-926: Excellent extraction of data mapping logic.The method properly handles all edge cases, maintains type safety with
satisfies, and eliminates code duplication between API versions.
928-938: Secure token decoding with proper validation.The method correctly validates both JWT integrity and filter consistency, preventing pagination token manipulation attacks.
940-948: Proper JWT token encoding with security considerations.The method correctly creates tokens with filter hash validation and proper expiration settings.
437-437: Good refactoring to use extracted mapping method.Using the centralized
_mapRelatorioToDtomethod maintains consistency across both API versions.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
|



Summary by CodeRabbit
New Features
Refactor