// Package expense holds the rules of the expense tracker: what a valid expense // is, how amounts are written, and how totals are worked out. It knows nothing // about files, the web or the command line. package expense import ( "errors" "fmt" "slices" "strconv" "strings" "time" "unicode/utf8" ) // DateLayout and MonthLayout are the reference layouts from Chapter 35. const DateLayout = "2006-01-02" const MonthLayout = "2006-01" const MaxCategoryLength = 30 const MaxNoteLength = 100 // MaxCents is the largest amount one expense can have: 1000000.00. const MaxCents = 100_000_000 // Expense is one thing that was paid for. Amounts are whole cents, so that // 0.10 + 0.20 is exactly 0.30. The JSON tags give the names used by the API. // omitempty leaves the ID out while it is still 0, so a new expense can be // sent to the API, which gives the ID itself. type Expense struct { ID int `json:"id,omitempty"` Date string `json:"date"` Category string `json:"category"` Note string `json:"note"` Cents int64 `json:"cents"` } // New trims and checks the values, and returns an expense without an ID. The // store gives it an ID when it is added. func New(date string, category string, note string, cents int64) (Expense, error) { date = strings.TrimSpace(date) category = strings.ToLower(strings.TrimSpace(category)) note = strings.TrimSpace(note) _, err := time.Parse(DateLayout, date) if err != nil { return Expense{}, fmt.Errorf("the date %q is not a real day written like 2026-11-25", date) } if category == "" { return Expense{}, errors.New("the category cannot be empty") } if utf8.RuneCountInString(category) > MaxCategoryLength { return Expense{}, fmt.Errorf("the category can have at most %d characters", MaxCategoryLength) } if utf8.RuneCountInString(note) > MaxNoteLength { return Expense{}, fmt.Errorf("the note can have at most %d characters", MaxNoteLength) } if cents <= 0 { return Expense{}, errors.New("the amount must be more than 0") } if cents > MaxCents { return Expense{}, fmt.Errorf("the amount can be at most %s", FormatCents(MaxCents)) } return Expense{Date: date, Category: category, Note: note, Cents: cents}, nil } // ParseAmount turns text such as "12", "12.5" or "12.50" into cents. func ParseAmount(text string) (int64, error) { text = strings.TrimSpace(text) whole, fraction, hasDot := strings.Cut(text, ".") if !allDigits(whole) || (hasDot && !allDigits(fraction)) || len(fraction) > 2 { return 0, fmt.Errorf("the amount %q must be a number like 12.50", text) } for len(fraction) < 2 { fraction = fraction + "0" } cents, err := strconv.ParseInt(whole+fraction, 10, 64) if err != nil { return 0, fmt.Errorf("the amount %q is too large", text) } return cents, nil } // allDigits reports whether text is not empty and has only the digits 0 to 9. func allDigits(text string) bool { if text == "" { return false } for _, r := range text { if r < '0' || r > '9' { return false } } return true } // FormatCents writes cents as an amount with two decimals: 1250 is "12.50". func FormatCents(cents int64) string { sign := "" if cents < 0 { sign = "-" cents = -cents } return fmt.Sprintf("%s%d.%02d", sign, cents/100, cents%100) } // CheckMonth returns an error if month is not written like 2026-11. func CheckMonth(month string) error { _, err := time.Parse(MonthLayout, month) if err != nil { return fmt.Errorf("the month %q must be written like 2026-11", month) } return nil } // InMonth returns the expenses whose date is in month, written like 2026-11. // An empty month returns all of them. func InMonth(list []Expense, month string) []Expense { found := []Expense{} for _, e := range list { if month == "" || strings.HasPrefix(e.Date, month+"-") { found = append(found, e) } } return found } // Sum is the total of one group, such as one category or one month. type Sum struct { Name string `json:"name"` Cents int64 `json:"cents"` } // Report is the totals of a list of expenses. type Report struct { Count int `json:"count"` TotalCents int64 `json:"total_cents"` ByCategory []Sum `json:"by_category"` ByMonth []Sum `json:"by_month"` } // Summarize adds up the expenses. Categories come largest first, and months // come oldest first. func Summarize(list []Expense) Report { perCategory := map[string]int64{} perMonth := map[string]int64{} var total int64 for _, e := range list { total = total + e.Cents perCategory[e.Category] = perCategory[e.Category] + e.Cents month := e.Date[:len(MonthLayout)] perMonth[month] = perMonth[month] + e.Cents } byCategory := toSums(perCategory) slices.SortFunc(byCategory, largestFirst) byMonth := toSums(perMonth) slices.SortFunc(byMonth, byName) return Report{ Count: len(list), TotalCents: total, ByCategory: byCategory, ByMonth: byMonth, } } // toSums turns a map of totals into a slice, which can be sorted. func toSums(totals map[string]int64) []Sum { sums := []Sum{} for name, cents := range totals { sums = append(sums, Sum{Name: name, Cents: cents}) } return sums } // largestFirst sorts sums by amount, largest first, and equal amounts by name. func largestFirst(a Sum, b Sum) int { if a.Cents > b.Cents { return -1 } if a.Cents < b.Cents { return 1 } return byName(a, b) } // byName sorts sums by name, A to Z. A month like 2026-11 sorts by date. func byName(a Sum, b Sum) int { return strings.Compare(a.Name, b.Name) }