Skip to content

Automatiza teste que tramita o processo para a fase de Orçamento - #448

Draft
jgaguiarm wants to merge 1 commit into
developfrom
feature/automates-test-tramit-process-succefully-to-budget
Draft

Automatiza teste que tramita o processo para a fase de Orçamento#448
jgaguiarm wants to merge 1 commit into
developfrom
feature/automates-test-tramit-process-succefully-to-budget

Conversation

@jgaguiarm

@jgaguiarm jgaguiarm commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

✅ Descrição do propósito desse Pull Request

Automatiza teste que tramita o processo para a fase de Orçamento

🧭 Referência a Issue

#447
#445

❓ O que foi feito para atingir isso?


🏃‍♀️ Tipo de mudança

Marque as opções relevantes:

  • Bug fix (correção de bug)
  • Nova feature (mudança não retrocompatível que adiciona funcionalidade)
  • Mudança de breaking (correção ou feature que faria com que a funcionalidade existente não funcionasse como esperado)
  • Documentação (somente mudanças ou atualizações na documentação)

🕵️ Como foi testado?

  • Critério de aceitação
  • Testes de software (TDD, BDD, UNITÁRIO, INTEGRAÇÃO, E2E)

Checklist: ✔️

  • Meu código segue as diretrizes do projeto
  • Eu fiz um code review com minha equipe
  • Eu comentei meu código, especialmente em áreas de difícil entendimento
  • Eu atualizei a documentação correspondente
  • Testes novos e existentes passaram localmente com minhas alterações

Observação:

Summary by CodeRabbit

  • New Features

    • Added support for submitting projects successfully from formalization through the budget phase.
    • Added legal opinion document creation during formalization.
    • Added project return and processing actions with confirmation and success validation.
  • Bug Fixes

    • Improved project selection and search validation using normalized project identifiers.
    • Updated required-field handling and Gazette document uploads for more reliable submissions.
  • Tests

    • Expanded end-to-end coverage for formalization, project return, and budget transition workflows.

@jgaguiarm
jgaguiarm requested a review from Junior-Shyko July 31, 2026 14:08
@jgaguiarm jgaguiarm self-assigned this Jul 31, 2026
@jgaguiarm jgaguiarm added the Quality Tarefas relacionadas a testes unitários e automáticos label Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a0f21147-ea98-46df-bd21-31bc21525d40

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)

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.

@jgaguiarm
jgaguiarm marked this pull request as draft July 31, 2026 14:08

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
cypress/pages/project/ProjectPage.js (1)

60-79: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Normalize both sides of the NUP comparison, on both branches, for consistency.

Line 64 duplicates Notice.normalizeNup's logic (text.replace(/\D/g, '')) instead of reusing it. Line 65 then compares the normalized formattedNup against the raw projectNup parameter without normalizing it. If a caller passes a formatted NUP (with separators), this assertion fails even though the values represent the same NUP.

The else branch (line 76) does the opposite: it normalizes only the expected side (Notice.normalizeNup(projectNup)) and matches it as a substring against the rendered DOM text via cy.contains, which depends on the DOM text also being digit-only.

Use Notice.normalizeNup consistently on both sides of both comparisons.

♻️ Suggested fix
             cy.get(el.projectList).within(() => {
                 cy.get(el.projectNupProjectList, { timeout: TIMEOUTS.SEARCH })
                     .invoke('text')
                     .then((text) => {
-                        const formattedNup = text.replace(/\D/g, '');
-                        expect(formattedNup).to.equal(projectNup);
+                        expect(Notice.normalizeNup(text)).to.equal(Notice.normalizeNup(projectNup));
                     });
             });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cypress/pages/project/ProjectPage.js` around lines 60 - 79, Update both NUP
assertions in the project-list flow to normalize the rendered value and expected
projectNup with Notice.normalizeNup before comparing them. Replace the
duplicated text.replace logic in the first branch, and ensure the else branch
compares normalized values rather than relying on cy.contains against raw DOM
text.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cypress/e2e/efomento/projects/formalization.cy.js`:
- Around line 69-75: The “should tramit process to budget successfully” test
must start with the original Formalization project state, because the preceding
workflow mutates backend state. Reset or reseed the project in an appropriate
hook before invoking FormalizationWorkflow.tramitProcessWithSuccessToBudget, or
switch this test to an isolated fixture; preserve the existing workflow and test
data setup otherwise.

