Build a Finance SaaS Platform -21 (Summary API)

Modify API Route

Modify app/api/[[...route]]/route.ts

1
2
3
4
5
6
7
8
...
import summary from "./summary";
...
const routes = app
.route("/accounts", accounts)
.route("/categories", categories)
.route("/transactions", transactions)
.route("/summary", summary);

Add Function:

Modify lib/utils.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

...

export function fillMissingDays(
activeDays: {
date: Date;
income: number;
expenses: number;
}[],
startDate: Date,
endDate: Date,
) {
if (activeDays.length === 0) {
return [];
}

const allDays = eachDayOfInterval({
start: startDate,
end: endDate,
});

const transactionsBy = allDays.map((day) => {
const found = activeDays.find((d) => isSameDay(d.date, day));

if (found) {
return found;
} else {
return {
date: day,
income: 0,
expenses: 0,
}
}
});

return transactionsBy;
}
...

Add Summary API

Add app/api/[[...route]]/summary.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
import { db } from "@/db/drizzle";
import { accounts, categories, transactions } from "@/db/schema";
import { calculcatePercentageChange, fillMissingDays } from "@/lib/utils";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";
import { zValidator } from "@hono/zod-validator";
import { subDays,parse, differenceInDays } from "date-fns";
import { and, eq, sql, sum,gte,lte, lt, desc } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";

const app = new Hono()
.get(
"/",
clerkMiddleware(),
zValidator(
"query",
z.object({
from: z.string().optional(),
to: z.string().optional(),
accountId: z.string().optional(),
})
),
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 periodLength = differenceInDays(endDate,startDate) + 1;
const lastPeriodStart = subDays(startDate,periodLength);
const lastPeriodEnd = subDays(endDate,periodLength);

async function fetchFinancialData(
userId:string,
startDate: Date,
endtDate: Date,
) {
return await db
.select({
income: sql`SUM(CASE WHEN ${transactions.amount} >= 0 THEN ${transactions.amount} ELSE 0 END)`.mapWith(Number),
expense: sql`SUM(CASE WHEN ${transactions.amount} < 0 THEN ${transactions.amount} ELSE 0 END)`.mapWith(Number),
remain: sum(transactions.amount).mapWith(Number),
})
.from(transactions)
.innerJoin(
accounts,
eq(
transactions.accountId,
accounts.id
),
)
.where(
and(
accountId ? eq(transactions.accountId, accountId) : undefined,
eq(accounts.userId, userId),
gte(transactions.date, startDate),
lte(transactions.date, endtDate),
)
)
}

const [currentPeriod] = await fetchFinancialData(
auth.userId,
startDate,
endDate,
);

const [lastPeriod] = await fetchFinancialData(
auth.userId,
startDate,
endDate,
);

const incomeChange = calculcatePercentageChange(
currentPeriod.income,
lastPeriod.income,
);

const expenseChange = calculcatePercentageChange(
currentPeriod.expense,
lastPeriod.expense,
);

const remainChange = calculcatePercentageChange(
currentPeriod.remain,
lastPeriod.remain,
);

const category = await db
.select({
name: categories.name,
value: sql`SUM(ABS(${transactions.amount}))`.mapWith(Number),
})
.from(transactions)
.innerJoin(
accounts,
eq(
transactions.accountId,
accounts.id,
),
)
.innerJoin(
categories,
eq(
transactions.categoryId,
categories.id,
)
)
.where(
and(
accountId ? eq(transactions.accountId, accountId) : undefined,
eq(accounts.userId, auth.userId),
lt(transactions.amount, 0),
gte(transactions.date, startDate),
lte(transactions.date, endDate),
)
)
.groupBy(categories.name)
.orderBy(desc(
sql`SUM(ABS(${transactions.amount}))`
));

const topCategories = category.slice(0,3);
const otherCategories = category.slice(3);
const otherSum = otherCategories
.reduce((sum,current) => sum + current.value,0);

const finalCategories = topCategories;
if (otherCategories.length > 0 ){
finalCategories.push({
name: "Others",
value: otherSum,
});
};

const activeDays = await db
.select({
date: transactions.date,
income: sql`SUM(CASE WHEN ${transactions.amount} >= 0 THEN ${transactions.amount} ELSE 0 END)`.mapWith(Number),
expenses: sql`SUM(CASE WHEN ${transactions.amount} < 0 THEN ${transactions.amount} ELSE 0 END)`.mapWith(Number),
})
.from(transactions)
.innerJoin(
accounts,
eq(
transactions.accountId,
accounts.id,
)
)
.where(
and(
accountId ? eq(transactions.accountId, accountId) : undefined,
eq(accounts.userId, auth.userId),
gte(transactions.date, startDate),
lte(transactions.date, endDate),
)
)
.groupBy(transactions.date)
.orderBy(transactions.date);

const days = fillMissingDays(
activeDays,
startDate,
endDate,
);

return c.json({
date: {
periodLength,
lastPeriodStart,
lastPeriodEnd,
currentPeriod,
lastPeriod,
remainingAmount: currentPeriod.remain,
remainChange,
incomeAmount: currentPeriod.income,
incomeChange,
expenseAmount: currentPeriod.expense,
expenseChange,
categories: finalCategories,
days,
},
});
},
);

export default app;

请我喝杯咖啡吧~

支付宝
微信