Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions backend/controllers/analytics.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import supabase from "../config/db.js";

const memberProfiles = [
{ id: "alex", name: "Alex Rivera", role: "Lead Frontend Engineer", focus: "Frontend", image: "https://i.pravatar.cc/96?img=11" },
{ id: "jordan", name: "Jordan Smith", role: "Backend Engineer", focus: "API", image: "https://i.pravatar.cc/96?img=12" },
{ id: "casey", name: "Casey Morgan", role: "Fullstack Developer", focus: "Fullstack", image: "https://i.pravatar.cc/96?img=13" },
{ id: "riley", name: "Riley Lee", role: "QA Analyst", focus: "QA", image: "https://i.pravatar.cc/96?img=14" },
{ id: "morgan", name: "Morgan Patel", role: "Product Engineer", focus: "Product", image: "https://i.pravatar.cc/96?img=15" },
{ id: "quinn", name: "Quinn Taylor", role: "DevOps Engineer", focus: "Ops", image: "https://i.pravatar.cc/96?img=16" },
];

function hashString(value) {
return String(value || "")
.split("")
.reduce((total, char) => total + char.charCodeAt(0), 0);
}

function buildMembers(tasks = [], messages = [], sprintOffset = 0) {
return memberProfiles.map((profile, index) => {
const assignedTasks = tasks.filter((task, taskIndex) => {
const seed = hashString(task.id || task.title || taskIndex);
return seed % memberProfiles.length === index;
});
const completedTasks = assignedTasks.filter((task) => task.status === "done");
const messageCount = messages.filter((message) => {
const seed = hashString(message.username || message.id);
return seed % memberProfiles.length === index;
}).length;

const assigned = Math.min(98, Math.max(35, assignedTasks.length * 12 + 48 - sprintOffset * 6));
const completed = Math.min(assigned, Math.max(20, completedTasks.length * 18 + messageCount * 4 + 34 - sprintOffset * 5));
const reviews = Math.max(6, messageCount * 2 + completedTasks.length + 8 - sprintOffset);
const activity = Array.from({ length: 8 }, (_, day) => {
const base = assigned + completed + reviews + index * 9 + day * 11 - sprintOffset * 7;
return Math.min(100, Math.max(18, base % 100));
});

return {
...profile,
assigned,
completed,
reviews,
activity,
};
});
}

export const getAnalytics = async (req, res) => {
try {
const [{ data: tasks, error: tasksError }, { data: messages, error: messagesError }] =
await Promise.all([
supabase.from("tasks").select("id,title,status,position,created_at"),
supabase.from("messages").select("id,username,text,created_at"),
]);

if (tasksError) throw tasksError;
if (messagesError) throw messagesError;

res.status(200).json({
sprints: [
{ label: "Sprint 42", members: buildMembers(tasks || [], messages || [], 0) },
{ label: "Sprint 41", members: buildMembers(tasks || [], messages || [], 1) },
],
generatedAt: new Date().toISOString(),
});
} catch (error) {
console.error("Error building analytics:", error);
res.status(500).json({ error: "Failed to load analytics" });
}
};
109 changes: 109 additions & 0 deletions backend/controllers/feed.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { randomUUID } from "crypto";
import supabase from "../config/db.js";

const manualItems = [];
Comment thread
Shriii19 marked this conversation as resolved.

function toRelativeTime(value) {
if (!value) return "Just now";
const createdAt = new Date(value).getTime();
const diffMinutes = Math.max(1, Math.floor((Date.now() - createdAt) / 60000));
if (diffMinutes < 60) return `${diffMinutes} min ago`;
const diffHours = Math.floor(diffMinutes / 60);
if (diffHours < 24) return `${diffHours} hours ago`;
return new Date(value).toLocaleDateString("en", { month: "short", day: "numeric" });
}

function groupForDate(value) {
if (!value) return "Today";
const itemDate = new Date(value);
const today = new Date();
const yesterday = new Date();
yesterday.setDate(today.getDate() - 1);

if (itemDate.toDateString() === today.toDateString()) return "Today";
if (itemDate.toDateString() === yesterday.toDateString()) return "Yesterday";
return "Earlier";
}

function taskToFeedItem(task) {
const isDone = task.status === "done";
return {
id: `task-${task.id}`,
type: isDone ? "milestone" : "code",
actor: isDone ? "System" : "FlowForge",
action: isDone ? "completed a task" : "updated a task",
title: task.title || "Untitled task",
body: task.description || `Status changed to ${String(task.status || "todo").replace("_", " ")}.`,
time: toRelativeTime(task.created_at),
group: groupForDate(task.created_at),
meta: isDone ? "Task completed" : "Task activity",
image: null,
progress: isDone ? 100 : task.status === "in_progress" ? 65 : 20,
};
}

