Skip to content

Ticket: Implementar V2 findAllTransferencia#389

Open
mateusmrosa wants to merge 1 commit intohomolfrom
feat/implementar-V2-findAllTransferencia
Open

Ticket: Implementar V2 findAllTransferencia#389
mateusmrosa wants to merge 1 commit intohomolfrom
feat/implementar-V2-findAllTransferencia

Conversation

@mateusmrosa
Copy link
Contributor

@mateusmrosa mateusmrosa commented Aug 6, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new paginated API endpoint for transfer data with enhanced filtering options and page-based navigation.
    • Added support for advanced filters, including year, sphere, completion status, keyword, and pagination controls.
    • Improved pagination experience with page tokens and total page count in responses.
  • Improvements

    • Enhanced validation and documentation for filter parameters in the transfer data API.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 6, 2025

Walkthrough

A new DTO for advanced transfer filtering and pagination was introduced. The controller now exposes a transferencia/v2 GET endpoint using this DTO and a new paginated response type. The service layer was refactored to modularize filtering, selection, and mapping logic, and to implement robust page-based navigation with JWT-backed pagination tokens.

Changes

Cohort / File(s) Change Summary
New DTO for Transfer Filtering and Pagination
backend/src/casa-civil/transferencia/dto/filter-transferencia-v2.dto.ts
Introduces FilterTransferenciaV2Dto class with various validated, transformable, and documented filter fields for transfer queries, supporting advanced filtering and pagination.
Controller Endpoint for Paginated Transfer Listing
backend/src/casa-civil/transferencia/transferencia.controller.ts
Adds a new GET endpoint transferencia/v2 to TransferenciaController, using the new DTO and returning a paginated response with page and token support.
Service Refactor and Pagination Logic
backend/src/casa-civil/transferencia/transferencia.service.ts
Refactors filtering and mapping into helper methods, introduces JWT-based page token encoding/decoding, and adds findAllTransferenciaV2 for advanced, page-based transfer listing. Updates original logic to use new helpers.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Service
    participant Prisma
    Client->>Controller: GET /transferencia/v2?filters
    Controller->>Service: findAllTransferenciaV2(filters, user)
    Service->>Service: _getWhereClauseForFindAll(filters, user)
    Service->>Prisma: transferencia.findMany(where, select, skip, take)
    Prisma-->>Service: Transfer records
    Service->>Service: _mapTransferenciaToDto(records)
    Service->>Service: encodePageToken(filters, total_rows)
    Service-->>Controller: PaginatedWithPagesDto<TransferenciaDto>
    Controller-->>Client: PaginatedWithPagesDto<TransferenciaDto>
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

🐇
A DTO hops in, with filters so neat,
New endpoints now serve, pagination complete.
Tokens are juggled, with JWT flair,
Modular logic, less code to repair.
Transfers now paged, with clarity anew—
A garden of endpoints, grown just for you!
🌱✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ 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/implementar-V2-findAllTransferencia

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

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

@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 6, 2025

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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9ded14b and 379a708.

