# 🧪 Goa-GEL End-to-End Testing Guide

## Overview
This guide provides a complete end-to-end testing workflow for the Goa-GEL blockchain verification platform. Follow these steps to verify all features are working correctly.

---

## 🔧 Prerequisites

### 1. Environment Setup
```bash
# Terminal 1 - Backend
cd backend
npm install
npm run db:migrate
npm run db:seed  # IMPORTANT: Seeds demo accounts with wallets
npm run start:dev

# Terminal 2 - Frontend
cd frontend
npm install
ng serve

# Terminal 3 - Blockchain (Optional for full workflow)
cd blockchain
npm install
# Configure local blockchain or testnet
```

### 2. Access URLs
- **Frontend**: http://localhost:4200
- **Backend API**: http://localhost:3000
- **API Docs**: http://localhost:3000/api

---

## 📋 Test Scenario: Complete License Approval Workflow

### **Step 1: Admin Login & Portal Access**

**Objective**: Verify admin can log in and access the admin portal

1. Navigate to http://localhost:4200/login
2. Use demo credentials:
   - **Email**: `admin@goa.gov.in`
   - **Password**: `Admin@123`
   - Or click the "Admin" demo credential button to auto-fill
3. Click "Sign In"

**Expected Results**:
- ✅ Successful login with no errors
- ✅ Redirected to dashboard
- ✅ User menu shows "Admin" role
- ✅ Admin menu item visible in navigation

---

### **Step 2: Access Admin Portal**

1. Click on user menu (top right)
2. Select "Admin" from dropdown
3. Or navigate directly to http://localhost:4200/admin

**Expected Results**:
- ✅ Admin portal loads with 6 tabs:
  - Dashboard
  - Departments
  - Users
  - Transactions
  - Events
  - Logs
- ✅ Platform statistics cards display:
  - Total Requests
  - Departments
  - Applicants
  - Blockchain Transactions

---

### **Step 3: Verify Pre-Seeded Data**

**Navigate through each tab to verify seed data:**

#### Dashboard Tab
- ✅ Platform stats show non-zero counts
- ✅ Stats cards have gradient backgrounds
- ✅ All numbers are clickable/informative

#### Departments Tab
- ✅ Shows pre-seeded departments:
  - Fire Department (FIRE_DEPT)
  - Tourism Department (TOURISM_DEPT)
  - Municipality (MUNICIPALITY)
- ✅ Each department shows:
  - Code
  - Name
  - Wallet Address (0x...)
  - Status (Active)
  - Action buttons

#### Users Tab
- ✅ Shows all 5 seeded users:
  - Admin
  - Fire Department Officer
  - Tourism Department Officer
  - Municipality Officer
  - Test Citizen
- ✅ Each user shows:
  - Email
  - Name
  - Role badge
  - Wallet Address

#### Transactions Tab (May be empty initially)
- ✅ Table structure loads correctly
- ✅ Filters available (Status dropdown)
- ✅ Statistics cards present
- ✅ Empty state shows: "No transactions found"

#### Events Tab (May be empty initially)
- ✅ Table structure loads correctly
- ✅ Filters available (Event Type, Contract Address)
- ✅ Empty state shows: "No events found"

#### Logs Tab
- ✅ Application logs displayed
- ✅ Filters work: Level, Module, Search
- ✅ Color-coded log levels (INFO=blue, WARN=orange, ERROR=red)
- ✅ Export button available

---

### **Step 4: Onboard New Department**

**Objective**: Test department onboarding with auto-wallet creation

1. In Admin Portal, go to **Departments** tab
2. Click **"Onboard New Department"** button
3. Fill in the form:
   ```
   Department Code: POLICE_DEPT
   Department Name: Police Department
   Description: Law enforcement and security clearances
   Contact Email: police@goa.gov.in
   Contact Phone: +91-832-2222222
   ```
4. Click **"Onboard Department"**

**Expected Results**:
- ✅ Success notification appears
- ✅ Alert/dialog shows:
  - ✅ **Wallet Address** (0x...)
  - ✅ **API Key** (starts with "pd_")
  - ✅ **API Secret** (long alphanumeric)
  - ✅ Warning: "Save these credentials - shown only once"
- ✅ **SAVE THESE CREDENTIALS** for later use
- ✅ Department appears in departments list
- ✅ Status shows "Active"

**Verification**:
1. Go to **Users** tab
2. Verify no new user was created (department accounts are separate from users)
3. Go back to **Departments** tab
4. Find "Police Department" in the list
5. Verify wallet address matches the one shown in alert

