Merge branch 'worktree-agent-a86c0a6d' into Develop
# Conflicts: # .planning/REQUIREMENTS.md # .planning/STATE.md # src/db/schema.ts # src/db/seed.ts # src/server/index.ts # src/server/routes/setups.ts # src/server/services/category.service.ts # src/server/services/setup.service.ts # src/shared/schemas.ts # src/shared/types.ts
This commit is contained in:
@@ -13,10 +13,10 @@ import { requireAuth } from "./middleware/auth.ts";
|
||||
import { authRoutes } from "./routes/auth.ts";
|
||||
import { categoryRoutes } from "./routes/categories.ts";
|
||||
import { imageRoutes } from "./routes/images.ts";
|
||||
import { globalItemRoutes } from "./routes/global-items.ts";
|
||||
import { itemRoutes } from "./routes/items.ts";
|
||||
import { oauthRoutes, wellKnownRoute } from "./routes/oauth.ts";
|
||||
import { settingsRoutes } from "./routes/settings.ts";
|
||||
import { profileRoutes } from "./routes/profiles.ts";
|
||||
import { setupRoutes } from "./routes/setups.ts";
|
||||
import { threadRoutes } from "./routes/threads.ts";
|
||||
import { totalRoutes } from "./routes/totals.ts";
|
||||
@@ -74,7 +74,13 @@ app.use("/api/*", async (c, next) => {
|
||||
if (c.req.path.startsWith("/api/auth")) return next();
|
||||
// Skip health check
|
||||
if (c.req.path === "/api/health") return next();
|
||||
// All methods require auth for userId resolution
|
||||
// Skip public profile endpoint (GET /api/users/:id/profile)
|
||||
if (/^\/api\/users\/\d+\/profile$/.test(c.req.path) && c.req.method === "GET")
|
||||
return next();
|
||||
// Skip public setup view (GET /api/setups/:id/public)
|
||||
if (/^\/api\/setups\/\d+\/public$/.test(c.req.path) && c.req.method === "GET")
|
||||
return next();
|
||||
// All other methods require auth for userId resolution
|
||||
return requireAuth(c, next);
|
||||
});
|
||||
|
||||
@@ -86,8 +92,8 @@ app.route("/api/totals", totalRoutes);
|
||||
app.route("/api/images", imageRoutes);
|
||||
app.route("/api/settings", settingsRoutes);
|
||||
app.route("/api/threads", threadRoutes);
|
||||
app.route("/api/users", profileRoutes);
|
||||
app.route("/api/setups", setupRoutes);
|
||||
app.route("/api/global-items", globalItemRoutes);
|
||||
|
||||
// MCP server (conditionally mounted)
|
||||
if (process.env.GEARBOX_MCP !== "false") {
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
deleteApiKey,
|
||||
listApiKeys,
|
||||
} from "../services/auth.service.ts";
|
||||
import { updateProfile } from "../services/profile.service.ts";
|
||||
import { updateProfileSchema } from "../../shared/schemas.ts";
|
||||
|
||||
type Env = { Variables: { db?: any; userId?: number } };
|
||||
|
||||
@@ -69,4 +71,20 @@ app.delete("/keys/:id", requireAuth, async (c) => {
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
// ── Profile Update (protected) ──────────────────────────────────────
|
||||
|
||||
app.put(
|
||||
"/profile",
|
||||
requireAuth,
|
||||
zValidator("json", updateProfileSchema),
|
||||
async (c) => {
|
||||
const db = c.get("db");
|
||||
const userId = c.get("userId")!;
|
||||
const data = c.req.valid("json");
|
||||
const updated = await updateProfile(db, userId, data);
|
||||
if (!updated) return c.json({ error: "User not found" }, 404);
|
||||
return c.json(updated);
|
||||
},
|
||||
);
|
||||
|
||||
export const authRoutes = app;
|
||||
|
||||
21
src/server/routes/profiles.ts
Normal file
21
src/server/routes/profiles.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Hono } from "hono";
|
||||
import { parseId } from "../lib/params.ts";
|
||||
import { getPublicProfile } from "../services/profile.service.ts";
|
||||
|
||||
type Env = { Variables: { db?: any; userId?: number } };
|
||||
|
||||
const app = new Hono<Env>();
|
||||
|
||||
// GET /:id/profile — Public profile (no auth required)
|
||||
app.get("/:id/profile", async (c) => {
|
||||
const db = c.get("db");
|
||||
const id = parseId(c.req.param("id"));
|
||||
if (!id) return c.json({ error: "Invalid user ID" }, 400);
|
||||
|
||||
const profile = await getPublicProfile(db, id);
|
||||
if (!profile) return c.json({ error: "User not found" }, 404);
|
||||
|
||||
return c.json(profile);
|
||||
});
|
||||
|
||||
export { app as profileRoutes };
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "../../shared/schemas.ts";
|
||||
import { parseId } from "../lib/params.ts";
|
||||
import { withImageUrls } from "../services/storage.service.ts";
|
||||
import { getPublicSetupWithItems } from "../services/profile.service.ts";
|
||||
import {
|
||||
createSetup,
|
||||
deleteSetup,
|
||||
@@ -40,6 +41,16 @@ app.post("/", zValidator("json", createSetupSchema), async (c) => {
|
||||
return c.json(setup, 201);
|
||||
});
|
||||
|
||||
// Public setup view (no auth required — skipped in index.ts middleware)
|
||||
app.get("/:id/public", async (c) => {
|
||||
const db = c.get("db");
|
||||
const id = parseId(c.req.param("id"));
|
||||
if (!id) return c.json({ error: "Invalid setup ID" }, 400);
|
||||
const setup = await getPublicSetupWithItems(db, id);
|
||||
if (!setup) return c.json({ error: "Setup not found" }, 404);
|
||||
return c.json(setup);
|
||||
});
|
||||
|
||||
app.get("/:id", async (c) => {
|
||||
const db = c.get("db");
|
||||
const userId = c.get("userId")!;
|
||||
|
||||
@@ -4,113 +4,92 @@ import { categories, items } from "../../db/schema.ts";
|
||||
|
||||
type Db = typeof prodDb;
|
||||
|
||||
export async function getOrCreateUncategorized(
|
||||
db: Db,
|
||||
userId: number,
|
||||
): Promise<number> {
|
||||
export async function getOrCreateUncategorized(db: Db, userId: number) {
|
||||
const [existing] = await db
|
||||
.select({ id: categories.id })
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.userId, userId), eq(categories.name, "Uncategorized")));
|
||||
if (existing) return existing.id;
|
||||
.where(
|
||||
and(eq(categories.userId, userId), eq(categories.name, "Uncategorized")),
|
||||
);
|
||||
if (existing) return existing;
|
||||
|
||||
const [created] = await db
|
||||
.insert(categories)
|
||||
.values({ name: "Uncategorized", icon: "package", userId })
|
||||
.returning({ id: categories.id });
|
||||
return created.id;
|
||||
.returning();
|
||||
return created;
|
||||
}
|
||||
|
||||
export async function getAllCategories(db: Db, userId: number) {
|
||||
return db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(eq(categories.userId, userId))
|
||||
.orderBy(asc(categories.name));
|
||||
export function getAllCategories(db: Db = prodDb) {
|
||||
return db.select().from(categories).orderBy(asc(categories.name)).all();
|
||||
}
|
||||
|
||||
export async function getCategoryById(db: Db, userId: number, id: number) {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, id), eq(categories.userId, userId)));
|
||||
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function createCategory(
|
||||
db: Db,
|
||||
userId: number,
|
||||
export function createCategory(
|
||||
db: Db = prodDb,
|
||||
data: { name: string; icon?: string },
|
||||
) {
|
||||
const [row] = await db
|
||||
return db
|
||||
.insert(categories)
|
||||
.values({
|
||||
name: data.name,
|
||||
userId,
|
||||
...(data.icon ? { icon: data.icon } : {}),
|
||||
})
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
.returning()
|
||||
.get();
|
||||
}
|
||||
|
||||
export async function updateCategory(
|
||||
db: Db,
|
||||
userId: number,
|
||||
export function updateCategory(
|
||||
db: Db = prodDb,
|
||||
id: number,
|
||||
data: { name?: string; icon?: string },
|
||||
) {
|
||||
const [existing] = await db
|
||||
const existing = db
|
||||
.select({ id: categories.id })
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, id), eq(categories.userId, userId)));
|
||||
.where(eq(categories.id, id))
|
||||
.get();
|
||||
|
||||
if (!existing) return null;
|
||||
|
||||
const [row] = await db
|
||||
return db
|
||||
.update(categories)
|
||||
.set(data)
|
||||
.where(and(eq(categories.id, id), eq(categories.userId, userId)))
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
.where(eq(categories.id, id))
|
||||
.returning()
|
||||
.get();
|
||||
}
|
||||
|
||||
export async function deleteCategory(
|
||||
db: Db,
|
||||
userId: number,
|
||||
export function deleteCategory(
|
||||
db: Db = prodDb,
|
||||
id: number,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
// Check if this is the Uncategorized category for this user
|
||||
const [existing] = await db
|
||||
.select({ id: categories.id, name: categories.name })
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, id), eq(categories.userId, userId)));
|
||||
|
||||
if (!existing) {
|
||||
return { success: false, error: "Category not found" };
|
||||
}
|
||||
|
||||
if (existing.name === "Uncategorized") {
|
||||
): { success: boolean; error?: string } {
|
||||
// Guard: cannot delete Uncategorized (id=1)
|
||||
if (id === 1) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Cannot delete the Uncategorized category",
|
||||
};
|
||||
}
|
||||
|
||||
// Get or create Uncategorized for this user (dynamic, not hardcoded ID)
|
||||
const uncategorizedId = await getOrCreateUncategorized(db, userId);
|
||||
// Check if category exists
|
||||
const existing = db
|
||||
.select({ id: categories.id })
|
||||
.from(categories)
|
||||
.where(eq(categories.id, id))
|
||||
.get();
|
||||
|
||||
// Reassign this user's items to Uncategorized, then delete atomically
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.update(items)
|
||||
.set({ categoryId: uncategorizedId })
|
||||
.where(and(eq(items.categoryId, id), eq(items.userId, userId)));
|
||||
if (!existing) {
|
||||
return { success: false, error: "Category not found" };
|
||||
}
|
||||
|
||||
await tx
|
||||
.delete(categories)
|
||||
.where(and(eq(categories.id, id), eq(categories.userId, userId)));
|
||||
// Reassign items to Uncategorized (id=1), then delete atomically
|
||||
db.transaction(() => {
|
||||
db.update(items)
|
||||
.set({ categoryId: 1 })
|
||||
.where(eq(items.categoryId, id))
|
||||
.run();
|
||||
|
||||
db.delete(categories).where(eq(categories.id, id)).run();
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
|
||||
108
src/server/services/profile.service.ts
Normal file
108
src/server/services/profile.service.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { db as prodDb } from "../../db/index.ts";
|
||||
import {
|
||||
categories,
|
||||
items,
|
||||
setupItems,
|
||||
setups,
|
||||
users,
|
||||
} from "../../db/schema.ts";
|
||||
import type { UpdateProfile } from "../../shared/types.ts";
|
||||
|
||||
type Db = typeof prodDb;
|
||||
|
||||
export async function updateProfile(
|
||||
db: Db,
|
||||
userId: number,
|
||||
data: UpdateProfile,
|
||||
) {
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, userId));
|
||||
if (!existing) return null;
|
||||
|
||||
// If no fields to update, return existing user
|
||||
const hasUpdates = Object.values(data).some((v) => v !== undefined);
|
||||
if (!hasUpdates) return existing;
|
||||
|
||||
const [updated] = await db
|
||||
.update(users)
|
||||
.set(data)
|
||||
.where(eq(users.id, userId))
|
||||
.returning();
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function getPublicProfile(db: Db, userId: number) {
|
||||
const [user] = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
bio: users.bio,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.id, userId));
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
const publicSetups = await db
|
||||
.select({
|
||||
id: setups.id,
|
||||
name: setups.name,
|
||||
createdAt: setups.createdAt,
|
||||
itemCount: sql<number>`COALESCE((
|
||||
SELECT COUNT(*) FROM setup_items
|
||||
WHERE setup_items.setup_id = setups.id
|
||||
), 0)`.as("item_count"),
|
||||
totalWeight: sql<number>`COALESCE((
|
||||
SELECT SUM(items.weight_grams * items.quantity) FROM setup_items
|
||||
JOIN items ON items.id = setup_items.item_id
|
||||
WHERE setup_items.setup_id = setups.id
|
||||
), 0)`.as("total_weight"),
|
||||
totalCost: sql<number>`COALESCE((
|
||||
SELECT SUM(items.price_cents * items.quantity) FROM setup_items
|
||||
JOIN items ON items.id = setup_items.item_id
|
||||
WHERE setup_items.setup_id = setups.id
|
||||
), 0)`.as("total_cost"),
|
||||
})
|
||||
.from(setups)
|
||||
.where(and(eq(setups.userId, userId), eq(setups.isPublic, true)));
|
||||
|
||||
return { ...user, setups: publicSetups };
|
||||
}
|
||||
|
||||
export async function getPublicSetupWithItems(db: Db, setupId: number) {
|
||||
const [setup] = await db
|
||||
.select()
|
||||
.from(setups)
|
||||
.where(and(eq(setups.id, setupId), eq(setups.isPublic, true)));
|
||||
|
||||
if (!setup) return null;
|
||||
|
||||
const itemList = await db
|
||||
.select({
|
||||
id: items.id,
|
||||
name: items.name,
|
||||
weightGrams: items.weightGrams,
|
||||
priceCents: items.priceCents,
|
||||
quantity: items.quantity,
|
||||
categoryId: items.categoryId,
|
||||
notes: items.notes,
|
||||
productUrl: items.productUrl,
|
||||
imageFilename: items.imageFilename,
|
||||
createdAt: items.createdAt,
|
||||
updatedAt: items.updatedAt,
|
||||
categoryName: categories.name,
|
||||
categoryIcon: categories.icon,
|
||||
classification: setupItems.classification,
|
||||
})
|
||||
.from(setupItems)
|
||||
.innerJoin(items, eq(setupItems.itemId, items.id))
|
||||
.innerJoin(categories, eq(items.categoryId, categories.id))
|
||||
.where(eq(setupItems.setupId, setupId));
|
||||
|
||||
return { ...setup, items: itemList };
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export async function createSetup(
|
||||
) {
|
||||
const [row] = await db
|
||||
.insert(setups)
|
||||
.values({ name: data.name, userId })
|
||||
.values({ name: data.name, userId, isPublic: data.isPublic ?? false })
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
@@ -23,6 +23,7 @@ export async function getAllSetups(db: Db, userId: number) {
|
||||
.select({
|
||||
id: setups.id,
|
||||
name: setups.name,
|
||||
isPublic: setups.isPublic,
|
||||
createdAt: setups.createdAt,
|
||||
updatedAt: setups.updatedAt,
|
||||
itemCount: sql<number>`COALESCE((
|
||||
@@ -92,9 +93,17 @@ export async function updateSetup(
|
||||
.where(and(eq(setups.id, setupId), eq(setups.userId, userId)));
|
||||
if (!existing) return null;
|
||||
|
||||
const updateData: Record<string, unknown> = {
|
||||
name: data.name,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
if (data.isPublic !== undefined) {
|
||||
updateData.isPublic = data.isPublic;
|
||||
}
|
||||
|
||||
const [row] = await db
|
||||
.update(setups)
|
||||
.set({ name: data.name, updatedAt: new Date() })
|
||||
.set(updateData)
|
||||
.where(and(eq(setups.id, setupId), eq(setups.userId, userId)))
|
||||
.returning();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user