In `@cypress/pages/project/formalizationTab/FormalizationTab.js`:
- Around line 20-40: Add officialGazetteFile to the destructured parameters in
the fillRequiredFields method signature so that the test's configured gazette
file value is captured. Then update the gazette file upload logic within
fillRequiredFields to use the officialGazetteFile parameter instead of the
hardcoded cypress/fixtures/teste.pdf path, ensuring the method respects the
fixture value passed by the caller.

In `@cypress/pages/project/ProjectPage.js`:
- Around line 15-29: Update goToProjectDetailsPage to stop queuing clicks inside
the .each() callback: identify the matching row through the
cy.get(el.projectNupProjectList) chain using jQuery/Cypress filtering, then call
cy.wrap(...).click() exactly once on that row before the existing URL assertion.
Remove the misleading early-return comment and preserve Notice.normalizeNup
comparisons.

---

Nitpick comments:
In `@cypress/pages/project/ProjectPage.js`:
- Around line 60-79: Update both NUP assertions in the project-list flow to
normalize the rendered value and expected projectNup with Notice.normalizeNup
before comparing them. Replace the duplicated text.replace logic in the first
branch, and ensure the else branch compares normalized values rather than
relying on cy.contains against raw DOM text.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9aad7fb3-f24b-450b-952d-ea6d03de8dfb

📥 Commits

Reviewing files that changed from the base of the PR and between 5463579 and 539778c.

