The Future of Blood Donation is Here!
An AI-powered, intelligent blood donation ecosystem that connects donors with recipients through cutting-edge technology and real-time matching algorithms.
|
|
|
|
graph TD
A[π©Έ CatchMyType] --> B[π€ AI Assistant]
A --> C[π Smart Matching]
A --> D[π± Real-time Alerts]
A --> E[π₯ Hospital Integration]
B --> B1[Natural Language Processing]
B --> B2[Intelligent Query Understanding]
B --> B3[Contextual Responses]
C --> C1[Blood Compatibility Matrix]
C --> C2[Location-Based Filtering]
C --> C3[Availability Tracking]
D --> D1[Push Notifications]
D --> D2[SMS Integration]
D --> D3[Email Alerts]
E --> E1[Inventory Management]
E --> E2[Staff Portal]
E --> E3[Analytics Dashboard]
| Feature | Description | Tech Stack |
|---|---|---|
| π€ AI Chat Assistant | Natural language blood donor search with intelligent parsing | React, NLP, Custom Algorithms |
| π Smart Donor Matching | Advanced compatibility algorithm with real-time availability | MongoDB, Express.js, Custom Logic |
| π± Real-time Notifications | Instant alerts for urgent blood requests across multiple channels | WebSocket, Push API, Nodemailer |
| π₯ Hospital Integration | Comprehensive hospital management with inventory tracking | MERN Stack, REST API |
| π Secure Authentication | JWT-based auth with role-based access control | JWT, bcrypt, Middleware |
| π Analytics Dashboard | Real-time statistics and request tracking with visualizations | Chart.js, D3.js, Custom Metrics |
| π Location Intelligence | GPS-based donor search covering 100+ Indian cities | Geolocation API, MongoDB GeoJSON |
| π¬ Multi-channel Communication | In-app chat, phone, email, and SMS integration | Socket.io, Twilio, Nodemailer |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π Frontend Layer β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β Next.js β β TypeScript β β Tailwind CSSβ β Shadcn/ui β β
β β 15.2 β β 5.x β β 3.4.17 β β Radix UI β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π API Gateway β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β Express.js β β Middleware β β CORS β β Rate Limit β β
β β 4.18.2 β β Stack β β Security β β Protection β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β πΎ Database Layer β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β MongoDB β β Mongoose β β Redis Cacheβ β Aggregation β β
β β Atlas β β ODM β β Layer β β Pipelines β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ποΈ Click to expand detailed project structure
CatchMyType_Hack4Bengal/
βββ π¨ app/ # Next.js 15 App Router
β βββ π± (mobile)/ # Mobile-specific routes
β βββ π₯ (hospital)/ # Hospital portal
β βββ π€ (user)/ # User dashboard
β βββ π donors/ # Donor management
β β βββ [id]/ # Dynamic donor routes
β β βββ search/ # Advanced search
β β βββ profile/ # Donor profiles
β βββ π analytics/ # Analytics dashboard
β βββ π©Έ inventory/ # Blood inventory
β βββ π auth/ # Authentication
β β βββ login/ # Login page
β β βββ register/ # Registration
β β βββ forgot-password/ # Password recovery
β βββ π request/ # Blood requests
β β βββ create/ # Create request
β β βββ [id]/ # Request details
β β βββ history/ # Request history
β βββ π¬ chat/ # Real-time chat
β βββ π± api/ # API routes
β β βββ auth/ # Authentication API
β β βββ donors/ # Donors API
β β βββ requests/ # Requests API
β β βββ chat/ # Chat API
β β βββ webhook/ # External webhooks
β βββ π¨ globals.css # Global styles
β βββ π layout.tsx # Root layout
β βββ π page.tsx # Home page
β βββ β not-found.tsx # 404 page
β βββ β οΈ error.tsx # Error boundary
β
βββ π§© components/ # Reusable Components
β βββ π€ ai/ # AI-related components
β β βββ chat-assistant.tsx # Main chat interface
β β βββ message-bubble.tsx # Chat messages
β β βββ typing-indicator.tsx # Typing animation
β βββ π¨ ui/ # UI Components (Shadcn)
β β βββ button.tsx # Button variants
β β βββ card.tsx # Card components
β β βββ dialog.tsx # Modal dialogs
β β βββ form.tsx # Form components
β β βββ input.tsx # Input fields
β β βββ toast.tsx # Notifications
β βββ π charts/ # Data visualization
β β βββ donation-chart.tsx # Donation trends
β β βββ blood-type-chart.tsx # Blood type distribution
β β βββ location-map.tsx # Interactive maps
β βββ π auth/ # Authentication
β β βββ login-form.tsx # Login form
β β βββ register-form.tsx # Registration form
β β βββ protected-route.tsx # Route protection
β βββ π₯ hospital/ # Hospital components
β β βββ inventory-table.tsx # Inventory management
β β βββ staff-dashboard.tsx # Staff interface
β β βββ request-manager.tsx # Request handling
β βββ π― features/ # Feature sections
β β βββ hero.tsx # Hero section
β β βββ features.tsx # Features showcase
β β βββ testimonials.tsx # User testimonials
β β βββ stats.tsx # Statistics display
β βββ π§ common/ # Common components
β βββ header.tsx # Navigation header
β βββ footer.tsx # Site footer
β βββ loading.tsx # Loading states
β βββ error-boundary.tsx # Error handling
β
βββ π§ lib/ # Utility Libraries
β βββ π api/ # API client
β β βββ client.ts # Axios instance
β β βββ endpoints.ts # API endpoints
β β βββ types.ts # API types
β βββ π auth/ # Authentication utils
β β βββ jwt.ts # JWT handling
β β βββ session.ts # Session management
β β βββ permissions.ts # Permission checks
β βββ π― utils/ # Helper functions
β β βββ blood-compatibility.ts # Blood matching logic
β β βββ location.ts # Location utilities
β β βββ date.ts # Date formatting
β β βββ validation.ts # Input validation
β βββ π€ ai/ # AI utilities
β β βββ nlp-parser.ts # Natural language processing
β β βββ donor-matcher.ts # Matching algorithms
β β βββ chat-processor.ts # Chat processing
β βββ π analytics/ # Analytics utilities
β βββ tracking.ts # Event tracking
β βββ metrics.ts # Performance metrics
β
βββ ποΈ contexts/ # React Context
β βββ π auth-context.tsx # Authentication state
β βββ π¨ theme-context.tsx # Theme management
β βββ π¬ chat-context.tsx # Chat state
β βββ π± notification-context.tsx # Notifications
β
βββ π£ hooks/ # Custom React Hooks
β βββ π use-auth.ts # Authentication hook
β βββ π use-api.ts # API calling hook
β βββ π± use-notifications.ts # Notification hook
β βββ π¨ use-theme.ts # Theme switching
β βββ π use-location.ts # Geolocation hook
β βββ π¬ use-chat.ts # Chat functionality
β
βββ π₯οΈ server/ # Backend Express Server
β βββ π§ config/ # Configuration
β β βββ database.js # MongoDB connection
β β βββ jwt.js # JWT configuration
β β βββ email.js # Email settings
β βββ π‘οΈ middleware/ # Express Middleware
β β βββ auth.js # Authentication middleware
β β βββ validation.js # Input validation
β β βββ rate-limit.js # Rate limiting
β β βββ cors.js # CORS configuration
β β βββ error-handler.js # Error handling
β βββ π models/ # Mongoose Schemas
β β βββ User.js # User model
β β βββ BloodRequest.js # Blood request model
β β βββ Inventory.js # Inventory model
β β βββ Hospital.js # Hospital model
β β βββ Donation.js # Donation history
β β βββ Chat.js # Chat messages
β βββ π£οΈ routes/ # API Routes
β β βββ auth.js # Authentication routes
β β βββ donors.js # Donor management
β β βββ requests.js # Blood requests
β β βββ inventory.js # Inventory management
β β βββ hospitals.js # Hospital routes
β β βββ chat.js # Chat functionality
β β βββ analytics.js # Analytics endpoints
β β βββ notifications.js # Notification system
β βββ π§ services/ # Business Logic
β β βββ ai-service.js # AI processing
β β βββ matching-service.js # Donor matching
β β βββ notification-service.js # Notifications
β β βββ email-service.js # Email handling
β β βββ analytics-service.js # Analytics processing
β βββ π§ utils/ # Server utilities
β β βββ logger.js # Logging utility
β β βββ helpers.js # Helper functions
β β βββ constants.js # Application constants
β βββ π scripts/ # Database Scripts
β β βββ seed.js # Database seeding
β β βββ migrate.js # Database migrations
β β βββ backup.js # Backup utilities
β βββ π§ͺ tests/ # Test Files
β β βββ auth.test.js # Authentication tests
β β βββ donors.test.js # Donor tests
β β βββ requests.test.js # Request tests
β β βββ integration.test.js # Integration tests
β βββ π server.js # Express server entry
β
βββ π public/ # Static Assets
β βββ πΌοΈ images/ # Image assets
β βββ π¨ icons/ # Icon files
β βββ π documents/ # Document files
β βββ π sounds/ # Sound files
β
βββ π¨ styles/ # Styling
β βββ globals.css # Global styles
β βββ components.css # Component styles
β βββ animations.css # Animation styles
β
βββ π types/ # TypeScript Types
β βββ auth.ts # Authentication types
β βββ user.ts # User types
β βββ blood.ts # Blood-related types
β βββ hospital.ts # Hospital types
β βββ api.ts # API response types
β
βββ π docs/ # Documentation
β βββ API.md # API documentation
β βββ DEPLOYMENT.md # Deployment guide
β βββ CONTRIBUTING.md # Contribution guidelines
β βββ CHANGELOG.md # Version history
β
βββ βοΈ Configuration Files
βββ π next.config.mjs # Next.js configuration
βββ π¨ tailwind.config.ts # Tailwind CSS config
βββ π¦ components.json # Shadcn/ui config
βββ π package.json # Dependencies
βββ π§ tsconfig.json # TypeScript config
βββ π eslint.config.js # ESLint configuration
βββ π― jest.config.ts # Jest test config
βββ π README.md # This file
interface ChatMessage {
id: string;
message: string;
sender: 'user' | 'ai';
timestamp: Date;
bloodType?: BloodType;
location?: string;
urgency?: UrgencyLevel;
parsedIntent?: QueryIntent;
}
// Example: "I need O+ blood in Kolkata urgently"
const parseQuery = (message: string): QueryIntent => {
return {
bloodType: extractBloodType(message), // "O+"
location: extractLocation(message), // "Kolkata"
urgency: extractUrgency(message), // "urgent"
intent: 'FIND_DONOR'
};
};const BLOOD_COMPATIBILITY_MATRIX = {
"O-": ["O-", "O+", "A-", "A+", "B-", "B+", "AB-", "AB+"],
"O+": ["O+", "A+", "B+", "AB+"],
"A-": ["A-", "A+", "AB-", "AB+"],
"A+": ["A+", "AB+"],
"B-": ["B-", "B+", "AB-", "AB+"],
"B+": ["B+", "AB+"],
"AB-": ["AB-", "AB+"],
"AB+": ["AB+"]
} as const;
const findCompatibleDonors = async (
requiredBloodType: BloodType,
location: string,
urgency: UrgencyLevel
): Promise<Donor[]> => {
const compatibleTypes = BLOOD_COMPATIBILITY_MATRIX[requiredBloodType];
return await Donor.find({
bloodType: { $in: compatibleTypes },
location: { $regex: location, $options: 'i' },
isAvailable: true,
lastDonation: {
$lt: new Date(Date.now() - 56 * 24 * 60 * 60 * 1000) // 56 days ago
}
}).sort({
urgency: urgency === 'CRITICAL' ? -1 : 1,
distance: 1,
lastActive: -1
});
};# Required versions
Node.js >= 18.17.0
MongoDB >= 5.0.0
npm >= 9.0.0 (or pnpm >= 8.0.0)# 1. Clone the repository
git clone https://github.com/mandrita16/CatchMyType
cd CatchMyType
# 2. Install dependencies (both frontend and backend)
npm run install:all
# 3. Setup environment variables
cp .env.example .env.local
cp server/.env.example server/.env
# 4. Start the development servers
npm run dev:allπ Frontend Environment (.env.local)
# Application URLs
NEXT_PUBLIC_API_URL=http://localhost:5000
NEXT_PUBLIC_APP_URL=http://localhost:3000
NEXT_PUBLIC_SOCKET_URL=ws://localhost:5000
# Features
NEXT_PUBLIC_ENABLE_AI_CHAT=true
NEXT_PUBLIC_ENABLE_PUSH_NOTIFICATIONS=true
NEXT_PUBLIC_ENABLE_GEOLOCATION=true
# Analytics
NEXT_PUBLIC_GOOGLE_ANALYTICS=G-XXXXXXXXXX
NEXT_PUBLIC_MIXPANEL_TOKEN=your-mixpanel-token
# Maps & Location
NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=your-google-maps-key
NEXT_PUBLIC_MAPBOX_ACCESS_TOKEN=your-mapbox-token
# Third-party Services
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
NEXT_PUBLIC_CRISP_WEBSITE_ID=your-crisp-idπ Backend Environment (server/.env)
# Server Configuration
NODE_ENV=development
PORT=5000
FRONTEND_URL=http://localhost:3000
# Database
MONGODB_URI=mongodb://localhost:27017/catchmytype
# Or MongoDB Atlas
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/catchmytype
# Authentication
JWT_SECRET=your-super-secret-jwt-key-make-it-long-and-random
JWT_REFRESH_SECRET=your-refresh-token-secret
JWT_EXPIRE=24h
REFRESH_TOKEN_EXPIRE=7d
# Email Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
FROM_EMAIL=noreply@catchmytype.com
# SMS Configuration (Twilio)
TWILIO_ACCOUNT_SID=your-twilio-account-sid
TWILIO_AUTH_TOKEN=your-twilio-auth-token
TWILIO_PHONE_NUMBER=+1234567890
# AI Services
OPENAI_API_KEY=sk-your-openai-api-key
HUGGING_FACE_API_KEY=your-hugging-face-key
# Cloud Storage
CLOUDINARY_CLOUD_NAME=your-cloudinary-name
CLOUDINARY_API_KEY=your-cloudinary-key
CLOUDINARY_API_SECRET=your-cloudinary-secret
# Push Notifications
VAPID_PUBLIC_KEY=your-vapid-public-key
VAPID_PRIVATE_KEY=your-vapid-private-key
# Redis (for caching and sessions)
REDIS_URL=redis://localhost:6379
REDIS_PASSWORD=your-redis-password
# Rate Limiting
RATE_LIMIT_WINDOW_MS=15
RATE_LIMIT_MAX_REQUESTS=100
# Security
CORS_ORIGIN=http://localhost:3000
COOKIE_SECRET=your-cookie-secret
ENCRYPTION_KEY=your-32-character-encryption-key| Method | Endpoint | Description | Body |
|---|---|---|---|
POST |
/api/auth/register |
Register new user | { name, email, password, role, bloodType } |
POST |
/api/auth/login |
User login | { email, password, rememberMe? } |
POST |
/api/auth/refresh |
Refresh access token | { refreshToken } |
POST |
/api/auth/logout |
User logout | { refreshToken } |
POST |
/api/auth/forgot-password |
Request password reset | { email } |
POST |
/api/auth/reset-password |
Reset password | { token, newPassword } |
GET |
/api/auth/profile |
Get user profile | Headers: Authorization: Bearer <token> |
PUT |
/api/auth/profile |
Update user profile | { name?, phone?, address?, ... } |
POST |
/api/auth/verify-email |
Verify email address | { token } |
| Method | Endpoint | Description | Query Params |
|---|---|---|---|
GET |
/api/donors |
Get all donors | ?bloodType=O+&location=Kolkata&available=true |
GET |
/api/donors/:id |
Get donor by ID | - |
PUT |
/api/donors/:id/availability |
Update availability | { isAvailable: boolean } |
POST |
/api/donors/search |
Advanced donor search | { bloodType, location, urgency, radius } |
GET |
/api/donors/compatibility/:bloodType |
Get compatible donors | - |
POST |
/api/donors/:id/contact |
Contact donor | { message, urgency } |
| Method | Endpoint | Description | Body |
|---|---|---|---|
GET |
/api/requests |
Get all requests | ?status=active&urgency=critical |
POST |
/api/requests |
Create new request | { bloodType, location, urgency, hospital, ... } |
GET |
/api/requests/:id |
Get request details | - |
PUT |
/api/requests/:id |
Update request | { status?, notes?, ... } |
POST |
/api/requests/:id/respond |
Respond to request | { response, contactInfo } |
DELETE |
/api/requests/:id |
Delete request | - |
GET |
/api/requests/user/:userId |
Get user's requests | - |
POST |
/api/requests/:id/fulfill |
Mark as fulfilled | { donorId, notes } |
| Method | Endpoint | Description | Body |
|---|---|---|---|
GET |
/api/hospitals |
Get all hospitals | ?city=Kolkata&bloodBank=true |
POST |
/api/hospitals |
Register hospital | { name, address, contactInfo, facilities } |
GET |
/api/inventory |
Get blood inventory | ?hospital=:id&bloodType=O+ |
POST |
/api/inventory |
Add inventory item | { bloodType, quantity, expiryDate, hospital } |
PUT |
/api/inventory/:id |
Update inventory | { quantity?, expiryDate?, status? } |
DELETE |
/api/inventory/:id |
Remove inventory item | - |
GET |
/api/inventory/low-stock |
Get low stock alerts | ?threshold=10 |
POST |
/api/inventory/transfer |
Transfer blood units | { from, to, bloodType, quantity } |
| Method | Endpoint | Description | Body |
|---|---|---|---|
GET |
/api/chat/conversations |
Get user conversations | - |
POST |
/api/chat/conversations |
Start new conversation | { participants, type } |
GET |
/api/chat/:conversationId/messages |
Get conversation messages | ?limit=50&offset=0 |
POST |
/api/chat/:conversationId/messages |
Send message | { content, type, attachments? } |
PUT |
/api/chat/messages/:id/read |
Mark message as read | - |
POST |
/api/chat/ai |
Chat with AI assistant | { message, context? } |
| Method | Endpoint | Description | Query Params |
|---|---|---|---|
GET |
/api/analytics/dashboard |
Get dashboard stats | ?period=30d®ion=all |
GET |
/api/analytics/donations |
Donation analytics | ?startDate=2024-01-01&endDate=2024-12-31 |
GET |
/api/analytics/requests |
Request analytics | ?groupBy=bloodType&status=all |
GET |
/api/analytics/hospitals |
Hospital performance | ?metric=response_time |
GET |
/api/analytics/users |
User activity stats | ?active=true&role=donor |
# Unit Tests
npm run test:unit
# Integration Tests
npm run test:integration
# End-to-End Tests
npm run test:e2e
# Coverage Report
npm run test:coverage
# Performance Tests
npm run test:performance
# All Tests
npm run test:all| Component | Coverage Target | Current |
|---|---|---|
| API Endpoints | 95% | π’ 97% |
| Authentication | 100% | π’ 100% |
| Blood Matching | 98% | π’ 99% |
| UI Components | 85% | π‘ 82% |
| AI Chat System | 90% | π’ 94% |
π¦ Vercel Deployment (Frontend)
# Install Vercel CLI
npm i -g vercel
# Deploy to production
vercel --prod
# Environment variables setup
vercel env add NEXT_PUBLIC_API_URL
vercel env add NEXT_PUBLIC_SOCKET_URL
# ... add all required env varsVercel Configuration (vercel.json):
{
"builds": [
{
"src": "package.json",
"use": "@vercel/next"
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "https://your-backend-url.com/api/$1"
}
],
"env": {
"NEXT_PUBLIC_API_URL": "@api-url",
"NEXT_PUBLIC_SOCKET_URL": "@socket-url"
}
}π₯οΈ Backend Deployment Options
Option 1: Railway
# Install Railway CLI
npm install -g @railway/cli
# Login and deploy
railway login
railway link
railway upOption 2: Heroku
# Install Heroku CLI
npm install -g heroku
# Create and deploy
heroku create catchmytype-api
git push heroku mainOption 3: DigitalOcean App Platform
# app.yaml
name: catchmytype-api
services:
- name: api
source_dir: /server
github:
repo: srinjaykarfa/CatchMyType_Hack4Bengal
branch: main
run_command: npm start
environment_slug: node-js
instance_count: 1
instance_size_slug: basic-xxs
envs:
- key: NODE_ENV
value: production
- key: MONGODB_URI
value: ${DATABASE_URL}# Dockerfile
FROM node:18-alpine AS builder
# Frontend build
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Backend setup
WORKDIR /app/server
COPY server/package*.json ./
RUN npm ci --only=production
FROM node:18-alpine AS production
WORKDIR /app
# Copy built frontend
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/package*.json ./
# Copy backend
COPY --from=builder /app/server ./server
EXPOSE 3000 5000
CMD ["npm", "run", "start:prod"]# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
- "5000:5000"
environment:
- NODE_ENV=production
- MONGODB_URI=mongodb://mongo:27017/catchmytype
depends_on:
- mongo
- redis
mongo:
image: mongo:7
restart: always
ports:
- "27017:27017"
volumes:
- mongo_data:/data/db
redis:
image: redis:7-alpine
restart: always
ports:
- "6379:6379"
volumes:
mongo_data:| Metric | Target | Current | Status |
|---|---|---|---|
| Page Load Time | < 2s | 1.3s | π’ Excellent |
| API Response Time | < 200ms | 145ms | π’ Excellent |
| Database Query Time | < 100ms | 78ms | π’ Excellent |
| Chat Message Latency | < 50ms | 32ms | π’ Excellent |
| AI Response Time | < 3s | 2.1s | π’ Good |
| Mobile Performance | > 90 | 94 | π’ Excellent |
| SEO Score | > 95 | 98 | π’ Excellent |
- Code Splitting: Automatic route-based splitting with Next.js
- Image Optimization: Next.js Image component with WebP conversion
- Caching Strategy: Redis for session data, CDN for static assets
- Database Indexing: Optimized MongoDB indexes for common queries
- Lazy Loading: Components and images loaded on demand
- Bundle Analysis: Regular bundle size monitoring and optimization
| Security Layer | Implementation | Status |
|---|---|---|
| Authentication | JWT with refresh tokens | π’ Active |
| Authorization | Role-based access control | π’ Active |
| Data Encryption | AES-256 for sensitive data | π’ Active |
| Password Security | bcrypt with salt rounds | π’ Active |
| Rate Limiting | Express rate limit middleware | π’ Active |
| CORS Protection | Configured CORS policies | π’ Active |
| Input Validation | Joi schema validation | π’ Active |
| SQL Injection | Mongoose ODM protection | π’ Active |
| XSS Protection | Helmet.js security headers | π’ Active |
| CSRF Protection | Double submit cookie pattern | π’ Active |
// Authentication Middleware
const authenticateToken = (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, process.env.JWT_SECRET!, (err, decoded) => {
if (err) {
return res.status(403).json({ error: 'Invalid or expired token' });
}
req.user = decoded;
next();
});
};
// Rate Limiting
const rateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP',
standardHeaders: true,
legacyHeaders: false,
});
// Input Validation
const validateBloodRequest = [
body('bloodType').isIn(['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']),
body('urgency').isIn(['CRITICAL', 'URGENT', 'MODERATE', 'ROUTINE']),
body('location').isString().trim().isLength({ min: 2, max: 100 }),
body('contactPhone').isMobilePhone('en-IN'),
];// AI Chat Assistant Implementation
class AIBloodAssistant {
private nlpProcessor: NLPProcessor;
private donorMatcher: DonorMatcher;
async processQuery(message: string, context: ChatContext): Promise<AIResponse> {
// Parse natural language input
const intent = await this.nlpProcessor.parseIntent(message);
switch (intent.type) {
case 'FIND_DONOR':
return await this.findDonors(intent);
case 'BLOOD_INFO':
return await this.getBloodInfo(intent);
case 'EMERGENCY':
return await this.handleEmergency(intent);
default:
return this.generateHelpResponse();
}
}
private async findDonors(intent: ParsedIntent): Promise<AIResponse> {
const donors = await this.donorMatcher.findCompatibleDonors({
bloodType: intent.bloodType,
location: intent.location,
urgency: intent.urgency,
radius: intent.radius || 10
});
return {
message: `Found ${donors.length} compatible donors in ${intent.location}`,
data: donors,
suggestedActions: ['contact_donor', 'create_request', 'emergency_alert']
};
}
}// public/manifest.json
{
"name": "CatchMyType - Smart Blood Donation",
"short_name": "CatchMyType",
"description": "AI-powered blood donation platform",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#dc2626",
"icons": [
{
"src": "/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"features": [
"offline_support",
"push_notifications",
"geolocation",
"camera_access"
]
}// Location-based donor search
const findNearbyDonors = async (
userLocation: Coordinates,
bloodType: BloodType,
radius: number = 10
): Promise<DonorWithDistance[]> => {
const donors = await Donor.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [userLocation.longitude, userLocation.latitude]
},
distanceField: "distance",
maxDistance: radius * 1000, // Convert km to meters
spherical: true,
query: {
bloodType: { $in: getCompatibleBloodTypes(bloodType) },
isAvailable: true
}
}
},
{
$addFields: {
distanceInKm: { $divide: ["$distance", 1000] }
}
},
{
$sort: { distance: 1 }
}
]);
return donors;
};- β User registration and authentication
- β Blood donor search and matching
- β Hospital inventory management
- β Real-time chat system
- β AI-powered chat assistant
- β Mobile-responsive design
- π Machine learning donor recommendations
- π Predictive analytics for blood demand
- π Blockchain-based donation tracking
- π Advanced health screening integration
- π Gamification and reward system
- π Multi-language support (Bengali, Hindi, English)
- π Government health system integration
- π Insurance and billing integration
- π Telemedicine consultation
- π Advanced logistics and transportation
- π International expansion
- π IoT device integration for health monitoring
- π AR/VR training modules
- π Drone delivery for emergency situations
- π Advanced genetic compatibility matching
- π Personalized health recommendations
- π Social impact measurement tools
We welcome contributions from the community! Here's how you can help make CatchMyType even better:
- π Bug Reports: Found a bug? Create an issue with detailed reproduction steps
- π‘ Feature Requests: Have an idea? We'd love to hear it!
- π§ Code Contributions: Submit pull requests for bug fixes or new features
- π Documentation: Help improve our docs and guides
- π¨ Design: Contribute to UI/UX improvements
- π Translations: Help us make CatchMyType multilingual
-
Fork the repository and create your feature branch
git checkout -b feature/amazing-feature
-
Follow our coding standards
- Use TypeScript for type safety
- Follow ESLint rules
- Write meaningful commit messages
- Add tests for new features
-
Test your changes
npm run test:all npm run build
-
Submit a Pull Request
- Provide a clear description of changes
- Reference any related issues
- Ensure all tests pass