Build a Finance SaaS Platform -14(Transaction API)

Create transaction API and Hook API

Add Transaction API

Add app/api/[[…route]]/transactions.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { z } from "zod"
import { Hono } from "hono";
import { parse, subDays } from "date-fns";
import { zValidator } from "@hono/zod-validator";
import { createId } from "@paralleldrive/cuid2";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";

import { db } from "@/db/drizzle";
import { categories,accounts, transactions, insertTransactionSchema } from "@/db/schema";
import { gte,lte,desc, and, eq, inArray,sql } from "drizzle-orm";

const app = new Hono()
.get("/",
zValidator("query", z.object({
from: z.string().optional(),
to: z.string().optional(),
accountId: z.string().optional(),
})),
clerkMiddleware(), async (c) => {
const auth = getAuth(c);
const { from, to, accountId } = c.req.valid("query");

if( !auth?.userId ) {
return c.json({ error:"Unauthorized!"}, 401);
}

const defaultTo = new Date();
const defaultFrom = subDays(defaultTo, 30);

const startDate = from
? parse(from, "yyyy-MM-dd", new Date() )
: defaultFrom;

const endDate = to
? parse(to, "yyyy-MM-dd", new Date())
: defaultTo;

const data = await db.select({
id: transactions.id,
date: transactions.date,
category: categories.name,
categoryId: transactions.categoryId,
payee : transactions.payee,
amount: transactions.amount,
notes: transactions.notes,
account: accounts.name,
accountId: transactions.accountId,
}).from(transactions)
.innerJoin(accounts, eq(transactions.accountId, accounts.id))
.leftJoin(categories, eq(transactions.categoryId, categories.id))
.where(
and(
accountId ? eq(transactions.accountId, accountId) : undefined,
eq(accounts.userId, auth.userId),
gte(transactions.date, startDate),
lte(transactions.date, endDate),
)
)
.orderBy(desc(transactions.date));

return c.json({ data });
})
.get(
"/:id",
zValidator("param",z.object({
id: z.string().optional(),
})),
clerkMiddleware(),
async (c) => {
const auth = getAuth(c);
const { id } = c.req.valid("param");

if (!id) {
return c.json({ error: "Missing id!" }, 400);
}

if (!auth?.userId) {
return c.json({ error: "Unauthorized!" }, 401);
}

const [data] = await db
.select({
id: transactions.id,
date: transactions.date,
categoryId: transactions.categoryId,
payee : transactions.payee,
amount: transactions.amount,
notes: transactions.notes,
accountId: transactions.accountId,
})
.from(transactions)
.innerJoin(accounts, eq(transactions.accountId, accounts.id))
.where(
and(
eq(transactions.id, id),
eq(accounts.userId, auth.userId),
),
);

if (!data) {
return c.json({ error: "Not Found!"}, 404);
};

return c.json({ data });
}
)
.post(
"/",
clerkMiddleware(),
zValidator('json',insertTransactionSchema.omit({
id: true,
})),
async(c) => {
const auth = getAuth(c);
const values = c.req.valid("json");

if(!auth?.userId){
return c.json({ error:"Unauthorized!"}, 401);
}

const data = await db.insert(transactions).values({
id: createId(),
...values,
}).returning();

return c.json({ data });
})
.post(
"/bulk-delete",
clerkMiddleware(),
zValidator(
"json",
z.object({
ids: z.array(z.string())
}),
),
async (c) =>{
const auth = getAuth(c);
const values = c.req.valid("json");

if (!auth?.userId) {
return c.json({ error: "Unauthorized"}, 401 );
}

const transactionsToDelete = db.$with("transactions_to_delete").as(
db.select({ id: transactions.id }).from(transactions)
.innerJoin(accounts, eq(transactions.accountId, accounts.id ))
.where(and(
inArray(transactions.id, values.ids),
eq(accounts.userId, auth.userId),
)),
);

const data = await db
.with(transactionsToDelete)
.delete(transactions)
.where(
inArray(transactions.id, sql`(select id from ${transactionsToDelete})`)
)
.returning({
id: transactions.id,
});

return c.json({ data });
},
)
.post(
"/bulk-create",
clerkMiddleware(),
zValidator(
"json",
z.array(
insertTransactionSchema.omit({
id: true,
})
)
),
async (c) => {
const auth = getAuth(c);
const values = c.req.valid("json");

if(auth?.userId) {
return c.json({error: "Unauthorized"}, 401);
}

const data = await db
.insert(transactions)
.values(
values.map((value) => ({
id: createId(),
...value,
}))
)
.returning();

return c.json({ data });
},
)
.patch(
"/:id",
clerkMiddleware(),
zValidator(
"param",
z.object({
id: z.string().optional(),
})
),
zValidator(
"json",
insertTransactionSchema.omit({
id: true,
})
),
async (c) => {
const auth = getAuth(c);
const { id } = c.req.valid("param");
const values = c.req.valid("json");

if (!id){
return c.json({ error: "Missing id"}, 401);
}

if (!auth?.userId) {
return c.json({ error: "Unauthorized"},401);
}

const transactionsToUpdate = db.$with("transactions_to_update").as(
db.select({ id: transactions.id }).from(transactions)
.innerJoin(accounts, eq(transactions.accountId, accounts.id ))
.where(and(
eq(transactions.id, id),
eq(accounts.userId, auth.userId),
)),
);

const [data] = await db
.with(transactionsToUpdate)
.update(transactions)
.set(values)
.where(
inArray(transactions.id, sql`(select id from ${transactionsToUpdate})`)
).
returning()

if (!data) {
return c.json({ error: "Not Found"}, 404);
}

return c.json({ data });
}
)
.delete(
"/:id",
clerkMiddleware(),
zValidator(
"param",
z.object({
id: z.string().optional(),
})
),
async (c) => {
const auth = getAuth(c);
const { id } = c.req.valid("param");

if (!id){
return c.json({ error: "Missing id"}, 401);
}

if (!auth?.userId) {
return c.json({ error: "Unauthorized"},401);
}

const transactionsToDelete = db.$with("transactions_to_delete").as(
db.select({ id: transactions.id }).from(transactions)
.innerJoin(accounts, eq(transactions.accountId, accounts.id ))
.where(and(
eq(transactions.id, id),
eq(accounts.userId, auth.userId),
)),
);

const [data] = await db
.with(transactionsToDelete)
.delete(transactions)
.where(
inArray(transactions.id, sql`(select id from ${transactionsToDelete})`)
).
returning({
id: transactions.id,
});

if (!data) {
return c.json({ error: "Not Found"}, 404);
}

return c.json({ data });
}
);

