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 { createSchedule, deleteSchedule, listSchedules, updateSchedule } from "../lib/server/schedules"; 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("schedules 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", [`schedule_${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", ["Schedules Test", uniqueInviteCode("Q"), 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: ["rent", "home"] }); const created = await createSchedule({ groupId, userId, entryType: "SPENDING", amountDollars: 1200, necessity: "NECESSARY", purchaseType: "Rent", notes: "Monthly rent", tags: ["rent", "home"], startsOn: "2026-03-01", frequency: "MONTHLY", intervalCount: 1, endCondition: "NEVER", createEntryNow: false }); const listed = await listSchedules(groupId); assert.equal(listed.length, 1); assert.equal(listed[0].id, created.id); assert.equal(listed[0].frequency, "MONTHLY"); assert.deepEqual(listed[0].tags.sort(), ["home", "rent"]); const updated = await updateSchedule({ id: created.id, groupId, userId, entryType: "SPENDING", amountDollars: 1300, necessity: "NECESSARY", purchaseType: "Rent", notes: "Updated rent", tags: ["rent"], startsOn: "2026-03-01", frequency: "MONTHLY", intervalCount: 1, endCondition: "AFTER_COUNT", endCount: 3, nextRunOn: "2026-04-01", isActive: true }); assert.ok(updated); assert.equal(updated?.amountDollars, 1300); assert.equal(updated?.endCondition, "AFTER_COUNT"); assert.equal(updated?.endCount, 3); assert.deepEqual(updated?.tags, ["rent"]); await deleteSchedule({ id: created.id, groupId, userId }); const afterDelete = await listSchedules(groupId); assert.equal(afterDelete.length, 0); } finally { await cleanupTestData(client, { userIds: [userId], groupId }); client.release(); } });