Skip to content

feat(variáveis): adiciona suporte para processamento automático de variáveis suspensas - #511

Merged
renatocron merged 7 commits into
homolfrom
feat/ciclo-var
Jan 19, 2026
Merged

renatocron merged 7 commits into
homolfrom
feat/ciclo-var

Conversation

@renatocron

@renatocron renatocron commented Jan 17, 2026 •

Copy link
Copy Markdown
Contributor

…

Implementa a capacidade de processar variáveis globais suspensas, copiando valores automaticamente para variáveis não acumulativas e definindo zero para acumulativas. Isso melhora a eficiência ao evitar a necessidade de intervenção manual para variáveis suspensas, garantindo que os ciclos possam ser fechados automaticamente quando todas as filhas estão suspensas. Além disso, adiciona novos campos e validações para gerenciar variáveis filhas e suspensas, aprimorando a integridade dos dados e a experiência do usuário.

Summary by CodeRabbit

  • New Features

    • Manual endpoint to trigger processing of suspended global variables
    • Responses include counts of suspended and non-suspended child variables
  • Improvements

    • Centralized suspension handling; suspended children excluded from validation, approval and status checks and are auto-filled
    • Automated processing of suspended globals and auto-closing of parent cycles when applicable
    • Added reference-date support, uniqueness enforcement and default processed timestamp for suspended-variable records
    • Update paths restrict child edits to suspension and base-value only

✏️ Tip: You can customize this high-level summary in your review settings.

…riáveis suspensas

Implementa a capacidade de processar variáveis globais suspensas, copiando valores automaticamente para variáveis não acumulativas e definindo zero para acumulativas. Isso melhora a eficiência ao evitar a necessidade de intervenção manual para variáveis suspensas, garantindo que os ciclos possam ser fechados automaticamente quando todas as filhas estão suspensas. Além disso, adiciona novos campos e validações para gerenciar variáveis filhas e suspensas, aprimorando a integridade dos dados e a experiência do usuário.
@coderabbitai

coderabbitai Bot commented Jan 17, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Schema and service were updated to support suspended global variables: added ciclo_referencia, made ciclo_fisico_* relations nullable, defaulted processado_em, added indexes; service/controller/DTOs extended to track/process suspended children, introduce bulk processing of suspended globals, propagate suspension changes, and auto-close parent cycles.

Changes

Cohort / File(s) Summary
Database Schema & Migration
backend/prisma/schema.prisma, backend/prisma/migrations/.../migration.sql
Added optional ciclo_referencia (Date), made ciclo_fisico_base_id and ciclo_fisico_corrente_id nullable and relations optional, set processado_em default to now()/CURRENT_TIMESTAMP, added unique index on (variavel_id,serie,ciclo_referencia), adjusted FKs to ON DELETE SET NULL.
Service: global suspended processing
backend/src/variavel/variavel.service.ts
Added centralized suspension handler (handleSuspensaoChange), processing methods (processVariaveisGlobaisSuspensasController, processVariaveisGlobaisSuspensas), auto-close parent-cycle logic, upsert logic for serie/controle entries, recalculation/task enqueueing, and related imports (CONST_BOT_USER_ID, MetaService, SerieCompactToken, UpdateVariavelFilhasDto).
Cycle handling & approval logic
backend/src/variavel/variavel.ciclo.service.ts
Added `suspendida_em?: Date
Controller endpoint
backend/src/variavel/variavel.controller.ts
Added POST /processa-variaveis-globais-suspensas endpoint delegating to service controller method (protected).
DTOs / Patch DTO
backend/src/variavel/dto/variavel.ciclo.dto.ts, backend/src/variavel/dto/update-valores-base-filhas.dto.ts
Response DTOs extended with filhas_suspensas_count and filhas_nao_suspensas_count; UpdateVariavelFilhasDto replaced by PartialType(PickType(UpdateVariavelDto,['suspendida','valor_base'])).
Controller / Service signatures
backend/src/variavel/*
Public API surface updated: ICicloCorrente items include `suspendida_em?: Date

Sequence Diagram