---

### **Step 5: Regenerate Department API Key**

**Objective**: Test API key regeneration functionality

1. In Departments tab, find "Police Department"
2. Click **"Regenerate Key"** button
3. Confirm the action

**Expected Results**:
- ✅ Success notification
- ✅ Alert shows new API credentials
- ✅ New API Key and Secret are different from original
- ✅ Wallet address remains the same

---

### **Step 6: Deactivate & Reactivate Department**

**Objective**: Test department lifecycle management

1. Find "Police Department"
2. Click **"Deactivate"** button
3. Confirm the action

**Expected Results**:
- ✅ Status changes to "Inactive"
- ✅ Status chip turns red/gray

4. Click **"Activate"** button
5. Confirm the action

**Expected Results**:
- ✅ Status changes to "Active"
- ✅ Status chip turns green

---

### **Step 7: Citizen Registration (Simulated)**

**Objective**: Test citizen account creation and license request

**Note**: This step requires the citizen registration endpoints to be accessible. If not yet fully implemented, document the expected behavior.

1. Log out from admin account
2. Navigate to citizen registration page (if available)
3. Or use API directly:

```bash
POST http://localhost:3000/auth/register
Content-Type: application/json

{
  "email": "john.doe@example.com",
  "password": "Citizen@123",
  "name": "John Doe",
  "role": "APPLICANT",
  "phone": "+91-9876543210"
}
```

**Expected Results**:
- ✅ Account created successfully
- ✅ Wallet automatically generated
- ✅ Response includes:
  - User ID
  - Email
  - Name
  - Wallet Address
  - Role: APPLICANT

---

### **Step 8: Create License Request**

**Objective**: Test license request creation with document upload

1. Log in as the new citizen: `john.doe@example.com` / `Citizen@123`
2. Navigate to "My Requests" or requests page
3. Click **"New Request"** or **"Create License Request"**
4. Fill in request form:
   ```
   Request Type: RESORT_LICENSE
   Resort Name: Goa Beach Resort
   Location: Calangute, Goa
   Capacity: 100 guests
   ... (other required fields)
   ```
5. Upload required documents:
   - Business Registration Certificate (PDF)
   - Property Ownership Proof (PDF)
   - Floor Plan (Image/PDF)

**Expected Results**:
- ✅ Request created with status "DRAFT"
- ✅ Documents uploaded successfully
- ✅ Each document shows:
  - File name
  - File size
  - Upload timestamp
  - File hash (generated)
  - Version 1

---

### **Step 9: Submit License Request**

**Objective**: Test request submission and NFT minting (blockchain operation)

1. From request detail page, click **"Submit Request"**
2. Confirm submission

**Expected Results**:
- ✅ Request status changes to "SUBMITTED"
- ✅ Blockchain transaction initiated
- ✅ Transaction hash appears in request details
- ✅ NFT Token ID assigned (if blockchain is active)

**Verify in Admin Portal**:
1. Log in as admin
2. Go to **Transactions** tab
3. Find the new transaction:
   - ✅ Transaction hash present
   - ✅ Status: PENDING → CONFIRMED
   - ✅ Gas used displayed
   - ✅ Linked to request ID

4. Go to **Events** tab
5. Find "LicenseRequested" event:
   - ✅ Event type correct
   - ✅ Contract address present
   - ✅ Block number displayed
   - ✅ Event parameters decoded

---

### **Step 10: Fire Department Review & Approval**

**Objective**: Test department approval workflow with document verification

1. Log out and log in as Fire Department:
   - **Email**: `fire@goa.gov.in`
   - **Password**: `Fire@123`
2. Navigate to "Pending Approvals" or assigned requests
3. Open the resort license request
4. Review documents:
   - ✅ All uploaded documents visible
   - ✅ Document viewer shows:
     - Thumbnails
     - File hashes
     - Version history (Version 1)
     - No department reviews yet
5. Click **"Approve"**
6. Enter remarks: "Fire safety requirements met. All documents verified."
7. Submit approval

**Expected Results**:
- ✅ Approval recorded with status "APPROVED"
- ✅ Blockchain transaction created for approval
- ✅ Approval timestamp recorded
- ✅ Remarks saved

**Verify in Admin Portal** (as admin):
1. **Transactions** tab:
   - ✅ New transaction for "ApprovalRecorded"
   - ✅ Transaction linked to approval ID
2. **Events** tab:
   - ✅ "ApprovalRecorded" event present
   - ✅ Department address in event data
3. **Request Documents** (in admin or citizen view):
   - ✅ Fire Department review shows "APPROVED"
   - ✅ Reviewed by and timestamp visible

---

### **Step 11: Tourism Department Requests Changes**

**Objective**: Test change request workflow and document versioning

1. Log in as Tourism Department:
   - **Email**: `tourism@goa.gov.in`
   - **Password**: `Tourism@123`
2. Open the same resort license request
3. Review documents
4. Click **"Request Changes"**
5. Fill in change request:
   ```
   Required Documents: Environmental Clearance Certificate
   Remarks: Additional environmental clearance required for beach resort operations.
   ```
6. Submit change request

**Expected Results**:
- ✅ Request status changes to "PENDING_RESUBMISSION"
- ✅ Change request recorded with timestamp
- ✅ Tourism review shows "CHANGES_REQUESTED"
- ✅ Fire Department approval status remains "APPROVED"

---

### **Step 12: Citizen Uploads New Document Version**

**Objective**: Test document versioning and version history tracking

1. Log in as citizen: `john.doe@example.com` / `Citizen@123`
2. Open the license request (now in "PENDING_RESUBMISSION" status)
3. Click **"Upload Additional Documents"** or **"Update Documents"**
4. Upload new document:
   - Document Type: Environmental Clearance Certificate
   - File: environmental_clearance.pdf
5. Add change description: "Environmental clearance certificate from Goa Pollution Control Board"
6. Submit

**Expected Results**:
- ✅ New document uploaded as Version 1
- ✅ Or existing document updated to Version 2
- ✅ Version history shows:
  - Version 1: Original upload
  - Version 2: Updated after change request (if applicable)
  - Change description visible
- ✅ Document viewer in request details shows new version
- ✅ Version history table accessible via expansion panel

---

### **Step 13: Fire Approval Invalidated**

**Objective**: Verify approval invalidation when documents change

**Check Fire Department Approval Status**:
1. In request details (as admin or fire dept user)
2. Find Fire Department approval

**Expected Results**:
- ✅ Fire approval shows "INVALIDATED" or "PENDING_REVALIDATION"
- ✅ Reason: "Document version changed"
- ✅ Original approval timestamp preserved
- ✅ Invalidation timestamp shown

**Note**: This may require backend logic to auto-invalidate approvals when documents are updated.

---

### **Step 14: Fire Department Re-Approves**

**Objective**: Test re-approval after document changes

1. Log in as Fire Department: `fire@goa.gov.in` / `Fire@123`
2. Open the resort license request (back in pending approvals)
3. Review updated documents:
   - ✅ Document viewer shows Version 2 (or new document)
   - ✅ Version history shows all versions
   - ✅ Change description visible
4. Click **"Approve"**
5. Enter remarks: "Reviewed updated documents. Fire safety still compliant."
6. Submit approval

**Expected Results**:
- ✅ New approval recorded
- ✅ Status changes to "APPROVED" (again)
- ✅ New blockchain transaction created
- ✅ Approval timestamp updated
- ✅ Previous invalidated approval still in history

---

### **Step 15: Tourism Department Final Approval**

**Objective**: Test final approval and license finalization

1. Log in as Tourism Department: `tourism@goa.gov.in` / `Tourism@123`
2. Open the resort license request
3. Review all documents including new environmental clearance
4. Verify Fire Department approval is "APPROVED"
5. Click **"Approve"**
6. Enter remarks: "All tourism requirements met. Environmental clearance verified."
7. Submit approval

**Expected Results**:
- ✅ Approval recorded successfully
- ✅ Request status changes to "APPROVED"
- ✅ All required department approvals complete
- ✅ NFT updated on blockchain (if applicable)
- ✅ Final approval timestamp recorded

---

### **Step 16: Verify Complete Approval Chain**

**Objective**: Verify all approvals are visible in request details

1. As citizen, open the approved license request
2. Navigate to **"Approvals"** tab

**Expected Results**:
- ✅ Shows 2 approvals:
  1. Fire Department (Re-approved after invalidation)
     - Status: APPROVED
     - Remarks visible
     - Timestamp present
  2. Tourism Department
     - Status: APPROVED
     - Remarks visible
     - Timestamp present
- ✅ Each approval shows department name, not just ID
- ✅ Approval timeline visible

---

### **Step 17: Verify Document History**

**Objective**: Test complete document version tracking

1. In the approved request, go to **"Documents"** tab
2. Find each document
3. Click to expand **"Version History"**

**Expected Results**:
- ✅ Environmental Clearance:
  - Version 1: Initial upload after change request
  - Uploaded by: John Doe
  - Upload date visible
  - File hash unique
- ✅ Other Documents:
  - Version 1 only (if not changed)
  - OR Version 1 & 2 if updated
- ✅ Each version has:
  - Version number
  - Upload timestamp
  - Uploaded by (user name)
  - File hash (first 8 chars)
  - Download button

---

### **Step 18: Verify Department Reviews on Documents**

**Objective**: Check department reviews are tracked per document

1. In document viewer, check **"Department Reviews"** section

**Expected Results**:
- ✅ Each document shows reviews from:
  - Fire Department: APPROVED (green chip)
  - Tourism Department: APPROVED (green chip)
- ✅ Review includes:
  - Department name
  - Status (APPROVED/REJECTED/PENDING)
  - Reviewed at timestamp
  - Reviewed by (officer name)
  - Comments (if any)

---

### **Step 19: Admin Dashboard Verification**

**Objective**: Verify all data is visible in admin monitoring dashboards

**As admin (`admin@goa.gov.in`), verify each dashboard:**

#### Transactions Dashboard
- ✅ Shows all transactions:
  1. Initial request submission (LicenseRequested)
  2. Fire approval #1
  3. Tourism change request
  4. Fire approval #2 (after invalidation)
  5. Tourism final approval
- ✅ Each transaction shows:
  - Transaction hash
  - From/To addresses
  - Status (CONFIRMED)
  - Block number
  - Gas used
  - Linked to correct request/approval
- ✅ Statistics cards updated:
  - Confirmed count increased
  - Total transactions increased

#### Events Dashboard
- ✅ Shows all blockchain events:
  - LicenseRequested
  - ApprovalRecorded (x3: Fire, Tourism change, Fire re-approval, Tourism final)
  - LicenseMinted (if applicable)
  - LicenseUpdated (if NFT updated)
- ✅ Each event shows:
  - Event type
  - Contract address
  - Block number
  - Transaction hash
  - Decoded parameters
  - Timestamp
- ✅ Filters work correctly
- ✅ Event type chips color-coded

#### Logs Dashboard
- ✅ Shows application logs for all operations:
  - User login events
  - Request creation
  - Document uploads
  - Approval submissions
  - Blockchain operations
  - Errors (if any)
- ✅ Filters work:
  - Level filter (INFO, WARN, ERROR)
  - Module filter (AuthService, RequestService, etc.)
  - Search functionality
- ✅ Error logs highlighted in red background
- ✅ Export to JSON works

#### Platform Stats
- ✅ Updated statistics:
  - Total Requests: +1
  - Request by Status: APPROVED: +1
  - Total Documents: +5 (or however many uploaded)
  - Total Blockchain Transactions: +5
  - Applicants: +1 (new citizen)
  - Departments: +1 (Police Department added)

---

### **Step 20: Document Download & Preview**

**Objective**: Test document download and preview functionality

1. As citizen, open approved license request
2. Go to Documents tab
3. For each document:

**Test Download**:
- Click **"Download"** button
- ✅ File downloads with correct filename
- ✅ File is intact and openable

**Test Preview**:
- Click **"Preview"** button or thumbnail
- ✅ Document opens in new tab/modal
- ✅ Content displays correctly

**Test Hash Copy**:
- Click copy icon next to file hash
- ✅ Hash copied to clipboard
- ✅ Confirmation message appears

---

## 🔍 Additional Verification Tests

### Test User Management
1. **Admin Portal → Users Tab**
2. Verify new citizen appears:
   - ✅ Email: john.doe@example.com
   - ✅ Name: John Doe
   - ✅ Role: APPLICANT
   - ✅ Wallet Address: 0x...
   - ✅ Last Login timestamp

### Test Department Management
1. **Admin Portal → Departments Tab**
2. Click on "Police Department"
3. Verify details:
   - ✅ Code: POLICE_DEPT
   - ✅ Name, Description, Contact info
   - ✅ Wallet Address
   - ✅ API Key (masked)
   - ✅ Status: Active
   - ✅ Created At timestamp

### Test Request Filtering (if applicable)
1. Create multiple requests with different statuses
2. Test filtering by:
   - Status (DRAFT, SUBMITTED, APPROVED, REJECTED)
   - Date range
   - Request type

