Files
LexiChain/docs/01-project-overview.md
2026-05-13 21:08:27 +01:00

219 lines
9.9 KiB
Markdown

# 01 — Project Overview
## What is LexiChain?
**LexiChain** is a full-stack BFSI (Banking, Financial Services & Insurance) contract intelligence platform. It transforms raw PDF and image contract documents into structured, searchable, and verifiable data through a multi-layer pipeline:
1. **Upload** — Users upload insurance policies, loan agreements, or investment contracts.
2. **AI Extraction** — Google Gemini (primary) or Mistral AI (fallback) reads the document and extracts structured metadata.
3. **RAG Q&A** — Users can ask natural-language questions about any analyzed contract.
4. **Blockchain Proof** — Every document's SHA-256 hash is registered on Ethereum (Sepolia testnet or local Hardhat) providing tamper-proof, timestamped proof-of-deposit.
5. **Notifications** — The platform emails users about upcoming contract renewals and expiries.
6. **Analytics** — A dashboard aggregates contract statistics, type distributions, and status trends.
---
## Feature List
| Feature | Description |
|---------|-------------|
| **Authentication** | Clerk-powered sign-in/sign-up with SSO support |
| **Contract Upload** | Drag-and-drop PDF/image upload via UploadThing |
| **AI Analysis** | Structured extraction: type, dates, premium, provider, key clauses |
| **AI Fallback** | Mistral Large + Pixtral vision model when Gemini is unavailable |
| **Contract Q&A** | RAG-grounded question answering on analyzed contracts |
| **Blockchain Proof** | On-chain document hash registration (Sepolia testnet) |
| **Blockchain Explorer** | In-app UI to verify document hashes and view transaction proofs |
| **Email Notifications** | SMTP-based renewal and expiry alerts |
| **In-App Notifications** | Real-time notification bar with read/dismiss |
| **Analytics Dashboard** | KPIs, status distribution, contract type charts (Recharts) |
| **Dark / Light Mode** | Full theme support via next-themes |
| **PDF Certificate Export** | Downloadable PDF certificates with QR codes |
| **CSV Export** | Contract list export to CSV |
---
## Technology Stack
### Core Framework
| Layer | Technology |
|-------|-----------|
| Framework | Next.js 16.x (App Router) |
| Language | TypeScript 5.x (strict mode) |
| Runtime | Node.js ≥ 20 |
| React | 19.x |
### Frontend
| Technology | Purpose |
|-----------|---------|
| Tailwind CSS + tailwindcss-animate | Utility-first styling |
| shadcn/ui (Radix UI primitives) | Accessible component library |
| Lucide React | Icon set |
| Motion (Framer Motion v12) | Animations and micro-interactions |
| Recharts | Analytics charts |
| Sonner | Toast notifications |
| next-themes | Dark/light mode |
| react-hook-form + zod | Form validation |
### Backend & Data
| Technology | Purpose |
|-----------|---------|
| PostgreSQL | Primary relational database |
| Prisma ORM | Schema management, type-safe queries, migrations |
| Clerk | Authentication, user management |
| UploadThing | File upload and CDN storage |
| Nodemailer | SMTP email delivery |
### AI & Intelligence
| Technology | Purpose |
|-----------|---------|
| Google Gemini (via `@google/generative-ai`) | Primary multimodal contract extraction |
| Mistral AI (REST API) | Fallback extraction + OCR |
| Pixtral (Mistral Vision) | Image/scanned document fallback |
| Gemini text-embedding-004 | Vector embeddings for RAG |
### Blockchain
| Technology | Purpose |
|-----------|---------|
| Solidity 0.8.24 | Smart contract language |
| Hardhat | Compilation, testing, local node, deployment |
| ethers.js v6 | Server-side blockchain interaction |
| Ethereum Sepolia | Production testnet (free, no cost) |
### PDF & Certificates
| Technology | Purpose |
|-----------|---------|
| PDFKit | Server-side PDF certificate generation |
| jsPDF + jspdf-autotable | Client-side PDF/table export |
| pdf-parse | PDF text extraction for OCR fallback |
| qrcode | QR code generation for certificates |
---
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ USER BROWSER │
│ Next.js App Router UI │
└───────────────────────┬─────────────────────────────────────────┘
┌─────────────▼──────────────┐
│ Clerk Middleware │ Route protection (proxy.ts)
│ (proxy.ts) │ Blocks unauthenticated access
└─────────────┬──────────────┘
┌─────────────▼──────────────┐
│ Server Actions │ lib/actions/* — authenticated
│ & Route Handlers │ server-side operations
└──────┬──────────┬──────────┘
│ │
┌────────────▼──┐ ┌────▼───────────┐
│ lib/services │ │ app/api/* │
│ (domain logic)│ │ (webhooks, │
│ │ │ uploadthing) │
└────────────────┘ └────────────────┘
┌──────┴──────────────────────────────────┐
│ External Integrations │
│ │
│ PostgreSQL UploadThing Gemini API │
│ (Prisma) (file CDN) (primary AI) │
│ │
│ Mistral AI Ethereum SMTP Server │
│ (fallback) Sepolia (email) │
└──────────────────────────────────────────┘
```
---
## User Flows
### 1. Sign Up & Onboarding
```
User visits /sign-up
→ Clerk handles registration
→ Clerk fires webhook (user.created)
→ app/api/webhooks/clerk syncs User record to PostgreSQL
→ User redirected to /dashboard
```
### 2. Contract Upload & Analysis
```
User uploads PDF from /contracts
→ UploadThing receives file → stores on CDN → returns URL
→ saveContract() server action creates Contract row (status: UPLOADED)
→ User clicks "Analyze"
→ analyzeContractAction() sets status: PROCESSING
→ AIService downloads file → sends to Gemini → parses JSON response
→ ContractService.updateWithAIResults() saves extracted data
→ BlockchainService hashes file → registers hash on Sepolia
→ Status set to COMPLETED
→ NotificationService creates in-app + email notification
```
### 3. Contract Q&A (RAG)
```
User asks question in contract detail page
→ askContractQuestionAction() fetches contract + RAG chunks
→ RAGService finds most similar chunks via cosine similarity
→ AIService sends contract context + question to Gemini
→ Answer streamed back to UI
```
### 4. Blockchain Verification
```
User opens /blockchain explorer
→ BlockchainService.getNetworkStats() queries Sepolia node
→ User pastes document hash or views registered documents
→ BlockchainService.verifyOnChain() calls verifyDocument() on Solidity contract
→ Result shown: exists / timestamp / depositor address
```
---
## Project Directory Structure
```
bfsi-project/
├── app/ Next.js App Router
│ ├── (auth)/ Sign-in / Sign-up pages
│ ├── (dashboard)/ Protected workspace pages
│ │ ├── dashboard/ Analytics overview
│ │ ├── contacts/ Contract list & detail
│ │ └── blockchain/ Blockchain explorer
│ └── api/ Route handlers
│ ├── contracts/ Contract CRUD endpoints
│ ├── uploadthing/ UploadThing integration
│ └── webhooks/ Clerk webhook receiver
├── blockchain/ Hardhat smart contract project
│ ├── contracts/ Solidity source files
│ └── scripts/ Deployment scripts
├── components/ Reusable React components
│ ├── layout/ Shell, sidebar, header
│ └── ui/ shadcn/ui design system
├── docs/ This documentation folder
├── features/ Feature-scoped components
│ ├── ai/ AI analysis UI
│ ├── analytics/ Dashboard charts
│ ├── auth/ Auth-related UI
│ ├── blockchain/ Blockchain explorer UI
│ ├── claims/ Claims management
│ ├── contracts/ Contract upload/list/detail
│ ├── home/ Landing page
│ └── notifications/ Notification center
├── hooks/ Custom React hooks
├── lib/
│ ├── db/ Prisma client singleton
│ ├── services/ All domain services (AI, Blockchain, etc.)
│ │ └── ai/ AI sub-modules (parser, normalizer, prompts)
│ ├── upload.ts UploadThing configuration
│ └── utils.ts Shared utility functions
├── prisma/ Database schema and migrations
├── public/ Static assets
├── scripts/ Dev tooling scripts
├── types/ Shared TypeScript types
├── proxy.ts Clerk middleware (route protection)
└── next.config.ts Next.js configuration
```