# User Management Documentation

## Creating New Users

### Method 1: Direct Database Insert (SQL)

#### Step 1: Generate Password Hash
```bash
node -e "
const bcrypt = require('bcryptjs');
bcrypt.hash('your-password-here', 12).then(hash => {
  console.log('Password hash:', hash);
});
"
```

#### Step 2: Insert User into Database
```sql
sqlite3 dev.db << 'EOF'
INSERT INTO users (
  id, name, username, email, password, role, position, department, 
  salary, phone, joinDate, isActive, createdAt, updatedAt
) VALUES (
  'unique-user-id',
  'Full Name',
  'username',
  'email@company.com',
  'bcrypt-hash-from-step-1',
  'ROLE_NAME',
  'Job Title',
  'Department Name',
  75000,
  '+1-555-0123',
  datetime('now'),
  1,
  datetime('now'),
  datetime('now')
);
EOF
```

#### Available Roles:
- `SUPER_ADMIN` - Full system access
- `UPPER_MANAGEMENT` - Senior leadership access
- `MANAGER` - Team management access
- `UNIT_LEAD` - Team lead access
- `MEMBER` - Standard user access

### Method 2: Node.js Script

Create a script file to add users programmatically:

```javascript
// add-user.js
const bcrypt = require('bcryptjs');
const { PrismaClient } = require('./lib/generated/prisma');

const db = new PrismaClient();

async function createUser(userData) {
  try {
    // Hash the password
    const hashedPassword = await bcrypt.hash(userData.password, 12);
    
    // Create user
    const user = await db.user.create({
      data: {
        name: userData.name,
        username: userData.username,
        email: userData.email,
        password: hashedPassword,
        role: userData.role,
        position: userData.position,
        department: userData.department,
        salary: userData.salary || null,
        phone: userData.phone || null,
      }
    });
    
    console.log('User created successfully:', user.email);
    return user;
  } catch (error) {
    console.error('Error creating user:', error);
  } finally {
    await db.$disconnect();
  }
}

// Example usage
createUser({
  name: 'John Doe',
  username: 'john.doe',
  email: 'john.doe@company.com',
  password: 'securepassword123',
  role: 'MEMBER',
  position: 'Software Developer',
  department: 'Engineering',
  salary: 75000,
  phone: '+1-555-0123'
});
```

### Method 3: Web Form (User Interface)

Use the built-in user creation form in the admin panel:

#### **Accessing the Form**
1. Login to the admin panel with appropriate permissions (Super Admin or Top Management)
2. Navigate to **Dashboard > Users**
3. Click the **"Add User"** button
4. Fill out the user creation form

#### **Form Fields**
- **Full Name**: User's complete name
- **Email Address**: User's email (will be used for login)
- **Password**: Minimum 8 characters (will be hashed automatically)
- **Designation**: Job title/position
  - Available options: CEO, CTO, VP Engineering, Engineering Manager, Team Lead, Senior Developer, Developer, Marketing Manager, Sales Manager, HR Manager, Finance Manager, Operations Manager, Product Manager, **Production Head**, Designer
- **Team**: Department/team assignment
  - Available options: Engineering, Marketing, Sales, HR, Finance, Operations, Design, Product, **Production**
- **Role**: User's system role (limited by your permissions)
  - Super Admin can create: All roles
  - Top Management can create: Manager, Unit Lead, Member
  - Manager can create: Unit Lead, Member

#### **Form Features**
- **Real-time Validation**: Immediate feedback on field requirements
- **Role-based Permissions**: Only shows roles you can assign
- **Automatic Username**: Generated from email address
- **Password Security**: Enforces minimum length requirements
- **Error Handling**: Clear error messages for validation failures
- **Success Feedback**: Automatic redirect to users list on success

### Method 4: API Endpoint (For Admin Users)

Create an admin-only API endpoint for user creation:

```typescript
// app/api/admin/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { db } from '@/lib/db'
import { hashPassword } from '@/lib/auth'
import { Role } from '@/lib/generated/prisma'

export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    
    // Only Super Admin and Top Management can create users
    if (!session || !['SUPER_ADMIN', 'UPPER_MANAGEMENT'].includes(session.user.role)) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
    }

    const userData = await request.json()
    
    // Validate required fields
    const { name, username, email, password, role, position, department } = userData
    
    if (!name || !username || !email || !password || !role || !position || !department) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
    }

    // Check if user already exists
    const existingUser = await db.user.findFirst({
      where: {
        OR: [{ email }, { username }]
      }
    })

    if (existingUser) {
      return NextResponse.json({ error: 'User already exists' }, { status: 400 })
    }

    // Hash password
    const hashedPassword = await hashPassword(password)

    // Create user
    const user = await db.user.create({
      data: {
        name,
        username,
        email,
        password: hashedPassword,
        role: role as Role,
        position,
        department,
        salary: userData.salary || null,
        phone: userData.phone || null,
      },
      select: {
        id: true,
        name: true,
        username: true,
        email: true,
        role: true,
        position: true,
        department: true,
        createdAt: true,
      }
    })

    return NextResponse.json({ message: 'User created successfully', user })

  } catch (error) {
    console.error('Error creating user:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
```

## Password Management

### Changing User Passwords