📒 Files selected for processing (3)
  • backend/src/casa-civil/transferencia/dto/filter-transferencia-v2.dto.ts (1 hunks)
  • backend/src/casa-civil/transferencia/transferencia.controller.ts (2 hunks)
  • backend/src/casa-civil/transferencia/transferencia.service.ts (5 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/casa-civil/transferencia/transferencia.service.ts
🧬 Code Graph Analysis (1)
backend/src/casa-civil/transferencia/transferencia.controller.ts (3)
backend/src/casa-civil/transferencia/entities/transferencia.dto.ts (1)
  • TransferenciaDto (18-44)
backend/src/casa-civil/transferencia/dto/filter-transferencia-v2.dto.ts (1)
  • FilterTransferenciaV2Dto (6-50)
backend/src/auth/models/PessoaFromJwt.ts (1)
  • PessoaFromJwt (16-249)
🔇 Additional comments (3)
backend/src/casa-civil/transferencia/transferencia.controller.ts (1)

38-47: LGTM! The new V2 endpoint follows established patterns.

The implementation correctly reuses the same authentication and authorization decorators as the existing endpoint, maintaining consistency in security controls.

backend/src/casa-civil/transferencia/dto/filter-transferencia-v2.dto.ts (1)

6-50: Well-structured DTO with proper validation constraints.

The DTO correctly implements validation decorators and transformations. The 500-item limit for ipp is a good safeguard against potential performance issues.

backend/src/casa-civil/transferencia/transferencia.service.ts (1)

1120-1160: Good refactoring to extract common logic.

The extraction of WHERE clause building, select clause, and mapping logic into helper methods improves code maintainability and ensures consistency between the V1 and V2 endpoints.

Comment on lines +1917 to +1959
async findAllTransferenciaV2(
filters: FilterTransferenciaV2Dto,
user: PessoaFromJwt
): Promise<PaginatedWithPagesDto<TransferenciaDto>> {
const ipp = filters.ipp ?? 25;
const page = filters.pagina ?? 1;
const skip = (page - 1) * ipp;
let total_registros = 0;
let token_paginacao = filters.token_paginacao;
const filtersForHash = { ...filters };
delete filtersForHash.pagina;
delete filtersForHash.token_paginacao;
if (token_paginacao) {
const decoded = this.decodePageToken(token_paginacao, filtersForHash);
total_registros = decoded.total_rows;
} else {
const where = await this._getWhereClauseForFindAll(filters, user);
total_registros = await this.prisma.transferencia.count({ where });
token_paginacao = this.encodePageToken(filtersForHash, total_registros);
}
const where = await this._getWhereClauseForFindAll(filters, user);
const rows = await this.prisma.transferencia.findMany({
where,
orderBy: [{ ano: 'desc' }, { identificador_nro: 'desc' }],
skip: skip,
take: ipp,
select: this._getTransferenciaSelectClause(),
});

const total_paginas = Math.ceil(total_registros / ipp);

const linhas = rows.map((r) => this._mapTransferenciaToDto(r));

return {
total_registros: total_registros,
paginas: total_paginas,
pagina_corrente: page,
token_paginacao: token_paginacao,
tem_mais: page < total_paginas,
token_ttl: PAGINATION_TOKEN_TTL,
linhas: linhas,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Optimize to avoid redundant database queries.

The method executes redundant queries that impact performance:

  1. The WHERE clause is built twice (lines 1933 and 1937)
  2. The count query runs even when total_registros is retrieved from the token (line 1934)

Apply this optimization:

 async findAllTransferenciaV2(
     filters: FilterTransferenciaV2Dto,
     user: PessoaFromJwt
 ): Promise<PaginatedWithPagesDto<TransferenciaDto>> {
     const ipp = filters.ipp ?? 25;
     const page = filters.pagina ?? 1;
     const skip = (page - 1) * ipp;
     let total_registros = 0;
     let token_paginacao = filters.token_paginacao;
     const filtersForHash = { ...filters };
     delete filtersForHash.pagina;
     delete filtersForHash.token_paginacao;
+    
+    const where = await this._getWhereClauseForFindAll(filters, user);
+    
     if (token_paginacao) {
         const decoded = this.decodePageToken(token_paginacao, filtersForHash);
         total_registros = decoded.total_rows;
     } else {
-        const where = await this._getWhereClauseForFindAll(filters, user);
         total_registros = await this.prisma.transferencia.count({ where });
         token_paginacao = this.encodePageToken(filtersForHash, total_registros);
     }
-    const where = await this._getWhereClauseForFindAll(filters, user);
     const rows = await this.prisma.transferencia.findMany({
         where,
         orderBy: [{ ano: 'desc' }, { identificador_nro: 'desc' }],
         skip: skip,
         take: ipp,
         select: this._getTransferenciaSelectClause(),
     });
📝 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
async findAllTransferenciaV2(
filters: FilterTransferenciaV2Dto,
user: PessoaFromJwt
): Promise<PaginatedWithPagesDto<TransferenciaDto>> {
const ipp = filters.ipp ?? 25;
const page = filters.pagina ?? 1;
const skip = (page - 1) * ipp;
let total_registros = 0;
let token_paginacao = filters.token_paginacao;
const filtersForHash = { ...filters };
delete filtersForHash.pagina;
delete filtersForHash.token_paginacao;
if (token_paginacao) {
const decoded = this.decodePageToken(token_paginacao, filtersForHash);
total_registros = decoded.total_rows;
} else {
const where = await this._getWhereClauseForFindAll(filters, user);
total_registros = await this.prisma.transferencia.count({ where });
token_paginacao = this.encodePageToken(filtersForHash, total_registros);
}
const where = await this._getWhereClauseForFindAll(filters, user);
const rows = await this.prisma.transferencia.findMany({
where,
orderBy: [{ ano: 'desc' }, { identificador_nro: 'desc' }],
skip: skip,
take: ipp,
select: this._getTransferenciaSelectClause(),
});
const total_paginas = Math.ceil(total_registros / ipp);
const linhas = rows.map((r) => this._mapTransferenciaToDto(r));
return {
total_registros: total_registros,
paginas: total_paginas,
pagina_corrente: page,
token_paginacao: token_paginacao,
tem_mais: page < total_paginas,
token_ttl: PAGINATION_TOKEN_TTL,
linhas: linhas,
};
}
async findAllTransferenciaV2(
filters: FilterTransferenciaV2Dto,
user: PessoaFromJwt
): Promise<PaginatedWithPagesDto<TransferenciaDto>> {
const ipp = filters.ipp ?? 25;
const page = filters.pagina ?? 1;
const skip = (page - 1) * ipp;
let total_registros = 0;
let token_paginacao = filters.token_paginacao;
const filtersForHash = { ...filters };
delete filtersForHash.pagina;
delete filtersForHash.token_paginacao;
const where = await this._getWhereClauseForFindAll(filters, user);
if (token_paginacao) {
const decoded = this.decodePageToken(token_paginacao, filtersForHash);
total_registros = decoded.total_rows;
} else {
total_registros = await this.prisma.transferencia.count({ where });
token_paginacao = this.encodePageToken(filtersForHash, total_registros);
}
const rows = await this.prisma.transferencia.findMany({
where,
orderBy: [{ ano: 'desc' }, { identificador_nro: 'desc' }],
skip: skip,
take: ipp,
select: this._getTransferenciaSelectClause(),
});
const total_paginas = Math.ceil(total_registros / ipp);
const linhas = rows.map((r) => this._mapTransferenciaToDto(r));
return {
total_registros: total_registros,
paginas: total_paginas,
pagina_corrente: page,
token_paginacao: token_paginacao,
tem_mais: page < total_paginas,
token_ttl: PAGINATION_TOKEN_TTL,
linhas: linhas,
};
}
🤖 Prompt for AI Agents
In backend/src/casa-civil/transferencia/transferencia.service.ts between lines
1917 and 1959, the method redundantly builds the WHERE clause twice and performs
a count query even when total_registros is already obtained from the decoded
token. To fix this, build the WHERE clause once before the conditional check,
then use it for both the count query and the findMany query. Also, skip the
count query if total_registros is retrieved from the token to avoid unnecessary
database calls.

Comment on lines +2070 to +2080
private decodePageToken(jwt: string, filters: object): TransferenciaPageTokenJwtBody {
try {
const decoded = this.jwtService.verify(jwt) as TransferenciaPageTokenJwtBody;
if (decoded.search_hash !== Object2Hash(filters)) {
throw new Error('Filter criteria changed during pagination.');
}
return decoded;
} catch (error) {
throw new HttpException(`Token de paginação inválido ou expirado. ${error.message}`, 400);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid exposing internal error details in user-facing messages.

Line 2078 includes the raw error message in the HttpException, which could expose internal implementation details to the client.

Apply this fix to sanitize the error message:

 private decodePageToken(jwt: string, filters: object): TransferenciaPageTokenJwtBody {
     try {
         const decoded = this.jwtService.verify(jwt) as TransferenciaPageTokenJwtBody;
         if (decoded.search_hash !== Object2Hash(filters)) {
             throw new Error('Filter criteria changed during pagination.');
         }
         return decoded;
     } catch (error) {
-        throw new HttpException(`Token de paginação inválido ou expirado. ${error.message}`, 400);
+        throw new HttpException('Token de paginação inválido ou expirado.', 400);
     }
 }
🤖 Prompt for AI Agents
In backend/src/casa-civil/transferencia/transferencia.service.ts around lines
2070 to 2080, the catch block includes the raw error message in the
HttpException, potentially exposing internal details. Modify the catch block to
throw a generic error message without appending error.message, ensuring the
client receives a sanitized, user-friendly message instead of internal error
details.

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.

1 participant