feat: auth foundation, similar tools, costs, redundancy, anonymous voting
This commit is contained in:
@@ -55,6 +55,7 @@ async function seedAdminUser(): Promise<void> {
|
||||
username: adminUsername,
|
||||
passwordHash,
|
||||
role: "admin",
|
||||
tier: "enterprise",
|
||||
});
|
||||
logger.info({ username: adminUsername }, "Admin user created");
|
||||
} catch (err) {
|
||||
@@ -62,9 +63,79 @@ async function seedAdminUser(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureToolRelationsTable(): Promise<void> {
|
||||
try {
|
||||
const exists = await db.execute(
|
||||
sql`SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'tool_relations')`,
|
||||
);
|
||||
const rows = exists.rows as [{ exists: boolean }];
|
||||
if (rows[0]?.exists) return;
|
||||
|
||||
await db.execute(
|
||||
sql`CREATE TABLE "tool_relations" ("id" serial NOT NULL, "tool_id" integer NOT NULL REFERENCES "tools"("id") ON DELETE CASCADE, "related_tool_id" integer NOT NULL REFERENCES "tools"("id") ON DELETE CASCADE, "relation_type" text NOT NULL DEFAULT 'similar', "notes" text, "created_by" integer REFERENCES "users"("id"), "created_at" timestamp with time zone NOT NULL DEFAULT NOW())`,
|
||||
);
|
||||
await db.execute(sql`ALTER TABLE "tool_relations" ADD PRIMARY KEY ("id")`);
|
||||
logger.info("tool_relations table created");
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to ensure tool_relations table");
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureToolCostsTable(): Promise<void> {
|
||||
try {
|
||||
const exists = await db.execute(
|
||||
sql`SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'tool_costs')`,
|
||||
);
|
||||
const rows = exists.rows as [{ exists: boolean }];
|
||||
if (rows[0]?.exists) return;
|
||||
|
||||
await db.execute(
|
||||
sql`CREATE TABLE "tool_costs" ("id" serial NOT NULL, "tool_id" integer NOT NULL REFERENCES "tools"("id") ON DELETE CASCADE, "license_type" text NOT NULL DEFAULT 'free', "cost" numeric(10,2), "currency" text DEFAULT 'EUR', "renewal_date" timestamp with time zone, "notes" text, "created_by" integer REFERENCES "users"("id"), "created_at" timestamp with time zone NOT NULL DEFAULT NOW())`,
|
||||
);
|
||||
await db.execute(sql`ALTER TABLE "tool_costs" ADD PRIMARY KEY ("id")`);
|
||||
logger.info("tool_costs table created");
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to ensure tool_costs table");
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureVoterTokenColumn(): Promise<void> {
|
||||
try {
|
||||
const exists = await db.execute(
|
||||
sql`SELECT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'ratings' AND column_name = 'voter_token')`,
|
||||
);
|
||||
const rows = exists.rows as [{ exists: boolean }];
|
||||
if (rows[0]?.exists) return;
|
||||
|
||||
await db.execute(sql`ALTER TABLE "ratings" ADD COLUMN "voter_token" text`);
|
||||
logger.info("voter_token column added to ratings");
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to add voter_token column");
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureAdminTier(): Promise<void> {
|
||||
try {
|
||||
const result = await db
|
||||
.update(usersTable)
|
||||
.set({ tier: "enterprise" })
|
||||
.where(sql`role = 'admin' AND (tier IS NULL OR tier = 'free')`)
|
||||
.returning({ id: usersTable.id, username: usersTable.username });
|
||||
if (result.length > 0) {
|
||||
logger.info({ count: result.length }, "Admin users upgraded to enterprise tier");
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to upgrade admin tier");
|
||||
}
|
||||
}
|
||||
|
||||
async function start(): Promise<void> {
|
||||
await ensureSessionsTable();
|
||||
await ensureToolRelationsTable();
|
||||
await ensureToolCostsTable();
|
||||
await ensureVoterTokenColumn();
|
||||
await seedAdminUser();
|
||||
await ensureAdminTier();
|
||||
|
||||
app.listen(port, (err) => {
|
||||
if (err) {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { type Request, type Response, type NextFunction } from "express";
|
||||
|
||||
const TIER_FEATURES: Record<string, string[]> = {
|
||||
free: ["browse", "rate", "search"],
|
||||
premium: ["browse", "rate", "search", "similar-tools", "costs", "redundancy", "analytics-advanced"],
|
||||
enterprise: ["browse", "rate", "search", "similar-tools", "costs", "redundancy", "analytics-advanced", "sso", "audit-export", "api-access"],
|
||||
};
|
||||
|
||||
export function hasFeature(tier: string | undefined, feature: string): boolean {
|
||||
const features = TIER_FEATURES[tier ?? "free"] ?? TIER_FEATURES.free;
|
||||
return features.includes(feature);
|
||||
}
|
||||
|
||||
export function requireFeature(feature: string) {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ error: "Authentication required" });
|
||||
return;
|
||||
}
|
||||
if (!hasFeature(req.session.user.tier, feature)) {
|
||||
res.status(403).json({ error: `Feature "${feature}" requires a higher tier` });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Router, type IRouter } from "express";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { db, toolsTable, ratingsTable } from "@workspace/db";
|
||||
import { requireAuth } from "../middleware/auth";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
router.get("/admin/redundancy", requireAuth, async (_req, res): Promise<void> => {
|
||||
const tools = await db.select().from(toolsTable).orderBy(toolsTable.category, toolsTable.name);
|
||||
|
||||
const allRatings = await db
|
||||
.select({ toolId: ratingsTable.toolId, usefulness: ratingsTable.usefulness, usability: ratingsTable.usability })
|
||||
.from(ratingsTable);
|
||||
|
||||
const ratingsByTool = new Map<number, { usefulness: number; usability: number }[]>();
|
||||
for (const r of allRatings) {
|
||||
const arr = ratingsByTool.get(r.toolId) ?? [];
|
||||
arr.push({ usefulness: r.usefulness, usability: r.usability });
|
||||
ratingsByTool.set(r.toolId, arr);
|
||||
}
|
||||
|
||||
function buildStats(t: typeof toolsTable.$inferSelect) {
|
||||
const ratings = ratingsByTool.get(t.id) ?? [];
|
||||
const count = ratings.length;
|
||||
const avgU = count > 0 ? ratings.reduce((s, r) => s + r.usefulness, 0) / count : null;
|
||||
const avgUs = count > 0 ? ratings.reduce((s, r) => s + r.usability, 0) / count : null;
|
||||
return {
|
||||
id: t.id, name: t.name, category: t.category, features: t.features ?? [], tags: t.tags ?? [],
|
||||
ratingCount: count,
|
||||
avgUsefulness: avgU, avgUsability: avgUs,
|
||||
avgCombined: avgU != null && avgUs != null ? (avgU + avgUs) / 2 : null,
|
||||
};
|
||||
}
|
||||
|
||||
const grouped: Record<string, any[]> = {};
|
||||
for (const t of tools) {
|
||||
const g = grouped[t.category] ?? [];
|
||||
g.push(buildStats(t));
|
||||
grouped[t.category] = g;
|
||||
}
|
||||
|
||||
const result = Object.entries(grouped).map(([category, items]) => {
|
||||
const pairs: { a: any; b: any; overlap: number; scoreDiff: number }[] = [];
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
for (let j = i + 1; j < items.length; j++) {
|
||||
const aFeat = new Set(items[i].features);
|
||||
const bFeat = new Set(items[j].features);
|
||||
const shared = [...aFeat].filter((f) => bFeat.has(f)).length;
|
||||
const total = new Set([...aFeat, ...bFeat]).size;
|
||||
const overlap = total > 0 ? Math.round((shared / total) * 100) : 0;
|
||||
const scoreDiff = (items[j].avgCombined ?? 0) - (items[i].avgCombined ?? 0);
|
||||
pairs.push({ a: items[i], b: items[j], overlap, scoreDiff });
|
||||
}
|
||||
}
|
||||
pairs.sort((a, b) => b.overlap - a.overlap || Math.abs(b.scoreDiff) - Math.abs(a.scoreDiff));
|
||||
return { category, tools: items, pairs: pairs.slice(0, 5) };
|
||||
});
|
||||
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -52,6 +52,46 @@ async function getClient(): Promise<Client | null> {
|
||||
}
|
||||
}
|
||||
|
||||
async function upsertUserFromOidc(userinfo: Record<string, unknown>): Promise<{ id: number; tier: string; role: string }> {
|
||||
const sub = String(userinfo.sub ?? "");
|
||||
if (!sub) throw new Error("Missing sub claim");
|
||||
|
||||
const email = typeof userinfo.email === "string" ? userinfo.email : undefined;
|
||||
const preferredUsername = typeof userinfo.preferred_username === "string" ? userinfo.preferred_username : undefined;
|
||||
const name = typeof userinfo.name === "string" ? userinfo.name : preferredUsername;
|
||||
const username = preferredUsername ?? email ?? `oidc-${sub.slice(0, 8)}`;
|
||||
|
||||
const [existing] = await db
|
||||
.select({ id: usersTable.id, tier: usersTable.tier, role: usersTable.role })
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.authProviderId, sub))
|
||||
.limit(1);
|
||||
|
||||
if (existing) {
|
||||
await db
|
||||
.update(usersTable)
|
||||
.set({ email, displayName: name })
|
||||
.where(eq(usersTable.id, existing.id));
|
||||
return existing;
|
||||
}
|
||||
|
||||
const [created] = await db
|
||||
.insert(usersTable)
|
||||
.values({
|
||||
username,
|
||||
email,
|
||||
displayName: name,
|
||||
role: "user",
|
||||
tier: "free",
|
||||
authProvider: "oidc",
|
||||
authProviderId: sub,
|
||||
})
|
||||
.returning({ id: usersTable.id, tier: usersTable.tier, role: usersTable.role });
|
||||
|
||||
logger.info({ username, sub }, "OIDC user created");
|
||||
return created;
|
||||
}
|
||||
|
||||
router.get("/auth/mode", (_req, res): void => {
|
||||
res.json({ mode: isOidcConfigured() ? "oidc" : "local" });
|
||||
});
|
||||
@@ -74,7 +114,7 @@ router.post("/auth/login", async (req, res): Promise<void> => {
|
||||
.where(eq(usersTable.username, String(username)))
|
||||
.limit(1);
|
||||
|
||||
if (!user) {
|
||||
if (!user || !user.passwordHash) {
|
||||
res.status(401).json({ error: "Invalid username or password" });
|
||||
return;
|
||||
}
|
||||
@@ -91,6 +131,7 @@ router.post("/auth/login", async (req, res): Promise<void> => {
|
||||
preferred_username: user.username,
|
||||
email: user.email ?? undefined,
|
||||
role: (user.role as "admin" | "user") ?? "user",
|
||||
tier: (user.tier as "free" | "premium" | "enterprise") ?? "free",
|
||||
isLocal: true,
|
||||
};
|
||||
|
||||
@@ -100,6 +141,7 @@ router.post("/auth/login", async (req, res): Promise<void> => {
|
||||
name: user.username,
|
||||
preferredUsername: user.username,
|
||||
role: user.role,
|
||||
tier: user.tier,
|
||||
isLocal: true,
|
||||
});
|
||||
});
|
||||
@@ -152,13 +194,15 @@ router.get("/auth/callback", async (req, res): Promise<void> => {
|
||||
});
|
||||
|
||||
const userinfo = await client.userinfo(tokenSet.access_token!);
|
||||
const dbUser = await upsertUserFromOidc(userinfo);
|
||||
|
||||
req.session.user = {
|
||||
sub: userinfo.sub,
|
||||
sub: dbUser.id.toString(),
|
||||
email: typeof userinfo.email === "string" ? userinfo.email : undefined,
|
||||
name: typeof userinfo.name === "string" ? userinfo.name : undefined,
|
||||
preferred_username: typeof userinfo.preferred_username === "string" ? userinfo.preferred_username : undefined,
|
||||
role: "user",
|
||||
role: (dbUser.role as "admin" | "user") ?? "user",
|
||||
tier: (dbUser.tier as "free" | "premium" | "enterprise") ?? "free",
|
||||
isLocal: false,
|
||||
};
|
||||
delete req.session.codeVerifier;
|
||||
@@ -198,6 +242,7 @@ router.get("/auth/me", async (req, res): Promise<void> => {
|
||||
name: u.name ?? null,
|
||||
preferredUsername: u.preferred_username ?? null,
|
||||
role: u.role ?? "user",
|
||||
tier: u.tier ?? "free",
|
||||
isLocal: u.isLocal ?? false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Router, type IRouter } from "express";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { db, toolsTable, toolCostsTable } from "@workspace/db";
|
||||
import { requireAuth } from "../middleware/auth";
|
||||
import { requireFeature } from "../middleware/feature";
|
||||
import { writeAuditLog } from "../lib/audit";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
router.get("/tools/:id/costs", async (req, res): Promise<void> => {
|
||||
const toolId = Number(req.params.id);
|
||||
if (isNaN(toolId)) { res.status(400).json({ error: "Invalid id" }); return; }
|
||||
|
||||
const [tool] = await db.select().from(toolsTable).where(eq(toolsTable.id, toolId));
|
||||
if (!tool) { res.status(404).json({ error: "Tool not found" }); return; }
|
||||
|
||||
const costs = await db
|
||||
.select()
|
||||
.from(toolCostsTable)
|
||||
.where(eq(toolCostsTable.toolId, toolId))
|
||||
.orderBy(toolCostsTable.createdAt);
|
||||
|
||||
res.json(costs);
|
||||
});
|
||||
|
||||
router.post("/tools/:id/costs", requireAuth, requireFeature("costs"), async (req, res): Promise<void> => {
|
||||
const toolId = Number(req.params.id);
|
||||
if (isNaN(toolId)) { res.status(400).json({ error: "Invalid id" }); return; }
|
||||
|
||||
const [tool] = await db.select().from(toolsTable).where(eq(toolsTable.id, toolId));
|
||||
if (!tool) { res.status(404).json({ error: "Tool not found" }); return; }
|
||||
|
||||
const { licenseType, cost, currency, renewalDate, notes } = req.body;
|
||||
|
||||
const [entry] = await db.insert(toolCostsTable).values({
|
||||
toolId,
|
||||
licenseType: licenseType ?? "free",
|
||||
cost: cost ?? null,
|
||||
currency: currency ?? "EUR",
|
||||
renewalDate: renewalDate ? new Date(renewalDate) : null,
|
||||
notes: notes ?? null,
|
||||
createdBy: Number(req.session.user!.sub),
|
||||
}).returning();
|
||||
|
||||
await writeAuditLog(req, "tool_cost", entry.id, "create", { toolId, licenseType, cost });
|
||||
res.status(201).json(entry);
|
||||
});
|
||||
|
||||
router.patch("/costs/:id", requireAuth, async (req, res): Promise<void> => {
|
||||
const id = Number(req.params.id);
|
||||
if (isNaN(id)) { res.status(400).json({ error: "Invalid id" }); return; }
|
||||
|
||||
const [existing] = await db.select().from(toolCostsTable).where(eq(toolCostsTable.id, id));
|
||||
if (!existing) { res.status(404).json({ error: "Cost entry not found" }); return; }
|
||||
|
||||
const { licenseType, cost, currency, renewalDate, notes } = req.body;
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (licenseType !== undefined) updateData.licenseType = licenseType;
|
||||
if (cost !== undefined) updateData.cost = cost;
|
||||
if (currency !== undefined) updateData.currency = currency;
|
||||
if (renewalDate !== undefined) updateData.renewalDate = renewalDate ? new Date(renewalDate) : null;
|
||||
if (notes !== undefined) updateData.notes = notes;
|
||||
|
||||
const [updated] = await db.update(toolCostsTable).set(updateData).where(eq(toolCostsTable.id, id)).returning();
|
||||
await writeAuditLog(req, "tool_cost", id, "update", { toolId: existing.toolId, ...updateData });
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.delete("/costs/:id", requireAuth, async (req, res): Promise<void> => {
|
||||
const id = Number(req.params.id);
|
||||
if (isNaN(id)) { res.status(400).json({ error: "Invalid id" }); return; }
|
||||
|
||||
const [existing] = await db.select().from(toolCostsTable).where(eq(toolCostsTable.id, id));
|
||||
if (!existing) { res.status(404).json({ error: "Cost entry not found" }); return; }
|
||||
|
||||
await writeAuditLog(req, "tool_cost", id, "delete", { toolId: existing.toolId });
|
||||
await db.delete(toolCostsTable).where(eq(toolCostsTable.id, id));
|
||||
res.sendStatus(204);
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -6,6 +6,8 @@ import analyticsRouter from "./analytics";
|
||||
import authRouter from "./auth";
|
||||
import usersRouter from "./users";
|
||||
import auditRouter from "./audit";
|
||||
import costsRouter from "./costs";
|
||||
import adminRouter from "./admin";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
@@ -13,6 +15,8 @@ router.use(authRouter);
|
||||
router.use(healthRouter);
|
||||
router.use(toolsRouter);
|
||||
router.use(ratingsRouter);
|
||||
router.use(costsRouter);
|
||||
router.use(adminRouter);
|
||||
router.use(analyticsRouter);
|
||||
router.use(usersRouter);
|
||||
router.use(auditRouter);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Router, type IRouter } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { db, toolsTable, ratingsTable } from "@workspace/db";
|
||||
import {
|
||||
ListToolRatingsParams,
|
||||
@@ -7,9 +7,16 @@ import {
|
||||
CreateRatingBody,
|
||||
} from "@workspace/api-zod";
|
||||
import { requireAuth } from "../middleware/auth";
|
||||
import crypto from "crypto";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
const VOTER_SECRET = process.env.VOTER_SECRET || "dev-voter-secret-change-in-production";
|
||||
|
||||
function computeVoterToken(userId: string): string {
|
||||
return crypto.createHmac("sha256", VOTER_SECRET).update(userId).digest("hex");
|
||||
}
|
||||
|
||||
router.get("/tools/:id/ratings", async (req, res): Promise<void> => {
|
||||
const params = ListToolRatingsParams.safeParse(req.params);
|
||||
if (!params.success) {
|
||||
@@ -51,12 +58,26 @@ router.post("/tools/:id/ratings", requireAuth, async (req, res): Promise<void> =
|
||||
return;
|
||||
}
|
||||
|
||||
const token = computeVoterToken(req.session.user!.sub);
|
||||
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(ratingsTable)
|
||||
.where(and(eq(ratingsTable.toolId, params.data.id), eq(ratingsTable.voterToken, token)))
|
||||
.limit(1);
|
||||
|
||||
if (existing) {
|
||||
res.status(409).json({ error: "You have already reviewed this tool." });
|
||||
return;
|
||||
}
|
||||
|
||||
const [rating] = await db.insert(ratingsTable).values({
|
||||
toolId: params.data.id,
|
||||
usefulness: parsed.data.usefulness,
|
||||
usability: parsed.data.usability,
|
||||
comment: parsed.data.comment ?? null,
|
||||
reviewerName: parsed.data.reviewerName ?? null,
|
||||
voterToken: token,
|
||||
}).returning();
|
||||
|
||||
res.status(201).json(rating);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Router, type IRouter } from "express";
|
||||
import { eq, ilike, desc, sql } from "drizzle-orm";
|
||||
import { db, toolsTable, ratingsTable } from "@workspace/db";
|
||||
import { eq, ilike, desc, sql, and, not } from "drizzle-orm";
|
||||
import { db, toolsTable, ratingsTable, toolRelationsTable } from "@workspace/db";
|
||||
import {
|
||||
ListToolsQueryParams,
|
||||
CreateToolBody,
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
DeleteToolParams,
|
||||
} from "@workspace/api-zod";
|
||||
import { requireAuth } from "../middleware/auth";
|
||||
import { requireFeature } from "../middleware/feature";
|
||||
import { writeAuditLog } from "../lib/audit";
|
||||
|
||||
const router: IRouter = Router();
|
||||
@@ -242,4 +243,122 @@ router.get("/features/all", async (_req, res): Promise<void> => {
|
||||
res.json([...featureSet].sort());
|
||||
});
|
||||
|
||||
// ── Similar Tools ──────────────────────────────────────────
|
||||
|
||||
function computeSimilarityScore(
|
||||
a: typeof toolsTable.$inferSelect,
|
||||
b: typeof toolsTable.$inferSelect,
|
||||
): number {
|
||||
let score = 0;
|
||||
if (a.category === b.category) score += 10;
|
||||
const sharedTags = (a.tags ?? []).filter((t) => (b.tags ?? []).includes(t)).length;
|
||||
score += sharedTags * 3;
|
||||
const sharedFeatures = (a.features ?? []).filter((f) => (b.features ?? []).includes(f)).length;
|
||||
score += sharedFeatures * 2;
|
||||
return score;
|
||||
}
|
||||
|
||||
router.get("/tools/:id/similar", async (req, res): Promise<void> => {
|
||||
const { id } = req.params;
|
||||
const toolId = Number(id);
|
||||
if (isNaN(toolId)) { res.status(400).json({ error: "Invalid id" }); return; }
|
||||
|
||||
const [tool] = await db.select().from(toolsTable).where(eq(toolsTable.id, toolId));
|
||||
if (!tool) { res.status(404).json({ error: "Tool not found" }); return; }
|
||||
|
||||
const allOthers = await db
|
||||
.select()
|
||||
.from(toolsTable)
|
||||
.where(not(eq(toolsTable.id, toolId)));
|
||||
|
||||
const manualRelations = await db
|
||||
.select({
|
||||
id: toolRelationsTable.id,
|
||||
relatedToolId: toolRelationsTable.relatedToolId,
|
||||
relationType: toolRelationsTable.relationType,
|
||||
notes: toolRelationsTable.notes,
|
||||
})
|
||||
.from(toolRelationsTable)
|
||||
.where(eq(toolRelationsTable.toolId, toolId));
|
||||
|
||||
const manualIds = new Set(manualRelations.map((r) => r.relatedToolId));
|
||||
|
||||
const autoSimilar = allOthers
|
||||
.filter((t) => !manualIds.has(t.id))
|
||||
.map((t) => ({ tool: t, score: computeSimilarityScore(tool, t), source: "auto" as const }))
|
||||
.filter((t) => t.score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, 5);
|
||||
|
||||
const manualTools = allOthers.filter((t) => manualIds.has(t.id));
|
||||
|
||||
const allRatings = await db
|
||||
.select({ toolId: ratingsTable.toolId, usefulness: ratingsTable.usefulness, usability: ratingsTable.usability })
|
||||
.from(ratingsTable)
|
||||
.where(sql`${ratingsTable.toolId} = ANY(${sql`ARRAY[${sql.join([...manualIds, ...autoSimilar.map((a) => a.tool.id)].map((id) => sql`${id}`), sql`, `)}]::int[]`})`);
|
||||
|
||||
const ratingsByTool = new Map<number, { usefulness: number; usability: number }[]>();
|
||||
for (const r of allRatings) {
|
||||
const arr = ratingsByTool.get(r.toolId) ?? [];
|
||||
arr.push({ usefulness: r.usefulness, usability: r.usability });
|
||||
ratingsByTool.set(r.toolId, arr);
|
||||
}
|
||||
|
||||
function buildStats(t: typeof toolsTable.$inferSelect) {
|
||||
const ratings = ratingsByTool.get(t.id) ?? [];
|
||||
const count = ratings.length;
|
||||
const avgU = count > 0 ? ratings.reduce((s, r) => s + r.usefulness, 0) / count : null;
|
||||
const avgUs = count > 0 ? ratings.reduce((s, r) => s + r.usability, 0) / count : null;
|
||||
return { ...t, ratingCount: count, avgUsefulness: avgU, avgUsability: avgUs, avgCombined: avgU != null && avgUs != null ? (avgU + avgUs) / 2 : null };
|
||||
}
|
||||
|
||||
const manual = manualRelations.map((r) => {
|
||||
const t = manualTools.find((mt) => mt.id === r.relatedToolId);
|
||||
return t ? { ...buildStats(t), relationId: r.id, relationType: r.relationType, notes: r.notes, source: "manual" as const } : null;
|
||||
}).filter(Boolean);
|
||||
|
||||
const auto = autoSimilar.map((a) => ({ ...buildStats(a.tool), score: a.score, source: a.source }));
|
||||
|
||||
res.json({ manual, auto });
|
||||
});
|
||||
|
||||
router.post("/tools/:id/relations", requireAuth, requireFeature("similar-tools"), async (req, res): Promise<void> => {
|
||||
const toolId = Number(req.params.id);
|
||||
if (isNaN(toolId)) { res.status(400).json({ error: "Invalid id" }); return; }
|
||||
|
||||
const { relatedToolId, relationType, notes } = req.body;
|
||||
if (!relatedToolId) { res.status(400).json({ error: "relatedToolId is required" }); return; }
|
||||
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(toolRelationsTable)
|
||||
.where(and(eq(toolRelationsTable.toolId, toolId), eq(toolRelationsTable.relatedToolId, relatedToolId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing) { res.status(409).json({ error: "Relation already exists" }); return; }
|
||||
|
||||
const [relation] = await db.insert(toolRelationsTable).values({
|
||||
toolId,
|
||||
relatedToolId,
|
||||
relationType: relationType ?? "similar",
|
||||
notes: notes ?? null,
|
||||
createdBy: Number(req.session.user!.sub),
|
||||
}).returning();
|
||||
|
||||
await writeAuditLog(req, "tool_relation", relation.id, "create", { toolId, relatedToolId, relationType });
|
||||
res.status(201).json(relation);
|
||||
});
|
||||
|
||||
router.delete("/tools/relations/:id", requireAuth, async (req, res): Promise<void> => {
|
||||
const id = Number(req.params.id);
|
||||
if (isNaN(id)) { res.status(400).json({ error: "Invalid id" }); return; }
|
||||
|
||||
const [existing] = await db.select().from(toolRelationsTable).where(eq(toolRelationsTable.id, id));
|
||||
if (!existing) { res.status(404).json({ error: "Relation not found" }); return; }
|
||||
|
||||
await writeAuditLog(req, "tool_relation", id, "delete", { toolId: existing.toolId, relatedToolId: existing.relatedToolId });
|
||||
await db.delete(toolRelationsTable).where(eq(toolRelationsTable.id, id));
|
||||
res.sendStatus(204);
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ declare module "express-session" {
|
||||
name?: string;
|
||||
preferred_username?: string;
|
||||
role?: "admin" | "user";
|
||||
tier?: "free" | "premium" | "enterprise";
|
||||
isLocal?: boolean;
|
||||
};
|
||||
codeVerifier?: string;
|
||||
|
||||
@@ -11,6 +11,7 @@ import ToolNew from "@/pages/tool-new";
|
||||
import ToolEdit from "@/pages/tool-edit";
|
||||
import Analytics from "@/pages/analytics";
|
||||
import Admin from "@/pages/admin";
|
||||
import Redundancy from "@/pages/redundancy";
|
||||
import Login from "@/pages/login";
|
||||
import NotFound from "@/pages/not-found";
|
||||
|
||||
@@ -34,6 +35,7 @@ function Router() {
|
||||
<Route path="/tools/:id" component={ToolDetail} />
|
||||
<Route path="/analytics" component={Analytics} />
|
||||
<Route path="/admin" component={Admin} />
|
||||
<Route path="/admin/redundancy" component={Redundancy} />
|
||||
<Route component={NotFound} />
|
||||
</Switch>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, useLocation } from "wouter";
|
||||
import { LayoutDashboard, Wrench, PlusCircle, BarChart3, LogIn, LogOut, User, ShieldCheck } from "lucide-react";
|
||||
import { LayoutDashboard, Wrench, PlusCircle, BarChart3, LogIn, LogOut, User, ShieldCheck, AlertTriangle } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
@@ -14,6 +14,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
|
||||
{ href: "/tools/new", label: "Add Tool", icon: PlusCircle },
|
||||
{ href: "/analytics", label: "Analytics", icon: BarChart3 },
|
||||
...(isAdmin ? [{ href: "/admin", label: "Admin", icon: ShieldCheck }] : []),
|
||||
...(isAdmin ? [{ href: "/admin/redundancy", label: "Redundancy", icon: AlertTriangle }] : []),
|
||||
];
|
||||
|
||||
return (
|
||||
|
||||
@@ -20,6 +20,7 @@ export function useAuth() {
|
||||
const isAuthenticated = !!user && !error;
|
||||
const isAdmin = isAuthenticated && user?.role === "admin";
|
||||
const isLocalMode = authMode?.mode === "local";
|
||||
const tier = isAuthenticated ? user?.tier ?? "free" : "free";
|
||||
|
||||
function login(returnTo?: string) {
|
||||
if (isLocalMode) {
|
||||
@@ -45,6 +46,7 @@ export function useAuth() {
|
||||
isAuthenticated,
|
||||
isAdmin,
|
||||
isLocalMode,
|
||||
tier,
|
||||
login,
|
||||
logout,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { useLocation, Link } from "wouter";
|
||||
import {
|
||||
useListUsers,
|
||||
useCreateUser,
|
||||
@@ -22,7 +22,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Users, ScrollText, ShieldAlert, Plus, Pencil, Trash2, Clock } from "lucide-react";
|
||||
import { Users, ScrollText, ShieldAlert, Plus, Pencil, Trash2, Clock, AlertTriangle } from "lucide-react";
|
||||
import { format } from "date-fns";
|
||||
|
||||
export default function Admin() {
|
||||
@@ -129,10 +129,17 @@ export default function Admin() {
|
||||
return (
|
||||
<Layout>
|
||||
<div className="space-y-6 pb-10">
|
||||
<div>
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight mb-2">Admin Panel</h1>
|
||||
<p className="text-muted-foreground">Manage users and review system changes.</p>
|
||||
</div>
|
||||
<Button asChild variant="outline" size="sm" className="gap-2">
|
||||
<Link href="/admin/redundancy"><AlertTriangle className="w-4 h-4" /> Redundancy Dashboard</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="users">
|
||||
<TabsList className="mb-4">
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Layout } from "@/components/layout";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Star, AlertTriangle } from "lucide-react";
|
||||
import { Link } from "wouter";
|
||||
import { customFetch } from "@workspace/api-client-react";
|
||||
|
||||
export default function RedundancyPage() {
|
||||
const [data, setData] = useState<any[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
customFetch<any[]>("/api/admin/redundancy")
|
||||
.then(setData)
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<AlertTriangle className="w-6 h-6 text-amber-500" />
|
||||
<h1 className="text-3xl font-bold">Redundancy Dashboard</h1>
|
||||
</div>
|
||||
<p className="text-muted-foreground">
|
||||
Tools grouped by category with feature overlap analysis.
|
||||
</p>
|
||||
|
||||
{loading ? (
|
||||
<div className="space-y-6">
|
||||
{Array.from({ length: 3 }).map((_, i) => <Skeleton key={i} className="h-40 rounded-xl" />)}
|
||||
</div>
|
||||
) : data && data.length > 0 ? (
|
||||
<div className="space-y-8">
|
||||
{data.map((group) => (
|
||||
<div key={group.category}>
|
||||
<h2 className="text-xl font-semibold mb-4 capitalize">{group.category}</h2>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
|
||||
{group.tools.map((tool: any) => (
|
||||
<Link key={tool.id} href={`/tools/${tool.id}`}>
|
||||
<Card className="hover-elevate transition-all cursor-pointer hover:border-primary/50">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<span className="font-medium">{tool.name}</span>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
|
||||
<span>{tool.ratingCount} reviews</span>
|
||||
{tool.avgCombined != null && (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span className="flex items-center gap-0.5">
|
||||
<Star className="w-3 h-3 fill-primary text-primary" />
|
||||
{tool.avgCombined.toFixed(1)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="outline">{tool.features.length} features</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{group.pairs.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">Overlap Analysis</h3>
|
||||
{group.pairs.map((pair: any, i: number) => (
|
||||
<Card key={i} className="border-dashed">
|
||||
<CardContent className="p-3 flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||
<span className="font-medium text-sm truncate">{pair.a.name}</span>
|
||||
<span className="text-muted-foreground text-xs shrink-0">vs</span>
|
||||
<span className="font-medium text-sm truncate">{pair.b.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Progress value={pair.overlap} className="w-16 h-2" />
|
||||
<span className="text-xs text-muted-foreground w-8">{pair.overlap}%</span>
|
||||
</div>
|
||||
{pair.scoreDiff !== 0 && (
|
||||
<Badge variant={pair.scoreDiff > 0 ? "default" : "secondary"} className="text-[10px]">
|
||||
{pair.scoreDiff > 0 ? `${pair.b.name} +${pair.scoreDiff.toFixed(1)}` : `${pair.a.name} +${Math.abs(pair.scoreDiff).toFixed(1)}`}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground py-8 text-center">No tools found.</p>
|
||||
)}
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRoute, useLocation } from "wouter";
|
||||
import {
|
||||
useGetTool,
|
||||
@@ -25,9 +25,17 @@ import { Progress } from "@/components/ui/progress";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts";
|
||||
import { ExternalLink, Star, ArrowLeft, Plus, Pencil, Trash2 } from "lucide-react";
|
||||
import { ExternalLink, Star, ArrowLeft, Plus, Pencil, Trash2, Link as LinkIcon } from "lucide-react";
|
||||
import { Link } from "wouter";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useDeleteTool, getListToolsQueryKey } from "@workspace/api-client-react";
|
||||
@@ -41,6 +49,7 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { customFetch } from "@workspace/api-client-react";
|
||||
|
||||
const ratingSchema = z.object({
|
||||
usefulness: z.number().min(1).max(5),
|
||||
@@ -64,6 +73,55 @@ export default function ToolDetail() {
|
||||
const { user, isAdmin } = useAuth();
|
||||
const deleteTool = useDeleteTool();
|
||||
|
||||
const [similarData, setSimilarData] = useState<{ manual: any[]; auto: any[] } | null>(null);
|
||||
const [similarLoading, setSimilarLoading] = useState(false);
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [linkToolId, setLinkToolId] = useState("");
|
||||
const [linkType, setLinkType] = useState("similar");
|
||||
const [linkNotes, setLinkNotes] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
setSimilarLoading(true);
|
||||
customFetch(`/api/tools/${id}/similar`)
|
||||
.then((r) => r.json())
|
||||
.then((data) => setSimilarData(data))
|
||||
.catch(() => {})
|
||||
.finally(() => setSimilarLoading(false));
|
||||
}, [id]);
|
||||
|
||||
async function handleCreateRelation() {
|
||||
if (!linkToolId) return;
|
||||
try {
|
||||
const res = await customFetch(`/api/tools/${id}/relations`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ relatedToolId: Number(linkToolId), relationType: linkType, notes: linkNotes || undefined }),
|
||||
});
|
||||
if (!res.ok) { const e = await res.json(); throw new Error(e.error); }
|
||||
toast({ title: "Relation created" });
|
||||
setLinkDialogOpen(false);
|
||||
setLinkToolId("");
|
||||
setLinkNotes("");
|
||||
setLinkType("similar");
|
||||
const r = await customFetch(`/api/tools/${id}/similar`).then((r2) => r2.json());
|
||||
setSimilarData(r);
|
||||
} catch (err: any) {
|
||||
toast({ title: "Failed to create relation", description: err.message, variant: "destructive" });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteRelation(relationId: number) {
|
||||
try {
|
||||
const res = await customFetch(`/api/tools/relations/${relationId}`, { method: "DELETE" });
|
||||
if (!res.ok) throw new Error("Failed to delete");
|
||||
toast({ title: "Relation deleted" });
|
||||
const r = await customFetch(`/api/tools/${id}/similar`).then((r2) => r2.json());
|
||||
setSimilarData(r);
|
||||
} catch {
|
||||
toast({ title: "Failed to delete relation", variant: "destructive" });
|
||||
}
|
||||
}
|
||||
|
||||
const { data: tool, isLoading: loadingTool } = useGetTool(id, {
|
||||
query: { enabled: !!id, queryKey: getGetToolQueryKey(id) }
|
||||
});
|
||||
@@ -273,6 +331,141 @@ export default function ToolDetail() {
|
||||
<div className="text-center py-10">Tool not found.</div>
|
||||
)}
|
||||
|
||||
{/* Similar Tools Section */}
|
||||
{tool && (
|
||||
<div className="space-y-4 mt-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-xl font-bold">Similar Tools</h3>
|
||||
{isAdmin && (
|
||||
<Button variant="outline" size="sm" onClick={() => setLinkDialogOpen(true)} className="gap-2">
|
||||
<LinkIcon className="w-4 h-4" /> Link Tool
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{similarLoading ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{Array.from({ length: 3 }).map((_, i) => <Skeleton key={i} className="h-20 rounded-lg" />)}
|
||||
</div>
|
||||
) : similarData && (similarData.manual.length > 0 || similarData.auto.length > 0) ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{similarData.manual.map((item: any) => (
|
||||
<Link key={item.relationId} href={`/tools/${item.id}`} className="group">
|
||||
<Card className="hover-elevate transition-all hover:border-primary/50 cursor-pointer h-full">
|
||||
<CardContent className="p-4 flex items-center justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium truncate">{item.name}</span>
|
||||
<Badge variant={item.relationType === "replaces" ? "destructive" : item.relationType === "superseded_by" ? "default" : "secondary"} className="text-[10px] px-1 py-0 shrink-0">
|
||||
{item.relationType === "superseded_by" ? "replaces" : item.relationType}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
|
||||
<span>{item.category}</span>
|
||||
{item.avgCombined != null && (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span className="flex items-center gap-0.5">
|
||||
<Star className="w-3 h-3 fill-primary text-primary" />
|
||||
{item.avgCombined.toFixed(1)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{item.notes && <p className="text-xs text-muted-foreground mt-1 italic">{item.notes}</p>}
|
||||
</div>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity h-7 w-7"
|
||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); handleDeleteRelation(item.relationId); }}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5 text-destructive" />
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
{similarData.auto.map((item: any) => (
|
||||
<Link key={item.id} href={`/tools/${item.id}`} className="group">
|
||||
<Card className="hover-elevate transition-all hover:border-primary/50 cursor-pointer h-full">
|
||||
<CardContent className="p-4 flex items-center gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-medium truncate block">{item.name}</span>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
|
||||
<span>{item.category}</span>
|
||||
{item.avgCombined != null && (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span className="flex items-center gap-0.5">
|
||||
<Star className="w-3 h-3 fill-primary text-primary" />
|
||||
{item.avgCombined.toFixed(1)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span>·</span>
|
||||
<span>Score: {item.score}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : similarData && similarData.manual.length === 0 && similarData.auto.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-4">No similar tools found.</p>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Link Tool Dialog */}
|
||||
<Dialog open={linkDialogOpen} onOpenChange={setLinkDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Link Similar Tool</DialogTitle>
|
||||
<DialogDescription>Manually link this tool to another tool.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Tool ID</label>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="Enter target tool ID"
|
||||
value={linkToolId}
|
||||
onChange={(e) => setLinkToolId(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Relation Type</label>
|
||||
<Select value={linkType} onValueChange={setLinkType}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="similar">Similar</SelectItem>
|
||||
<SelectItem value="replaces">Replaces</SelectItem>
|
||||
<SelectItem value="superseded_by">Superseded By</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Notes (Optional)</label>
|
||||
<Textarea
|
||||
placeholder="Why are these tools related?"
|
||||
value={linkNotes}
|
||||
onChange={(e) => setLinkNotes(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setLinkDialogOpen(false)}>Cancel</Button>
|
||||
<Button onClick={handleCreateRelation} disabled={!linkToolId}>Create Link</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Ratings & Reviews Section */}
|
||||
{tool && (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
|
||||
@@ -241,6 +241,7 @@ export interface AuthUser {
|
||||
/** @nullable */
|
||||
preferredUsername?: string | null;
|
||||
role?: AuthUserRole;
|
||||
tier?: "free" | "premium" | "enterprise";
|
||||
isLocal?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export * from "./generated/api";
|
||||
export * from "./generated/api.schemas";
|
||||
export { setBaseUrl, setAuthTokenGetter } from "./custom-fetch";
|
||||
export { setBaseUrl, setAuthTokenGetter, customFetch } from "./custom-fetch";
|
||||
export type { AuthTokenGetter } from "./custom-fetch";
|
||||
|
||||
@@ -3,3 +3,5 @@ export * from "./ratings";
|
||||
export * from "./users";
|
||||
export * from "./audit-logs";
|
||||
export * from "./sessions";
|
||||
export * from "./tool-relations";
|
||||
export * from "./tool-costs";
|
||||
|
||||
@@ -10,6 +10,7 @@ export const ratingsTable = pgTable("ratings", {
|
||||
usability: integer("usability").notNull(),
|
||||
comment: text("comment"),
|
||||
reviewerName: text("reviewer_name"),
|
||||
voterToken: text("voter_token"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { pgTable, text, serial, integer, numeric, timestamp } from "drizzle-orm/pg-core";
|
||||
import { toolsTable } from "./tools";
|
||||
import { usersTable } from "./users";
|
||||
|
||||
export const toolCostsTable = pgTable("tool_costs", {
|
||||
id: serial("id").primaryKey(),
|
||||
toolId: integer("tool_id").notNull().references(() => toolsTable.id, { onDelete: "cascade" }),
|
||||
licenseType: text("license_type", { enum: ["free", "subscription", "one_time", "usage_based"] }).notNull().default("free"),
|
||||
cost: numeric("cost", { precision: 10, scale: 2 }),
|
||||
currency: text("currency").default("EUR"),
|
||||
renewalDate: timestamp("renewal_date", { withTimezone: true }),
|
||||
notes: text("notes"),
|
||||
createdBy: integer("created_by").references(() => usersTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { pgTable, text, serial, integer, timestamp } from "drizzle-orm/pg-core";
|
||||
import { toolsTable } from "./tools";
|
||||
import { usersTable } from "./users";
|
||||
|
||||
export const toolRelationsTable = pgTable("tool_relations", {
|
||||
id: serial("id").primaryKey(),
|
||||
toolId: integer("tool_id").notNull().references(() => toolsTable.id, { onDelete: "cascade" }),
|
||||
relatedToolId: integer("related_tool_id").notNull().references(() => toolsTable.id, { onDelete: "cascade" }),
|
||||
relationType: text("relation_type", { enum: ["similar", "replaces", "superseded_by"] }).notNull().default("similar"),
|
||||
notes: text("notes"),
|
||||
createdBy: integer("created_by").references(() => usersTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
@@ -5,9 +5,13 @@ import { z } from "zod/v4";
|
||||
export const usersTable = pgTable("users", {
|
||||
id: serial("id").primaryKey(),
|
||||
username: text("username").notNull().unique(),
|
||||
passwordHash: text("password_hash").notNull(),
|
||||
email: text("email"),
|
||||
role: text("role").notNull().default("user"),
|
||||
passwordHash: text("password_hash"),
|
||||
tier: text("tier").notNull().default("free"),
|
||||
authProvider: text("auth_provider").notNull().default("local"),
|
||||
authProviderId: text("auth_provider_id"),
|
||||
displayName: text("display_name"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user