function messageToFeedItem(message) {
return {
id: `message-${message.id}`,
type: "discussion",
actor: message.username || "Team member",
action: "shared an update",
title: "Team discussion",
body: message.text || "Shared an attachment.",
time: toRelativeTime(message.created_at),
group: groupForDate(message.created_at),
meta: "Chat activity",
image: "https://i.pravatar.cc/96?u=" + encodeURIComponent(message.username || message.id),
progress: null,
};
}

export const getFeedItems = async (req, res) => {
try {
const [{ data: tasks, error: tasksError }, { data: messages, error: messagesError }] =
await Promise.all([
supabase.from("tasks").select("id,title,description,status,created_at").order("created_at", { ascending: false }).limit(12),
supabase.from("messages").select("id,username,text,created_at").order("created_at", { ascending: false }).limit(12),
]);

if (tasksError) throw tasksError;
if (messagesError) throw messagesError;

const items = [
...manualItems,
...(tasks || []).map(taskToFeedItem),
...(messages || []).map(messageToFeedItem),
].sort((a, b) => String(b.id).localeCompare(String(a.id)));
Comment thread
Shriii19 marked this conversation as resolved.

res.status(200).json({ items });
} catch (error) {
console.error("Error loading feed:", error);
res.status(500).json({ error: "Failed to load activity feed" });
}
};

export const createFeedItem = async (req, res) => {
const { title, body, type = "discussion" } = req.body || {};

if (!title || !body) {
return res.status(400).json({ error: "Title and body are required" });
}

const item = {
id: `manual-${randomUUID()}`,
type,
actor: "You",
action: "created an insight",
title,
body,
time: "Just now",
group: "Today",
meta: "Manual insight",
image: null,
progress: null,
};

manualItems.unshift(item);
req.app.get("io")?.emit("feed-created", item);
res.status(201).json({ item });
};
143 changes: 143 additions & 0 deletions backend/controllers/insights.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import supabase from "../config/db.js";

const fallbackContributors = ["Alex Rivera", "Casey Morgan", "Jordan Smith", "Riley Lee"];

function relativeTime(value) {
if (!value) return "Recently";
const timestamp = new Date(value).getTime();
if (Number.isNaN(timestamp)) return "Recently";
const minutes = Math.max(1, Math.floor((Date.now() - timestamp) / 60000));
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}

function statusLabel(status) {
if (status === "in_progress") return "In Progress";
if (status === "done") return "Done";
return "Todo";
}

function buildHeatmap(tasks = [], messages = []) {
const total = tasks.length + messages.length;
return Array.from({ length: 365 }, (_, index) => {
const value = (index * 7 + total * 3 + Math.floor(index / 13)) % 6;
return value;
});
}

function countByStatus(tasks = []) {
return tasks.reduce(
(acc, task) => {
if (task.status === "done") acc.done += 1;
else if (task.status === "in_progress") acc.in_progress += 1;
else acc.todo += 1;
return acc;
},
{ todo: 0, in_progress: 0, review: 0, done: 0 }
);
}
Comment thread
Shriii19 marked this conversation as resolved.

async function loadSourceData() {
const [{ data: tasks, error: tasksError }, { data: messages, error: messagesError }] =
await Promise.all([
supabase.from("tasks").select("*"),
supabase.from("messages").select("*"),
]);

if (tasksError) throw tasksError;
if (messagesError) throw messagesError;

return {
tasks: tasks || [],
messages: messages || [],
};
}

export const getOverviewInsights = async (req, res) => {
try {
const { tasks, messages } = await loadSourceData();
const counts = countByStatus(tasks);
const completed = counts.done;
const active = counts.in_progress;
const total = tasks.length;
const velocity = total ? Number(((completed / total) * 100).toFixed(1)) : 0;
const momentum = Math.min(100, Math.round(velocity + active * 4 + messages.length));

const recentActivity = [
...tasks.slice(-4).map((task) => ({
id: `task-${task.id}`,
label: `${task.title || "Untitled task"} moved to ${statusLabel(task.status)}`,
time: relativeTime(task.created_at),
})),
...messages.slice(-3).map((message) => ({
id: `message-${message.id}`,
label: `${message.username || "Team member"} shared an update`,
time: relativeTime(message.created_at),
})),
].slice(-5).reverse();

res.status(200).json({
projectName: "Project Alpha",
velocity,
momentum,
activeTasks: active,
completedTasks: completed,
heatmap: buildHeatmap(tasks, messages),
recentActivity,
topContributors: fallbackContributors.slice(0, Math.max(3, Math.min(4, messages.length || 3))),
});
} catch (error) {
console.error("Error loading overview insights:", error);
res.status(500).json({ error: "Failed to load overview insights" });
}
};