export default app;

Hook API

features/transactions/api/use-bulk-create-transactions.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { InferRequestType,InferResponseType } from "hono";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import { client } from "@/lib/hono";

type ResponseType = InferResponseType<typeof client.api.transactions["bulk-create"]["$post"]>;
type RequestType = InferRequestType<typeof client.api.transactions["bulk-create"]["$post"]>["json"];

export const useBulkCreateTransactions = () => {
const queryClient = useQueryClient();

const mutation = useMutation<
ResponseType,
Error,
RequestType
>({
mutationFn: async (json) => {
const response = await client.api.transactions["bulk-create"]["$post"]({json});
return response.json();
},
onSuccess: () => {
toast("Transaction created!");
queryClient.invalidateQueries({ queryKey:["transactions"]});
//TODO: Also invalidate summary
},
onError: () => {
toast("Failed to create transactions")
},
});

return mutation;
}

features/transactions/api/use-bulk-delete-transactions.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { InferRequestType,InferResponseType } from "hono";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import { client } from "@/lib/hono";

type ResponseType = InferResponseType<typeof client.api.transactions["bulk-delete"]["$post"]>;
type RequestType = InferRequestType<typeof client.api.transactions["bulk-delete"]["$post"]>["json"];

export const useBulkDeleteTransactions = () => {
const queryClient = useQueryClient();

const mutation = useMutation<
ResponseType,
Error,
RequestType
>({
mutationFn: async (json) => {
const response = await client.api.transactions["bulk-delete"]["$post"]({json});
return response.json();
},
onSuccess: () => {
toast("Transaction Deleted!");
queryClient.invalidateQueries({ queryKey:["transactions"]});
//TODO: Also invalidate summary
},
onError: () => {
toast("Failed to delete transactions")
},
});

return mutation;
}