sequenceDiagram
    participant Client
    participant Controller as VariavelGlobalController
    participant Service as VariavelService
    participant DB as PrismaDatabase
    participant Recalc as RecalculationEngine

    Client->>Controller: POST /processa-variaveis-globais-suspensas
    Controller->>Service: processVariaveisGlobaisSuspensasController()
    Service->>Service: begin transaction
    Service->>DB: query suspended global variables (variavel, suspendida_em, ciclo_referencia)
    DB-->>Service: suspended variable rows

    loop per suspended variable
        Service->>DB: upsert serie_variavel (copy previous or set 0)
        DB-->>Service: upsert result
        Service->>DB: insert/update variavel_suspensa_controle (ciclo_referencia, processado_em)
    end

    Service->>Recalc: trigger dependent series recalculation
    Recalc->>DB: update dependent series
    Recalc-->>Service: recalculation complete

    Service->>DB: query parent cycles affected
    DB-->>Service: parent cycle info
    alt parent with all children suspended
        Service->>DB: close parent cycle, insert automatic analysis entry
        Service->>Recalc: enqueue recalculation/meta tasks
    end

    Service->>Service: commit transaction
    Service-->>Controller: return processed variable IDs
    Controller-->>Client: 200 OK with results
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • GustavoFSoares

Poem

🐰
I hopped through schemas, made dates align,
Noted who naps and which rows must fill in kind,
Auto-copied values when little ones rest,
Closed parent cycles when none passed the test,
A rabbit claps — the pipeline hops along!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: implementing automatic processing of suspended variables, which is the core feature across all modified files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 Fix all issues with AI agents
In
`@backend/prisma/migrations/20260117025443_add_ciclo_referencia_to_suspensa_controle/migration.sql`:
- Around line 13-14: The index on variavel_suspensa_controle
(variavel_suspensa_controle_variavel_id_serie_ciclo_referenc_idx) currently
allows duplicates; if (variavel_id, serie, ciclo_referencia) must be unique,
change the migration to create a UNIQUE index (replace CREATE INDEX with CREATE
UNIQUE INDEX for that index name) so the DB enforces singleton rows, otherwise
update the schema/migration comments to clarify that uniqueness is not required
to avoid implying uniqueness.

In `@backend/prisma/schema.prisma`:
- Around line 2026-2029: The schema comment incorrectly calls the constraint an
"índice único" while the actual declaration is @@index([variavel_id, serie,
ciclo_referencia]); either change that declaration to @@unique([variavel_id,
serie, ciclo_referencia]) so the DB enforces uniqueness for the global
suspension control, and regenerate/create a migration that creates a UNIQUE
index, or if uniqueness is not intended, update the comment text to remove
"índice único" and clarify it is a non-unique index; locate the @@index line and
the surrounding comment in the Prisma model to make the appropriate change.

In `@backend/src/variavel/variavel.ciclo.service.ts`:
- Around line 1056-1061: The current logic in formatarValores (where
filhasNaoSuspensas and todasVariaveis are built) allows pushing the parent into
the editable list when all children are suspended, but validaValoresVariaveis
rejects parent submissions if the variable has any children; fix by keeping the
parent out whenever the variable has children regardless of their suspended
state: replace the fallback that pushes variavel into todasVariaveis with a
check against variavel.variaveis_filhas.length (i.e., only push the parent when
variavel.variaveis_filhas.length === 0), and ensure formatarValores and
validaValoresVariaveis share the same rule; alternatively, if you prefer showing
the parent row, set a flag on the parent (e.g., isEditableParent = false) in
formatarValores so the UI can disable/hide inputs and validation will accept no
editable parent values.

