Skip to content

Codex/corrigir problema de conexao com api da meta 155281 - #5

Open
Marcelo-Rosas wants to merge 5 commits into
thaleslaray:mainfrom
Marcelo-Rosas:codex/corrigir-problema-de-conexao-com-api-da-meta-155281
Open

Codex/corrigir problema de conexao com api da meta 155281#5
Marcelo-Rosas wants to merge 5 commits into
thaleslaray:mainfrom
Marcelo-Rosas:codex/corrigir-problema-de-conexao-com-api-da-meta-155281

Conversation

@Marcelo-Rosas

@Marcelo-Rosas Marcelo-Rosas commented Dec 22, 2025

Copy link
Copy Markdown

Summary by CodeRabbit

Release Notes

  • Chores

    • Updated Next.js to version 16.0.10
    • Added Vercel Analytics integration for app monitoring
    • Added dependencies: @vercel/analytics and react-is
  • Refactor

    • Enhanced credential management system with improved storage and retrieval mechanisms
    • Improved account identification in API requests for better data accuracy

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

vercel Bot and others added 5 commits December 10, 2025 01:03
## Vercel Web Analytics Installation and Configuration

Successfully installed and configured Vercel Web Analytics for the Next.js project.

### Changes Made

**Modified Files:**
1. **app/layout.tsx** - Root layout component
   - Added import: `import { Analytics } from '@vercel/analytics/next'`
   - Added `<Analytics />` component inside the `<body>` tag after the `{children}` prop
   - The Analytics component is placed at the end of the body content to ensure all page elements are tracked

**Updated Dependencies:**
1. **package.json** - Added two dependencies:
   - `@vercel/analytics@^1.6.1` - Vercel Web Analytics package for Next.js
   - `react-is@^19.2.1` - Peer dependency required by recharts (was missing, causing build issues)

2. **package-lock.json** - Lockfile automatically updated with new dependencies and their transitive dependencies

### Implementation Details

- **Project Type:** App Router (Next.js 16.0.7 with Turbopack)
- **Package Manager:** npm
- **Build Status:** ✅ Successfully compiled and built
- **Routes Generated:** 47 static/dynamic routes

The Analytics component is now properly integrated and will automatically track web analytics events for the SmartZap WhatsApp Manager application. The component is placed at the end of the body to ensure all page interactions are captured.

### Notes

- The `react-is` package was installed as a dependency because it was required by recharts (v3.5.0) but was missing from node_modules
- All changes were made following the existing code structure and conventions
- The build completed successfully without errors
- The Analytics import uses the correct Next.js-specific export from '@vercel/analytics/next'

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
…to-nextjs-sex5wn

Add Vercel Web Analytics to Next.js
Updated dependencies to fix Next.js and React CVE vulnerabilities.

The fix-react2shell-next tool automatically updated the following packages to their secure versions:
- next
- react-server-dom-webpack
- react-server-dom-parcel  
- react-server-dom-turbopack

All package.json files have been scanned and vulnerable versions have been patched to the correct fixed versions based on the official React advisory.

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
…ts-cve-vu-b7dosq

Fix React Server Components CVE vulnerabilities
@coderabbitai

coderabbitai Bot commented Dec 22, 2025

Copy link
Copy Markdown

Walkthrough

This PR refactors credential management by centralizing WhatsApp credential handling through helper functions in a dedicated module, adds businessAccountId parameter support to API account limit fetching with enhanced Meta API field requests, integrates Vercel Analytics into the app layout, and updates package dependencies including Next.js version and new utility packages.

Changes

Cohort / File(s) Summary
Credential Management Abstraction
app/api/settings/credentials/route.ts, lib/whatsapp-credentials.ts
Replaced direct environment variable access with centralized helper functions (getWhatsAppCredentials, saveWhatsAppCredentials, deleteWhatsAppCredentials, getCredentialsSource). Updated GET/POST/DELETE flows to use imported WhatsAppCredentials type. Added Redis-backed credential persistence and deletion with error handling.
API Account Limits Enhancement
app/api/account/limits/route.ts
Extended fetchLimitsFromMeta signature to accept businessAccountId parameter. Updated Meta API requests to include throughput, quality_rating, quality_score fields and use businessAccountId for WhatsApp Business Manager limit queries. Enhanced quality parsing with fallback logic. Updated error handling (GET returns 502 on fetch failure).
Analytics Integration
app/layout.tsx
Added Vercel Analytics component import and rendering within app layout body.
Dependency Updates
package.json
Added @vercel/analytics (^1.6.1) and react-is (^19.2.1) dependencies; upgraded next from ^16.0.7 to 16.0.10 (exact version).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • app/api/settings/credentials/route.ts: Verify all GET/POST/DELETE flows correctly integrate new credential helper functions and that businessAccountId flows through to API calls.
  • app/api/account/limits/route.ts: Check that businessAccountId parameter propagation is consistent across both GET and POST error paths; validate quality rating fallback logic handles edge cases.
  • lib/whatsapp-credentials.ts: Confirm Redis error handling and guards against unavailability are sufficient; verify error logging doesn't expose sensitive credentials.
  • package.json & app/layout.tsx: Verify Analytics component placement doesn't impact performance or rendering order.