#### Method 1: Direct Database Update
```bash
# Generate new password hash
node -e "
const bcrypt = require('bcryptjs');
bcrypt.hash('new-password', 12).then(hash => {
  console.log('New password hash:', hash);
});
"

# Update user password
sqlite3 dev.db "UPDATE users SET password = 'new-hash-here' WHERE email = 'user@company.com';"
```

#### Method 2: Password Reset API
```typescript
// app/api/admin/users/[id]/reset-password/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions, hashPassword } from '@/lib/auth'
import { db } from '@/lib/db'

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    
    // Only admins can reset passwords
    if (!session || !['SUPER_ADMIN', 'UPPER_MANAGEMENT', 'MANAGER'].includes(session.user.role)) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
    }

    const { newPassword } = await request.json()
    
    if (!newPassword || newPassword.length < 8) {
      return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 400 })
    }

    const hashedPassword = await hashPassword(newPassword)

    await db.user.update({
      where: { id: params.id },
      data: { password: hashedPassword }
    })

    return NextResponse.json({ message: 'Password reset successfully' })

  } catch (error) {
    console.error('Error resetting password:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
```

## User Management Operations

### Viewing All Users
```sql
sqlite3 dev.db "SELECT id, name, email, role, position, department, isActive FROM users;"
```

### Deactivating a User
```sql
sqlite3 dev.db "UPDATE users SET isActive = 0 WHERE email = 'user@company.com';"
```

### Reactivating a User
```sql
sqlite3 dev.db "UPDATE users SET isActive = 1 WHERE email = 'user@company.com';"
```

### Updating User Role
```sql
sqlite3 dev.db "UPDATE users SET role = 'MANAGER' WHERE email = 'user@company.com';"
```

### Deleting a User (Not Recommended)
```sql
sqlite3 dev.db "DELETE FROM users WHERE email = 'user@company.com';"
```

## Security Best Practices

### Password Requirements
- Minimum 8 characters
- Use bcrypt with 12 salt rounds
- Store only hashed passwords, never plain text

### Role Hierarchy
1. **SUPER_ADMIN** (Level 5) - Can manage all users including other Super Admins
2. **UPPER_MANAGEMENT** (Level 4) - Can manage all users except Super Admins
3. **MANAGER** (Level 3) - Can manage Unit Leads and Members
4. **UNIT_LEAD** (Level 2) - Limited management capabilities
5. **MEMBER** (Level 1) - Standard user access

### Permission Guidelines
- Only users with appropriate roles can create/modify other users
- Users cannot elevate their own privileges
- Super Admins cannot demote themselves
- Always validate role hierarchy before operations

## Bulk User Import

For importing multiple users, create a CSV import script:

```javascript
// import-users.js
const fs = require('fs');
const csv = require('csv-parser');
const bcrypt = require('bcryptjs');
const { PrismaClient } = require('./lib/generated/prisma');

const db = new PrismaClient();

async function importUsers(csvFile) {
  const users = [];
  
  fs.createReadStream(csvFile)
    .pipe(csv())
    .on('data', (row) => {
      users.push(row);
    })
    .on('end', async () => {
      for (const userData of users) {
        try {
          const hashedPassword = await bcrypt.hash(userData.password, 12);
          
          await db.user.create({
            data: {
              name: userData.name,
              username: userData.username,
              email: userData.email,
              password: hashedPassword,
              role: userData.role,
              position: userData.position,
              department: userData.department,
              salary: userData.salary ? parseInt(userData.salary) : null,
              phone: userData.phone || null,
            }
          });
          
          console.log(`Created user: ${userData.email}`);
        } catch (error) {
          console.error(`Error creating user ${userData.email}:`, error);
        }
      }
      
      await db.$disconnect();
      console.log('Import completed');
    });
}

// Usage: node import-users.js
// CSV format: name,username,email,password,role,position,department,salary,phone
```

## Troubleshooting

### Common Issues

1. **"User not found" during login**
   - Check if user exists: `sqlite3 dev.db "SELECT * FROM users WHERE email = 'email@company.com';"`
   - Verify isActive is set to 1

2. **"Invalid password" error**
   - Verify password hash was generated correctly
   - Check bcrypt version compatibility

3. **Permission denied errors**
   - Verify user role hierarchy
   - Check session authentication

### Database Backup
```bash
# Create backup
cp dev.db dev.db.backup.$(date +%Y%m%d_%H%M%S)

# Restore backup
cp dev.db.backup.TIMESTAMP dev.db
```

## Quick Reference Commands

### Create Super Admin
```bash
node -e "const bcrypt = require('bcryptjs'); bcrypt.hash('admin123', 12).then(h => console.log(h));"
# Copy the hash, then:
sqlite3 dev.db "INSERT INTO users (id, name, username, email, password, role, position, department, joinDate, isActive, createdAt, updatedAt) VALUES ('admin-$(date +%s)', 'Admin User', 'admin', 'admin@company.com', 'HASH_HERE', 'SUPER_ADMIN', 'Administrator', 'IT', datetime('now'), 1, datetime('now'), datetime('now'));"
```

### List All Users
```bash
sqlite3 dev.db "SELECT name, email, role, isActive FROM users;"
```

### Reset Password
```bash
node -e "const bcrypt = require('bcryptjs'); bcrypt.hash('newpassword', 12).then(h => console.log(h));"
sqlite3 dev.db "UPDATE users SET password = 'NEW_HASH' WHERE email = 'user@company.com';"
``` 