Skip to content

V2 - #14

Merged
ApexYash11 merged 2 commits into
mainfrom
v2
Jun 4, 2026
Merged

V2#14
ApexYash11 merged 2 commits into
mainfrom
v2

Conversation

@ApexYash11

@ApexYash11 ApexYash11 commented Jun 4, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Enhanced chat functionality with multi-policy support and timeout handling.
    • Admin monitoring and diagnostic endpoints for system health checks.
    • Structured policy management with improved upload, analysis, and comparison workflows.
  • Bug Fixes

    • Improved error handling with standardized exception messages and recovery suggestions.
    • Fixed duplicate policy handling with automatic filename de-duplication.
  • Performance

    • Converted embeddings to async-first architecture for faster processing.
    • Added explicit timeouts for external API calls to prevent hangs.
  • Improvements

    • Enhanced rate limiting enforcement across user endpoints.
    • Better logging and diagnostics for troubleshooting.

…callback logic; delete unused quick actions and stats card components; remove debug and test HTML files; streamline API utilities and adjust policy types; update tests for async compatibility and improve error handling; clean up unused authentication code and dependencies.
@vercel

vercel Bot commented Jun 4, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
claim_wise Error Error Jun 4, 2026 3:23pm
claimwise-9t6e Error Error Jun 4, 2026 3:23pm
claimwise-fht9 Error Error Jun 4, 2026 3:23pm
claimwise-gi96 Error Error Jun 4, 2026 3:23pm

@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 79e51323-4f68-4b43-9d74-9afe2ab7c225

📥 Commits

Reviewing files that changed from the base of the PR and between 57f24f4 and ca7cefe.