Poem

🐰 With credentials tucked safe in a module so grand,
And businessAccountId across the land,
We measure our limits and watch where they flow,
While Vercel observes all we do, high and low!

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is in Portuguese and uses vague terminology ('corrigir problema de conexao') combined with a ticket reference, making it unclear what the specific technical change is without additional context. Consider using a more descriptive English title that clearly explains the main change, such as 'Add businessAccountId parameter to Meta API calls' or similar, to improve clarity for team members reviewing the PR history.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 90.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@Marcelo-Rosas
Marcelo-Rosas marked this pull request as draft December 22, 2025 05:03
@Marcelo-Rosas
Marcelo-Rosas marked this pull request as ready for review December 22, 2025 05:03

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

🧹 Nitpick comments (5)
package.json (1)

79-79: Verify the exact version pinning of Next.js.

The caret (^) was removed from the Next.js version, changing it from "^16.0.7" to "16.0.10". This prevents automatic patch and minor updates. While exact pinning can provide stability, it also means missing out on bug fixes and security patches.

Was this intentional? If not, consider restoring the caret: "^16.0.10".

lib/whatsapp-credentials.ts (2)

76-87: Consider returning success indicators instead of silent failures.

The function silently fails if Redis is unavailable or if an error occurs, making it impossible for callers to know whether credentials were actually saved. This could lead to user-facing flows appearing successful when persistence actually failed.

🔎 Proposed refactor to return boolean success indicator
 /**
  * Persist WhatsApp credentials to Redis (if available)
+ * @returns true if saved successfully, false otherwise
  */
