import { test } from "node:test"; import assert from "node:assert/strict"; import path from "node:path"; import { fileURLToPath } from "node:url"; import dotenv from "dotenv"; import getPool from "../lib/server/db"; import { createBucket, deleteBucket, listBuckets, updateBucket } from "../lib/server/buckets"; import { ensureTagsForGroup } from "../lib/server/tags"; import { cleanupTestData, uniqueInviteCode } from "./test-helpers"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const envLoaded = dotenv.config({ path: path.resolve(__dirname, "../../../.env") }); const hasDb = Boolean(process.env.DATABASE_URL); test("buckets CRUD", async t => { if (!hasDb) { t.skip("DATABASE_URL not set"); return; } if (envLoaded.error) t.diagnostic(String(envLoaded.error)); const pool = getPool(); const client = await pool.connect(); let userId: number | null = null; let groupId: number | null = null; try { const userRes = await client.query( "insert into users(email, password_hash) values($1,$2) returning id", [`bucket_${Date.now()}@example.com`, "hash"] ); userId = userRes.rows[0].id as number; const groupRes = await client.query( "insert into groups(name, invite_code, created_by) values($1,$2,$3) returning id", ["Buckets Test", uniqueInviteCode("B"), userId] ); groupId = groupRes.rows[0].id as number; await client.query( "insert into group_members(group_id, user_id, role) values($1,$2,'GROUP_ADMIN')", [groupId, userId] ); await ensureTagsForGroup({ userId, groupId, tags: ["groceries", "weekly"] }); const bucket = await createBucket({ groupId, userId, name: "Groceries", description: "Weekly groceries", iconKey: "food", budgetLimitDollars: 200, tags: ["groceries", "weekly"] }); const list = await listBuckets(groupId); assert.equal(list.length, 1); assert.equal(list[0].id, bucket.id); assert.deepEqual(list[0].tags.sort(), ["groceries", "weekly"]); const updated = await updateBucket({ id: bucket.id, groupId, userId, name: "Groceries+", description: "Updated", iconKey: "food", budgetLimitDollars: 250, tags: ["groceries"] }); assert.ok(updated); assert.equal(updated?.name, "Groceries+"); assert.deepEqual(updated?.tags.sort(), ["groceries"]); await deleteBucket({ id: bucket.id, groupId, userId }); const listAfter = await listBuckets(groupId); assert.equal(listAfter.length, 0); } finally { await cleanupTestData(client, { userIds: [userId], groupId }); client.release(); } });