| name | enterprise-user-management-ai-system |
| description | Full-stack user management system with AI-powered analytics, task tracking, and intelligent ticket routing |
| triggers | ["set up enterprise user management with AI","implement user management system with task tracking","create admin dashboard with AI analytics","build user management app with ticket system","add AI-based risk detection to user management","integrate ML service for user behavior analysis","configure Kanban board with time tracking","deploy enterprise user management system"] |
Enterprise User Management AI System
Skill by ara.so — Data Skills collection.
A full-stack enterprise user management system featuring AI-powered analytics, task management with Kanban boards, support ticket handling, and intelligent insights including risk detection, anomaly detection, and burnout analysis.
What It Does
This system provides:
- User Management: Role-based access control, authentication with JWT
- Task Management: Kanban boards (To Do → In Progress → Done) with time tracking
- Support System: Ticket creation, tracking, and AI-based classification
- AI Analytics: Risk prediction, anomaly detection, burnout analysis, project delay prediction
- Admin Controls: User CRUD operations, audit logs, organization analytics
- Real-time Insights: Performance metrics, workload analysis, suspicious activity alerts
Installation
Prerequisites
Clone and Setup
git clone https://github.com/Nareshkumar2583/Enterprise-User-Management-System-with-AI-Analytics.git
cd Enterprise-User-Management-System-with-AI-Analytics
Backend Setup
cd backend
npm install
cat > .env << EOF
PORT=5000
MONGODB_URI=mongodb://localhost:27017/enterprise-user-mgmt
JWT_SECRET=${JWT_SECRET}
JWT_EXPIRE=7d
ML_SERVICE_URL=http://localhost:8000
EOF
npm start
ML Service Setup
cd ml-service
pip install -r requirements.txt
cat > .env << EOF
MODEL_PATH=./models
LOG_LEVEL=INFO
EOF
uvicorn main:app --reload --host 0.0.0.0 --port 8000
Frontend Setup
cd frontend
npm install
cat > .env << EOF
REACT_APP_API_URL=http://localhost:5000/api
REACT_APP_ML_URL=http://localhost:8000
EOF
npm start
Key API Endpoints
Authentication
POST /api/auth/register
{
"name": "John Doe",
"email": "john@example.com",
"password": "securepass123",
"role": "user"
}
POST /api/auth/login
{
"email": "john@example.com",
"password": "securepass123"
}
User Management (Admin)
GET /api/users
Headers: { Authorization: "Bearer ${JWT_TOKEN}" }
PUT /api/users/:userId
{
"name": "Updated Name",
"role": "admin",
"status": "active"
}
DELETE /api/users/:userId
Task Management
POST /api/tasks
{
"title": "Implement new feature",
"description": "Build user profile page",
"assignedTo": "userId",
"status": "todo",
"priority": "high",
"dueDate": "2026-05-01"
}
PATCH /api/tasks/:taskId/status
{
"status": "inprogress",
"timeSpent": 3600
}
GET /api/tasks/user/:userId
Support Tickets
POST /api/tickets
{
"subject": "Login issue",
"description": "Cannot access dashboard",
"priority": "high",
"category": "technical"
}
GET /api/tickets?status=open&priority=high
PATCH /api/tickets/:ticketId
{
"status": "resolved",
"resolution": "Password reset sent"
}
AI Analytics Endpoints
POST /api/ai/risk-prediction
{
"userId": "user123",
"taskLoad": 15,
"overdueCount": 3,
"avgCompletionTime": 72
}
POST /api/ai/anomaly-detection
{
"userId": "user123",
"loginTime": "2026-04-15T03:30:00Z",
"location": "unusual-ip",
"activityPattern": [...]
}
POST /api/ai/burnout-analysis
{
"userId": "user123",
"weeklyHours": 65,
"taskCount": 25,
"overtimeFrequency": 0.8
}
POST /api/ai/project-prediction
{
"projectId": "proj123",
"tasksCompleted": 40,
"tasksRemaining": 60,
"averageVelocity": 8,
"deadline": "2026-06-01"
}
Frontend Integration Examples
Authentication Hook
import { useState, useEffect } from 'react';
import axios from 'axios';
const API_URL = process.env.REACT_APP_API_URL;
export const useAuth = () => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
fetchUser();
} else {
setLoading(false);
}
}, []);
const fetchUser = async () => {
try {
const res = await axios.get(`${API_URL}/auth/me`);
setUser(res.data.user);
} (error) {
.();
} {
();
}
};
= () => {
res = axios.(, { email, password });
.(, res..);
axios...[] = ;
(res..);
res.;
};
= () => {
.();
axios...[];
();
};
{ user, loading, login, logout, : user?. === };
};
Kanban Board Component
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './KanbanBoard.css';
const API_URL = process.env.REACT_APP_API_URL;
const KanbanBoard = ({ userId }) => {
const [tasks, setTasks] = useState({ todo: [], inprogress: [], done: [] });
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchTasks();
}, [userId]);
const fetchTasks = async () => {
try {
const res = await axios.get(`${API_URL}/tasks/user/${userId}`);
const grouped = res.data.reduce((acc, task) => {
acc[task.status].push(task);
return acc;
}, { todo: [], inprogress: [], done: [] });
setTasks(grouped);
} (error) {
.(, error);
} {
();
}
};
= () => {
{
axios.(, { : newStatus });
();
} (error) {
.(, error);
}
};
= () => (
);
(loading) ;
(
);
};
;
AI Risk Dashboard Component
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const API_URL = process.env.REACT_APP_API_URL;
const AIRiskDashboard = ({ userId }) => {
const [riskData, setRiskData] = useState(null);
const [burnoutData, setBurnoutData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchAIAnalytics();
}, [userId]);
const fetchAIAnalytics = async () => {
try {
const [riskRes, burnoutRes] = await Promise.all([
axios.post(`${API_URL}/ai/risk-prediction`, { userId }),
axios.post(`${API_URL}/ai/burnout-analysis`, { userId })
]);
setRiskData(riskRes.data);
setBurnoutData(burnoutRes.data);
} catch (error) {
console.(, error);
} {
();
}
};
(loading) ;
(
);
};
;
Backend Implementation Patterns
User Controller
const User = require('../models/User');
const jwt = require('jsonwebtoken');
exports.getAllUsers = async (req, res) => {
try {
const users = await User.find().select('-password');
res.json({ success: true, count: users.length, data: users });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
exports.updateUser = async (req, res) => {
try {
const { name, email, role, status } = req.body;
const user = await User.findByIdAndUpdate(
req.params.id,
{ name, email, role, status },
{ new: true, runValidators: true }
).();
(!user) {
res.().({ : , : });
}
res.({ : , : user });
} (error) {
res.().({ : , : error. });
}
};
. = (req, res) => {
{
user = .(req..);
(!user) {
res.().({ : , : });
}
res.({ : , : {} });
} (error) {
res.().({ : , : error. });
}
};
Task Model
const mongoose = require('mongoose');
const TaskSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'Please add a title'],
trim: true,
maxlength: [100, 'Title cannot exceed 100 characters']
},
description: {
type: String,
required: [true, 'Please add a description']
},
status: {
type: String,
enum: ['todo', 'inprogress', 'done'],
default: 'todo'
},
priority: {
type: String,
enum: ['low', 'medium', 'high', 'urgent'],
default: 'medium'
},
assignedTo: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
},
createdBy: {
: mongoose..,
: ,
:
},
: {
: ,
: [, ]
},
: {
: ,
:
},
:
}, {
:
});
.({ : , : });
. = mongoose.(, );
Authentication Middleware
const jwt = require('jsonwebtoken');
const User = require('../models/User');
exports.protect = async (req, res, next) => {
let token;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
token = req.headers.authorization.split(' ')[1];
}
if (!token) {
return res.status(401).json({ success: false, error: 'Not authorized to access this route' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-password');
next();
} catch (error) {
return res.status(401).json({ : , : });
}
};
. = {
{
(!roles.(req..)) {
res.().({
: ,
:
});
}
();
};
};
ML Service Implementation
FastAPI ML Service
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import numpy as np
from sklearn.ensemble import RandomForestClassifier
import joblib
import os
app = FastAPI(title="Enterprise User Management ML Service")
MODEL_PATH = os.getenv("MODEL_PATH", "./models")
class RiskPredictionRequest(BaseModel):
userId: str
taskLoad: int
overdueCount: int
avgCompletionTime: float
class AnomalyDetectionRequest(BaseModel):
userId: str
loginTime: str
location: str
activityPattern: List[float]
class BurnoutAnalysisRequest(BaseModel):
userId: str
weeklyHours: float
taskCount: int
overtimeFrequency: float
@app.post("/risk-prediction")
async def predict_risk(request: RiskPredictionRequest):
:
features = np.array([[
request.taskLoad,
request.overdueCount,
request.avgCompletionTime,
request.taskLoad * request.overdueCount
]])
risk_score = (
request.taskLoad * +
request.overdueCount * +
(request.avgCompletionTime / ) *
)
risk_level =
risk_score > :
risk_level =
risk_score > :
risk_level =
factors = []
request.taskLoad > :
factors.append()
request.overdueCount > :
factors.append()
request.avgCompletionTime > :
factors.append()
{
: risk_level,
: (risk_score / , ),
: factors
}
Exception e:
HTTPException(status_code=, detail=(e))
():
:
datetime datetime
login_hour = datetime.fromisoformat(request.loginTime.replace(, )).hour
is_anomaly =
score =
reason =
login_hour < login_hour > :
is_anomaly =
score +=
reason =
request.location.lower():
is_anomaly =
score +=
reason +=
{
: is_anomaly,
: (score, ),
: reason reason
}
Exception e:
HTTPException(status_code=, detail=(e))
():
:
burnout_score = (
(request.weeklyHours - ) * +
request.taskCount * +
request.overtimeFrequency *
)
risk_level =
recommendation =
burnout_score > :
risk_level =
recommendation =
burnout_score > :
risk_level =
recommendation =
{
: risk_level,
: burnout_score,
: recommendation,
: {
: request.weeklyHours,
: request.taskCount,
: request.overtimeFrequency
}
}
Exception e:
HTTPException(status_code=, detail=(e))
():
{: , : }
Configuration
Backend Environment Variables
PORT=5000
NODE_ENV=production
MONGODB_URI=mongodb://localhost:27017/enterprise-user-mgmt
JWT_SECRET=${JWT_SECRET}
JWT_EXPIRE=7d
ML_SERVICE_URL=http://localhost:8000
CORS_ORIGIN=http://localhost:3000
Frontend Environment Variables
REACT_APP_API_URL=http://localhost:5000/api
REACT_APP_ML_URL=http://localhost:8000
REACT_APP_ENV=development
ML Service Configuration
import os
from pydantic import BaseSettings
class Settings(BaseSettings):
model_path: str = os.getenv("MODEL_PATH", "./models")
log_level: str = os.getenv("LOG_LEVEL", "INFO")
max_workers: int = 4
class Config:
env_file = ".env"
settings = Settings()
Common Patterns
Admin Dashboard Data Fetching
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const API_URL = process.env.REACT_APP_API_URL;
const AdminDashboard = () => {
const [stats, setStats] = useState({
totalUsers: 0,
activeTasks: 0,
openTickets: 0,
highRiskUsers: []
});
useEffect(() => {
fetchDashboardStats();
}, []);
const fetchDashboardStats = async () => {
try {
const [usersRes, tasksRes, ticketsRes, riskRes] = await Promise.all([
axios.get(`${API_URL}/users/count`),
axios.get(`${API_URL}/tasks/active/count`),
axios.get(`${API_URL}/tickets?status=open`),
axios.get(`${API_URL}/ai/high-risk-users`)
]);
setStats({
: usersRes..,
: tasksRes..,
: ticketsRes..,
: riskRes..
});
} (error) {
.(, error);
}
};
(
);
};
;
Time Tracker Component
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const TimeTracker = ({ taskId }) => {
const [seconds, setSeconds] = useState(0);
const [isActive, setIsActive] = useState(false);
useEffect(() => {
let interval = null;
if (isActive) {
interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
} else if (!isActive && seconds !== 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isActive, seconds]);
const toggle = () => {
setIsActive(!isActive);
};
const reset = () => {
setSeconds(0);
setIsActive(false);
};
const saveTime = async () => {
{
axios.(, {
: seconds
});
();
} (error) {
.(, error);
}
};
= () => {
hours = .(totalSeconds / );
minutes = .((totalSeconds % ) / );
secs = totalSeconds % ;
;
};
(
);
};
;
Troubleshooting
MongoDB Connection Issues
const mongoose = require('mongoose');
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000
});
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.error(`Error: ${error.message}`);
setTimeout(connectDB, 5000);
}
};
module.exports = connectDB;
CORS Issues
const cors = require('cors');
app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
JWT Token Expiration Handling
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
axiosInstance.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default axiosInstance;
ML Service Not Responding
curl http://localhost:8000/health
tail -f ml-service/logs/app.log
cd ml-service
uvicorn main:app --reload --log-level debug
Task Status Not Updating
const updateTaskStatus = async (taskId, newStatus) => {
try {
const response = await axios.patch(
`${API_URL}/tasks/${taskId}/status`,
{ status: newStatus },
{ headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
);
setTasks(prevTasks => ({
...prevTasks,
[newStatus]: [...prevTasks[newStatus], response.data.data]
}));
} catch (error) {
console.error('Update failed:', error.response?.data || error.message);
}
};
Performance Optimization
GET /api/users?page=1&limit=20
exports.getAllUsers = async (req, res) => {
const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 20;
const startIndex = (page - 1) * limit;
const users = await User.find()
.select('-password')
.skip(startIndex)
.limit(limit);
const total = await User.countDocuments();
res.json({
success: true,
count: users.length,
total,
page,
pages: Math.ceil(total / limit),
data: users
});
};
This enterprise user management system provides a complete solution for managing users, tasks, and support with AI-powered insights for better decision-making