-export async function saveWhatsAppCredentials(credentials: WhatsAppCredentials): Promise<void> {
-  if (!isRedisAvailable() || !redis) return
+export async function saveWhatsAppCredentials(credentials: WhatsAppCredentials): Promise<boolean> {
+  if (!isRedisAvailable() || !redis) {
+    console.warn('Redis not available - credentials not persisted')
+    return false
+  }

   try {
     await redis.set(CREDENTIALS_KEY, JSON.stringify(credentials))
+    return true
   } catch (error) {
     console.error('Error saving WhatsApp credentials to Redis:', error)
+    return false
   }
 }

89-100: Consider returning success indicators instead of silent failures.

Similar to saveWhatsAppCredentials, this function silently fails without indicating success or failure to the caller.

🔎 Proposed refactor to return boolean success indicator
 /**
  * Delete WhatsApp credentials from Redis
+ * @returns true if deleted successfully, false otherwise
  */
-export async function deleteWhatsAppCredentials(): Promise<void> {
-  if (!isRedisAvailable() || !redis) return
+export async function deleteWhatsAppCredentials(): Promise<boolean> {
+  if (!isRedisAvailable() || !redis) {
+    console.warn('Redis not available - no credentials to delete')
+    return false
+  }

   try {
     await redis.del(CREDENTIALS_KEY)
+    return true
   } catch (error) {
     console.error('Error deleting WhatsApp credentials from Redis:', error)
+    return false
   }
 }
app/api/account/limits/route.ts (1)

48-51: Review the double optional chaining pattern for quality parsing.

The quality parsing uses an unusual double optional chaining pattern:

const rawQuality =
  throughputData.quality_rating?.toUpperCase?.() ||
  throughputData.quality_score?.score?.toUpperCase?.()

The ?.toUpperCase?.() pattern treats the toUpperCase method itself as optional. If quality_rating is a string, it will always have the toUpperCase method, making the second ? unnecessary. If quality_rating could be a non-string type, explicit type checking would be clearer.

🔎 Proposed clarification
  // Parse quality score
- const rawQuality =
-   throughputData.quality_rating?.toUpperCase?.() ||
-   throughputData.quality_score?.score?.toUpperCase?.()
+ const rawQuality = (
+   typeof throughputData.quality_rating === 'string' 
+     ? throughputData.quality_rating.toUpperCase()
+     : typeof throughputData.quality_score?.score === 'string'
+     ? throughputData.quality_score.score.toUpperCase()
+     : undefined
+ )
  const qualityScore = ['GREEN', 'YELLOW', 'RED'].includes(rawQuality) ? rawQuality : 'UNKNOWN'
app/api/settings/credentials/route.ts (1)

97-104: Consider handling Redis persistence failures in the user response.

The saveWhatsAppCredentials() call may silently fail if Redis is unavailable (as noted in lib/whatsapp-credentials.ts review). While the credentials validation succeeded, the user receives a success message even if persistence failed.

Consider informing the user if credentials couldn't be persisted to Redis, though this may be acceptable if environment variables serve as the fallback.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3221a89 and 139054e.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • app/api/account/limits/route.ts
  • app/api/settings/credentials/route.ts
  • app/layout.tsx
  • lib/whatsapp-credentials.ts
  • package.json
🧰 Additional context used
🧬 Code graph analysis (2)
app/api/settings/credentials/route.ts (1)
lib/whatsapp-credentials.ts (5)
  • getWhatsAppCredentials (29-66)
  • getCredentialsSource (105-127)
  • WhatsAppCredentials (12-18)
  • saveWhatsAppCredentials (79-87)
  • deleteWhatsAppCredentials (92-100)
app/api/account/limits/route.ts (1)
lib/whatsapp-credentials.ts (1)
  • getWhatsAppCredentials (29-66)
🔇 Additional comments (4)
app/layout.tsx (1)

6-6: LGTM! Vercel Analytics integration is correctly implemented.

The Analytics component is properly imported and rendered inside the body element. Placement outside the Providers wrapper is appropriate for Vercel Analytics.

Also applies to: 30-30

app/api/account/limits/route.ts (2)

15-19: LGTM! The businessAccountId integration is correctly implemented.

The businessAccountId parameter is properly threaded through:

  • Function signature updated
  • Credential validation checks include it
  • Both GET and POST handlers correctly pass it to the Meta API call

This aligns with the PR objective to fix Meta API connection issues.

Also applies to: 80-92, 107-141


23-23: Review field names against WhatsApp Cloud API v24.0 documentation.

The quality_rating field is correct for phone number queries, but correct the following:

  • quality_score is not a valid API field
  • Use messaging_limit_tier instead of whatsapp_business_manager_messaging_limit for querying messaging limits

Also applies to: 27-27

app/api/settings/credentials/route.ts (1)

2-8: LGTM! Excellent refactoring to centralized credential management.

The refactoring properly:

  • Uses the centralized WhatsAppCredentials type
  • Leverages getWhatsAppCredentials() for retrieval
  • Calls saveWhatsAppCredentials() after validation
  • Implements actual deletion via deleteWhatsAppCredentials()

This eliminates code duplication and provides a single source of truth for credential management.

Also applies to: 13-58, 62-124, 127-137

Comment thread package.json
"@upstash/qstash": "^2.8.4",
"@upstash/redis": "^1.35.7",
"@upstash/workflow": "^0.2.22",
"@vercel/analytics": "^1.6.1",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

git ls-files | grep -E "package\.json$" | head -5

Repository: thaleslaray/smartzap_template

Length of output: 85


🏁 Script executed:

sed -n '60,95p' package.json | cat -n

Repository: thaleslaray/smartzap_template

Length of output: 1427


Upgrade Next.js to 16.1.0, the latest stable version with improved stability.

Next.js 16.1 (released December 18, 2025) focuses on faster development workflows and improved stability, with major updates to Turbopack and tooling. The project currently uses 16.0.10, which while containing necessary security patches, is not the latest stable version. Next.js 16.0.10 addresses critical security vulnerabilities (CVE-2025-66478, CVE-2025-55183, CVE-2025-55184), but upgrading to 16.1.0 is recommended for production stability. Review the migration guide for breaking changes, including minimum Node.js 20.9.0 and TypeScript 5.1.0 requirements, plus middleware.ts → proxy.ts migration. @vercel/analytics 1.6.1 is compatible with Next.js 16.

Also applies to: 79-79, 86-86

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread app/layout.tsx
import './globals.css'
import { Providers } from './providers'
import { Toaster } from 'sonner'
import { Analytics } from '@vercel/analytics/next'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fix unsupported Vercel Analytics import

app/layout.tsx imports Analytics from @vercel/analytics/next, but the package exposes the React entrypoint (@vercel/analytics/react) rather than a Next-specific one. With the current path the module cannot be resolved during the Next.js build, causing the app to fail to compile. Using the documented React import avoids the module-not-found error and lets the build succeed.

Useful? React with 👍 / 👎.

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