export const getTaskInsights = async (req, res) => {
try {
const { tasks } = await loadSourceData();
const counts = countByStatus(tasks);
const total = Math.max(1, tasks.length);

const stages = [
{ label: "Todo", value: Number((counts.todo * 1.2 + 1).toFixed(1)), active: counts.todo > 0 },
{ label: "In Progress", value: Number((counts.in_progress * 1.5 + 1).toFixed(1)), active: counts.in_progress > 0 },
{ label: "Review", value: Number((counts.review * 1.1 + 0.8).toFixed(1)), active: false },
{ label: "Total Cycle", value: Number(((tasks.length + counts.in_progress + counts.done) / total * 4).toFixed(1)), active: false },
];

const flowNodes = [
{ label: "Todo", sub: "Queue", value: counts.todo, active: counts.todo >= counts.in_progress && counts.todo >= counts.done },
{ label: "In Progress", sub: "Active", value: counts.in_progress, active: counts.in_progress > 0 },
{ label: "Review", sub: "Verify", value: counts.review, active: false },
{ label: "Done", sub: "Archived", value: counts.done, active: counts.done > 0 && counts.done >= counts.in_progress },
];

const history = tasks.slice(-12).reverse().map((task, index) => ({
id: String(task.id || index),
task: task.title || `FLOW-${1280 + index}: Untitled task`,
assignee: fallbackContributors[index % fallbackContributors.length],
avatar: `https://i.pravatar.cc/96?u=${encodeURIComponent(String(task.id || index))}`,
state: statusLabel(task.status),
time: task.created_at ? new Date(task.created_at).toLocaleString() : "Recently",
trigger: task.status === "done" ? "Completion Event" : "System Trigger",
transition: relativeTime(task.created_at),
}));

res.status(200).json({
summary: {
totalTasks: tasks.length,
completedTasks: counts.done,
activeTasks: counts.in_progress,
completionRate: Math.round((counts.done / total) * 100),
},
stages,
flowNodes,
history,
});
} catch (error) {
console.error("Error loading task insights:", error);
res.status(500).json({ error: "Failed to load task insights" });
}
};
8 changes: 8 additions & 0 deletions backend/routes/analytics.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import express from "express";
import { getAnalytics } from "../controllers/analytics.controller.js";

const router = express.Router();

router.get("/", getAnalytics);

export default router;
9 changes: 9 additions & 0 deletions backend/routes/feed.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import express from "express";
import { createFeedItem, getFeedItems } from "../controllers/feed.controller.js";

const router = express.Router();

router.get("/", getFeedItems);
router.post("/", createFeedItem);

export default router;
9 changes: 9 additions & 0 deletions backend/routes/insights.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import express from "express";
import { getOverviewInsights, getTaskInsights } from "../controllers/insights.controller.js";

const router = express.Router();

router.get("/overview", getOverviewInsights);
router.get("/tasks", getTaskInsights);

export default router;
8 changes: 7 additions & 1 deletion backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import http from "http";
import { Server } from "socket.io";
import chatRoutes from "./routes/chat.routes.js";
import taskRoutes from "./routes/tasks.routes.js";
import analyticsRoutes from "./routes/analytics.routes.js";
import feedRoutes from "./routes/feed.routes.js";
import insightsRoutes from "./routes/insights.routes.js";

dotenv.config();

Expand Down Expand Up @@ -32,6 +35,9 @@ app.get("/", (req, res) => {

app.use("/api/chat", chatRoutes);
app.use("/api/tasks", taskRoutes);
app.use("/api/analytics", analyticsRoutes);
app.use("/api/feed", feedRoutes);
app.use("/api/insights", insightsRoutes);
Comment thread
Shriii19 marked this conversation as resolved.

io.on("connection", (socket) => {
console.log("⚡ User connected:", socket.id);
Expand Down Expand Up @@ -92,4 +98,4 @@ const PORT = process.env.PORT || 5000;

server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
});
Loading
Loading