# Mobile Login Endpoint Update - No treelogy_id Required

## 🎯 Change Summary

Updated the mobile login endpoint to **no longer require `treelogy_id`** in the URL. The system now automatically determines the user's project from their mapping or direct assignment.

---

## 📝 What Changed

### Endpoint URL

**Before:**
```
POST /api/mobile/project/:treelogy_id/login
```

**After:**
```
POST /api/mobile/project/login
```

---

## 🔄 How It Works Now

### Login Flow

```
1. Mobile app sends member_id + password
2. Backend finds user in login table
3. Backend checks user's project mapping:
   - First: Check mapping table for assigned project
   - Fallback: Use user's direct treelogy_id
4. Backend validates project exists
5. Backend returns token + project details
```

### Code Logic

```javascript
// Find user by member_id only (no treelogy_id)
const user = await Login.findOne({
  where: { member_id: email, status: 'Y' },
  include: [Mapping, UserMaster]
});

// Determine project from mapping or direct assignment
let projectId = null;
if (user.Mappings && user.Mappings.length > 0) {
  projectId = user.Mappings[0].treelogy_id; // Get from mapping
} else if (user.treelogy_id) {
  projectId = user.treelogy_id; // Get from user record
}

// Return error if no project assigned
if (!projectId) {
  return error('No project assigned to this user');
}
```

---

## 📱 Mobile App Request

### Old Request (With treelogy_id)

```json
POST /api/mobile/project/1/login
{
  "email": "SURV001",
  "password": "password123"
}
```

### New Request (No treelogy_id)

```json
POST /api/mobile/project/login
{
  "email": "SURV001", 
  "password": "password123"
}
```

---

## 🎯 Benefits

### For Mobile Users

1. **Simpler Login** - No need to select/know project ID
2. **Automatic Project** - System determines their assigned project
3. **Better UX** - Just enter username and password

### For Administrators

1. **Centralized Control** - Manage project assignments in mapping table
2. **Flexible Assignment** - Easy to reassign users to different projects
3. **Clear Error Messages** - Users notified if no project assigned

---

## 📊 User Type Handling

### Surveyor (SURVEYOR)

```
Login Request: { email: "SURV001", password: "xxx" }
↓
System checks Mapping table
↓
Finds project_id: 5
↓
Returns token + Project 5 details
```

### QC User 1 (QC_USER)

```
Login Request: { email: "QC001", password: "xxx" }
↓
System checks Mapping table
↓
Finds project_id: 5
↓
Returns token + Project 5 details
```

### QC User 2 (QC_USER_2)

```
Login Request: { email: "QC002", password: "xxx" }
↓
System checks Mapping table
↓
Finds project_id: 5
↓
Returns token + Project 5 details
```

---

## 🗄️ Database Requirements

### Mapping Table

Ensure mobile users have entries in the `mapping` table:

```sql
-- Check user's project mapping
SELECT 
  l.member_id,
  l.name,
  m.treelogy_id,
  t.treelogy_name,
  u.role_name
FROM login l
LEFT JOIN mapping m ON l.login_id = m.login_id
LEFT JOIN treelogy t ON m.treelogy_id = t.treelogy_id
LEFT JOIN user_master u ON l.role_id = u.id
WHERE l.member_id = 'SURV001';
```

### Create Mapping

If user has no mapping, create one:

```sql
INSERT INTO mapping (login_id, treelogy_id, "createdAt", "updatedAt")
VALUES (
  (SELECT login_id FROM login WHERE member_id = 'SURV001'),
  5, -- project ID
  NOW(),
  NOW()
);
```

---

## 🧪 Testing

### Test Case 1: Surveyor Login

**Request:**
```bash
curl -X POST http://localhost:3000/api/mobile/project/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "SURV001",
    "password": "password123"
  }'
```

**Expected Response:**
```json
{
  "tag": "login",
  "success": 1,
  "error": 0,
  "uid": 123,
  "token": "eyJhbGc...",
  "project": {
    "treelogy_id": 5,
    "treelogy_name": "My Project",
    "dbname": "project_db"
  },
  "user": {
    "first_name": "Surveyor One",
    "email": "SURV001"
  }
}
```

### Test Case 2: QC User Login

**Request:**
```bash
curl -X POST http://localhost:3000/api/mobile/project/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "QC001",
    "password": "password123"
  }'
```

**Expected Response:**
```json
{
  "tag": "login",
  "success": 1,
  "error": 0,
  "uid": 456,
  "token": "eyJhbGc...",
  "project": {
    "treelogy_id": 5,
    "treelogy_name": "My Project"
  }
}
```

### Test Case 3: User with No Project

**Request:**
```bash
curl -X POST http://localhost:3000/api/mobile/project/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "NOPROJECT",
    "password": "password123"
  }'
```

**Expected Response:**
```json
{
  "tag": "login",
  "success": 0,
  "error": 1,
  "error_msg": "No project assigned to this user. Please contact administrator."
}
```

---

## 🔧 Files Modified

### Backend (2 files)

1. **`Backend/routes/mobileRoutes.js`**
   - Changed route from `/:treelogy_id/login` to `/login`
   - Updated comments

