feat: changing event exchange rate recalculates all expense converted amounts
- New RecalculateExpenses DB function updates all expenses for an event - Expenses in different currency: converted = ROUND(amount * new_rate, 2) - Expenses already in base currency: left unchanged - Called from UpdateEvent handler after saving the new event rate
This commit is contained in:
parent
b0dfb5fad3
commit
aa07ff3c50
2 changed files with 23 additions and 0 deletions
|
|
@ -307,6 +307,23 @@ func UpdateEvent(db *sql.DB, id, baseCurrency string, exchangeRate float64) erro
|
|||
return err
|
||||
}
|
||||
|
||||
// RecalculateExpenses updates all expense converted_amounts for an event
|
||||
// using the new exchange rate. Expenses already in the base currency are left unchanged.
|
||||
func RecalculateExpenses(db *sql.DB, eventID, baseCurrency string, exchangeRate float64) error {
|
||||
_, err := db.Exec(
|
||||
`UPDATE expenses SET
|
||||
converted_amount = CASE WHEN currency != ? THEN ROUND(amount * ?, 2) ELSE amount END,
|
||||
base_currency = ?
|
||||
WHERE event_id = ?`,
|
||||
baseCurrency, exchangeRate, baseCurrency, eventID,
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("ERROR [%s] database: RecalculateExpenses(%s): %v",
|
||||
time.Now().Format(time.RFC3339), eventID, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Expense queries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -362,6 +362,12 @@ func (h *EventHandler) UpdateEvent(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
// Recalculate all existing expense converted amounts with the new rate.
|
||||
if err := database.RecalculateExpenses(h.DB, eventID, baseCurrency, exchangeRate); err != nil {
|
||||
log.Printf("ERROR [%s] handlers: UpdateEvent: recalc expenses: %v", time.Now().Format(time.RFC3339), err)
|
||||
// Non-fatal — the event was updated, but expenses may have stale conversions.
|
||||
}
|
||||
|
||||
w.Header().Set("HX-Redirect", "/dashboard")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue