88 lines
2.3 KiB
TypeScript
88 lines
2.3 KiB
TypeScript
import { query, mutation } from "./_generated/server";
|
|
import { v } from "convex/values";
|
|
import { assertOwned, requireUserId } from "./lib/helpers";
|
|
|
|
const accountValidator = v.object({
|
|
_id: v.id("accounts"),
|
|
_creationTime: v.number(),
|
|
userId: v.id("users"),
|
|
name: v.string(),
|
|
type: v.string(),
|
|
iban: v.optional(v.string()),
|
|
openingBalance: v.number(),
|
|
currency: v.string(),
|
|
isArchived: v.boolean(),
|
|
externalId: v.optional(v.string()),
|
|
});
|
|
|
|
export const list = query({
|
|
args: {},
|
|
returns: v.array(accountValidator),
|
|
handler: async (ctx) => {
|
|
const userId = await requireUserId(ctx);
|
|
return await ctx.db
|
|
.query("accounts")
|
|
.withIndex("by_user", (q) => q.eq("userId", userId))
|
|
.collect();
|
|
},
|
|
});
|
|
|
|
export const create = mutation({
|
|
args: {
|
|
name: v.string(),
|
|
type: v.string(),
|
|
iban: v.optional(v.string()),
|
|
openingBalance: v.number(),
|
|
currency: v.optional(v.string()),
|
|
},
|
|
returns: v.id("accounts"),
|
|
handler: async (ctx, args) => {
|
|
const userId = await requireUserId(ctx);
|
|
return await ctx.db.insert("accounts", {
|
|
userId,
|
|
name: args.name,
|
|
type: args.type,
|
|
iban: args.iban,
|
|
openingBalance: args.openingBalance,
|
|
currency: args.currency ?? "EUR",
|
|
isArchived: false,
|
|
});
|
|
},
|
|
});
|
|
|
|
export const update = mutation({
|
|
args: {
|
|
id: v.id("accounts"),
|
|
name: v.optional(v.string()),
|
|
type: v.optional(v.string()),
|
|
iban: v.optional(v.string()),
|
|
openingBalance: v.optional(v.number()),
|
|
isArchived: v.optional(v.boolean()),
|
|
},
|
|
returns: v.null(),
|
|
handler: async (ctx, args) => {
|
|
const userId = await requireUserId(ctx);
|
|
await assertOwned(await ctx.db.get("accounts", args.id), userId, "Konto");
|
|
const { id, ...updates } = args;
|
|
const patch: Record<string, unknown> = {};
|
|
for (const [key, value] of Object.entries(updates)) {
|
|
if (value !== undefined) patch[key] = value;
|
|
}
|
|
if (Object.keys(patch).length > 0) {
|
|
await ctx.db.patch(id, patch);
|
|
}
|
|
return null;
|
|
},
|
|
});
|
|
|
|
export const remove = mutation({
|
|
args: { id: v.id("accounts") },
|
|
returns: v.null(),
|
|
handler: async (ctx, args) => {
|
|
const userId = await requireUserId(ctx);
|
|
await assertOwned(await ctx.db.get("accounts", args.id), userId, "Konto");
|
|
await ctx.db.delete(args.id);
|
|
return null;
|
|
},
|
|
});
|