In `@backend/src/variavel/variavel.service.ts`:
- Around line 2431-2460: The auto-close loop over ownersToClose creates
variavelGlobalCicloAnalise and updates variavelCicloCorrente but fails to call
the database function f_atualiza_variavel_ciclo_corrente or the same
enqueue/recalc logic used by marcaLiberacaoEnviada, leaving cycle state stale;
update the loop (after prismaTx.variavelCicloCorrente.update) to invoke
f_atualiza_variavel_ciclo_corrente for the given variavel_id and to enqueue the
same recalculation/job dispatch used by marcaLiberacaoEnviada so the ciclo state
and downstream recalcs are refreshed immediately.
- Around line 2277-2353: The temp table _suspend_values_global currently uses
COALESCE(last_val.valor_nominal, 0) for valor_novo which creates a 0 Realizado
when there was no prior value; change the SELECT that defines valor_novo to:
WHEN j.acumulativa = true THEN 0 ELSE last_val.valor_nominal END (i.e., remove
COALESCE) so non-acumulativa rows produce NULL when no prior value exists, and
then in the INSERT (ins_real / INSERT INTO serie_variavel ... FROM
_suspend_values_global) add a filter to skip rows where valor_novo IS NULL for
non-acumulativa variables (e.g., add WHERE (acumulativa = true) OR (valor_novo
IS NOT NULL)) so you only insert copied values when a previous value exists and
only default 0 for RealizadoAcumulado.
- Around line 1395-1408: The current check in variavel.service.ts (using
selfBefUpdate, allowedFieldsForChildren and UpdateVariavelDto) rejects any
child-variable PATCH except 'suspendida' but the error message is generic;
update the HttpException text to clearly instruct clients to use the dedicated
child endpoint (PATCH variavel/:id/filha/:id2) for changes that require
valor_base and indicate which fields are allowed via the generic endpoint (e.g.,
only 'suspendida' here) so callers know to migrate to the child-specific route.

Comment thread backend/prisma/schema.prisma Resolved
…o de variáveis filhas

Implementa um método dedicado para atualizar o status de suspensão de variáveis filhas, garantindo que apenas o campo 'suspendida' possa ser alterado diretamente. Isso melhora a segurança e a integridade dos dados, assegurando que outras alterações sejam feitas através da variável mãe. Além disso, a lógica de formatação de valores foi ajustada para permitir a inclusão da variável mãe quando todas as filhas estão suspensas, se configurado.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/variavel/variavel.service.ts (1)

1395-1417: Add Calculada suspension guard to updateSuspensaoFilha.

The early return for child variables bypasses the Calculada suspension check. Since Calculada variables can be created as children (confirmed in variavel.calculada.service.ts:219), a Calculada child could be suspended through updateSuspensaoFilha, which lacks the guard present in the parent update path. Add the same check from line 1416 before processing the suspension.

🤖 Fix all issues with AI agents
In
`@backend/prisma/migrations/20260117162549_add_ciclo_referencia_to_suspensa_controle/migration.sql`:
- Around line 14-20: The unique index
"variavel_suspensa_controle_variavel_id_serie_ciclo_referenc_key" on table
"variavel_suspensa_controle" will not enforce uniqueness for rows where
"ciclo_referencia" is NULL; either backfill "ciclo_referencia" and ALTER COLUMN
"ciclo_referencia" SET NOT NULL then create the UNIQUE INDEX, or replace the
index with a partial unique index that only enforces uniqueness for non-NULL
values (e.g., UNIQUE ON ("variavel_id","serie","ciclo_referencia") WHERE
"ciclo_referencia" IS NOT NULL); choose one approach, apply the corresponding
migration steps (backfill, change nullability, recreate index OR create partial
index) and ensure the migration drops the previous index before creating the
corrected one.

In `@backend/src/variavel/variavel.service.ts`:
- Around line 2378-2391: When no rows are inserted by ins_real (filledVarIds is
empty) the current logic skips autoCloseParentCyclesIfAllChildrenSuspended, so
parent cycles never close; change the flow to always compute cycleOwnerIds from
the suspend-job source (use affectedVars or derive from
_suspend_jobs_global/ins_ctrl when affectedVars has no filled entries) and call
autoCloseParentCyclesIfAllChildrenSuspended(cycleOwnerIds, prismaTx)
unconditionally, while keeping calls to recalc_series_dependentes(filledVarIds,
prismaTx) and recalc_indicador_usando_variaveis(filledVarIds, prismaTx) gated
behind filledVarIds.length > 0 so recalculations only run when actual inserts
occurred.

…ora validação de campos

A atualização de variáveis filhas foi simplificada ao consolidar a lógica de suspensão e valor_base em um único método, reduzindo duplicação de código. A validação de campos agora assegura que apenas 'suspendida' e 'valor_base' podem ser alterados, melhorando a segurança e clareza do código. Além disso, a lógica de suspensão foi extraída para uma função dedicada, tornando o código mais modular e fácil de manter.
…is mãe sem valores inseridos

