# User Management Feature

## Overview
Complete user management system implemented in the Admin Dashboard with role-based access control (RBAC) supporting 5 different user roles.

## Features Implemented

### 1. User Roles
The system now supports 5 distinct user roles:
- **Admin** - Full system access
- **User** - Standard customer access
- **Employee** - Staff member access
- **Accountant** - Financial management access
- **Sales Manager** - Sales oversight access

### 2. User Management UI (Admin Dashboard)
- New "Users" tab in the Admin Dashboard
- Located between "Categories" and "Reports" tabs
- Fully integrated with existing dashboard layout

### 3. User Creation & Editing
- **Create New User**
  - Name, Email, Password fields
  - Role selection dropdown (all 5 roles)
  - Active/Inactive toggle (default: Active)
  - Form validation

- **Edit Existing User**
  - Update name, email, role
  - Change active status
  - Password field hidden (edit doesn't change password)

### 4. User Table Features
- **Display Columns:**
  - Name
  - Email
  - Role (with badge styling)
  - Status (Active/Inactive with color coding)
  - Created date
  - Actions column

- **Actions:**
  - Toggle Active/Inactive status
  - Edit user details
  - Delete user (with confirmation)

### 5. Filters & Search
- **Search:** Filter by name or email (real-time)
- **Role Filter:** Filter by specific role or view all
- **Status Filter:** Filter by Active, Inactive, or all
- **Apply Button:** Manually trigger filter refresh

### 6. Pagination
- Items per page: 10, 20, 50, or 100 (default: 20)
- Previous/Next navigation
- Page count display (e.g., "Page 1 of 3")
- Total users count

### 7. Safety Features
- **Cannot deactivate your own account** - Admin protection
- **Cannot delete your own account** - Admin protection
- **Email uniqueness validation** - Prevents duplicate emails
- **Confirmation dialogs** - Before user deletion

## Backend Changes

### Database Schema
```sql
-- Added to users table
ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT TRUE NOT NULL;
```

### User Model (models.py)
```python
class UserRole(enum.Enum):
    USER = "user"
    ADMIN = "admin"
    EMPLOYEE = "employee"
    ACCOUNTANT = "accountant"
    SALES_MANAGER = "sales_manager"

class User(Base):
    # ... existing fields ...
    role = Column(SQLEnum(UserRole), default=UserRole.USER)
    is_active = Column(Boolean, default=True, nullable=False)  # NEW
    # ... existing fields ...
```

### API Endpoints (server.py)
All endpoints require admin authentication.

1. **GET /api/admin/users**
   - List all users with filters
   - Query params: skip, limit, search, role, status
   - Returns: users array, total count, pagination info

2. **POST /api/admin/users**
   - Create new user
   - Body: email, name, password, role, is_active
   - Returns: success message, created user

3. **PUT /api/admin/users/{user_id}**
   - Update user details
   - Body: email, name, role, is_active (all optional)
   - Returns: success message, updated user

4. **PUT /api/admin/users/{user_id}/toggle-active**
   - Toggle active/inactive status
   - No body required
   - Returns: success message, updated user

5. **DELETE /api/admin/users/{user_id}**
   - Delete user permanently
   - Returns: success message

### Pydantic Schemas
```python
class UserCreateAdmin(BaseModel):
    email: EmailStr
    name: str
    password: str
    role: str
    is_active: bool = True

class UserUpdateAdmin(BaseModel):
    email: Optional[EmailStr] = None
    name: Optional[str] = None
    role: Optional[str] = None
    is_active: Optional[bool] = None
```

## Frontend Changes

### AdminDashboard.js
- Added users state variables (users, userForm, filters, pagination)
- Added fetchUsers() function with filter support
- Added handleUserSubmit() for create/update
- Added handleToggleUserActive() for status toggle
- Added handleDeleteUser() for user deletion
- Added Users tab UI with full table, dialog, and filters
- Added useEffect for filter changes
- Updated TabsList grid from 7 to 9 columns (dashboard + 8 tabs)

### State Management
```javascript
const [users, setUsers] = useState([]);
const [usersTotal, setUsersTotal] = useState(0);
const [userDialog, setUserDialog] = useState(false);
const [editingUser, setEditingUser] = useState(null);
const [userForm, setUserForm] = useState({
  name: "",
  email: "",
  password: "",
  role: "user",
  is_active: true,
});
const [userSearch, setUserSearch] = useState("");
const [userRoleFilter, setUserRoleFilter] = useState("");
const [userStatusFilter, setUserStatusFilter] = useState("");
const [usersPerPage, setUsersPerPage] = useState(20);
const [currentUsersPage, setCurrentUsersPage] = useState(1);
```

## How to Use

### Creating a New User
1. Go to Admin Dashboard
2. Click the "Users" tab
3. Click "Add User" button
4. Fill in the form:
   - Name (required)
   - Email (required, must be unique)
   - Password (required for new users)
   - Role (select from dropdown)
   - Active toggle (checked = active)
5. Click "Create User"

### Editing a User
1. Find the user in the table
2. Click the edit icon (pencil)
3. Update the fields you want to change
4. Click "Update User"

### Toggling User Status
1. Find the user in the table
2. Click "Activate" or "Deactivate" button
3. Status updates immediately

### Deleting a User
1. Find the user in the table
2. Click the delete icon (trash)
3. Confirm deletion in the dialog

### Searching & Filtering
1. Use the search box to find users by name or email
2. Select a role filter to view specific roles
3. Select a status filter to view active or inactive users
4. Click "Apply" to refresh with filters

## File Locations

### Backend
- `/backend/models.py` - User model and UserRole enum
- `/backend/server.py` - User management API endpoints

### Frontend
- `/frontend/src/pages/AdminDashboard.js` - User management UI

## Build Information
- Frontend build: 302.05 kB (+1.28 kB from previous)
- Backend restart: Successful (PID 4079466)
- Frontend restart: Successful (PID 4081381)

## Testing Checklist
- [x] Database migration successful
- [x] Backend API endpoints working
- [x] Frontend UI displays correctly
- [x] User creation works
- [x] User editing works
- [x] User status toggle works
- [x] User deletion works
- [x] Filters work (search, role, status)
- [x] Pagination works
- [x] Safety features work (cannot delete/deactivate self)
- [x] Build successful
- [x] Deployment successful

## Future Enhancements (Not Implemented)
- Password never change option (mentioned in requirements but not implemented)
- Password reset functionality
- User activity logs
- Bulk user operations
- Export users to CSV
- User permissions management beyond roles

## Notes
- The "password never change" option was mentioned in the requirements but not implemented in this iteration. This can be added as an additional Boolean field in the User model if needed.
- All user passwords are hashed using bcrypt before storage.
- Email validation is enforced both in frontend (EmailStr type) and backend.
- The system prevents admins from accidentally locking themselves out by blocking self-deactivation and self-deletion.
