Skip to content

Implementar Endpoint V2 de Relatórios com Paginação Contada e Baseada em Token#388

Open
mateusmrosa wants to merge 4 commits intohomolfrom
feat/endpoint-V2-relatorios
Open

Implementar Endpoint V2 de Relatórios com Paginação Contada e Baseada em Token#388
mateusmrosa wants to merge 4 commits intohomolfrom
feat/endpoint-V2-relatorios

Conversation

@mateusmrosa
Copy link
Contributor

@mateusmrosa mateusmrosa commented Aug 5, 2025

Summary by CodeRabbit

  • New Features

    • Added a versioned reports endpoint (v2) with enhanced filtering (source, type, visibility, date range) and page-number pagination.
    • Pagination includes total pages, current page, has-more flag and a secure token to preserve filter consistency.
    • Report listings now include richer metadata (progress, creator display, download tokens) for improved UX.
  • Refactor

    • Permission/visibility handling improved to ensure users see only authorized reports.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 5, 2025

Walkthrough

A 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

Cohort / File(s) Change Summary
Filter DTO
backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts
Added FilterRelatorioV2Dto with validated optional fields: pdm_id, fonte, tipo, visibilidade, criado_em_de, criado_em_ate, token_paginacao, pagina (default 1), and ipp (default 25). Uses class-validator, class-transformer, and Swagger decorators.
Controller
backend/src/reports/relatorios/reports.controller.ts
Added GET /relatorios/v2 endpoint using FilterRelatorioV2Dto, protected by existing auth/roles, returning PaginatedWithPagesDto<RelatorioDto>, and documented with ApiPaginatedWithPagesResponse. Delegates to reportsService.findAllV2.
Service & Helpers
backend/src/reports/relatorios/reports.service.ts
Refactored permission clause into _getPermissionClause(user). Added _getWhereClauseForFindAll(filters, user), findAllV2(...) (page-based pagination with JWT page tokens), _mapRelatorioToDto(...), and encodePageToken/decodePageToken with ReportsPageTokenJwtBody. Kept existing findAll but replaced inline permission logic.

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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Poem

In the meadow a rabbit taps keys with glee,
New filters and pages hop out for to see.
Tokens that guard each query’s intent,
Keep results in order—no steps misspent.
Hop on, dear devs, v2 sings with a spree! 🐇✨

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 details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c8dc071 and 57906f7.

📒 Files selected for processing (1)
  • backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/reports/relatorios/dto/filter-relatorio-v2.dto.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/endpoint-V2-relatorios

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
backend/src/reports/relatorios/reports.controller.ts (1)

99-99: Consider using Portuguese for consistency in comments

The 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 contada
backend/src/reports/relatorios/reports.service.ts (1)

51-51: Use relative import path for consistency

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between b842a34 and 6c65899.

📒 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 validation

The 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.

Comment on lines +27 to +33
@IsOptional()
@IsDateString()
criado_em_de?: string;

@IsOptional()
@IsDateString()
criado_em_ate?: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Comment on lines +35 to +37
@IsOptional()
@IsString()
token_paginacao?: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Suggested change
@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.

Comment on lines +39 to +50
@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;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add API documentation and clarify default value handling.

The pagination parameters need improvements:

  1. Missing API documentation: Add @ApiProperty decorators
  2. 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Token consistency validation: Verify that the token's ipp matches the requested ipp to prevent inconsistencies.
  2. Performance optimization: When a valid token exists, avoid the redundant count query since total_rows is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c80d23 and c8dc071.

📒 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 _getPermissionClause method 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_id is 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 _mapRelatorioToDto method maintains consistency across both API versions.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@sonarqubecloud
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants