# Mobile API Quick Start Guide

## ✅ What Was Fixed

### 1. **Database Connection Flow**
- **Before**: APIs tried to CREATE database every time (`createProjectDatabase`)
- **After**: APIs now properly:
  1. Look up project from root DB using `treelogy_id`
  2. Get the `dbname` from the project record
  3. Connect to existing project database
  4. Execute queries on project-specific tables

### 2. **Request Body Parsing**
- Added `express.urlencoded({ extended: true })` to `app.js`
- Now supports both `application/json` and `application/x-www-form-urlencoded`

### 3. **Route Parameters**
- All mobile routes now include `:treelogy_id` parameter
- Format: `/api/mobile/project/:treelogy_id/<endpoint>`

### 4. **New Endpoint Added**
- `/getEnumerators` - Returns list of users/enumerators

---

## 📋 Available Endpoints

All endpoints are prefixed with: `/api/mobile/project/:treelogy_id/`

### Authentication
- `POST /:treelogy_id/login` - User login
- `POST /:treelogy_id/register` - User registration
- `POST /:treelogy_id/updateSqId` - Update sequence ID
- `POST /:treelogy_id/getSqId` - Get sequence ID
- `POST /:treelogy_id/getSyncId` - Get sync ID

### Master Data
- `POST /:treelogy_id/treedetails` - Get all master data (tree list, conditions, etc.)
- `POST /:treelogy_id/refreshsocietyroad` - Refresh society and road lists
- `POST /:treelogy_id/getEnumerators` - Get list of enumerators/users

### Tree Survey
- `POST /:treelogy_id/storetreedetails` - Store new tree survey data
- `POST /:treelogy_id/updatetreedetails` - Update existing tree data
- `POST /:treelogy_id/getTreeDetailsByUserID` - Get trees by user

### QC (Quality Control)
- `POST /:treelogy_id/getTreeDetailsForQC` - Get trees pending QC
- `POST /:treelogy_id/qc` - Update QC status

### Location Tracking
- `POST /:treelogy_id/submit_location` - Submit login location
- `POST /:treelogy_id/savetrackpath` - Save GPS tracking path
- `POST /:treelogy_id/getNearbyTrees` - Get trees in bounding box

### Reports
- `POST /:treelogy_id/getExcelReport` - Get Excel report data
- `POST /:treelogy_id/getQcReport` - Get QC statistics

---

## 🚀 Testing

### Quick Test (Windows PowerShell)
```powershell
# Test login
curl.exe -X POST "http://172.17.46.11:63318/api/mobile/project/1/login" `
  -H "Content-Type: application/x-www-form-urlencoded" `
  -d "email=anilqc&password=40bd001563085fc35165329ea1ff5c5ecbdbbeef"
```

### Using the Test Script (Git Bash / Linux / Mac)
```bash
cd Backend
chmod +x test_mobile_apis.sh
./test_mobile_apis.sh
```

### Manual Testing with Postman
1. Import the collection from `apiformat.json`
2. Update all URLs to: `http://172.17.46.11:63318/api/mobile/project/1/<endpoint>`
3. Replace `1` with your actual `treelogy_id`
4. Set body type to `x-www-form-urlencoded`

---

## ⚠️ Important Prerequisites

### 1. **Project Must Exist in Root DB**
Before using mobile APIs, ensure:
- A project record exists in the `treelogy` table with a valid `treelogy_id`
- The project has a `dbname` field populated
- The project database exists and is accessible

### 2. **Project Database Must Have Required Tables**
The project-specific database needs these tables:
- `treeusers` - User accounts
- `treelist` - Tree species master data
- `treedetailsentered` - Tree survey data
- `condition` - Tree condition master data
- `ownership` - Ownership types
- `remarks` - Remarks master data
- `spacial_comment` - Spatial comments
- `bird_nest` - Bird nest data
- `treebal_imbalance` - Balance/imbalance data
- `login_details` - Login tracking
- `track_path` - GPS tracking

### 3. **Sample Project Setup**
```sql
-- In root database
INSERT INTO treelogy (treelogy_id, treelogy_code, treelogy_name, dbname, client_id, status)
VALUES (1, 'PROJ001', 'Test Project', 'project_1_db', 1, 'Y');

-- Then create the project database and tables
-- (Use your existing migration/setup scripts)
```

---

## 🔧 Troubleshooting

### Error: "Project not found"
- Check that `treelogy_id` in URL matches a record in root DB `treelogy` table
- Verify the project status is active

### Error: "relation 'tablename' does not exist"
- The project database is missing required tables
- Run your database migration/setup script for that project DB

### Error: "Cannot destructure property ... of 'req.body'"
- Ensure you're sending `Content-Type: application/x-www-form-urlencoded`
- Check that all required fields are included in request body

### Error: "database already exists"
- This is expected on subsequent requests
- The code now handles this gracefully by connecting to existing DB

---

## 📝 Example Requests

### Login
```bash
curl -X POST http://172.17.46.11:63318/api/mobile/project/1/login \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "email=testuser@example.com" \
  -d "password=hashedpassword"
```

### Get Tree Details (Master Data)
```bash
curl -X POST http://172.17.46.11:63318/api/mobile/project/1/treedetails \
  -H "Content-Type: application/x-www-form-urlencoded"
```

### Get Nearby Trees
```bash
curl -X POST http://172.17.46.11:63318/api/mobile/project/1/getNearbyTrees \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "northLat=19.1756" \
  -d "southLat=19.1720" \
  -d "westLon=72.8424" \
  -d "eastLon=72.8462"
```

### Store Tree Details
```bash
curl -X POST http://172.17.46.11:63318/api/mobile/project/1/storetreedetails \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "user_id=1" \
  -d "tree_id=5" \
  -d "latitude=19.1747" \
  -d "longitude=72.8446" \
  -d "grith_cm=100" \
  -d "height_mtr=15" \
  # ... (add all required fields)
```

---

## 🎯 Next Steps

1. **Restart your Node.js server** to apply all changes
2. **Verify a project exists** in your root database
3. **Test with the provided curl commands** or test script
4. **Check server logs** for any errors
5. **Ensure project database has all required tables**

---

## 📞 Support

If you encounter issues:
1. Check server logs for detailed error messages
2. Verify database connections are working
3. Ensure all environment variables are set correctly in `.env`
4. Confirm project database exists and has required schema

