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
5 changes: 3 additions & 2 deletions backend/src/controllers/community.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ export async function getGraphController(
res: Response
): Promise<void> {
try {
const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 20;
const requestedLimit = typeof req.query.limit === "string" ? Number(req.query.limit) : 20;
const limit = Number.isInteger(requestedLimit) ? Math.max(1, Math.min(20, requestedLimit)) : 20;

const { getGraph } = await import("../processors/community/getGraph.processor.js");
const graph = await getGraph(limit);
Expand All @@ -155,4 +156,4 @@ export async function getGraphController(
const message = error instanceof Error ? error.message : String(error);
res.status(500).json({ error: message });
}
}
}
4 changes: 2 additions & 2 deletions backend/src/processors/community/getGraph.processor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getTrendingGraph, type GraphNode, type GraphEdge } from "../../services/community.service.js";
import { getTrendingGraph } from "../../services/community.service.js";

export async function getGraph(limit = 20): Promise<{ nodes: GraphNode[]; edges: GraphEdge[] }> {
export function getGraph(limit = 20) {
return getTrendingGraph(limit);
}
135 changes: 85 additions & 50 deletions backend/src/services/community.service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { rankTrendingPaths, type PathVote, type RankedCommunityPath } from "./trendingPaths.js";
import { getSession, closeSession } from "./neo4j.service.js";
import { attachExperienceGoals, mapJourneyExperience, mapJourneyGoal, mapJourneyTransition } from "./journeyMapping.js";

Expand Down Expand Up @@ -147,7 +148,7 @@ export async function searchCommunityUsers(
hasVerifiedExperience,
journeyHighlights,
journeyScore
WHERE size(matchingGoals) > 0
WHERE size(matchingGoals) > 0 OR ($topic IS NULL AND $subtopic IS NULL AND size(journeyHighlights) > 0 AND journeyHighlights[0] IS NOT NULL)

WITH
u,
Expand Down Expand Up @@ -434,7 +435,8 @@ export async function toggleUpvote(
WITH u, e, author, rel
WITH u, e, author, rel
WHERE rel IS NULL
MERGE (u)-[:UPVOTED]->(e)
MERGE (u)-[vote:UPVOTED]->(e)
ON CREATE SET vote.createdAt = datetime()
SET author.reputationScore = coalesce(author.reputationScore, 0) + 2
RETURN true AS toggledState
}
Expand Down Expand Up @@ -471,64 +473,97 @@ export interface GraphEdge {
label: string | null;
}

export async function getTrendingGraph(limit = 20): Promise<{ nodes: GraphNode[]; edges: GraphEdge[] }> {
export async function getTrendingGraph(limit = 20): Promise<{
nodes: GraphNode[];
edges: GraphEdge[];
paths: RankedCommunityPath[];
}> {
const session = getSession();
const now = Date.now();
const since = new Date(now - 30 * 86_400_000).toISOString();
const candidateLimit = Math.max(80, limit * 8);

try {
const result = await session.run(
const seedResult = await session.run(
`
MATCH (u1:User)-[:HAS_EXPERIENCE]->(e1:Experience)-[t:TRANSITION]->(e2:Experience)<-[:HAS_EXPERIENCE]-(u2:User)

WITH e1, e2, t, u1, u2, count { (e1)<-[:UPVOTED]-() } AS e1Upvotes, count { (e2)<-[:UPVOTED]-() } AS e2Upvotes

ORDER BY (e1Upvotes + e2Upvotes) DESC, e1.startDate DESC
LIMIT toInteger($limit)

RETURN
e1.id AS e1Id, e1.title AS e1Title, u1.username AS e1Author, e1Upvotes,
e2.id AS e2Id, e2.title AS e2Title, u2.username AS e2Author, e2Upvotes,
t.decisionLabel AS decisionLabel
MATCH (author:User)-[:HAS_EXPERIENCE]->(seed:Experience)
WHERE author.username IS NOT NULL AND NOT coalesce(author.isFlagged, false)
AND EXISTS {
MATCH (seed)-[:TRANSITION]-(neighbor:Experience)<-[:HAS_EXPERIENCE]-(other:User)
WHERE other.username IS NOT NULL AND NOT coalesce(other.isFlagged, false)
}
WITH DISTINCT seed
OPTIONAL MATCH (seed)<-[vote:UPVOTED]-(voter:User)
WHERE NOT EXISTS { MATCH (voter)-[:HAS_EXPERIENCE]->(seed) }
WITH seed, count(DISTINCT voter) AS lifetime,
count(DISTINCT CASE WHEN vote.createdAt >= datetime($since) AND vote.createdAt <= datetime($now) THEN voter END) AS recent
WITH seed, lifetime, recent
ORDER BY recent DESC, lifetime DESC, seed.startDate DESC, seed.id
LIMIT toInteger($candidateLimit)
RETURN seed.id AS id
`,
{ limit }
{ since, now: new Date(now).toISOString(), candidateLimit },
);
const seedIds = seedResult.records.map(record => record.get("id") as string);
if (!seedIds.length) return { nodes: [], edges: [], paths: [] };

const nodesMap = new Map<string, GraphNode>();
const edges: GraphEdge[] = [];

for (const record of result.records) {
const e1Id = record.get("e1Id");
const e2Id = record.get("e2Id");

if (!nodesMap.has(e1Id)) {
nodesMap.set(e1Id, {
id: e1Id,
title: record.get("e1Title"),
authorUsername: record.get("e1Author"),
upvoteCount: Number(record.get("e1Upvotes"))
});
}

if (!nodesMap.has(e2Id)) {
nodesMap.set(e2Id, {
id: e2Id,
title: record.get("e2Title"),
authorUsername: record.get("e2Author"),
upvoteCount: Number(record.get("e2Upvotes"))
});
const edgeResult = await session.run(
`
UNWIND $seedIds AS seedId
MATCH (seed:Experience {id: seedId})
CALL {
WITH seed
MATCH (seed)-[transition:TRANSITION]-(neighbor:Experience)
WITH DISTINCT transition
WITH startNode(transition) AS source, endNode(transition) AS target, transition
MATCH (a:User)-[:HAS_EXPERIENCE]->(source), (b:User)-[:HAS_EXPERIENCE]->(target)
WHERE a.username IS NOT NULL AND b.username IS NOT NULL
AND NOT coalesce(a.isFlagged, false) AND NOT coalesce(b.isFlagged, false)
WITH source, target, transition, min(a.username) AS sourceAuthor, min(b.username) AS targetAuthor
ORDER BY
(CASE WHEN source.id IN $seedIds THEN 1 ELSE 0 END) +
(CASE WHEN target.id IN $seedIds THEN 1 ELSE 0 END) DESC,
source.id, target.id
LIMIT 12
RETURN source, target, sourceAuthor, targetAuthor, transition
}

edges.push({
fromId: e1Id,
toId: e2Id,
label: record.get("decisionLabel") || null
});
RETURN DISTINCT source.id AS fromId, source.title AS fromTitle, sourceAuthor,
target.id AS toId, target.title AS toTitle, targetAuthor, transition.decisionLabel AS label
ORDER BY fromId, toId, label
`,
{ seedIds },
);
const nodes = new Map<string, GraphNode>();
const edges = new Map<string, GraphEdge>();
for (const record of edgeResult.records) {
const fromId = record.get("fromId") as string;
const toId = record.get("toId") as string;
nodes.set(fromId, { id: fromId, title: record.get("fromTitle"), authorUsername: record.get("sourceAuthor"), upvoteCount: 0 });
nodes.set(toId, { id: toId, title: record.get("toTitle"), authorUsername: record.get("targetAuthor"), upvoteCount: 0 });
const key = JSON.stringify([fromId, toId]);
if (!edges.has(key)) edges.set(key, { fromId, toId, label: record.get("label") ?? null });
}
if (!nodes.size) return { nodes: [], edges: [], paths: [] };

return {
nodes: Array.from(nodesMap.values()),
edges
};
const voteResult = await session.run(
`
UNWIND $ids AS id
MATCH (e:Experience {id: id})<-[vote:UPVOTED]-(voter:User)
WHERE NOT EXISTS { MATCH (voter)-[:HAS_EXPERIENCE]->(e) }
WITH e, voter, max(vote.createdAt) AS latestVote
RETURN e.id AS experienceId, elementId(voter) AS voterId, latestVote.epochMillis AS castAt
`,
{ ids: [...nodes.keys()] },
);
const votes: PathVote[] = voteResult.records.map(record => {
const experienceId = record.get("experienceId") as string;
const castAt = record.get("castAt");
nodes.get(experienceId)!.upvoteCount++;
return { experienceId, voterId: record.get("voterId"), castAt: castAt == null ? null : Number(castAt) };
});
const paths = rankTrendingPaths(seedIds, [...nodes.values()], [...edges.values()], votes, now, limit);
return { paths, nodes: paths.flatMap(path => path.nodes), edges: paths.flatMap(path => path.edges) };
} finally {
await closeSession(session);
}
}
}
95 changes: 95 additions & 0 deletions backend/src/services/trendingPaths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import type { GraphEdge, GraphNode } from "./community.service.js";

const DAY = 86_400_000;
const MAX_PATH_EDGES = 12;

export interface PathVote {
experienceId: string;
voterId: string;
castAt: number | null;
}

export interface RankedCommunityPath {
id: string;
nodes: GraphNode[];
edges: GraphEdge[];
recentVoters: number;
lifetimeVoters: number;
}

export function rankTrendingPaths(
seedIds: string[],
nodes: GraphNode[],
edges: GraphEdge[],
votes: PathVote[],
now: number,
limit: number,
): RankedCommunityPath[] {
const nodeById = new Map(nodes.map(node => [node.id, node]));
const votesByNode = new Map<string, PathVote[]>();
for (const vote of votes) {
const entries = votesByNode.get(vote.experienceId) ?? [];
entries.push(vote);
votesByNode.set(vote.experienceId, entries);
}

const adjacent = new Map<string, GraphEdge[]>();
for (const edge of edges) {
for (const id of new Set([edge.fromId, edge.toId])) {
const incident = adjacent.get(id) ?? [];
incident.push(edge);
adjacent.set(id, incident);
}
}

const candidates = new Map<string, { path: RankedCommunityPath; score: number; latest: number }>();
for (const seed of seedIds) {
const ids = new Set([seed]);
const pathEdges = new Set<GraphEdge>();
for (const id of ids) {
if (pathEdges.size >= MAX_PATH_EDGES) break;
for (const edge of adjacent.get(id) ?? []) {
pathEdges.add(edge);
ids.add(edge.fromId);
ids.add(edge.toId);
if (pathEdges.size >= MAX_PATH_EDGES) break;
}
}
if (!pathEdges.size) continue;
const pathNodes = [...ids].map(id => nodeById.get(id)).filter((node): node is GraphNode => !!node);
const id = JSON.stringify([...pathEdges].map(edge => [edge.fromId, edge.toId]).sort());
if (candidates.has(id)) continue;

const lifetime = new Set<string>();
const recent = new Map<string, number>();
for (const nodeId of ids) {
for (const vote of votesByNode.get(nodeId) ?? []) {
lifetime.add(vote.voterId);
if (vote.castAt !== null && vote.castAt >= now - 30 * DAY && vote.castAt <= now) {
recent.set(vote.voterId, Math.max(vote.castAt, recent.get(vote.voterId) ?? -Infinity));
}
}
}
const dates = [...recent.values()];
candidates.set(id, {
path: { id, nodes: pathNodes, edges: [...pathEdges], recentVoters: recent.size, lifetimeVoters: lifetime.size },
score: dates.reduce((sum, time) => sum + 2 ** (-(now - time) / (14 * DAY)), 0),
latest: dates.reduce((latest, time) => Math.max(latest, time), 0),
});
}

const ranked = [...candidates.values()].sort((a, b) =>
b.score - a.score || b.latest - a.latest ||
(a.score === 0 && b.score === 0 ? b.path.lifetimeVoters - a.path.lifetimeVoters : 0) ||
a.path.id.localeCompare(b.path.id),
);
const used = new Set<string>();
const paths: RankedCommunityPath[] = [];
for (const { path } of ranked) {
if (path.nodes.some(node => used.has(node.id))) continue;
paths.push(path);
for (const node of path.nodes) used.add(node.id);
if (paths.length === limit) break;
}
return paths;
}
54 changes: 54 additions & 0 deletions backend/tests/trendingPaths.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { rankTrendingPaths, type PathVote } from "../src/services/trendingPaths.js";

const now = Date.UTC(2026, 10, 14);
const day = 86_400_000;
const node = (id: string) => ({ id, title: id, authorUsername: "author", upvoteCount: 0 });
const edge = (fromId: string, toId: string) => ({ fromId, toId, label: fromId + " to " + toId });
const vote = (experienceId: string, voterId: string, daysAgo: number | null): PathVote => ({
experienceId, voterId, castAt: daysAgo === null ? null : now - daysAgo * day,
});

test("connected paths still display before their first vote", () => {
const edges = [edge("a", "b"), edge("b", "c")];
const paths = rankTrendingPaths(["a", "b", "c"], ["a", "b", "c"].map(node), edges, [], now, 5);
assert.equal(paths.length, 1);
assert.deepEqual(paths[0]?.edges, edges);
assert.equal(paths[0]?.recentVoters, 0);
assert.equal(paths[0]?.lifetimeVoters, 0);
});

test("recent distinct voters outrank lifetime popularity and duplicated votes count once", () => {
const edges = [edge("a", "b"), edge("b", "c"), edge("x", "y")];
const votes = [
vote("a", "recent", 12), vote("b", "recent", 1), vote("c", "second", 4),
vote("x", "old1", null), vote("x", "old2", 40), vote("y", "old3", null),
];
const paths = rankTrendingPaths(["x", "a", "b"], ["a", "b", "c", "x", "y"].map(node), edges, votes, now, 5);
assert.equal(paths.length, 2);
assert.deepEqual(paths[0]?.edges, edges.slice(0, 2));
assert.equal(paths[0]?.recentVoters, 2);
assert.equal(paths[0]?.lifetimeVoters, 2);
assert.equal(paths[1]?.recentVoters, 0);
assert.equal(paths[1]?.lifetimeVoters, 3);
});

test("recent weighting uses the latest vote per voter and ties are stable", () => {
const edges = [edge("a", "b"), edge("x", "y"), edge("j", "k")];
const nodes = ["a", "b", "x", "y", "j", "k"].map(node);
const votes = [vote("a", "u1", 1), vote("b", "u1", 1), vote("x", "u2", 1), vote("j", "u3", 0)];
const paths = rankTrendingPaths(["x", "a", "j"], nodes, edges, votes, now, 3);
assert.deepEqual(paths.map(path => path.edges[0]?.fromId), ["j", "a", "x"]);
});

test("a large hub has a bounded path and cannot take multiple slots", () => {
const edges = Array.from({ length: 16 }, (_, index) => edge("hub", String(index)));
edges.push(edge("x", "y"));
const nodes = [...new Set(edges.flatMap(({ fromId, toId }) => [fromId, toId]))].map(node);
const votes = [vote("hub", "voter", 0), vote("15", "other", 0), vote("x", "popular", null)];
const paths = rankTrendingPaths(["hub", "15", "x"], nodes, edges, votes, now, 3);
assert.equal(paths.length, 2);
assert.equal(paths[0]?.edges.length, 12);
assert.equal(paths[1]?.edges[0]?.fromId, "x");
});
9 changes: 9 additions & 0 deletions frontend/api/community.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ export interface GraphEdge {
export interface CommunityGraph {
nodes: GraphNode[];
edges: GraphEdge[];
paths?: RankedCommunityPath[];
}

export interface RankedCommunityPath {
id: string;
nodes: GraphNode[];
edges: GraphEdge[];
recentVoters: number;
lifetimeVoters: number;
}

export async function getCommunityGraph(limit = 20): Promise<CommunityGraph> {
Expand Down
Loading
Loading