-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
501 lines (430 loc) · 15.5 KB
/
main.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
package main
import (
"database/sql"
"encoding/json"
"expense-tracker/apihandlers"
"expense-tracker/firebase"
"expense-tracker/handlers"
"expense-tracker/middleware"
"expense-tracker/models"
"expense-tracker/reports"
"expense-tracker/storage"
"expense-tracker/utils"
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
_ "github.com/mattn/go-sqlite3"
"github.com/pquerna/otp/totp"
)
var (
db *sql.DB
templates map[string]*template.Template
connectionString string
)
func init() {
// Database path configuration
dbPath := filepath.Join("data", "expenses.db")
connectionString = dbPath
// Create data directory if it doesn't exist
if err := os.MkdirAll("data", 0755); err != nil {
log.Fatalf("Failed to create data directory: %v", err)
}
templates = make(map[string]*template.Template)
templateFiles := []string{"dashboard", "home", "add", "view", "report", "currencies", "receipts", "footer", "login", "register"}
for _, tmpl := range templateFiles {
t, err := template.ParseFiles("templates/"+tmpl+".html", "templates/footer.html")
if err != nil {
log.Fatalf("Failed to parse template %s: %v", tmpl, err)
}
templates[tmpl] = t
}
}
func main() {
// Initialize database connection
var err error
db, err = sql.Open("sqlite3", connectionString)
if err != nil {
log.Fatalf("Error opening database: %v", err)
}
defer db.Close()
// Initialize database tables after connection is established
if err := handlers.CreateReceiptsTable(db); err != nil {
log.Fatalf("Failed to create receipts table: %v", err)
}
// Test the database connection
if err = db.Ping(); err != nil {
log.Fatalf("Error connecting to the database: %v", err)
}
// Load environment variables from .env file
fmt.Println("Attempting to load .env file...")
if err := godotenv.Load(); err != nil {
log.Fatalf("Err loading .env file: %v", err)
}
fmt.Println(".env file loaded successfully!")
// Create necessary tables - call only once
if err := createCurrenciesTable(db); err != nil {
log.Fatalf("Failed to create currencies table: %v", err)
}
if err := createBudgetTable(db); err != nil {
log.Fatalf("Failed to create budget table: %v", err)
}
// Create necessary tables
if err := models.CreateExpensesTable(db); err != nil {
log.Fatalf("Failed to create expenses table %v", err)
}
// Print environment variables status
apiKey := os.Getenv("FIREBASE_API_KEY")
serviceAccountKey := os.Getenv("FIREBASE_SERVICE_ACCOUNT_KEY")
if apiKey != "" {
fmt.Println("FIREBASE_API_KEY loaded successfully")
}
if serviceAccountKey != "" {
fmt.Println("FIREBASE_SERVICE_ACCOUNT_KEY loaded successfully")
}
// Create necessary tables
if err := createCurrenciesTable(db); err != nil {
log.Fatalf("Failed to create currencies table: %v", err)
}
if err := createBudgetTable(db); err != nil {
log.Fatalf("Failed to create budget table: %v", err)
}
go utils.UpdateExchangeRates()
go utils.ProcessRecurringExpenses(db)
// Initialize Firebase
err = firebase.InitFirebase()
if err != nil {
log.Fatalf("Error initializing Firebase: %v", err)
}
// Initialize the auth middleware
if err := middleware.InitAuthMiddleware(); err != nil {
log.Fatalf("Failed to initialize auth middleware: %v", err)
}
// Call the backup function periodically
go func() {
for {
time.Sleep(24 * time.Hour)
err := storage.BackupDB("data/expenses.db")
if err != nil {
log.Println("Error creating backup:", err)
}
}
}()
r := mux.NewRouter()
// Public routes
r.HandleFunc("/api/login", middleware.LoginHandler).Methods("POST")
r.HandleFunc("/api/register", middleware.RegisterHandler).Methods("POST")
r.HandleFunc("/login", loginHandler).Methods("GET")
r.HandleFunc("/register", registerHandler).Methods("GET")
// Redirect root to login
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/login", http.StatusSeeOther)
})
// Protected routes
protected := r.PathPrefix("/api").Subrouter()
protected.Use(middleware.AuthMiddleware)
protected.HandleFunc("/expenses", apihandlers.GetExpensesAPI(db)).Methods("GET")
// Add other protected routes here
// Other routes
r.HandleFunc("/dashboard", dashboardHandler)
r.HandleFunc("/home", homeHandler)
r.HandleFunc("/add", addExpenseHandler)
r.HandleFunc("/view", viewExpensesHandler)
r.HandleFunc("/report", generateReportHandler)
r.HandleFunc("/receipts", ReceiptsHandler)
r.HandleFunc("/upload-receipts", storage.UploadReceipt)
r.HandleFunc("/view-receipts", handlers.ViewReceipt)
r.HandleFunc("/setup-2fa", setup2FAHandler)
r.HandleFunc("/verify-2fa", verify2FAHandler)
r.HandleFunc("/admin", requireRole("admin", adminHandler))
r.HandleFunc("/currencies", currenciesHandler)
r.HandleFunc("/report/weekly", generateWeeklyReportHandler)
r.HandleFunc("/report/yearly", generateYearlyReportHandler)
// File Upload Router
r.HandleFunc("/upload", apihandlers.UploadFileHandler).Methods("POST")
// Register API routes
r.HandleFunc("/api/overview", apihandlers.OverviewHandler(db))
r.HandleFunc("/api/recent-transactions", apihandlers.RecentTransactionsHandler(db))
r.HandleFunc("/api/expense-distribution", apihandlers.ExpenseDistributionHandler(db))
r.HandleFunc("/api/budget-tracking", budgetTrackingHandler)
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// Currency conversion API route
convertedAmount, _ := utils.ConvertCurrency(100, "USD", "EUR")
fmt.Println("Converted amount:", convertedAmount)
// Search and Bulk expenses handlers
r.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
handlers.SearchExpensesHandler(db, w, r)
})
r.HandleFunc("/bulk-add", handlers.BulkAddExpensesHandler(db))
fmt.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", r))
}
func budgetTrackingHandler(w http.ResponseWriter, r *http.Request) {
budgets, err := handlers.GetCategoryBudgets(db)
if err != nil {
http.Error(w, "Error retrieving budgets", http.StatusInternalServerError)
return
}
var budgetTracking []struct {
Category string `json:"category"`
BudgetAmount float64 `json:"budgetAmount"`
ActualAmount float64 `json:"actualAmount"`
}
for _, budget := range budgets {
var actualAmount float64
err := db.QueryRow("SELECT COALESCE(SUM(amount), 0) FROM expenses WHERE category = ?", budget.Category).Scan(&actualAmount)
if err != nil {
http.Error(w, "Error calculating actual amount", http.StatusInternalServerError)
return
}
budgetTracking = append(budgetTracking, struct {
Category string `json:"category"`
BudgetAmount float64 `json:"budgetAmount"`
ActualAmount float64 `json:"actualAmount"`
}{
Category: budget.Category,
BudgetAmount: budget.BudgetAmount,
ActualAmount: actualAmount,
})
}
json.NewEncoder(w).Encode(budgetTracking)
}
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "dashboard", nil)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "home", nil)
}
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
t, ok := templates[tmpl]
if !ok {
http.Error(w, "Template not found", http.StatusInternalServerError)
return
}
err := t.Execute(w, data)
if err != nil {
log.Printf("Template execution error: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
func createBudgetTable(db *sql.DB) error {
query := `
CREATE TABLE IF NOT EXISTS budgets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL UNIQUE,
amount REAL NOT NULL
);`
_, err := db.Exec(query)
if err != nil {
return err
}
return nil
}
func addExpenseHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
exp := models.Expense{
Amount: parseFloat(r.FormValue("amount")),
Category: r.FormValue("category"),
Description: r.FormValue("description"),
Date: r.FormValue("date"),
CurrencyCode: r.FormValue("currency"),
}
if err := handlers.AddExpenses(db, exp); err != nil {
http.Error(w, "Error adding expense", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
currencies, err := handlers.GetCurrencies(db)
if err != nil {
http.Error(w, "Error retrieving currencies", http.StatusInternalServerError)
return
}
renderTemplate(w, "add", currencies)
}
func viewExpensesHandler(w http.ResponseWriter, r *http.Request) {
expenses, err := handlers.GetExpenses(db)
if err != nil {
http.Error(w, "Error retrieving expenses", http.StatusInternalServerError)
return
}
renderTemplate(w, "view", expenses)
}
func ReceiptsHandler(w http.ResponseWriter, r *http.Request) {
receipts, err := handlers.GetReceipts(db)
if err != nil {
log.Println("Error retrieving receipts:", err)
http.Error(w, "Error retrieving receipts", http.StatusInternalServerError)
return
}
// Data structure
data := struct {
Receipts []models.Receipt
}{
Receipts: receipts,
}
renderTemplate(w, "receipts", data)
}
func generateReportHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
reportType := r.FormValue("report_type")
startDate := r.FormValue("start_date")
endDate := r.FormValue("end_date")
exportFormat := r.FormValue("format")
log.Printf("Generating report for %s Report:\nStart Date: %s\nEnd Date: %s\nExport Format: %s\n", reportType, startDate, endDate, exportFormat)
// Generate the report based on the form date
err := reports.GenerateReport(db, reportType, startDate, endDate, exportFormat)
if err != nil {
log.Println("Eror generating repport:", err)
http.Error(w, "Error generating report", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}
renderTemplate(w, "report", nil)
}
func generateWeeklyReportHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
startDate := r.FormValue("start_date")
endDate := r.FormValue("end_date")
exportFormat := r.FormValue("format")
log.Printf("Getting weekly report from %s to %s in %s format", startDate, endDate, exportFormat)
if err := reports.GenerateWeeklyReport(db, startDate, endDate, exportFormat); err != nil {
log.Println("Error generating report:", err)
http.Error(w, "Error generating report", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
return
}
renderTemplate(w, "report", nil)
}
func generateYearlyReportHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
startDate := r.FormValue("start_date")
endDate := r.FormValue("end_date")
exportFormat := r.FormValue("format")
log.Printf("Generating yearly report from %s to %s in %s format", startDate, endDate, exportFormat)
if err := reports.GenerateYearlyReport(db, startDate, endDate, exportFormat); err != nil {
log.Println("Error generating report:", err)
http.Error(w, "Error generating report", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
return
}
renderTemplate(w, "report", nil)
}
func currenciesHandler(w http.ResponseWriter, r *http.Request) {
currencies, err := handlers.GetCurrencies(db)
if err != nil {
http.Error(w, "Error retrieving currencies", http.StatusInternalServerError)
return
}
renderTemplate(w, "currencies", currencies)
}
func createCurrenciesTable(db *sql.DB) error {
query := `
CREATE TABLE IF NOT EXISTS currencies (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT UNIQUE NOT NULL,
symbol TEXT NOT NULL,
name TEXT NOT NULL
);`
_, err := db.Exec(query)
if err != nil {
return fmt.Errorf("failed to create currencies table: %v", err)
}
var count int
err = db.QueryRow("SELECT COUNT(*) FROM currencies").Scan(&count)
if err != nil {
return fmt.Errorf("failed to count currencies: %v", err)
}
if count == 0 {
currencies := []struct {
code string
symbol string
name string
}{
{"USD", "$", "US Dollar"},
{"EUR", "€", "Euro"},
{"GBP", "£", "British Pound"},
{"NGN", "₦", "Nigerian Naira"},
}
for _, c := range currencies {
_, err := db.Exec(`
INSERT OR IGNORE INTO currencies (code, symbol)
VALUES (?, ?, ?)`,
c.code, c.symbol, c.name)
if err != nil {
return fmt.Errorf("failed to insert currency %s: %v", c.code, err)
}
}
fmt.Println("Default currencies inserted successfully!")
}
return nil
}
// 2FA setup and verification endpoints
func setup2FAHandler(w http.ResponseWriter, r *http.Request) {
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "ExpenseTracker",
AccountName: "[email protected]",
})
if err != nil {
http.Error(w, "Error generating 2FA key", http.StatusInternalServerError)
}
// save key.Secrete() to the user's account in the database
http.Redirect(w, r, "/verify-2fa?secret="+key.Secret(), http.StatusSeeOther)
}
func verify2FAHandler(w http.ResponseWriter, r *http.Request) {
secret := r.URL.Query().Get("secret")
code := r.FormValue("code")
if totp.Validate(code, secret) {
// Mark the user as verified in the database
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
} else {
http.Error(w, "Invalid 2FA code", http.StatusUnauthorized)
}
}
func parseFloat(s string) float64 {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0
}
return f
}
// Admin handler
func adminHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "admin", nil)
}
// Middleware for role-based access control
func requireRole(role string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := 1 // Get user ID from session or content
userRole, err := models.GetUserRole(db, userId)
if err != nil || userRole != role {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next(w, r)
}
}
type ReportData struct {
ReportType string
StartDate string
EndDate string
ExportFormat string
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "login", nil)
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "register", nil)
}