diff --git a/internal/handlers/expenses.go b/internal/handlers/expenses.go index f4b7834..416f9d5 100644 --- a/internal/handlers/expenses.go +++ b/internal/handlers/expenses.go @@ -286,13 +286,22 @@ func (h *ExpenseHandler) SaveExpense(w http.ResponseWriter, r *http.Request) { if convertedAmountStr != "" { convertedAmount, _ = strconv.ParseFloat(convertedAmountStr, 64) } - if baseCurrency == "" || baseCurrency == currency { - baseCurrency = currency - convertedAmount = amount + + // Fetch the event to get its exchange rate for auto-calculation. + event, err := database.GetEventByID(h.DB, eventID) + if err != nil || event == nil || event.UserID != getUserID(r) { + http.Error(w, "Forbidden", http.StatusForbidden) + return } - if convertedAmount <= 0 { + + // Auto-calculate conversion. + if baseCurrency == "" || baseCurrency == currency { + baseCurrency = event.BaseCurrency + } + if convertedAmount <= 0 && baseCurrency != currency { + convertedAmount = amount * event.ExchangeRate + } else if convertedAmount <= 0 { convertedAmount = amount - baseCurrency = currency } // 5. Build and save the expense record. @@ -435,10 +444,7 @@ func (h *ExpenseHandler) UpdateExpense(w http.ResponseWriter, r *http.Request) { amount, _ := strconv.ParseFloat(r.FormValue("amount"), 64) convertedAmount, _ := strconv.ParseFloat(r.FormValue("converted_amount"), 64) baseCurrency := r.FormValue("base_currency") - if baseCurrency == "" { - baseCurrency = r.FormValue("currency") - convertedAmount = amount - } + currency := r.FormValue("currency") // Fetch the existing expense to preserve the event_id and image_path. existing, err := database.GetExpenseByID(h.DB, expenseID) @@ -460,6 +466,16 @@ func (h *ExpenseHandler) UpdateExpense(w http.ResponseWriter, r *http.Request) { return } + // Auto-calculate conversion. + if baseCurrency == "" { + baseCurrency = event.BaseCurrency + } + if convertedAmount <= 0 && baseCurrency != currency { + convertedAmount = amount * event.ExchangeRate + } else if convertedAmount <= 0 { + convertedAmount = amount + } + expense := database.Expense{ ID: expenseID, EventID: existing.EventID,