⛔ Files ignored due to path filters (1)
  • cypress/fixtures/teste.pdf is excluded by !**/*.pdf
📒 Files selected for processing (7)
  • cypress/e2e/efomento/projects/formalization.cy.js
  • cypress/fixtures/projects.json
  • cypress/pages/project/ProjectPage.js
  • cypress/pages/project/formalizationTab/FormalizationTab.js
  • cypress/support/workflows/FormalizationWorkflow.js
  • resources/js/Components/ReturnProcessAction.vue
  • resources/js/Pages/ProjectDetails/Partials/Tabs/Actions/TramitButton.vue
💤 Files with no reviewable changes (1)
  • resources/js/Pages/ProjectDetails/Partials/Tabs/Actions/TramitButton.vue

Comment on lines +69 to +75
it('should tramit process to budget successfully', function () {
FormalizationWorkflow.tramitProcessWithSuccessToBudget({
role: 'formalization',
notice: this.notice,
project: this.project,
});
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Map the spec before inspecting hooks and state-reset commands.
ast-grep outline cypress/e2e/efomento/projects/formalization.cy.js --items all

# Find local and global Cypress hooks that can reset persisted test state.
rg -n -C 4 --glob '*.{js,ts}' \
  '\b(beforeEach|afterEach|before|after)\s*\(|\b(reset|seed|truncate|migrate|database|db:|cy\.task)\b' \
  cypress

# Inspect commands that implement project creation, reset, or fixture seeding.
rg -n -C 4 --glob '*.{js,ts}' \
  '\b(createProject|resetProject|seedProject|resetDatabase|seedDatabase)\s*\(' \
  cypress

Repository: secultce/efomento

Length of output: 7057


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== cypress files =="
find cypress -maxdepth 5 -type f | sed 's#^\./##' | sort | head -200

echo "== formalization.spec focused lines =="
cat -n cypress/e2e/efomento/projects/formalization.cy.js | sed -n '1,140p'

echo "== FormalizationWorkflow outline and relevant files =="
fd -a 'FormalizationWorkflow\.(js|ts)$' . | sed 's#^\./##'
for f in $(fd 'FormalizationWorkflow\.(js|ts)$' .); do
  echo "--- $f"
  wc -l "$f"
  ast-grep outline "$f" --items all || true
  rg -n -C 3 'tramitProcessWithSuccessToBudget|tramitProcessWithSuccessToLegal|formalization|reset|seed|reload|fixture|project' "$f"
done

echo "== support config/task imports and Cypress plugins =="
find cypress -maxdepth 4 -type f \( -name '*.js' -o -name '*.ts' \) | sort
for f in $(find cypress -maxdepth 4 -type f \( -name '*.js' -o -name '*.ts' \) | sort); do
  rg -l 'beforeEach|afterEach|before|after|cy\.task|drop|truncate|reset|seed|migrate|database|migrations' "$f" && echo "=== $f ===" && sed -n '1,220p' "$f"
done

Repository: secultce/efomento

Length of output: 37192


Reset the project state before tramiting to budget.

This spec reloads fixtures in beforeEach, but returnProcessToLealAnalysisTab() changes backend state through FormalizationTab.clickReturnProcessButton() before the next workflow starts. If the database is not reset globally, this test starts on a project that no longer has the same Formalization state. Add a seed/reset in a hook, restore the original project, or use a separate fixture for this test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cypress/e2e/efomento/projects/formalization.cy.js` around lines 69 - 75, The
“should tramit process to budget successfully” test must start with the original
Formalization project state, because the preceding workflow mutates backend
state. Reset or reseed the project in an appropriate hook before invoking
FormalizationWorkflow.tramitProcessWithSuccessToBudget, or switch this test to
an isolated fixture; preserve the existing workflow and test data setup
otherwise.

Comment on lines +20 to +40
fillRequiredFields({
asjurFinalisticProcessingDate,
asjurProcessReceivedDate,
processAssignedTo,
reportStatusSelected,
eparceriasCertificateDate,
asjurProcessingDate,
responsibleAtAsjur,
termNumber,
termSignatureSentAt,
termSignedAt,
sentToOfficeAt,
signedByOfficeAt,
saccNumber,
cgeAtendeTicket,
deliberationOption,
sentToChiefOfStaffAt,
officialGazettePublishedAt,
instrumentValidityStartAt,
instrumentValidityEndAt,
}) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use the configured gazette file.

fillRequiredFields drops officialGazetteFile and always uploads cypress/fixtures/teste.pdf. tramitProcessWithSuccessToBudget passes project.officialGazetteFile, but the test never uses that fixture value.

Proposed fix
         officialGazettePublishedAt,
+        officialGazetteFile,
         instrumentValidityStartAt,
         instrumentValidityEndAt,
     }) {
...
-        cy.get(el.officialGazetteFileInput).selectFile('cypress/fixtures/teste.pdf', { force: true });
+        cy.get(el.officialGazetteFileInput).selectFile(officialGazetteFile, { force: true });

Also applies to: 79-79

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cypress/pages/project/formalizationTab/FormalizationTab.js` around lines 20 -
40, Add officialGazetteFile to the destructured parameters in the
fillRequiredFields method signature so that the test's configured gazette file
value is captured. Then update the gazette file upload logic within
fillRequiredFields to use the officialGazetteFile parameter instead of the
hardcoded cypress/fixtures/teste.pdf path, ensuring the method respects the
fixture value passed by the caller.

Comment on lines 15 to 29
goToProjectDetailsPage(projectNup) {
const expectedNup = Notice.normalizeNup(projectNup);

cy.get(el.rowTableProjectList)
.contains(el.projectNupProjectList, expectedNup)
.closest(el.rowTableProjectList)
.find(el.openProjectOpeningTabButton)
.click();
cy.get(el.projectNupProjectList).each(($element) => {
const currentNup = Notice.normalizeNup($element.text());

if (currentNup === expectedNup) {
cy.wrap($element).closest(el.rowTableProjectList).find(el.openProjectOpeningTabButton).click();

return false; // interrompe o .each()
}
});

cy.url({ timeout: 10000 }).should('match', /\/editais\/\d+\/projetos\/\d+(?:\?tab=.*)?$/);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Cypress .each() return false stop iteration when queuing a cy command inside the callback

💡 Result:

In Cypress, you can stop the.each loop early by returning false in the callback function [1][2]. However, this mechanism only works for synchronous code [3][4]. When you enqueue Cypress commands inside the.each callback, those commands are scheduled to run asynchronously [3][5]. Because.each iterates and queues these commands synchronously before the commands themselves have executed, returning false at the end of the callback will not stop the commands that have already been placed in the Cypress command queue for subsequent iterations [5][6]. To achieve an early exit when using Cypress commands, you must use a flag variable and wrap your conditional logic inside a cy.then callback [5][6]. This ensures that the decision to stop is evaluated asynchronously as the commands run, rather than synchronously while the loop is still being built [5][6]. Recommended Pattern for Early Exit: 1. Define a boolean flag (e.g., let shouldStop = false) outside the.each loop [5][6]. 2. Use cy.then inside the.each callback to check the flag before performing any actions [5][6]. 3. If the stopping condition is met, update the flag within a command chain (e.g., inside.then) so that subsequent iterations see the updated value and skip their actions [5][6]. Example: let shouldStop = false; cy.get('selector').each(($el) => { cy.then( => { if (shouldStop) return; cy.wrap($el).click.then( => { if (conditionMet) { shouldStop = true; } }); }); });

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repo files matching ProjectPage.js:"
fd -a 'ProjectPage\.js$' . || true

file="$(fd 'ProjectPage\.js$' . | head -n 1 | xargs -r readlink -f || true)"
if [ -n "$file" ]; then
  echo
  echo "File: $file"
  wc -l "$file"
  echo
  sed -n '1,80p' "$file" | cat -n

  echo
  echo "Occurrences of goToProjectDetailsPage and projectNupProjectList:"
  rg -n "goToProjectDetailsPage|projectNupProjectList|Notice\.normalizeNup" .
fi

Repository: secultce/efomento

Length of output: 4940


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Notice implementation:"
while IFS= read -r f; do
  echo "--- $f"
  wc -l "$f"
  sed -n '1,180p' "$f" | cat -n
done < <(fd 'index\.js$' cypress/pages/notice cypress/pages | sed 's#^#./#')

echo
echo "Normalize NUP occurrences:"
rg -n "normalizeNup|NUP|nup" cypress/pages cypress/fixtures cypress/e2e -S

echo
echo "FormalizationWorkflow context:"
f="$(fd 'FormalizationWorkflow\.js$' . | head -n 1 | xargs -r readlink -f || true)"
if [ -n "$f" ]; then
  wc -l "$f"
  sed -n '1,80p' "$f" | cat -n
fi

echo
echo "Project page usages in e2e/support:"
rg -n "goToProjectDetailsPage\\(|\\.openProjectOpeningTabButton|\\[data-cy=project-nup-project-list\\]" cypress cypress -S || true

Repository: secultce/efomento

Length of output: 230


🏁 Script executed:

#!/bin/bash
set -euo pipefail

f="$(fd 'index\.js$' cypress/pages/notice -d 2 2>/dev/null | head -n 1 || true)"
if [ -n "$f" ]; then
  echo "Notice implementation: $f"
  wc -l "$f"
  sed -n '1,180p' "$f" | cat -n
fi

echo
echo "Normalize NUP occurrences:"
rg -n "normalizeNup|NUP|nup" cypress/pages cypress/fixtures cypress/e2e -S || true

echo
echo "FormalizationWorkflow context:"
wf="$(fd 'FormalizationWorkflow\.js$' . | head -n 1 | xargs -r readlink -f || true)"
if [ -n "$wf" ]; then
  wc -l "$wf"
  sed -n '1,120p' "$wf" | cat -n
fi

echo
echo "Project page usages in cypress:"
rg -n "goToProjectDetailsPage\(|\.openProjectOpeningTabButton|project-nup-project-list" cypress -S || true

echo
echo "Fixture project NUP samples (if present):"
python3 - <<'PY'
import pathlib, json
for p in pathlib.Path('cypress/fixtures').rglob('.json') if pathlib.Path('cypress/fixtures').exists() else []:
    try:
        data = json.loads(p.read_text())
    except Exception:
        continue
    samples = {}
    def walk(x):
        if isinstance(x, dict):
            for k,v in x.items():
                if 'nup' in k.lower() or k in ('projectNup','NUP','nup'):
                    samples[str(k)] = v
                walk(v)
        elif isinstance(x, list):
            walk(x)
    walk(data)
    if samples:
        print(p, samples)
PY

Repository: secultce/efomento

Length of output: 16002


Stop the NUP lookup outside of .each().

The matching branch queues cy.wrap(...).click() before returning false, so Cypress keeps building the .each() callback queue and the comment // interrompe o .each() is misleading. If more than one row normalizes to the same NUP, this can queue multiple click commands.

Find the matching row with jQuery/Cypress command chains after cy.get(...), then call cy.wrap(...).click() once for that row.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cypress/pages/project/ProjectPage.js` around lines 15 - 29, Update
goToProjectDetailsPage to stop queuing clicks inside the .each() callback:
identify the matching row through the cy.get(el.projectNupProjectList) chain
using jQuery/Cypress filtering, then call cy.wrap(...).click() exactly once on
that row before the existing URL assertion. Remove the misleading early-return
comment and preserve Notice.normalizeNup comparisons.

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

Labels

Quality Tarefas relacionadas a testes unitários e automáticos

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant