Skip to content

activar usuario#96

Open
IsaacAburto1548 wants to merge 3 commits into
masterfrom
activar-usuario-
Open

activar usuario#96
IsaacAburto1548 wants to merge 3 commits into
masterfrom
activar-usuario-

Conversation

@IsaacAburto1548

@IsaacAburto1548 IsaacAburto1548 commented Jun 27, 2026

Copy link
Copy Markdown
Collaborator

Ahora, al darle al botón de eliminar y seleccionar "Desactivar (Soft Delete)" en el sistema de gestión de usuarios, pedirá de forma obligatoria el motivo (ej. "ya no pertenece a la iglesia"). El motivo aparecerá visualmente bajo la etiqueta "Inactivo" en la lista de usuarios. Aparecerá un nuevo botón verde (✓) para los usuarios inactivos que permite reactivarlos instantáneamente.

Summary by CodeRabbit

  • New Features
    • Deactivate users now requires an inactive reason; the reason is stored and shown in the user management view.
    • Inactive users display the reason and offer a quick reactivate action.
    • Added an admin-only update flow to set, update, or clear the inactive reason.
  • Bug Fixes
    • Improved validation for deactivation: missing or blank reasons are rejected, and inactive status/reason remain consistent across listings and updates.
  • Chores
    • Build now runs the database sync step before compiling to keep schema changes current.

Ahora, al darle al botón de eliminar y seleccionar "Desactivar (Soft Delete)" en el sistema de gestión de usuarios, pedirá de forma obligatoria el motivo (ej. "ya no pertenece a la iglesia").
El motivo aparecerá visualmente bajo la etiqueta "Inactivo" en la lista de usuarios.
Aparecerá un nuevo botón verde (✓) para los usuarios inactivos que permite reactivarlos instantáneamente.
@vercel

vercel Bot commented Jun 27, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
scrcr Ready Ready Preview, Comment Jun 27, 2026 7:12pm

@coderabbitai

coderabbitai Bot commented Jun 27, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a7d9a3af-ee18-49c3-8557-e8ed2f133e41

📥 Commits

Reviewing files that changed from the base of the PR and between 43c55ac and 9b214bb.

📒 Files selected for processing (1)
  • src/app/api/usuarios/[id]/route.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/app/api/usuarios/[id]/route.ts

📝 Walkthrough

Walkthrough

Adds motivoInactivo to the user model, persists it through the DAO and API, and updates the management UI to capture, display, and clear the reason during soft-delete and reactivation.

User Inactivation Reason

Layer / File(s) Summary
Data model and schema
src/models/Usuario.ts, prisma/schema.prisma, package.json
Usuario and the Prisma schema gain motivoInactivo, and the build script now runs prisma db push before building.
DAO mapping and query
src/dao/usuario.dao.ts
findAll selects motivoInactivo, and mapToUsuario returns it on the model object.
API update and soft-delete
src/app/api/usuarios/[id]/route.ts
Adds a PUT handler for estado and motivoInactivo, and the DELETE soft-delete path now requires a non-empty reason.
User management UI
src/app/gestion-usuarios/gestion-usuarios.tsx
handleEliminar now separates permanent delete from soft-delete with reason, and inactive users show the reason plus reactivation controls.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 A reason to rest, a field to explain,
Inactive bunnies hop back when reined.
Soft-delete with care, then clear the trail,
And reactivation bells merrily sail.
Motivo saved softly — hop, hop, hooray!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and clearly related to the reactivation portion of the user-management change, though it doesn’t capture the soft-delete reason update.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch activar-usuario-

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

@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: 5

Caution

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

⚠️ Outside diff range comments (1)
src/app/gestion-usuarios/gestion-usuarios.tsx (1)

191-203: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Hide the soft-delete choice for inactive users.

For estado === 0, the delete button says “Eliminar permanentemente”, but handleEliminar still offers “Desactivar (Soft Delete)”. Pass estado into the handler and disable the deny option for inactive users.

