|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "strconv" |
| 8 | + "time" |
| 9 | + "io/ioutil" |
| 10 | +) |
| 11 | + |
| 12 | +type Expense struct { |
| 13 | + Amount float64 `json:"amount"` |
| 14 | + Category string `json:"category"` |
| 15 | + Date time.Time `json:"date"` |
| 16 | +} |
| 17 | + |
| 18 | +const dataFile = "expenses.json" |
| 19 | + |
| 20 | +func loadExpenses() ([]Expense, error) { |
| 21 | + data, err := ioutil.ReadFile(dataFile) |
| 22 | + if err != nil { |
| 23 | + if os.IsNotExist(err) { |
| 24 | + return []Expense{}, nil |
| 25 | + } |
| 26 | + return nil, err |
| 27 | + } |
| 28 | + var expenses []Expense |
| 29 | + err = json.Unmarshal(data, &expenses) |
| 30 | + return expenses, err |
| 31 | +} |
| 32 | + |
| 33 | +func saveExpenses(expenses []Expense) error { |
| 34 | + data, err := json.MarshalIndent(expenses, "", " ") |
| 35 | + if err != nil { |
| 36 | + return err |
| 37 | + } |
| 38 | + return ioutil.WriteFile(dataFile, data, 0644) |
| 39 | +} |
| 40 | + |
| 41 | +func addExpense(args []string) { |
| 42 | + if len(args) < 2 { |
| 43 | + fmt.Println("Usage: add <amount> <category>") |
| 44 | + return |
| 45 | + } |
| 46 | + amount, err := strconv.ParseFloat(args[0], 64) |
| 47 | + if err != nil { |
| 48 | + fmt.Println("Invalid amount.") |
| 49 | + return |
| 50 | + } |
| 51 | + category := args[1] |
| 52 | + expenses, err := loadExpenses() |
| 53 | + if err != nil { |
| 54 | + fmt.Println("Error loading expenses:", err) |
| 55 | + return |
| 56 | + } |
| 57 | + expense := Expense{ |
| 58 | + Amount: amount, |
| 59 | + Category: category, |
| 60 | + Date: time.Now(), |
| 61 | + } |
| 62 | + expenses = append(expenses, expense) |
| 63 | + if err := saveExpenses(expenses); err != nil { |
| 64 | + fmt.Println("Error saving expense:", err) |
| 65 | + } else { |
| 66 | + fmt.Println("Expense added.") |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func listExpenses() { |
| 71 | + expenses, err := loadExpenses() |
| 72 | + if err != nil { |
| 73 | + fmt.Println("Error loading expenses:", err) |
| 74 | + return |
| 75 | + } |
| 76 | + if len(expenses) == 0 { |
| 77 | + fmt.Println("No expenses recorded.") |
| 78 | + return |
| 79 | + } |
| 80 | + var total float64 |
| 81 | + for _, e := range expenses { |
| 82 | + fmt.Printf("- $%.2f [%s] (%s)\n", e.Amount, e.Category, e.Date.Format("2006-01-02")) |
| 83 | + total += e.Amount |
| 84 | + } |
| 85 | + fmt.Printf("Total: $%.2f\n", total) |
| 86 | +} |
| 87 | + |
| 88 | +func main() { |
| 89 | + if len(os.Args) < 2 { |
| 90 | + fmt.Println("Commands: add <amount> <category> | list") |
| 91 | + return |
| 92 | + } |
| 93 | + cmd := os.Args[1] |
| 94 | + switch cmd { |
| 95 | + case "add": |
| 96 | + addExpense(os.Args[2:]) |
| 97 | + case "list": |
| 98 | + listExpenses() |
| 99 | + default: |
| 100 | + fmt.Println("Unknown command.") |
| 101 | + } |
| 102 | +} |
0 commit comments