⛔ Files ignored due to path filters (3)
  • frontend/public/placeholder-logo.png is excluded by !**/*.png
  • frontend/public/placeholder-user.jpg is excluded by !**/*.jpg
  • frontend/public/placeholder.jpg is excluded by !**/*.jpg
📒 Files selected for processing (51)
  • README.md
  • backend/requirements.txt
  • backend/src/auth.py
  • backend/src/embeddings.py
  • backend/src/exceptions.py
  • backend/src/llm_groq.py
  • backend/src/main.py
  • backend/src/main_app.py
  • backend/src/rag.py
  • backend/src/repositories/__init__.py
  • backend/src/repositories/policy_repository.py
  • backend/src/routes/__init__.py
  • backend/src/routes/admin.py
  • backend/src/routes/analysis.py
  • backend/src/routes/auth.py
  • backend/src/routes/chat.py
  • backend/src/routes/dashboard.py
  • backend/src/routes/monitoring.py
  • backend/src/routes/policies.py
  • backend/src/services/__init__.py
  • backend/src/services/activity_service.py
  • docs/api/architectural-review.md
  • docs/api/rag-review.md
  • frontend/app/admin/policies/page.tsx
  • frontend/app/analyze/page.tsx
  • frontend/app/chat/page.tsx
  • frontend/app/globals.css
  • frontend/app/upload/page.tsx
  • frontend/chat-migration-cleanup.js
  • frontend/components/analysis/policy-card.tsx
  • frontend/components/analysis/policy-comparison-new.tsx
  • frontend/components/chat/chat-widget.tsx
  • frontend/components/dashboard/quick-actions.tsx
  • frontend/components/dashboard/recent-activity.tsx
  • frontend/components/dashboard/stats-card.tsx
  • frontend/components/ui/calendar.tsx
  • frontend/components/ui/sidebar.tsx
  • frontend/debug.html
  • frontend/hooks/use-auth.tsx
  • frontend/lib/api.ts
  • frontend/lib/auth-backup.ts
  • frontend/lib/get-supabase.ts
  • frontend/next.config.mjs
  • frontend/package.json
  • frontend/test-auth.html
  • frontend/types/policies.ts
  • requirements.txt
  • runtime.txt
  • test/conftest.py
  • test/test_rag.py
  • test/test_rag_chunk.py

📝 Walkthrough

Walkthrough

This PR modularizes the FastAPI backend by extracting inline route handlers into separate router modules, converts the embedding and RAG systems to async-first architecture with background threading and timeouts, refactors the frontend to use dynamic per-request Supabase client initialization, standardizes exception handling, and simplifies the API surface by removing deprecated features.

Changes

Backend Routing Modularization & App Setup

Layer / File(s) Summary
Main app bootstrap & exception handler wiring
backend/src/main.py
Refactored to bootstrap FastAPI and wire route modules via include_router instead of defining endpoints inline. CORS setup simplified, ClaimWiseError handler registered, startup monitoring initialized.
Application helpers: admin checks, rate limiting, debug gating
backend/src/main_app.py
New module provides environment configuration, admin user verification via Supabase users table with env allowlist fallback, per-user rate limit enforcement raising HTTP 429, debug route gating raising HTTP 404 in production, and constraint-specific duplicate conflict message extraction.
Monitoring router
backend/src/routes/monitoring.py
Public root and healthz endpoints plus admin-protected endpoints returning performance summary, endpoint statistics, and async health diagnostics.
Policies router
backend/src/routes/policies.py
POST /upload-policy with PDF validation, text extraction, Storage upload with duplicate handling via timestamp, and optional document validation; GET /policies listing user policies; GET /policies/{id}/file-url for signed URLs; DELETE /policies/{id} with ownership verification.
Analysis router
backend/src/routes/analysis.py
POST /analyze-policy runs analysis on extracted text and persists validation metadata; POST /compare-policies generates and stores comparison results. Both enforce per-user rate limiting.
Chat router
backend/src/routes/chat.py
POST /chat for single-policy chat with RAG retrieval and citations; POST /chat-multiple for combined multi-policy responses. Both include rate limiting and activity logging.
Dashboard router
backend/src/routes/dashboard.py
/history endpoint with pagination and unified activity feed; /activities with fallback generation; /dashboard/stats and /dashboard/stats-dev counting policies/comparisons; /dashboard/metrics and /dashboard/metrics-dev computing protection/risk/coverage scores; /history-legacy debug endpoint.
Admin router
backend/src/routes/admin.py
Debug endpoints gated by admin authorization: list/update/analyze policies, test Gemini config, check Groq API status, manage test comparisons.
Auth router
backend/src/routes/auth.py
POST /refresh-token for token refresh; POST /test-gemini for uploading files to Gemini and extracting text.

Backend Services & Repository Pattern

Layer / File(s) Summary
Exception system refactor
backend/src/exceptions.py
Refactored to use consistent ClaimWiseError base class with to_dict() serialization, subclasses for validation/auth/authorization/processing/file-db/external-API/rate-limiting, handle_exceptions decorator that wraps async/sync functions and converts unexpected exceptions, HTTP conversion mapping, and global exception handler for JSON responses.
Activity logging service and export
backend/src/services/activity_service.py, backend/src/services/__init__.py
New log_activity() function constructs and inserts activity records with UUID, metadata, details, status, and timestamp. Services init.py exports log_activity for package API.
PolicyRepository: CRUD operations
backend/src/repositories/policy_repository.py
New PolicyRepository class with find_by_user, find_by_id, create (with user existence verification), delete (cascading to document_chunks), and update methods. All operations include exception handling and return appropriate null/empty/boolean values on failure.

Async Embeddings & RAG Conversion

Layer / File(s) Summary
Embeddings async-first with provider threading and timeouts
backend/src/embeddings.py
Refactored to async operation: OpenAI/Gemini calls use asyncio.to_thread with timeouts (OpenAI 15s), SentenceTransformer uses asyncio.to_thread with 10s timeout, HuggingFace uses asyncio.to_thread. EmbeddingManager.embed_texts decorated with @handle_exceptions, includes provider validation and cache lookup logic. Synchronous embed_texts_with_cache and embed_text_with_cache wrappers removed.
RAG async conversion: index and retrieve
backend/src/rag.py
index_documents and retrieve_top_k converted to async. index_documents awaits embed_texts and treats None result as hard failure. retrieve_top_k awaits query embeddings and returns [] on RPC/embedding failures.

Auth & LLM Improvements

Layer / File(s) Summary
JWT decoding: cache removal and logging improvements
backend/src/auth.py
Removed @lru_cache decorator from decode_token. Reformatted JWT decode and error logging to multi-line. refresh_token reformatted with multi-line returns/errors but same control flow.
LLM Groq timeouts and fallback handling
backend/src/llm_groq.py
Added explicit timeout=30 to all three Groq client chat completion calls. Changed behavior to return rule-based fallback analysis instead of raising exception when all LLM providers fail.

Frontend Supabase Client Refactoring

Layer / File(s) Summary
Dynamic Supabase client helper with caching
frontend/lib/get-supabase.ts
New async getSupabase() function dynamically imports @supabase/supabase-js, reads env vars, caches the client, and falls back to dummy client with console warning when env vars missing.
Auth provider async client acquisition and typed events
frontend/hooks/use-auth.tsx
Refactored to acquire Supabase client via getSupabase() during effect initialization. resolveUserRole updated to accept supabase instance. Auth state change listener uses typed AuthChangeEvent/Session with isMounted guards and auto-sync user profile behavior.
Pages updated to use dynamic Supabase client
frontend/app/admin/policies/page.tsx, frontend/app/analyze/page.tsx, frontend/app/chat/page.tsx, frontend/app/upload/page.tsx
Pages call getSupabase() at start of handlers instead of using static import. PolicySummary import moved to @/types/policies.
Components updated to use dynamic Supabase client
frontend/components/dashboard/recent-activity.tsx, frontend/components/chat/chat-widget.tsx
Components initialize Supabase client via getSupabase() inside useEffect/handlers. Chat widget refactored to POST /chat-multiple endpoint with Bearer token authorization.

Frontend API Surface & Type Restructuring

Layer / File(s) Summary
API surface narrowing and getPolicies refactor
frontend/lib/api.ts
Rewritten to export only getPolicies() and re-export PolicySummary from @/types/policies. Removed PolicyAnalysisRequest, PolicyAnalysisResponse, and all upload/compare/chat/history API functions. getPolicies() uses getSupabase() and fetchWithTimeout with updated mapping logic.
PolicySummary type definition with analysis fields
frontend/types/policies.ts
New interface with required policy identifiers, provider, coverage/premium/deductible, key features, expiration, and optional rawAnalysis containing coverage, exclusions, claim process, readiness score, waiting period, copay.

Frontend Component & File Cleanup

Layer / File(s) Summary
Removed analysis/dashboard UI components
frontend/components/analysis/policy-card.tsx, frontend/components/analysis/policy-comparison-new.tsx, frontend/components/dashboard/quick-actions.tsx, frontend/components/dashboard/stats-card.tsx
Deleted PolicyCard, PolicyComparison, QuickActions, and StatsCard components no longer used after refactoring.
Removed debug and backup auth files
frontend/debug.html, frontend/test-auth.html, frontend/lib/auth-backup.ts, frontend/chat-migration-cleanup.js
Removed browser debug pages, standalone auth test page, backup auth utilities, and legacy chat history cleanup script.
UI component CSS variable updates
frontend/components/ui/sidebar.tsx, frontend/components/ui/calendar.tsx, frontend/app/globals.css
Updated sidebar-gap and sidebar-container CSS calcs to use 1rem instead of --spacing(4). Updated calendar --cell-size from --spacing(8) to 2rem. Removed tw-animate-css import.

Build Configuration & Dependency Updates

Layer / File(s) Summary
Next.js config: optimizePackageImports and turbopack
frontend/next.config.mjs
Moved experimental.optimizePackageImports from production-only to unconditional. Removed custom webpack hook. Added turbopack configuration.
Package.json script and dependency updates
frontend/package.json
Updated dev script to include NODE_OPTIONS memory flag and --turbo flag. Pinned @supabase/supabase-js from latest to 2.44.4.
Runtime and config file updates
runtime.txt, README.md
Removed Python version entry. Updated docs tree labels for api/ and deployment/ directories.

Test Infrastructure Updates

Layer / File(s) Summary
Pytest async configuration and RAG test conversion
test/conftest.py, test/test_rag.py, test/test_rag_chunk.py
Added anyio_backend fixture returning "asyncio". Converted RAG tests to async with importlib imports and pytestmark. Updated mocking to patch src.rag directly. Removed TestEmbedTexts, simplified TestChunkTexts, added embedding-dimension-mismatch test, converted retrieve tests to async.

🎯 4 (Complex) | ⏱️ ~60 minutes

🐰 A rabbit hops through async routes,
Where embeddings now take threads for boots,
Supabase clients dance on demand,
Exception handlers take their stand,
ClaimWise code, now modular and grand! 🚀

✨ 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 v2

@ApexYash11
ApexYash11 merged commit 960afd1 into main Jun 4, 2026
4 of 9 checks passed

This branch had an error being deployed

4 failed deployments
Preview – claimwise-9t6e — ca7cefe7 Deployed Jun 4, 2026 by vercel[bot]
Preview – claimwise-gi96 — ca7cefe7 Deployed Jun 4, 2026 by vercel[bot]
Preview – claim_wise — ca7cefe7 Deployed Jun 4, 2026 by vercel[bot]
Preview – claimwise-fht9 — ca7cefe7 Deployed Jun 4, 2026 by vercel[bot]
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