Ajusta a consulta para buscar todos os cycle owners, garantindo que ciclos de variáveis mãe sejam fechados automaticamente mesmo quando não há valores inseridos. Isso é necessário para lidar com casos em que todas as variáveis filhas estão suspensas, mas não há valores novos, assegurando a consistência do estado do ciclo.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@backend/src/variavel/variavel.service.ts`:
- Around line 2421-2435: The created variavelGlobalCicloAnalise record uses an
array for the valores field (valores: []) while other flows use an object
(valores: {}); update the variavelGlobalCicloAnalise.create call in
variavel.service.ts (the block that builds the auto-close record for owner.id /
fase 'Liberacao') to set valores to the consistent JSON shape used elsewhere
(e.g., valores: {}) so downstream consumers receive the expected object
structure.
- Around line 2400-2415: The query populating ownersToClose (prismaTx.$queryRaw
in variavel.service.ts) can match childless variables because NOT EXISTS(...) is
true for standalones; modify the SQL to also require that the parent has at
least one child by adding an EXISTS(...) clause that checks for any child rows
(e.g., SELECT 1 FROM variavel child WHERE child.variavel_mae_id =
vcc.variavel_id AND child.removido_em IS NULL AND child.tipo = 'Global') so only
parents with children are considered for auto-close; update the query that
selects from variavel_ciclo_corrente (alias vcc) accordingly.

Comment on lines +2421 to +2435
// Cria registro de análise para cada fase pendente
await prismaTx.variavelGlobalCicloAnalise.create({
data: {
variavel_id: owner.id,
fase: 'Liberacao',
referencia_data: owner.ultimo_periodo_valido,
informacoes_complementares:
'Ciclo encerrado automaticamente: Todas as variáveis filhas estão suspensas.',
eh_liberacao_auto: true,
aprovada: true,
ultima_revisao: true,
valores: [],
criado_por: CONST_BOT_USER_ID,
sincronizar_serie_variavel: false,
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Use a consistent JSON shape for valores.

Other flows set valores: {}, but this auto-close path writes []. If consumers expect an object, this mismatch can break parsing.

🛠️ Suggested fix
-                    valores: [],
+                    valores: {},
📝 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
// Cria registro de análise para cada fase pendente
await prismaTx.variavelGlobalCicloAnalise.create({
data: {
variavel_id: owner.id,
fase: 'Liberacao',
referencia_data: owner.ultimo_periodo_valido,
informacoes_complementares:
'Ciclo encerrado automaticamente: Todas as variáveis filhas estão suspensas.',
eh_liberacao_auto: true,
aprovada: true,
ultima_revisao: true,
valores: [],
criado_por: CONST_BOT_USER_ID,
sincronizar_serie_variavel: false,
},
// Cria registro de análise para cada fase pendente
await prismaTx.variavelGlobalCicloAnalise.create({
data: {
variavel_id: owner.id,
fase: 'Liberacao',
referencia_data: owner.ultimo_periodo_valido,
informacoes_complementares:
'Ciclo encerrado automaticamente: Todas as variáveis filhas estão suspensas.',
eh_liberacao_auto: true,
aprovada: true,
ultima_revisao: true,
valores: {},
criado_por: CONST_BOT_USER_ID,
sincronizar_serie_variavel: false,
},
🤖 Prompt for AI Agents
In `@backend/src/variavel/variavel.service.ts` around lines 2421 - 2435, The
created variavelGlobalCicloAnalise record uses an array for the valores field
(valores: []) while other flows use an object (valores: {}); update the
variavelGlobalCicloAnalise.create call in variavel.service.ts (the block that
builds the auto-close record for owner.id / fase 'Liberacao') to set valores to
the consistent JSON shape used elsewhere (e.g., valores: {}) so downstream
consumers receive the expected object structure.

…iáveis independentes

Adiciona uma verificação para garantir que variáveis independentes, que podem estar em cycleOwnerIds, não passem incorretamente na verificação NOT EXISTS. Isso corrige um problema onde variáveis sem filhos eram tratadas de forma inadequada, assegurando que apenas variáveis com filhos ativos e não removidos sejam consideradas.
@renatocron
renatocron merged commit d844f20 into homol Jan 19, 2026
@renatocron
renatocron deleted the feat/ciclo-var branch January 19, 2026 13:34
@sonarqubecloud

Copy link
Copy Markdown

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