Proposed fix
-  const handleEliminar = (id: number, nombre: string) => {
+  const handleEliminar = (id: number, nombre: string, estado: number) => {
+    const esInactivo = estado === 0;
     Swal.fire({
-      title: 'Eliminar Usuario',
-      text: `¿Qué deseas hacer con el usuario ${nombre}?`,
+      title: esInactivo ? 'Eliminar Usuario Permanentemente' : 'Eliminar Usuario',
+      text: esInactivo
+        ? `¿Deseas eliminar permanentemente al usuario ${nombre}?`
+        : `¿Qué deseas hacer con el usuario ${nombre}?`,
       icon: 'warning',
       showCancelButton: true,
-      showDenyButton: true,
+      showDenyButton: !esInactivo,
-                                onClick={() => handleEliminar(u.id, u.nombreCompleto)} 
+                                onClick={() => handleEliminar(u.id, u.nombreCompleto, u.estado)} 
-                              onClick={() => handleEliminar(u.id, u.nombreCompleto)} 
+                              onClick={() => handleEliminar(u.id, u.nombreCompleto, u.estado)} 

Also applies to: 523-527, 561-564

🤖 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 `@src/app/gestion-usuarios/gestion-usuarios.tsx` around lines 191 - 203, The
delete flow in handleEliminar still shows the “Desactivar (Soft Delete)” deny
option for inactive users, which should be hidden when estado === 0. Update
handleEliminar to accept estado alongside id and nombre, then use that value to
conditionally disable or omit showDenyButton and denyButtonText for inactive
users while keeping the permanent delete path. Also update the call sites that
trigger handleEliminar so they pass estado from the user row, including the
related delete buttons mentioned in the other affected sections.
🤖 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 `@package.json`:
- Line 8: The build script currently couples schema mutation with application
build by running prisma db push before next build; remove prisma db push from
the build entry so the build is isolated from live database access and schema
changes. Update the package.json build script only, keeping next build
--turbopack as the build command, and move any schema update behavior to a
separate migration/deploy workflow.

In `@src/app/api/usuarios/`[id]/route.ts:
- Around line 129-137: The update response in the usuario route is leaking
sensitive fields because prisma.usuario.update() returns the full Usuario
record, including passwordHash. Fix the handler in the update flow by using a
select on prisma.usuario.update() or by mapping the returned usuario before
NextResponse.json so the payload excludes passwordHash. Keep the change
localized to the usuario update endpoint and ensure the returned data object is
safe for the browser.
- Around line 120-127: The user update handler in route.ts is still allowing
inactive users to be saved without a valid reason. Update the main request body
handling around request.json() and dataToUpdate so that estado: 0 is rejected
unless motivoInactivo is present and non-blank, and keep the existing nulling
behavior when estado === 1. Also align the DELETE soft-delete path in this same
route so it enforces the same inactivation-reason contract instead of writing
only estado: 0.

In `@src/app/gestion-usuarios/gestion-usuarios.tsx`:
- Around line 515-529: The icon-only action buttons in gestion-usuarios need
accessible names beyond title or visible icon text. Update the button elements
that call handleReactivar and handleEliminar to include an aria-label that
describes the specific user action using u.nombreCompleto and the current state,
and apply the same fix to the matching action buttons elsewhere in this
component. Ensure the aria-label clearly matches each button’s purpose so
assistive tech announces the action unambiguously.
- Around line 227-240: The inactive-reason validator in gestion-usuarios.tsx
only rejects empty values, so whitespace-only input still gets submitted as
motivoInactivo. Update the inputValidator used with the motivo prompt to trim
the value before checking it, and keep the existing flow around motivo and the
fetch PUT request in GestionUsuarios so only a non-empty, non-whitespace reason
can proceed.

---

Outside diff comments:
In `@src/app/gestion-usuarios/gestion-usuarios.tsx`:
- Around line 191-203: The delete flow in handleEliminar still shows the
“Desactivar (Soft Delete)” deny option for inactive users, which should be
hidden when estado === 0. Update handleEliminar to accept estado alongside id
and nombre, then use that value to conditionally disable or omit showDenyButton
and denyButtonText for inactive users while keeping the permanent delete path.
Also update the call sites that trigger handleEliminar so they pass estado from
the user row, including the related delete buttons mentioned in the other
affected sections.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 92199545-9cdc-4f50-a450-b4d516002b35

📥 Commits

Reviewing files that changed from the base of the PR and between ca3b5d7 and c1f8117.

📒 Files selected for processing (6)
  • package.json
  • prisma/schema.prisma
  • src/app/api/usuarios/[id]/route.ts
  • src/app/gestion-usuarios/gestion-usuarios.tsx
  • src/dao/usuario.dao.ts
  • src/models/Usuario.ts

Comment thread package.json
"postinstall": "prisma generate",
"dev": "next dev --turbopack",
"build": "next build --turbopack",
"build": "prisma db push && next build --turbopack",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Remove prisma db push from the build script.

next build should not require live DB access or mutate schema state; run schema changes in a dedicated migration/deploy step instead.

🤖 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 `@package.json` at line 8, The build script currently couples schema mutation
with application build by running prisma db push before next build; remove
prisma db push from the build entry so the build is isolated from live database
access and schema changes. Update the package.json build script only, keeping
next build --turbopack as the build command, and move any schema update behavior
to a separate migration/deploy workflow.

Comment thread src/app/api/usuarios/[id]/route.ts Outdated
Comment thread src/app/api/usuarios/[id]/route.ts
Comment thread src/app/gestion-usuarios/gestion-usuarios.tsx
Comment thread src/app/gestion-usuarios/gestion-usuarios.tsx

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

Caution

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

⚠️ Outside diff range comments (1)
src/app/api/usuarios/[id]/route.ts (1)

135-149: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Block self-deactivation in the new PUT flow.

Line 47 already prevents deleting your own account, but the current UI uses PUT /api/usuarios/:id for soft-delete/reactivation (src/app/gestion-usuarios/gestion-usuarios.tsx:220-286). As written, an admin can deactivate themself here and lock themselves out.

Suggested change
     const body = await request.json();
     const { estado, motivoInactivo } = body;
 
+    if (caller.id === id && estado === 0) {
+      return NextResponse.json(
+        { success: false, message: "No puedes desactivar tu propia cuenta" },
+        { status: 400 }
+      );
+    }
+
     const dataToUpdate: any = {};
🤖 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 `@src/app/api/usuarios/`[id]/route.ts around lines 135 - 149, The PUT handler
in `route.ts` allows soft-deleting a user via `estado = 0` without checking
whether the target user is the same as the authenticated admin, so add a
self-deactivation guard in this update flow. Update the logic around `body`,
`estado`, and `dataToUpdate` to reject requests where the route user id matches
the current session user before applying the state change, and return a 400/403
response with an appropriate message. Make sure the check is applied in the same
`PUT /api/usuarios/:id` path used by `gestion-usuarios.tsx` so admins cannot
deactivate themselves.
🤖 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 `@src/app/api/usuarios/`[id]/route.ts:
- Around line 72-89: `update`/`PUT` in `route.ts` is trusting `estado` and
`motivoInactivo` without type checks, so invalid payloads can reach `trim()` or
be persisted. In the handler that reads `request.json()` and later calls
`prisma.usuario.update`, validate that `motivoInactivo` is a string before
trimming it, and reject non-string values with a 400. Also validate `estado`
against the supported values before using it or storing it, and return a clear
400 for unsupported or non-numeric states.
- Around line 159-176: In the PUT handler that uses prisma.usuario.update and
returns the selected usuario fields, handle the stale-id case explicitly instead
of letting it fall into the generic 500 path. Catch Prisma P2025 around the
update in this route or verify the user exists before calling update, and return
the same 404 response/message used by the DELETE flow ("Usuario no encontrado").

---

Outside diff comments:
In `@src/app/api/usuarios/`[id]/route.ts:
- Around line 135-149: The PUT handler in `route.ts` allows soft-deleting a user
via `estado = 0` without checking whether the target user is the same as the
authenticated admin, so add a self-deactivation guard in this update flow.
Update the logic around `body`, `estado`, and `dataToUpdate` to reject requests
where the route user id matches the current session user before applying the
state change, and return a 400/403 response with an appropriate message. Make
sure the check is applied in the same `PUT /api/usuarios/:id` path used by
`gestion-usuarios.tsx` so admins cannot deactivate themselves.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: debd4f3e-fe26-4fa5-a122-039ba46067d9

📥 Commits

Reviewing files that changed from the base of the PR and between c1f8117 and 43c55ac.

📒 Files selected for processing (2)
  • src/app/api/usuarios/[id]/route.ts
  • src/app/gestion-usuarios/gestion-usuarios.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/app/gestion-usuarios/gestion-usuarios.tsx

Comment thread src/app/api/usuarios/[id]/route.ts
Comment thread src/app/api/usuarios/[id]/route.ts
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