-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhandlers.go
391 lines (336 loc) · 10.3 KB
/
handlers.go
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package main
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"github.com/labstack/echo/v4"
"github.com/mr-karan/gullak/internal/db"
"github.com/mr-karan/gullak/internal/llm"
"github.com/mr-karan/gullak/pkg/models"
)
type ExpenseInput struct {
Line string `json:"line"`
}
type Resp struct {
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
Data interface{} `json:"data"`
}
type CategorySummary struct {
Category string `json:"category"`
TotalSpent float64 `json:"total_spent"`
}
type DailySpendingSummary struct {
TransactionDate string `json:"transaction_date"`
TotalSpent float64 `json:"total_spent"`
}
func handleIndex(c echo.Context) error {
return c.JSON(http.StatusOK, Resp{
Message: "Welcome to Gullak. POST to /api/transactions to save expenses.",
})
}
func handleCreateTransaction(c echo.Context) error {
m := c.Get("app").(*App)
var input ExpenseInput
if err := c.Bind(&input); err != nil {
m.log.Error("Error binding input", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Error saving expenses",
})
}
if input.Line == "" {
m.log.Error("Empty input", "error", errors.New("empty input"))
return c.JSON(http.StatusBadRequest, Resp{
Error: "Empty input",
})
}
transactions, err := m.llm.Parse(input.Line)
if err != nil {
var noTxErr *llm.NoValidTransactionError
if errors.As(err, &noTxErr) {
m.log.Error("No valid transactions found", "error", noTxErr)
return c.JSON(http.StatusBadRequest, Resp{
Error: noTxErr.Error(),
})
}
m.log.Error("Error parsing expenses", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Error parsing expenses",
})
}
savedTransactions, err := m.Save(transactions)
if err != nil {
m.log.Error("Error saving transactions", "error", err)
return c.JSON(http.StatusInternalServerError, Resp{
Error: "Error saving transactions",
})
}
return c.JSON(http.StatusOK, Resp{
Message: "Expenses saved",
Data: savedTransactions,
})
}
func handleListTransactions(c echo.Context) error {
m := c.Get("app").(*App)
var params db.ListTransactionsParams
if confirmStr := c.QueryParam("confirm"); confirmStr != "" {
// Convert and check the confirm parameter
confirm, err := strconv.ParseBool(confirmStr)
if err != nil {
return c.JSON(http.StatusBadRequest, Resp{Error: "Invalid confirm value"})
}
params.Confirm = confirm
} else {
params.Confirm = nil // Explicitly setting as nil if not provided
}
startDateStr := c.QueryParam("start_date")
endDateStr := c.QueryParam("end_date")
var startDate, endDate time.Time
var err error
if startDateStr != "" {
startDate, err = time.Parse("2006-01-02", startDateStr)
if err != nil {
return c.JSON(http.StatusBadRequest, Resp{Error: "Invalid start date format"})
}
params.StartDate = startDate
} else {
params.StartDate = nil // Explicitly setting as nil if not provided
}
if endDateStr != "" {
endDate, err = time.Parse("2006-01-02", endDateStr)
if err != nil {
return c.JSON(http.StatusBadRequest, Resp{Error: "Invalid end date format"})
}
params.EndDate = endDate
} else {
params.EndDate = nil // Explicitly setting as nil if not provided
}
// Validate the date range if both dates are provided
if startDateStr != "" && endDateStr != "" {
if err := validateDateRange(startDate, endDate); err != nil {
return c.JSON(http.StatusBadRequest, Resp{
Error: err.Error(),
})
}
}
transactions, err := m.queries.ListTransactions(context.Background(), params)
if err != nil {
m.log.Error("Error retrieving transactions", "error", err)
return c.JSON(http.StatusInternalServerError, Resp{Error: "Error retrieving transactions"})
}
return c.JSON(http.StatusOK, Resp{
Data: transactions,
Message: "Transactions retrieved",
})
}
func handleGetTransaction(c echo.Context) error {
m := c.Get("app").(*App)
idStr := c.Param("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
m.log.Error("Invalid transaction ID", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid transaction ID",
})
}
transaction, err := m.queries.GetTransaction(context.Background(), id)
if err != nil {
m.log.Error("Error retrieving transaction", "error", err)
return c.JSON(http.StatusNotFound, Resp{
Error: "Transaction not found",
})
}
return c.JSON(http.StatusOK, Resp{
Data: transaction,
Message: "Transaction retrieved",
})
}
func handleUpdateTransaction(c echo.Context) error {
m := c.Get("app").(*App)
idStr := c.Param("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
m.log.Error("Invalid transaction ID", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid transaction ID",
})
}
var input models.Item // Ensure models.Item has the appropriate fields
if err := c.Bind(&input); err != nil {
m.log.Error("Error binding input", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid input",
})
}
// Ensure transaction_date is in the correct format
transactionDate, err := time.Parse("2006-01-02", input.TransactionDate)
if err != nil {
m.log.Error("Error parsing transaction date", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid transaction date",
})
}
params := db.UpdateTransactionParams{
Amount: input.Amount,
Currency: input.Currency,
Category: input.Category,
Description: input.Description,
Confirm: input.Confirm,
TransactionDate: transactionDate,
ID: id,
}
if err := m.queries.UpdateTransaction(context.Background(), params); err != nil {
m.log.Error("Error updating transaction", "error", err)
return c.JSON(http.StatusInternalServerError, Resp{
Error: "Error updating transaction",
})
}
return c.JSON(http.StatusOK, Resp{
Message: "Transaction updated",
Data: params,
})
}
func handleDeleteTransaction(c echo.Context) error {
m := c.Get("app").(*App)
idStr := c.Param("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
m.log.Error("Invalid transaction ID", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid transaction ID",
})
}
if err := m.queries.DeleteTransaction(context.Background(), id); err != nil {
m.log.Error("Error deleting transaction", "error", err)
return c.JSON(http.StatusInternalServerError, Resp{
Error: "Error deleting transaction",
})
}
return c.JSON(http.StatusOK, Resp{
Message: "Transaction deleted",
})
}
func handleTopExpenseCategories(c echo.Context) error {
m := c.Get("app").(*App)
startDateStr := c.QueryParam("start_date")
endDateStr := c.QueryParam("end_date")
if startDateStr == "" || endDateStr == "" {
return c.JSON(http.StatusBadRequest, Resp{
Error: "Missing required parameters: start_date, end_date",
})
}
// Parse start date and end date strings into time.Time
startDate, err := time.Parse("2006-01-02", startDateStr)
if err != nil {
m.log.Error("Invalid start date", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid start date format, use YYYY-MM-DD",
})
}
endDate, err := time.Parse("2006-01-02", endDateStr)
if err != nil {
m.log.Error("Invalid end date", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid end date format, use YYYY-MM-DD",
})
}
// Validate the date range
if err := validateDateRange(startDate, endDate); err != nil {
return c.JSON(http.StatusBadRequest, Resp{
Error: err.Error(),
})
}
params := db.TopExpenseCategoriesParams{
StartDate: startDate,
EndDate: endDate,
}
rawCategories, err := m.queries.TopExpenseCategories(context.Background(), params)
if err != nil {
m.log.Error("Error retrieving top expense categories", "error", err)
return c.JSON(http.StatusInternalServerError, Resp{
Error: "Error retrieving top expense categories",
})
}
// Transform into client-friendly structure
categories := make([]CategorySummary, len(rawCategories))
for i, cat := range rawCategories {
totalSpent := 0.0
if cat.TotalSpent.Valid {
totalSpent = cat.TotalSpent.Float64
}
categories[i] = CategorySummary{
Category: cat.Category,
TotalSpent: totalSpent,
}
}
return c.JSON(http.StatusOK, Resp{
Data: categories,
Message: "Top expense categories retrieved",
})
}
func handleDailySpending(c echo.Context) error {
m := c.Get("app").(*App)
startDateStr := c.QueryParam("start_date")
endDateStr := c.QueryParam("end_date")
if startDateStr == "" || endDateStr == "" {
return c.JSON(http.StatusBadRequest, Resp{
Error: "Missing required parameters: start_date, end_date",
})
}
startDate, err := time.Parse("2006-01-02", startDateStr)
if err != nil {
m.log.Error("Invalid start date", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid start date format, use YYYY-MM-DD",
})
}
endDate, err := time.Parse("2006-01-02", endDateStr)
if err != nil {
m.log.Error("Invalid end date", "error", err)
return c.JSON(http.StatusBadRequest, Resp{
Error: "Invalid end date format, use YYYY-MM-DD",
})
}
// Validate the date range
if err := validateDateRange(startDate, endDate); err != nil {
return c.JSON(http.StatusBadRequest, Resp{
Error: err.Error(),
})
}
params := db.DailySpendingParams{
StartDate: startDate,
EndDate: endDate,
}
rawSpending, err := m.queries.DailySpending(context.Background(), params)
if err != nil {
m.log.Error("Error retrieving daily spending", "error", err)
return c.JSON(http.StatusInternalServerError, Resp{
Error: "Error retrieving daily spending",
})
}
// Transform into client-friendly structure
spendingSummaries := make([]DailySpendingSummary, len(rawSpending))
for i, daily := range rawSpending {
totalSpent := 0.0
if daily.TotalSpent.Valid {
totalSpent = daily.TotalSpent.Float64
}
spendingSummaries[i] = DailySpendingSummary{
TransactionDate: daily.TransactionDate.Format("2006-01-02"),
TotalSpent: totalSpent,
}
}
return c.JSON(http.StatusOK, Resp{
Data: spendingSummaries,
Message: "Daily spending totals retrieved successfully",
})
}
// validateDateRange ensures that the start date is before or the same as the end date.
func validateDateRange(startDate, endDate time.Time) error {
if startDate.After(endDate) {
return errors.New("start date must be on or before end date")
}
return nil
}