security: remove obsolete ABDM sandbox docs, DreamSoft middleware references, and purge exposed credentials

This commit is contained in:
DevSoftTech Server 2026-10-28 00:17:24 +05:30
parent 2ae0ba5d6f
commit 6c1c19153c
7 changed files with 5 additions and 1918 deletions

View File

@ -13,8 +13,8 @@ namespace App\Libraries\Abdm;
*/ */
class AbdmV3DirectHelper class AbdmV3DirectHelper
{ {
protected string $clientId = 'SBXID_033661'; protected string $clientId = '';
protected string $clientSecret = '656f79f1-ef99-495f-9f37-713219ecbbcf'; protected string $clientSecret = '';
protected string $sessionsUrl = 'https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions'; protected string $sessionsUrl = 'https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions';
protected string $certUrl = 'https://abhasbx.abdm.gov.in/abha/api/v3/profile/public/certificate'; protected string $certUrl = 'https://abhasbx.abdm.gov.in/abha/api/v3/profile/public/certificate';
protected string $searchUrl = 'https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha/search'; protected string $searchUrl = 'https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha/search';
@ -64,11 +64,11 @@ class AbdmV3DirectHelper
if (function_exists('env')) { if (function_exists('env')) {
$envClientId = env('abdm.directClientId', env('BRIDGE_SOURCE_CODE', '')); $envClientId = env('abdm.directClientId', env('BRIDGE_SOURCE_CODE', ''));
if (! empty($envClientId) && $this->clientId === 'SBXID_033661') { if (! empty($envClientId) && empty($this->clientId)) {
$this->clientId = (string) $envClientId; $this->clientId = (string) $envClientId;
} }
$envSecret = env('abdm.directClientSecret', ''); $envSecret = env('abdm.directClientSecret', '');
if (! empty($envSecret) && $this->clientSecret === '656f79f1-ef99-495f-9f37-713219ecbbcf') { if (! empty($envSecret) && empty($this->clientSecret)) {
$this->clientSecret = (string) $envSecret; $this->clientSecret = (string) $envSecret;
} }
} }

View File

@ -1,475 +0,0 @@
# ABDM Integration Architecture - With Middleware Gateway
**Date:** May 12, 2026
**Setup:** Two Gateway Options (CSNOtk vs Custom)
---
## 🏗️ System Architecture
```
┌─────────────────┐
│ HMS CI4 │
│ (PHP/CI4) │
└────────┬────────┘
│
│ ABDM API Calls
│
▼
┌────────────────────────────────────┐
│ Middleware Gateway (Node.js) │
│ https://abdm-bridge.e-atria.in │
│ (Your Custom Gateway) │
└────────┬───────────┬─────┬─────────┘
│ │ │
┌────────▼─┐ ┌──────▼──┐ │
│ ABDM │ │ SNOMED │ │ (Alternative: CSNOtk Public)
│ M3 API │ │ Service │ │
└──────────┘ └─────────┘ │
│
┌────────────▼────────────┐
│ CSNOtk Public Gateway │
│ (csnotk.e-atria.in) │
│ (Fallback Option) │
└─────────────────────────┘
```
---
## 🔀 Two Gateway Options
### Option 1: CSNOtk Public Gateway (Current - No Setup Needed)
```
HMS → CSNOtk Gateway → ABDM M3 API
```
**Pros:**
- ✅ No infrastructure setup required
- ✅ Pre-configured and stable
- ✅ Shared bearer token approach
**Cons:**
- ❌ Shared infrastructure (potential bottleneck)
- ❌ No audit trail for your organization
- ❌ Limited customization
- ❌ Vendor dependency
**Configuration:**
```env
BRIDGE_SYNC_URL = https://csnotk.e-atria.in/api/bridge
```
---
### Option 2: Custom Middleware Gateway (New - Recommended for Production)
```
HMS → Your Gateway (abdm-bridge.e-atria.in) → ABDM M3 API
↓
Your Infrastructure
```
**Pros:**
- ✅ Full control and customization
- ✅ Detailed logging and audit trail
- ✅ Custom rate limiting per client
- ✅ Advanced monitoring and alerting
- ✅ Dedicated infrastructure
- ✅ Better performance for your use case
- ✅ Future extensibility
**Cons:**
- ⚠️ Requires Ubuntu server setup
- ⚠️ Ongoing maintenance responsibility
- ⚠️ SSL certificate renewal
**Configuration:**
```env
BRIDGE_SYNC_URL = https://abdm-bridge.e-atria.in/api/v3
```
---
## 📋 Comparison Matrix
| Feature | CSNOtk Public | Your Gateway |
|---------|---------------|--------------|
| Setup Time | 5 min (edit .env) | 15 min (deploy script) |
| Audit Trail | Limited | Full audit logs |
| Rate Limiting | Global | Per-HMS instance |
| Performance | Shared | Dedicated |
| Monitoring | By CSNOtk | Full control |
| Customization | No | Full Node.js code |
| Cost | Included | Server cost only |
| SLA | Vendor SLA | Your responsibility |
| Latency | Depends on CSNOtk | Depends on your server |
---
## 🎯 Recommendation
**Use Your Gateway (Option 2) if:**
- ✅ Production deployment planned
- ✅ High transaction volume expected
- ✅ Compliance/audit trail required
- ✅ Want full control over integration
- ✅ Planning to scale beyond sandbox
**Use CSNOtk Public (Option 1) if:**
- ✅ Testing/sandbox only
- ✅ Low transaction volume
- ✅ Want zero infrastructure setup
- ✅ Short-term PoC
---
## 🚀 Deployment Scenarios
### Scenario 1: Quick Testing (This Week)
```
Step 1: Keep CSNOtk gateway
Step 2: Test OPD consult → SNOMED → ABHA → Consent
Step 3: Run full 7-step test sequence
Status: Fastest path to validation
```
### Scenario 2: Prepare for Production
```
Step 1: Deploy your gateway to Ubuntu server
- Use deploy.sh for automation
- Takes ~15 minutes
Step 2: Configure HMS to use your gateway
- Edit .env: BRIDGE_SYNC_URL
Step 3: Run full test sequence again
Step 4: Monitor logs and performance
Status: Ready for production deployment
```
### Scenario 3: Hybrid (Recommended)
```
Phase 1 (Week 1):
- Use CSNOtk for immediate testing
- Complete 7-step validation
Phase 2 (Week 2):
- Deploy your gateway in parallel
- Run alongside CSNOtk
Phase 3 (Week 3):
- Switch to your gateway
- Keep CSNOtk as fallback
Phase 4 (Month 2+):
- Production operations
- Retire CSNOtk if desired
```
---
## 🔧 Switching Between Gateways
### From CSNOtk to Your Gateway
**Step 1:** Gateway already deployed at `abdm-bridge.e-atria.in`
**Step 2:** Update HMS `.env`
```bash
# Before
BRIDGE_SYNC_URL = https://csnotk.e-atria.in/api/bridge
# After
BRIDGE_SYNC_URL = https://abdm-bridge.e-atria.in/api/v3
```
**Step 3:** Restart HMS
```bash
# If using Docker
docker-compose restart hms-app
# Or PHP-FPM
sudo systemctl restart php-fpm
```
**Step 4:** Verify
```bash
# Test health
curl https://abdm-bridge.e-atria.in/api/v3/health
# Test OPD save
# Should work without any HMS code changes
```
---
## 📊 Request Flow Comparison
### Using CSNOtk Gateway
```
HMS
└─ POST /api/v3/abha/validate
└─ BRIDGE_SYNC_URL = https://csnotk.e-atria.in/api/bridge
└─ CSNOtk Gateway
└─ ABDM M3 API
└─ Returns response
```
### Using Your Gateway
```
HMS
└─ POST /api/v3/abha/validate
└─ BRIDGE_SYNC_URL = https://abdm-bridge.e-atria.in/api/v3
└─ Your Node.js Gateway
└─ ABDM M3 API
└─ Returns response
└─ Logs request to /logs/combined.log
└─ Tracks metrics (response time, errors)
```
---
## 🛠️ Your Gateway Capabilities
Once deployed, your gateway provides:
### 1. Request/Response Logging
```bash
# Every API call logged with:
# - Request ID
# - Timestamp
# - Authorization status
# - Response time
# - Error details (if any)
sudo docker logs -f abdm-bridge-gateway | grep "ABHA validation"
```
### 2. Performance Monitoring
```bash
# Response times for each endpoint
docker stats abdm-bridge-gateway
# Memory usage
free -h
```
### 3. Custom Metrics
- Total requests per hour
- ABHA validations succeeded/failed
- Average response time
- Error rates by endpoint
### 4. Security Features
- Rate limiting (100 req/15min per IP)
- Bearer token authentication
- Request ID tracking
- SSL/TLS encryption
- CORS policy
### 5. Future Extensibility
- Add JWT token support
- Implement caching layer
- Add request signing
- Custom consent workflows
- FHIR bundle transformation
---
## 📈 Performance Expectations
### CSNOtk Gateway
- **Avg Response Time:** 500-1000ms
- **Rate Limit:** Shared with all users
- **Latency:** Depends on CSNOtk load
### Your Gateway (Dedicated Server)
- **Avg Response Time:** 100-300ms (faster)
- **Rate Limit:** 100 per 15 min (per HMS instance)
- **Latency:** Controlled infrastructure
---
## 🔐 Security Considerations
### Token Management
```
CSNOtk: Shared bearer token
└─ Single point of failure
└─ Limited audit trail
Your Gateway: Individual tokens per service
└─ Rotate quarterly
└─ Full audit trail
└─ Can revoke per-HMS
```
### Audit Trail
```
CSNOtk: Minimal logging
└─ No visibility into errors
└─ Compliance unclear
Your Gateway: Complete logging
└─ Every request tracked
└─ Full error details
└─ Compliance-ready
```
---
## 💰 Cost Comparison
### CSNOtk Public (Option 1)
- **Server Cost:** $0 (shared)
- **Maintenance:** Vendor responsibility
- **Setup Time:** 5 min
- **Annual Cost:** $0
### Your Gateway (Option 2)
- **Server Cost:** $10-50/month (Ubuntu VPS)
- **Maintenance:** Your responsibility
- **Setup Time:** 15 min (automated)
- **Annual Cost:** $120-600
**ROI:** Worth it for production; skip for PoC
---
## 🎓 Implementation Roadmap
```
Week 1: Testing Phase
├─ Use CSNOtk gateway
├─ Complete 7-step test sequence
└─ Validate ABDM integration works
Week 2: Production Prep
├─ Deploy your gateway (15 min)
├─ Test both gateways in parallel
├─ Verify identical responses
└─ Performance benchmark
Week 3: Migration
├─ Switch to your gateway
├─ Keep CSNOtk as fallback
├─ Monitor for issues
└─ Document any differences
Week 4+: Production
├─ Run on your gateway only
├─ Setup monitoring/alerting
├─ Prepare disaster recovery
└─ Plan scaling strategy
```
---
## ✅ Decision Matrix
### Quick Decision Tree
```
Question 1: Is this production?
├─ YES → Deploy your gateway → Option 2
└─ NO → Continue with CSNOtk → Option 1
Question 2: High transaction volume expected?
├─ YES (>1000/day) → Your gateway → Option 2
└─ NO (<1000/day) → CSNOtk OK → Option 1
Question 3: Compliance/audit requirements?
├─ YES → Must have your gateway → Option 2
└─ NO → CSNOtk sufficient → Option 1
Question 4: Budget for infrastructure?
├─ YES → Deploy your gateway → Option 2
└─ NO → Use CSNOtk for now → Option 1
```
---
## 📞 Making the Switch
### If You Decide to Deploy Your Gateway Later
1. **Create Ubuntu Server**
```bash
VPS provider: DigitalOcean, Linode, AWS, etc.
OS: Ubuntu 20.04+
Size: 1GB RAM, 25GB SSD
```
2. **Copy Files**
```bash
scp -r middleware-gateway/ root@SERVER_IP:/opt/
```
3. **Run Deploy Script**
```bash
ssh root@SERVER_IP
cd /opt/middleware-gateway
sudo ./deploy.sh
```
4. **Update HMS .env**
```bash
BRIDGE_SYNC_URL = https://abdm-bridge.e-atria.in/api/v3
```
5. **Restart HMS & Test**
Done! Fully automatic upgrade path.
---
## 🎯 Recommendation for Your Project
### Current Status: May 12, 2026
- ✅ ABDM credentials ready (SBXID_033661)
- ✅ OPD form ABDM-compliant
- ✅ CSNOtk gateway accessible
- ✅ Your gateway code ready to deploy
### Immediate Next (This Week)
```
Use CSNOtk Gateway:
1. Quick testing of OPD → ABDM flow
2. Validate SNOMED integration
3. Complete 7-step test sequence
Duration: 2-3 days
```
### Future (Production Ready)
```
Deploy Your Gateway:
1. Use automated deploy.sh
2. Takes 15 minutes
3. Seamless switch for HMS
4. Full control + audit trail
Recommended: Before live usage
```
---
**Status:** 🟢 Both options ready
**Quick Start:** CSNOtk (no setup)
**Production Ready:** Your Gateway (15 min setup)
**Recommendation:** Start with CSNOtk, upgrade to your gateway in Week 2
---
## 📚 Next Steps
1. **This Week:** Use CSNOtk, run tests, validate ABDM integration
2. **Next Week:** Review this document, decide on production path
3. **Before Go-Live:** Deploy your gateway using `deploy.sh`
4. **Post-Go-Live:** Monitor, optimize, scale as needed
---
**Questions?** Reference the detailed guides:
- Quick Start: `docs/ABDM_QUICK_START.md`
- Full Deployment: `middleware-gateway/DEPLOYMENT_GUIDE.md`
- Custom Gateway: `middleware-gateway/README.md`

View File

@ -1,293 +0,0 @@
# ABDM Sandbox Integration — Quick Start Guide
**Approved:** May 12, 2026
**Client ID:** `SBXID_033661`
**Integration Mode:** DreamSoft Middleware (csnotk.e-atria.in)
---
## 🎯 What's Ready
Your HMS application now has:
✅ **ABDM Sandbox Credentials Configured**
- Client ID: `SBXID_033661`
- Client Secret: Configured in `.env`
- Middleware Gateway: `https://csnotk.e-atria.in`
✅ **ABDM Controllers Ready**
- ABHA validation endpoint
- Consent request/callback handlers
- Bundle push for OPD, Lab, Discharge
- FHIR bundle generation
✅ **OPD Enhancements for ABDM**
- ABHA number input field
- SNOMED CT diagnosis/complaint coding
- Vitals with proper units
- Medicine SNOMED/ATC coding
- Recent patient entries chips (for faster data reuse)
✅ **Documentation Created**
- `docs/ABDM_SANDBOX_SETUP.md` — Complete integration guide
- `docs/ABDM_SANDBOX_CHECKLIST.md` — Testing checklist
- This quick start guide
---
## 🚀 Immediate Next Steps
### Step 1: Get Missing Bearer Token (BLOCKING)
Contact your middleware provider (CSNOtk/DreamSoft) to obtain:
```
BRIDGE_SYNC_TOKEN = <your-bearer-token>
```
Once received, update `.env`:
```env
BRIDGE_SYNC_TOKEN = your-token-here
```
### Step 2: Register in ABDM Sandbox
1. Go to: https://sandbox.abdm.gov.in
2. Register your organization with Client ID: `SBXID_033661`
3. Note your **HFR ID** (Health Facility Registry ID)
4. Note your **NPI** (National Practitioner Identifier)
### Step 3: Update .env with Your IDs
```env
ABDM_HFR_ID = your-hfr-id
ABDM_NPI_ID = your-npi-id
```
### Step 4: Get Test ABHA Numbers
From ABDM sandbox portal, get 2-3 test ABHA numbers, e.g.:
```
14-0061-0000-0001
14-0061-0000-0002
14-0061-0000-0003
```
### Step 5: Create Test Patient in HMS
```
Patient Name: Test Patient
ABHA Number: 14-0061-0000-0001
Gender: Male
Age: 35
```
---
## 🧪 Testing Sequence
### Test 1: Verify Middleware Connectivity (2 min)
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://csnotk.e-atria.in/api/bridge/status
# Should return: {"status": "ok"}
```
### Test 2: ABHA Validation (5 min)
1. Open OPD Consult form in HMS
2. Create new patient → Enter ABHA: `14-0061-0000-0001`
3. Click "Validate ABHA"
4. **Expected:** ✅ ABHA linked successfully
### Test 3: SNOMED Terminology (3 min)
1. In Diagnosis field → Type: `fever`
2. Click search icon
3. **Expected:** Dropdown shows SNOMED codes via csnotk
4. Select one → SNOMED ID auto-fills
### Test 4: OPD Consult Creation (10 min)
1. Fill OPD form:
- Complaints: `Fever and cough`
- Vital Signs: BP 120/80, Pulse 72, Temp 37.5°C
- Diagnosis: Select fever (SNOMED)
- Prescription: Add 1-2 medicines
2. Click "Save & Submit"
3. Check database:
```sql
SELECT opd_id, fhir_bundle_id, abdm_push_status
FROM opd_prescription
ORDER BY id DESC LIMIT 1;
```
4. **Expected:** `fhir_bundle_id` populated, `abdm_push_status = 0`
### Test 5: Consent Request (5 min)
1. Open saved OPD record
2. Scroll to "ABDM Actions" section
3. Click "Request Consent"
4. Check sandbox portal for consent request
5. **Expected:** Consent request appears in ABDM sandbox
### Test 6: Accept Consent in Sandbox (2 min)
1. Login to https://sandbox.abdm.gov.in with test account
2. Navigate to "Consent Requests"
3. Accept the request from your HMS
4. **Expected:** Status changes to "GRANTED"
### Test 7: Push Bundle to ABDM (3 min)
1. After consent granted in HMS, refresh page
2. Click "Share Records" → "Push to ABDM"
3. Check ABDM sandbox for record appearance
4. **Expected:** ✅ Record pushed successfully
---
## 📊 Dashboard Access
Once configured, access ABDM features via:
1. **OPD Consult** → Bottom section "ABDM Actions"
- Link ABHA
- Request Consent
- Share Records
2. **ABDM Task Board** → Menu → "ABDM"
- View all ABDM operations
- Monitor consent status
- Check bundle push history
3. **Patient Profile** → "ABHA" tab
- View linked ABHA
- History of shares
---
## 🔑 Key API Endpoints (for your reference)
| Operation | Endpoint | Method |
|-----------|----------|--------|
| ABHA Validate | `/AbdmGateway/abha_validate` | POST |
| Consent Request | `/AbdmGateway/consent_request` | POST |
| Push OPD | `/AbdmGateway/share_prescription_bundle` | POST |
| Push Lab | `/AbdmGateway/share_diagnosis_report_bundle` | POST |
| Push Discharge | `/AbdmGateway/share_ipd_discharge_bundle` | POST |
---
## ⚠️ Common Issues & Fixes
### Issue: "Middleware unreachable"
```
BRIDGE_SYNC_URL = https://csnotk.e-atria.in/api/bridge
BRIDGE_SYNC_TOKEN = <missing-or-invalid>
```
**Fix:**
1. Verify `.env` has correct URL and token
2. Contact middleware provider for token
3. Check firewall allows HTTPS outbound
### Issue: "ABHA validation stuck in 'pending'"
**Fix:**
1. Verify ABHA number exists in sandbox
2. Check token has permission for ABHA operations
3. Check logs: `writable/logs/log-*.log`
### Issue: "SNOMED code not found in diagnosis"
**Fix:**
1. Ensure CSNOtk service is responding
2. Try common term: `fever`, `cough`, `headache`
3. Check: `snomed.csnotk.baseUrl` in `.env`
### Issue: "Consent never shows 'GRANTED' status"
**Fix:**
1. Login to ABDM sandbox portal
2. Navigate to "Consent Requests" section
3. Manually accept the request (for testing)
4. Refresh HMS page — status updates
---
## 📋 Configuration Summary
**Current State:**
```
Environment: development
ABDM Connector: dreamsoft
Middleware URL: https://csnotk.e-atria.in
SNOMED Service: https://csnotk.e-atria.in/csnoserv
Direct ABDM URL: https://dev.abdm.gov.in/api/v3
```
**Sandbox Credentials:**
```
Client ID: SBXID_033661
Client Secret: 656f79f1-ef99-495f-9f37-713219ecbbcf
Mode: Approved & Ready
```
**Still Needed:**
- [ ] Bearer token for middleware
- [ ] HFR ID from facility registration
- [ ] NPI ID for practitioner
- [ ] Test ABHA numbers from sandbox
---
## 📞 Support
### Middleware Support
- **Provider:** CSNOtk / DreamSoft
- **URL:** https://csnotk.e-atria.in
- **Contact:** Check middleware provider documentation
### ABDM Sandbox Support
- **Portal:** https://sandbox.abdm.gov.in
- **Docs:** https://sandbox.abdm.gov.in/sandbox/v3/new-documentation
- **API Docs:** NHA ABDM M3 Integration Guide
### Application Logs
Check for errors:
```bash
tail -f writable/logs/log-*.log
```
---
## 🎓 Learning Path
1. **Day 1:** Complete steps 1-4 (get credentials)
2. **Day 2:** Run Tests 1-2 (connectivity & ABHA)
3. **Day 3:** Run Tests 3-4 (SNOMED & OPD creation)
4. **Day 4:** Run Tests 5-7 (full consent → push flow)
5. **Day 5+:** Move to Phase 2 (database schema additions)
---
**Status:** 🟢 Ready for Sandbox Testing
**Last Updated:** May 12, 2026
---
## Quick Reference: .env Configuration
```env
# ABDM Sandbox Mode
abdm.connector = dreamsoft
# Direct API Fallback
abdm.directClientId = SBXID_033661
abdm.directClientSecret = 656f79f1-ef99-495f-9f37-713219ecbbcf
abdm.directBaseUrl = https://dev.abdm.gov.in/api/v3
# Middleware Gateway (DreamSoft)
BRIDGE_SYNC_URL = https://csnotk.e-atria.in/api/bridge
BRIDGE_SYNC_TOKEN = <TO_BE_OBTAINED>
BRIDGE_SOURCE_CODE = SBXID_033661
BRIDGE_SYNC_TIMEOUT = 20
# SNOMED CT Terminology
snomed.csnotk.baseUrl = https://csnotk.e-atria.in/csnoserv
snomed.csnotk.enabled = true
snomed.csnotk.timeoutSec = 10
# Facility Details
ABDM_HFR_ID = <TO_BE_OBTAINED>
ABDM_NPI_ID = <TO_BE_OBTAINED>
```
---
**Ready to proceed? → Start with Step 1 above!** 🚀

View File

@ -1,187 +0,0 @@
# ABDM Sandbox Configuration Checklist
**Project:** HMS CI4 - ABDM Sandbox Integration
**Date Created:** May 12, 2026
**Status:** Approved Sandbox Credentials Received
## Configuration Status
### ✅ Completed
- [x] Client ID obtained: `SBXID_033661`
- [x] Client Secret received: `656f79f1-ef99-495f-9f37-713219ecbbcf`
- [x] .env configured with credentials
- [x] ABDM config file reviewed: `app/Config/AbdmConnector.php`
- [x] ABDM controllers present: `AbdmGateway.php`, `AbdmTaskBoard.php`
- [x] FHIR builder available: `app/Libraries/FhirR4Builder.php`
- [x] Sandbox documentation created: `docs/ABDM_SANDBOX_SETUP.md`
- [x] Recent OPD entry chips implemented (prerequisite feature)
### ⏳ Todo - Immediate (This Session)
- [ ] Get Bearer token from middleware provider (csnotk.e-atria.in)
- [ ] Update `.env` with `BRIDGE_SYNC_TOKEN`
- [ ] Register test user in ABDM sandbox portal
- [ ] Get test ABHA numbers from sandbox
- [ ] Get HFR ID and NPI from facility registration
- [ ] Verify middleware connectivity test
- [ ] Create test patient record in HMS
### ⏳ Todo - Phase 1 (Testing)
- [ ] Test ABHA validation endpoint
- [ ] Verify SNOMED CT terminology service (CSNOtk)
- [ ] Test OPD consult FHIR bundle generation
- [ ] Test consent request flow
- [ ] Test bundle push to sandbox
- [ ] Validate pushed bundles appear in ABDM portal
### ⏳ Todo - Phase 2 (Database Schema)
- [ ] Run migrations to add ABDM fields to opd_prescription
- [ ] Add ABHA fields to patient_master
- [ ] Create abdm_consent tracking table
- [ ] Create abdm_bundle_audit table
- [ ] Add abdm_consent_audit for trail
### ⏳ Todo - Phase 3 (UI/UX)
- [ ] Add ABHA link UI in patient registration
- [ ] Add ABDM actions panel to OPD consult
- [ ] Add consent request UI
- [ ] Add records sharing UI
- [ ] Add ABDM task board dashboard
### ⏳ Todo - Phase 4 (Additional HI Types)
- [ ] Implement Lab Report (DiagnosticReportRecord) bundle
- [ ] Implement Discharge Summary (DischargeSummaryRecord) bundle
- [ ] Implement Wellness Record (vitals, habits)
- [ ] Implement Immunization Record (if needed)
### ⏳ Todo - Phase 5 (Production Hardening)
- [ ] Set up error logging for ABDM API failures
- [ ] Create ABDM retry/reconciliation service
- [ ] Set up notifications for consent approvals
- [ ] Audit trail for ABDM operations
- [ ] Security: Encrypt stored client secret in DB
- [ ] Rate limiting for ABDM API calls
---
## Current Configuration
### Environment Setup
```env
abdm.connector = dreamsoft
abdm.directClientId = SBXID_033661
BRIDGE_SYNC_URL = https://csnotk.e-atria.in/api/bridge
BRIDGE_SOURCE_CODE = SBXID_033661
snomed.csnotk.baseUrl = https://csnotk.e-atria.in/csnoserv
```
### Related Features Already Implemented
- OPD Consult FHIR bundle generation
- SNOMED CT complaint/diagnosis coding
- ABHA input field in OPD form
- Vitals normalization (numeric validation)
- Medicine master SNOMED/ATC coding
- Recent patient entries chips (for fast data reuse)
### Middleware Gateway
- **Provider:** CSNOtk / DreamSoft
- **URL:** https://csnotk.e-atria.in
- **Services:** ABHA validation, Consent relay, Bundle routing, SNOMED search
- **Status:** Requires bearer token configuration
### ABDM API Integration Points
1. **OPD Consult** → OPConsultRecord + PrescriptionRecord
2. **Lab Reports** → DiagnosticReportRecord (future)
3. **Discharge Summary** → DischargeSummaryRecord (future)
4. **Billing/Invoice** → InvoiceRecord (future)
---
## Contact & Credentials Safeguard
### Important Security Notes
- **NEVER commit credentials to git** (already in .env, add to .gitignore)
- **Rotate secrets periodically** in production
- **Use environment variables** for CI/CD deployment
- **Log ABDM API errors separately** (don't log secrets)
- **Audit ABDM operations** for compliance
### Credentials Storage (Current)
```
File: .env (local development)
Status: ❌ NOT for production
Next: Move to secure vault/environment variables
```
### Provider Contacts
- **Middleware Support:** https://csnotk.e-atria.in
- **ABDM Sandbox:** https://sandbox.abdm.gov.in
- **NHA Support:** https://nha.gov.in/contact
---
## Testing Quick Start
### 1. Verify Middleware Connectivity
```php
// In controller:
$response = $this->callAbdmGateway('test_connection');
if($response['status'] === 'ok') {
echo "Middleware reachable ✓";
}
```
### 2. Test ABHA Validation
- Go to: http://localhost/Opd_prescription/Prescription/1
- In ABHA section: Enter test ABHA `14-0061-0000-0001`
- Click "Validate ABHA"
- Expected: ✓ ABHA linked
### 3. Test SNOMED Search
- In Diagnosis field: Type "fever"
- Expected: Dropdown shows SNOMED terms (via csnotk)
- Select one → SNOMED ID auto-fills
### 4. Test OPD Save
- Fill OPD consult with all fields
- Click "Save & Submit"
- Check logs for FHIR bundle generation
- Verify: `opd_prescription.fhir_bundle_id` populated
### 5. Test Consent Flow
- Open saved OPD
- Click "ABDM Actions" → "Request Consent"
- Verify: Consent request created in `abdm_consent` table
- Manually accept in ABDM sandbox portal
### 6. Test Bundle Push
- After consent granted
- Click "Share Records"
- Verify: Bundle pushed, `abdm_push_status = 1`
- Check ABDM sandbox portal for record appearance
---
## Known Limitations (Sandbox)
1. **Test ABHA Numbers Only** → Use only sandbox test ABHAs
2. **No Real Patient Data** → Sandbox is isolated
3. **Consent Always Pending** → Must manually accept in portal
4. **No PDF Generation** → Bundles are JSON only
5. **Rate Limits Exist** → ~100 calls/day per sandbox
---
## Success Metrics
- [ ] ABHA validation ≤ 2 seconds
- [ ] Consent request created ≤ 5 seconds
- [ ] FHIR bundle generation ≤ 3 seconds
- [ ] Bundle push successful 95% of time
- [ ] No uncaught ABDM API exceptions
- [ ] All SNOMED codes resolve within 2 attempts
- [ ] Zero compromise of credentials in logs
---
**Last Updated:** May 12, 2026
**Next Review:** After Phase 1 testing completion

View File

@ -1,424 +0,0 @@
# ABDM Sandbox Integration - HMS Setup Guide
**Date:** May 12, 2026
**Status:** Sandbox Approved
**Client ID:** `SBXID_033661`
**Integration Mode:** DreamSoft Middleware Gateway
---
## 1. Overview
This HMS application integrates with **ABDM (Ayushman Bharat Digital Mission)** sandbox environment to support:
- **ABHA (Ayushman Bharat Health Account)** linking and validation
- **Health Information** exchange and consent management
- **FHIR R4** bundle creation for OPD, Lab, and Discharge records
- **Direct prescription/report sharing** with ABDM ecosystem
The integration supports two modes:
- **DreamSoft (Current)**: Routes through middleware gateway (csnotk.e-atria.in)
- **Direct ABDM**: Direct API calls to NHA ABDM M3 (future/testing)
---
## 2. Sandbox Credentials
```
Client ID: SBXID_033661
Client Secret: 656f79f1-ef99-495f-9f37-713219ecbbcf
Mode: DreamSoft Middleware Gateway
Middleware URL: https://csnotk.e-atria.in
```
### Credential Storage
- **Production**: Store in secure vault/secrets manager
- **Sandbox**: Currently in `.env` (do NOT commit to source control)
- **CI/CD**: Use environment variables or secret management system
---
## 3. Configuration Details
### 3.1 .env File Setup
```env
# ABDM Connector Mode
abdm.connector = dreamsoft
# Direct ABDM M3 API (for future direct mode)
abdm.directClientId = SBXID_033661
abdm.directClientSecret = 656f79f1-ef99-495f-9f37-713219ecbbcf
abdm.directBaseUrl = https://dev.abdm.gov.in/api/v3
abdm.directTimeoutSec = 30
# DreamSoft Middleware Gateway
BRIDGE_SYNC_URL = https://csnotk.e-atria.in/api/bridge
BRIDGE_SYNC_TOKEN = <your-bearer-token-here>
BRIDGE_SOURCE_CODE = SBXID_033661
BRIDGE_SYNC_TIMEOUT = 20
BRIDGE_SYNC_PROVIDER = bridge
# SNOMED CT Terminology Service
snomed.csnotk.baseUrl = https://csnotk.e-atria.in/csnoserv
snomed.csnotk.enabled = true
snomed.csnotk.timeoutSec = 10
# ABDM Sandbox Test Users
ABDM_SANDBOX_USERNAME = <your-sandbox-username>
ABDM_SANDBOX_PASSWORD = <your-sandbox-password>
ABDM_HFR_ID = <health-facility-registry-id>
ABDM_NPI_ID = <national-practitioner-identifier>
```
### 3.2 Config File: `app/Config/AbdmConnector.php`
Located at: `app/Config/AbdmConnector.php`
```php
class AbdmConnector extends BaseConfig
{
public string $connector = 'dreamsoft'; // or 'direct_abdm'
public string $dreamsoftBridgeUrl = ''; // Loaded from .env
public string $dreamsoftBridgeToken = '';
public string $dreamsoftSourceCode = '';
public int $dreamsoftTimeoutSec = 20;
// Direct ABDM settings
public string $directAbdmBaseUrl = 'https://dev.abdm.gov.in/api/v3';
public string $directAbdmClientId = '';
public string $directAbdmClientSecret = '';
}
```
---
## 4. Available ABDM API Endpoints
All ABDM endpoints require permission: `abdm.access`, `abdm.taskboard.access`, or `abdm.gateway.use`
### 4.1 ABHA Validation
```
POST /AbdmGateway/abha_validate
```
**Purpose:** Validate and link an ABHA number/address to a patient record.
**Request:**
```json
{
"patient_id": 12345,
"abha_number": "14-0061-0000-0001",
"abha_address": "patient123@abdm"
}
```
**Response:**
```json
{
"update": 1,
"message": "ABHA linked successfully",
"patient_abha_id": "14-0061-0000-0001"
}
```
### 4.2 Consent Request
```
POST /AbdmGateway/consent_request
```
**Purpose:** Initiate consent request with a patient to share their health records.
**Request:**
```json
{
"patient_id": 12345,
"consent_purpose": "treatment",
"hi_types": ["OPConsultRecord", "PrescriptionRecord"],
"date_range_from": "2024-01-01",
"date_range_to": "2026-05-12"
}
```
**Response:**
```json
{
"update": 1,
"consent_request_id": "REQ-2026-001",
"consent_url": "https://sandbox.abdm.gov.in/consent/REQ-2026-001"
}
```
### 4.3 Share Prescription Bundle (OPD Consult)
```
POST /AbdmGateway/share_prescription_bundle
```
**Purpose:** Push OPD prescription/consult record to ABDM in FHIR format.
**Request:**
```json
{
"opd_id": 5678,
"patient_id": 12345,
"consent_id": "CST-2026-001"
}
```
**Response:**
```json
{
"update": 1,
"bundle_id": "2c49bc31-b79f-43c7-838f-e5c8c61f50df",
"status": "pushed",
"timestamp": "2026-05-12T10:30:00Z"
}
```
### 4.4 Share Lab Report Bundle (Diagnostic)
```
POST /AbdmGateway/share_diagnosis_report_bundle
```
**Purpose:** Push lab/diagnostic reports to ABDM.
**Request:**
```json
{
"lab_report_id": 9012,
"patient_id": 12345,
"consent_id": "CST-2026-001"
}
```
### 4.5 Share Discharge Summary (IPD)
```
POST /AbdmGateway/share_ipd_discharge_bundle
```
**Purpose:** Push IPD discharge summary to ABDM.
---
## 5. Sandbox Testing Workflow
### Step 1: Register Patient with ABHA
1. Go to **OPD → Consult Form**
2. Enter patient details
3. In "ABHA Link" section, enter test ABHA number (e.g., `14-0061-0000-0001`)
4. Click "Validate ABHA"
5. System connects to ABDM sandbox via middleware to link ABHA
### Step 2: Create OPD Consult
1. Fill in OPD consult form with:
- Complaints
- Diagnosis (with SNOMED CT codes)
- Vital signs (BP, pulse, temp, SpO2)
- Prescriptions
- Investigations
2. Click "Save & Submit"
3. System auto-generates FHIR bundle locally
### Step 3: Initiate Consent Request
1. Patient record loaded → "ABDM Actions" panel
2. Click "Request Consent"
3. Select HI types (OPConsultRecord, PrescriptionRecord)
4. Choose date range
5. System sends consent request to ABDM sandbox
6. Patient receives consent link (sandbox email/SMS)
### Step 4: Patient Grants Consent (Sandbox Only)
1. Patient logs into ABDM sandbox (https://sandbox.abdm.gov.in)
2. Accepts the consent request from your HMS
3. Consent status changes to "GRANTED" in system
### Step 5: Push Records to ABDM
1. After consent granted, click "Share Records"
2. Select records to push (OPD, Lab, Discharge)
3. System creates FHIR bundle and pushes via middleware
4. Receive bundle ID and push timestamp confirmation
---
## 6. Database Schema Requirements for ABDM
The following fields must exist in respective tables:
### opd_prescription table
```sql
ALTER TABLE opd_prescription ADD COLUMN (
abha_id VARCHAR(50),
abha_address VARCHAR(100),
encounter_id VARCHAR(100),
care_provider_npi VARCHAR(50),
hfr_id VARCHAR(50),
fhir_bundle_id VARCHAR(100),
abdm_push_status INT DEFAULT 0, -- 0=pending, 1=pushed, 2=failed
abdm_push_timestamp DATETIME,
diagnosis_snomed_id VARCHAR(50),
diagnosis_snomed_term VARCHAR(255),
complaint_onset VARCHAR(100),
complaint_duration_days INT,
complaint_severity VARCHAR(50)
);
```
### patient_master table
```sql
ALTER TABLE patient_master ADD COLUMN (
abha_number VARCHAR(50) UNIQUE,
abha_address VARCHAR(100) UNIQUE,
abha_linked_at DATETIME,
abha_link_status VARCHAR(20) -- pending, confirmed, failed
);
```
### New: abdm_consent table
```sql
CREATE TABLE abdm_consent (
id INT PRIMARY KEY AUTO_INCREMENT,
patient_id INT,
consent_request_id VARCHAR(100) UNIQUE,
consent_id VARCHAR(100),
purpose VARCHAR(100),
hi_types JSON,
date_from DATE,
date_to DATE,
status VARCHAR(20), -- pending, granted, denied, expired
requested_at DATETIME,
granted_at DATETIME,
expires_at DATETIME,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (patient_id) REFERENCES patient_master(id)
);
```
---
## 7. FHIR Bundle Structure
The system generates FHIR R4 bundles for:
### OPConsultRecord Bundle
- **Composition**: Document wrapper
- **Bundle**: Contains multiple resources
- **Encounter**: OPD visit details
- **Patient**: Demographics
- **Practitioner**: Doctor info
- **Observation**: Vitals, physical exam
- **Condition**: Complaints, diagnosis
- **AllergyIntolerance**: Drug allergies
- **ServiceRequest**: Investigations
- **MedicationRequest**: Prescriptions
### PrescriptionRecord Bundle
- **Composition**: Prescription document
- **MedicationRequest**: Each medicine prescribed
- **Dosage**: Strength, frequency, route
- **Performer**: Dispensing info (if available)
---
## 8. Middleware Gateway Integration
### CSNOtk.e-atria.in Gateway
**Purpose:** Acts as bridge between HMS and ABDM sandbox.
**Key Features:**
- ABHA validation proxy
- Consent request relay
- FHIR bundle routing
- SNOMED CT terminology service
**Authentication:**
- Bearer token required in `BRIDGE_SYNC_TOKEN`
- Source code (HFR/Client ID) in headers
- TLS 1.2+ required
**Endpoints Exposed:**
```
POST /api/bridge/abha/validate
POST /api/bridge/consent/request
POST /api/bridge/consent/status
POST /api/bridge/bundle/push
GET /api/bridge/bundle/{bundleId}/status
GET /csnoserv/search/suggest?term=<query>
```
---
## 9. Testing Credentials (Sandbox)
Contact ABDM Sandbox Support:
- **Website:** https://sandbox.abdm.gov.in
- **Portal:** Login with your organization credentials
- **Test Patients:** Available in sandbox portal
- **Test ABHA Numbers:** Examples provided in portal
### Sample Test ABHA Numbers
```
14-0061-0000-0001 (Patient A)
14-0061-0000-0002 (Patient B)
14-0061-0000-0003 (Patient C)
```
---
## 10. Permissions & Access Control
User roles required for ABDM operations:
```php
'abdm.access' => 'Can view ABDM module',
'abdm.taskboard.access' => 'Can access ABDM task board',
'abdm.gateway.use' => 'Can run ABDM gateway actions',
```
**Recommended Role:** Admin, Doctor, ABDM Coordinator
---
## 11. Troubleshooting
### Issue: ABHA Validation Fails
**Cause:** Middleware unreachable or credentials invalid
**Fix:**
1. Check `BRIDGE_SYNC_URL` is correct
2. Verify `BRIDGE_SYNC_TOKEN` with middleware provider
3. Check firewall/proxy allows outbound HTTPS
### Issue: Consent Request Stuck in "Pending"
**Cause:** Patient hasn't accepted in sandbox portal
**Fix:**
1. Log into ABDM sandbox portal
2. Navigate to "Consent Requests"
3. Manually accept request for testing
4. System polls for status updates
### Issue: FHIR Bundle Rejected
**Cause:** Missing required SNOMED codes or invalid structure
**Fix:**
1. Ensure diagnosis has SNOMED ID (not just text)
2. Ensure vitals in proper FHIR units (mmHg, BPM, etc.)
3. Check bundle in `/logs` for validation errors
---
## 12. Next Steps
1. **Set Bearer Token:** Contact ABDM/middleware provider to get `BRIDGE_SYNC_TOKEN`
2. **Configure HFR/NPI IDs:** Update `.env` with your facility identifiers
3. **Create Test User:** Register test user in ABDM sandbox portal
4. **Test ABHA Linking:** Use test ABHA from sandbox portal
5. **Run Consent Flow:** Test full consent → push workflow
6. **Verify FHIR Bundles:** Check generated bundles in database logs
---
## 13. Reference Documentation
- **ABDM Official Docs:** https://sandbox.abdm.gov.in/sandbox/v3/new-documentation
- **FHIR R4 Spec:** http://hl7.org/fhir/R4
- **NHA Integration Guide:** https://nha.gov.in/abdm/guidelines
- **Local Implementation:** [app/Controllers/AbdmGateway.php](../../app/Controllers/AbdmGateway.php)
---
**Last Updated:** May 12, 2026
**Maintained By:** HMS Development Team

View File

@ -1,534 +0,0 @@
# ABDM Bridge Gateway - PHP/CI4 Edition
**Architecture:** Native PHP (CodeIgniter 4)
**Requirements:** Apache 2.4+, PHP 8.3+, MySQL 8.0+
**Ram Usage:** ~50MB (vs 512MB+ for Docker)
**Disk Usage:** ~20MB (vs 500MB+ for Docker)
**Database:** Native MySQL (no containers)
---
## 📋 Project Structure
```
abdm-bridge-gateway/
├── app/
│ ├── Controllers/
│ │ ├── AbdmGateway.php # Main ABDM endpoints
│ │ ├── HealthCheck.php # Health monitoring
│ │ └── DependencyCheck.php # Dependency health
│ ├── Models/
│ │ ├── AbdmRequestLog.php # Request logging
│ │ ├── AbdmAuditTrail.php # Audit trail
│ │ └── AbdmBundle.php # Bundle tracking
│ ├── Config/
│ │ ├── Routes.php # Gateway routes
│ │ ├── AbdmGateway.php # ABDM config
│ │ └── Database.php # Database config
│ ├── Database/
│ │ └── Migrations/
│ │ ├── 2026-05-12-000001_create_abdm_request_logs.php
│ │ ├── 2026-05-12-000002_create_abdm_audit_trail.php
│ │ └── 2026-05-12-000003_create_abdm_bundles.php
│ └── Views/
│ ├── dashboard.php # Admin dashboard
│ └── health_check.php # Health status page
├── public/
│ └── index.php # Entry point (CI4 standard)
├── writable/
│ ├── cache/
│ ├── logs/
│ └── uploads/
├── .env # Configuration
├── .env.example # Configuration template
├── .gitignore # Git ignore
├── spark # CI4 CLI
├── composer.json # Dependencies
├── README.md # Documentation
└── docs/
├── SETUP_GUIDE.md # Installation guide
├── API_REFERENCE.md # Endpoint documentation
└── DATABASE_SCHEMA.md # Schema details
```
---
## 🚀 Quick Setup (5 minutes)
### Step 1: Create CI4 Project
```bash
# On your server
cd /var/www
composer create-project codeigniter4/appstarter abdm-bridge-gateway
# Navigate
cd abdm-bridge-gateway
```
### Step 2: Copy Gateway Files
Copy all files from this package into the project directory.
### Step 3: Configure Database
```bash
# Edit .env
APP_NAME = "ABDM Bridge Gateway"
APP_DEBUG = false
CI_ENVIRONMENT = production
# Database
database.default.hostname = localhost
database.default.username = root
database.default.password = your-password
database.default.database = abdm_gateway
database.default.DBDriver = MySQLi
```
### Step 4: Run Migrations
```bash
php spark migrate
```
### Step 5: Set Permissions
```bash
sudo chown -R www-data:www-data /var/www/abdm-bridge-gateway
sudo chmod -R 755 /var/www/abdm-bridge-gateway
sudo chmod -R 775 /var/www/abdm-bridge-gateway/writable
```
### Step 6: Configure Apache VirtualHost
Create `/etc/apache2/sites-available/abdm-bridge.conf`:
```apache
<VirtualHost *:80>
ServerName abdm-bridge.e-atria.in
DocumentRoot /var/www/abdm-bridge-gateway/public
<Directory /var/www/abdm-bridge-gateway/public>
AllowOverride All
Allow from all
Require all granted
</Directory>
# Redirect HTTP to HTTPS
Redirect permanent / https://abdm-bridge.e-atria.in/
</VirtualHost>
<VirtualHost *:443>
ServerName abdm-bridge.e-atria.in
DocumentRoot /var/www/abdm-bridge-gateway/public
SSLEngine On
SSLCertificateFile /etc/letsencrypt/live/abdm-bridge.e-atria.in/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/abdm-bridge.e-atria.in/privkey.pem
<Directory /var/www/abdm-bridge-gateway/public>
AllowOverride All
Allow from all
Require all granted
</Directory>
# Security headers
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header set X-Content-Type-Options "nosniff"
Header set X-Frame-Options "DENY"
Header set X-XSS-Protection "1; mode=block"
# Error logs
ErrorLog ${APACHE_LOG_DIR}/abdm-bridge-error.log
CustomLog ${APACHE_LOG_DIR}/abdm-bridge-access.log combined
</VirtualHost>
```
### Step 7: Enable VirtualHost & SSL
```bash
# Enable vhost
sudo a2ensite abdm-bridge
# Enable required Apache modules
sudo a2enmod rewrite
sudo a2enmod ssl
sudo a2enmod headers
# Get SSL certificate
sudo certbot certonly --apache -d abdm-bridge.e-atria.in
# Restart Apache
sudo systemctl restart apache2
```
### Step 8: Test
```bash
curl https://abdm-bridge.e-atria.in/api/v3/health
# Should return: {"status":"ok","service":"abdm-bridge-gateway"...}
```
---
## 🔗 API Endpoints
All endpoints require `Authorization: Bearer TOKEN` header (except health).
### 1. Health Check (Public)
```
GET /api/v3/health
Response: {"status":"ok","service":"abdm-bridge-gateway"}
```
### 2. ABHA Validation
```
POST /api/v3/abha/validate
Body: {"abha_id":"14-0061-0000-0001"}
Response: Proxied to ABDM M3 API
Logs: All requests to abdm_request_logs table
```
### 3. Consent Request
```
POST /api/v3/consent/request
Body: {"patient_abha":"14-0061-0000-0001","purpose":"treatment","hi_types":[...]}
Logs: Audit trail in abdm_audit_trail table
```
### 4. Bundle Push
```
POST /api/v3/bundle/push
Body: {"fhir_bundle":{...},"consent_id":"...","hi_type":"OPConsultRecord"}
Logs: Bundle tracking in abdm_bundles table
```
### 5. SNOMED Search
```
GET /api/v3/snomed/search?term=fever&return_limit=10
Response: Proxied from CSNOtk terminology service
```
### 6. Gateway Status
```
GET /api/v3/gateway/status
Response: {"gateway":"ok","abdm_m3":"ok","snomed_service":"ok"}
```
---
## 📊 Database Schema
### `abdm_request_logs` Table
```sql
CREATE TABLE abdm_request_logs (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
request_id VARCHAR(100) UNIQUE,
method VARCHAR(10),
endpoint VARCHAR(255),
status_code INT,
response_time_ms INT,
user_agent VARCHAR(255),
ip_address VARCHAR(50),
authorization_status VARCHAR(20),
error_message TEXT,
request_body JSON,
response_body JSON,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX (endpoint),
INDEX (status_code),
INDEX (created_at)
);
```
### `abdm_audit_trail` Table
```sql
CREATE TABLE abdm_audit_trail (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
request_id VARCHAR(100),
action VARCHAR(100),
patient_abha VARCHAR(50),
consent_id VARCHAR(100),
hi_types JSON,
action_status VARCHAR(20),
details JSON,
performed_by VARCHAR(100),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX (patient_abha),
INDEX (consent_id),
INDEX (created_at)
);
```
### `abdm_bundles` Table
```sql
CREATE TABLE abdm_bundles (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
bundle_id VARCHAR(100) UNIQUE,
consent_id VARCHAR(100),
hi_type VARCHAR(100),
bundle_hash VARCHAR(255),
push_status VARCHAR(20),
push_timestamp DATETIME,
response_status INT,
response_body JSON,
retry_count INT DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME ON UPDATE CURRENT_TIMESTAMP,
INDEX (bundle_id),
INDEX (consent_id),
INDEX (push_status),
INDEX (created_at)
);
```
---
## 🔧 Configuration (.env)
```env
# App
APP_NAME = "ABDM Bridge Gateway"
APP_DEBUG = false
CI_ENVIRONMENT = production
# Database
database.default.hostname = localhost
database.default.username = root
database.default.password =
database.default.database = abdm_gateway
database.default.DBDriver = MySQLi
# ABDM Gateway
gateway.source_code = SBXID_033661
gateway.bearer_token = your-bearer-token
# ABDM M3 API
abdm.m3.url = https://dev.abdm.gov.in/api/v3
abdm.m3.token = your-abdm-m3-token
abdm.m3.timeout = 30
# SNOMED Service
snomed.service.url = https://csnotk.e-atria.in/csnoserv
snomed.service.timeout = 10
# Rate Limiting
rate_limit.requests = 100
rate_limit.window_minutes = 15
# Logging
log.database = true
log.level = info
log.request_body = true
log.response_body = false
```
---
## 💾 Database Size Estimation
| Table | Est. Rows/Year | Size |
|-------|----------------|------|
| abdm_request_logs | 500K | 50MB |
| abdm_audit_trail | 100K | 10MB |
| abdm_bundles | 10K | 2MB |
**Total Annual:** ~62MB (very small)
---
## 🔐 Security Features
✅ Bearer token authentication
✅ Rate limiting per IP
✅ HTTPS/SSL required
✅ Request logging (audit trail)
✅ CORS protection
✅ SQL injection prevention (CI4 ORM)
✅ XSS protection (CI4 security)
---
## 📈 Performance
| Metric | Value |
|--------|-------|
| Response Time | 100-300ms |
| Memory Usage | 20-50MB |
| Database Queries | 2-3 per request |
| Concurrent Users | 100+ |
---
## 🛠️ Maintenance
### View Logs
```bash
tail -f /var/www/abdm-bridge-gateway/writable/logs/log-*.log
```
### Check Database
```bash
# SSH to server
mysql -u root -p
# Select database
USE abdm_gateway;
# Check request logs
SELECT * FROM abdm_request_logs ORDER BY created_at DESC LIMIT 10;
# Check audit trail
SELECT * FROM abdm_audit_trail ORDER BY created_at DESC LIMIT 10;
# Check bundle status
SELECT * FROM abdm_bundles WHERE push_status = 'pending';
```
### Run Migrations
```bash
# Run all pending migrations
php spark migrate
# Check migration status
php spark migrate:status
# Rollback
php spark migrate:rollback --batch=1
```
---
## 🔄 CI4 CLI Commands
```bash
# Serve locally (for development)
php spark serve
# Create new controller
php spark make:controller AbdmGateway
# Create new model
php spark make:model AbdmRequestLog
# Create migration
php spark make:migration CreateAbdmRequestLogs
# Show routes
php spark routes
```
---
## 📦 Dependencies (composer.json)
```json
{
"require": {
"php": "^8.3",
"codeigniter4/framework": "^4.4",
"curl": "*"
}
}
```
All dependencies are built into PHP/CI4 - no additional packages needed!
---
## 🚀 Deployment to Production
### Step 1: Create Database
```bash
mysql -u root -p -e "CREATE DATABASE abdm_gateway;"
```
### Step 2: Upload Project
```bash
# Using git (recommended)
cd /var/www
git clone https://your-repo.git abdm-bridge-gateway
# Or SFTP/SCP
scp -r abdm-bridge-gateway/ root@server:/var/www/
```
### Step 3: Install & Setup
```bash
cd /opt/abdm-bridge-gateway
composer install
php spark migrate
```
### Step 4: Configure Apache (see above)
### Step 5: Start Service
```bash
sudo systemctl restart apache2
```
### Step 6: Test
```bash
curl https://abdm-bridge.e-atria.in/api/v3/health
```
---
## 🎓 Git Repository
### Initialize Repository
```bash
cd /var/www/abdm-bridge-gateway
git init
git add .
git commit -m "Initial ABDM Bridge Gateway - PHP/CI4"
git remote add origin https://your-git-server.com/abdm-bridge-gateway.git
git push -u origin main
```
### .gitignore
```
/vendor/
/writable/
.env
.env.local
.DS_Store
*.log
.vscode/
```
---
## 📚 Additional Features (Easy to Add)
- ✅ Admin dashboard (CI4 views)
- ✅ Request metrics (CI4 queries)
- ✅ API rate limiting (CI4 middleware)
- ✅ Custom logging (CI4 logging)
- ✅ JWT tokens (libraries)
- ✅ Webhook callbacks (CI4 controllers)
---
## ✅ Advantages Over Docker Version
| Feature | Docker | PHP/CI4 Native |
|---------|--------|----------------|
| RAM Usage | 512MB+ | 50MB |
| Disk Usage | 500MB+ | 20MB |
| Startup Time | 10-30s | <1s |
| Monitoring | Complex | Easy (PHP logs) |
| Database | Container | Native MySQL |
| Code Updates | Rebuild images | Git pull + restart |
| Troubleshooting | docker logs | tail -f logs/ |
| Learning Curve | Docker + Node.js | PHP + CI4 (you know it!) |
---
**Status:** 🟢 READY FOR CI4 IMPLEMENTATION
**Setup Time:** 5 minutes
**Complexity:** Simple (standard CI4 app)
**Maintenance:** Minimal (pure PHP)
Next: I'll create all the actual PHP files for you!

View File

@ -128,7 +128,7 @@ Header: Authorization: Bearer YOUR_TOKEN
| Variable | Value | Notes | | Variable | Value | Notes |
|----------|-------|-------| |----------|-------|-------|
| `BRIDGE_SOURCE_CODE` | `SBXID_033661` | Client ID from ABDM | | `BRIDGE_SOURCE_CODE` | `<your-abdm-client-id>` | Client ID from ABDM |
| `BRIDGE_SYNC_TOKEN` | Bearer token | Get from middleware provider | | `BRIDGE_SYNC_TOKEN` | Bearer token | Get from middleware provider |
| `ABDM_M3_URL` | `https://dev.abdm.gov.in/api/v3` | Sandbox API endpoint | | `ABDM_M3_URL` | `https://dev.abdm.gov.in/api/v3` | Sandbox API endpoint |
| `ABDM_M3_TOKEN` | Bearer token | ABDM M3 authentication | | `ABDM_M3_TOKEN` | Bearer token | ABDM M3 authentication |