### Test Blockchain Explorer Links (if implemented)
1. In request details with blockchain data
2. Click "View on Explorer" links
3. ✅ Opens blockchain explorer (Etherscan, etc.)
4. ✅ Shows transaction details
5. ✅ Shows NFT details

---

## ❌ Error Scenario Testing

### Test Invalid Credentials
1. Try logging in with wrong password
- ✅ Error message: "Invalid email or password"
- ✅ User stays on login page

### Test Unauthorized Access
1. Log in as citizen
2. Try accessing `/admin`
- ✅ Redirected to dashboard or shows "Unauthorized"

### Test Duplicate Department Code
1. As admin, try onboarding department with existing code
- ✅ Error message: "Department code already exists"
- ✅ Form not submitted

### Test Missing Required Documents
1. As citizen, try submitting request without required documents
- ✅ Error message: "Please upload all required documents"
- ✅ Submit button disabled

### Test Approval by Unauthorized Department
1. As Fire Department, try approving request not assigned to Fire
- ✅ Error or approval not allowed

---

## 📊 Performance Testing (Optional)

### Load Testing
1. Create 100+ license requests
2. Verify:
   - ✅ Pagination works smoothly
   - ✅ Filters respond quickly
   - ✅ No UI lag or freezing

### Large Document Upload
1. Upload document > 10MB
2. Verify:
   - ✅ Upload progress indicator
   - ✅ Successful upload
   - ✅ Hash generation works

---

## ✅ Test Completion Checklist

### Core Functionality
- [ ] Admin login and portal access
- [ ] Department onboarding with wallet creation
- [ ] Citizen registration with wallet creation
- [ ] License request creation
- [ ] Document upload with hash generation
- [ ] Request submission with blockchain transaction
- [ ] Department approval workflow
- [ ] Change request submission
- [ ] Document versioning
- [ ] Approval invalidation on document change
- [ ] Re-approval after changes
- [ ] Final approval and license finalization

### Admin Monitoring
- [ ] Platform statistics accurate
- [ ] Transaction tracking complete
- [ ] Event tracking functional
- [ ] Application logs viewer working
- [ ] User management displays all users
- [ ] Department management functional

### Document Management
- [ ] Document viewer displays correctly
- [ ] Version history accessible
- [ ] Department reviews visible
- [ ] File hash displayed and copyable
- [ ] IPFS hash shown (if applicable)
- [ ] Download functionality works
- [ ] Preview functionality works

### UI/UX
- [ ] Responsive design on mobile
- [ ] Loading spinners show during operations
- [ ] Error messages clear and helpful
- [ ] Success notifications appear
- [ ] Material Design consistent
- [ ] Color-coded status chips
- [ ] Pagination works on all lists

### Security
- [ ] Passwords are hashed (bcrypt)
- [ ] Private keys encrypted (AES-256-CBC)
- [ ] JWT tokens expire correctly
- [ ] Unauthorized access blocked
- [ ] API endpoints protected

---

## 🐛 Known Issues & Limitations

### Document any discovered issues here:

1. **Issue**: [Description]
   - **Severity**: High/Medium/Low
   - **Steps to Reproduce**: [Steps]
   - **Expected**: [Expected behavior]
   - **Actual**: [Actual behavior]
   - **Fix Required**: [Yes/No]

---

## 📝 Test Results Summary

**Test Date**: _____________

**Tested By**: _____________

**Total Tests**: 20 scenarios

**Passed**: ___ / 20

**Failed**: ___ / 20

**Blocked**: ___ / 20

**Notes**:
```
[Add any additional notes, observations, or recommendations here]
```

---

## 🚀 Next Steps After Testing

1. **If All Tests Pass**:
   - Mark project as production-ready
   - Deploy to staging environment
   - Conduct UAT with actual users

2. **If Tests Fail**:
   - Document failing tests
   - Create bug tickets
   - Prioritize fixes
   - Retest after fixes

3. **Performance Optimization**:
   - Profile slow API endpoints
   - Optimize database queries
   - Add caching where appropriate
   - Consider pagination limits

4. **Security Audit**:
   - Review all authentication flows
   - Verify encryption implementation
   - Check for SQL injection vulnerabilities
   - Test CORS policies

---

## 📞 Support

For issues or questions during testing:
- Check backend logs: `backend/logs/`
- Check browser console for frontend errors
- Review API documentation: http://localhost:3000/api
- Check database directly using SQL client

---

**End of E2E Testing Guide**