features/transactions/api/use-create-transaction.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { InferRequestType,InferResponseType } from "hono";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import { client } from "@/lib/hono";

type ResponseType = InferResponseType<typeof client.api.transactions.$post>;
type RequestType = InferRequestType<typeof client.api.transactions.$post>["json"];

export const useCreateTransaction = () => {
const queryClient = useQueryClient();

const mutation = useMutation<
ResponseType,
Error,
RequestType
>({
mutationFn: async (json) => {
const response = await client.api.transactions.$post({json});
return response.json();
},
onSuccess: () => {
toast("Transaction Created!");
queryClient.invalidateQueries({ queryKey:["transactions"]});
},
onError: () => {
toast("Failed to create transaction")
},
});

return mutation;
}

features/transactions/api/use-delete-transaction.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { InferResponseType } from "hono";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import { client } from "@/lib/hono";

type ResponseType = InferResponseType<typeof client.api.transactions[":id"]["$delete"]>;

export const useDeleteTransaction = (id?:string) => {
const queryClient = useQueryClient();

const mutation = useMutation<
ResponseType,
Error
>({
mutationFn: async (json) => {
const response = await client.api.transactions[":id"]["$delete"]({
param: { id },
});
return response.json();
},
onSuccess: () => {
toast("Transaction deleted!");
queryClient.invalidateQueries({ queryKey:["transactions", { id }]});
queryClient.invalidateQueries({ queryKey:["transactions"]});
// TODO: Invalidate Summary and transactions
},
onError: () => {
toast("Failed to delete transactoin")
},
});

return mutation;
}

features/transactions/api/use-edit-transaction.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { InferRequestType,InferResponseType } from "hono";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import { client } from "@/lib/hono";

type ResponseType = InferResponseType<typeof client.api.transactions[":id"]["$patch"]>;
type RequestType = InferRequestType<typeof client.api.transactions[":id"]["$patch"]>["json"];

export const useEditTransaction = (id?:string) => {
const queryClient = useQueryClient();

const mutation = useMutation<
ResponseType,
Error,
RequestType
>({
mutationFn: async (json) => {
const response = await client.api.transactions[":id"]["$patch"]({
json,
param: { id },
});
return response.json();
},
onSuccess: () => {
toast("Transaction updated!");
queryClient.invalidateQueries({ queryKey:["transactions", { id }]});
queryClient.invalidateQueries({ queryKey:["transactions"]});
// TODO: Invalidate Summary and transactions
},
onError: () => {
toast("Failed to edit transaction")
},
});

return mutation;
}

features/transactions/api/use-get-transaction.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { useQuery } from "@tanstack/react-query";

import { client } from "@/lib/hono"

export const useGetTransaction = (id?: string ) => {
const query = useQuery({
enabled: !!id,
queryKey: ["transactions", { id }],
queryFn: async () => {
const res = await client.api.transactions[":id"].$get({
param: { id }
});

if(!res.ok){
throw new Error("Failed to fetch transactoin");
}

const { data } = await res.json();
return data;
},
});

return query;
};

features/transactions/api/use-get-transactions.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { useQuery } from "@tanstack/react-query";

import { client } from "@/lib/hono"
import { useSearchParams } from "next/navigation";

export const useGetTransactions = () => {
const params = useSearchParams();
const from = params.get("from") || "";
const to = params.get("to") || "";
const accountId = params.get("accountId") || "";

const query = useQuery({
//TODO: check if param are needed in the key
queryKey: ["transactions", { from, to, accountId }],
queryFn: async () => {
const res = await client.api.transactions.$get({
query: {
from,
to,
accountId
},
});

if(!res.ok){
throw new Error("Failed to fetch transactions");
}

const { data } = await res.json();
return data;
},
});

return query;
};

请我喝杯咖啡吧~

支付宝
微信