2. **`Backend/controllers/mobileController.js`**
   - Added imports for Mapping and UserMaster models
   - Removed `treelogy_id` from URL parameter
   - Added logic to find project from mapping table
   - Added fallback to user's direct treelogy_id
   - Added proper error message if no project assigned
   - Updated JWT token to include determined projectId

---

## 📋 Migration Guide

### For Mobile App Developers

**Update your login API call:**

```javascript
// OLD
const login = async (memberId, password, projectId) => {
  const response = await fetch(
    `${API_URL}/mobile/project/${projectId}/login`,
    {
      method: 'POST',
      body: JSON.stringify({ email: memberId, password })
    }
  );
};

// NEW - No projectId needed!
const login = async (memberId, password) => {
  const response = await fetch(
    `${API_URL}/mobile/project/login`,
    {
      method: 'POST',
      body: JSON.stringify({ email: memberId, password })
    }
  );
};
```

---

## 🐛 Troubleshooting

### Issue: "No project assigned to this user"

**Cause:** User has no mapping and no direct treelogy_id

**Solution:**
```sql
-- Add mapping for the user
INSERT INTO mapping (login_id, treelogy_id, "createdAt", "updatedAt")
VALUES (
  (SELECT login_id FROM login WHERE member_id = 'USER_ID'),
  PROJECT_ID,
  NOW(),
  NOW()
);
```

### Issue: User logs into wrong project

**Cause:** User has multiple mappings, system uses first one

**Solution:**
```sql
-- Check user's mappings
SELECT * FROM mapping WHERE login_id = (
  SELECT login_id FROM login WHERE member_id = 'USER_ID'
);

-- Delete unwanted mappings
DELETE FROM mapping 
WHERE login_id = (SELECT login_id FROM login WHERE member_id = 'USER_ID')
AND treelogy_id != CORRECT_PROJECT_ID;
```

### Issue: Still getting "Invalid credentials"

**Checks:**
1. Verify user exists: `SELECT * FROM login WHERE member_id = 'XXX'`
2. Verify password is hashed: Should start with `$2a$` or `$2b$`
3. Verify user status is 'Y': `status = 'Y'`
4. Verify user has project mapping or treelogy_id

---

## ✅ Backward Compatibility

### Old Mobile Apps

If you have old mobile apps still using the old endpoint:

**Option 1: Keep both endpoints temporarily**
```javascript
// In mobileRoutes.js
router.post('/login', login); // New endpoint
router.post('/:treelogy_id/login', login); // Old endpoint (deprecated)
```

**Option 2: Add route redirect**
```javascript
router.post('/:treelogy_id/login', (req, res, next) => {
  // Ignore treelogy_id parameter and call login
  return login(req, res);
});
```

---

## 📊 Impact Analysis

### Mobile App Changes Required

- ❌ Remove project selection UI
- ❌ Remove treelogy_id from login request
- ✅ Just send member_id + password
- ✅ System handles project assignment

### Backend Changes

- ✅ Login endpoint updated
- ✅ Project determined from mapping
- ✅ Proper error handling
- ✅ No breaking changes for other endpoints

---

## 🔍 Verification Queries

### Check User's Project Assignment

```sql
-- Method 1: Via Mapping
SELECT 
  l.member_id,
  l.name,
  m.treelogy_id as mapped_project,
  t.treelogy_name
FROM login l
LEFT JOIN mapping m ON l.login_id = m.login_id
LEFT JOIN treelogy t ON m.treelogy_id = t.treelogy_id
WHERE l.member_id = 'SURV001';

-- Method 2: Direct Assignment
SELECT 
  member_id,
  name,
  treelogy_id as direct_project
FROM login
WHERE member_id = 'SURV001';
```

### List All Mobile Users and Their Projects

```sql
SELECT 
  l.member_id,
  l.name,
  u.role_name,
  COALESCE(m.treelogy_id, l.treelogy_id) as assigned_project,
  t.treelogy_name
FROM login l
JOIN user_master u ON l.role_id = u.id
LEFT JOIN mapping m ON l.login_id = m.login_id
LEFT JOIN treelogy t ON COALESCE(m.treelogy_id, l.treelogy_id) = t.treelogy_id
WHERE u.role_name IN ('SURVEYOR', 'QC_USER', 'QC_USER_2')
ORDER BY u.role_name, l.member_id;
```

---

## 📞 Support

### Common Questions

**Q: Do I need to update the mobile app?**
- A: Yes, remove the treelogy_id parameter from the login URL

**Q: What if a user has multiple project mappings?**
- A: System uses the first mapping. For mobile users, assign only one project.

**Q: Can I still use treelogy_id in the URL?**
- A: You can add backward compatibility (see Backward Compatibility section)

**Q: What about QC users who review multiple projects?**
- A: For mobile app, they should have one primary project. For web app, they can switch projects.

---

## ✅ Success Criteria

- [x] Mobile login works without treelogy_id in URL
- [x] System finds project from mapping table
- [x] Fallback to direct treelogy_id works
- [x] Proper error if no project assigned
- [x] Token includes correct project ID
- [x] Works for SURVEYOR, QC_USER, QC_USER_2
- [x] Documentation complete

---

**Last Updated:** 2025-01-03  
**Version:** 1.0.0  
**Status:** ✅ COMPLETE



