mirror of
https://github.com/rjNemo/rentease.git
synced 2026-06-06 02:36:49 +00:00
Some checks failed
CI / checks (push) Has been cancelled
Refactor booking retrieval to return errors instead of nil values, enabling more robust error handling throughout the booking, payment, and PDF endpoints. Add custom HTTP error page rendering for not found and internal server errors. Update interfaces and tests to match new method signatures. This improves user feedback and code maintainability.
72 lines
1.8 KiB
Go
72 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
u "github.com/rjNemo/underscore"
|
|
|
|
"github.com/rjNemo/rentease/internal/config"
|
|
"github.com/rjNemo/rentease/internal/service/booking"
|
|
)
|
|
|
|
func handlePdfCreateInvoice(bs *booking.Service, hc *config.Host) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
idStr := chi.URLParam(r, "id")
|
|
id, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
http.Error(w, "invalid booking id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
b, err := bs.One(id)
|
|
if bookingLookupFailed(w, err) {
|
|
return
|
|
}
|
|
|
|
filePath, err := bs.BuildInvoice(b, hc)
|
|
if err != nil {
|
|
slog.Error("failed to build invoice", slog.Any("error", err))
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.ServeFile(w, r, filePath)
|
|
}
|
|
}
|
|
|
|
func handlePdfCreateReport(bs *booking.Service) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
period := r.URL.Query().Get("period")
|
|
if !u.Contains([]string{"month", "year"}, period) {
|
|
http.Error(w, fmt.Sprintf("%q is not a valid period", period), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
monthStr := r.URL.Query().Get("month")
|
|
month, err := strconv.Atoi(monthStr)
|
|
if err != nil || month < 1 || month > 12 {
|
|
http.Error(w, fmt.Sprintf("%q is not a valid month", monthStr), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
yearStr := r.URL.Query().Get("year")
|
|
year, err := strconv.Atoi(yearStr)
|
|
if err != nil {
|
|
http.Error(w, fmt.Sprintf("%q is not a valid year", yearStr), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
report := bs.Report(period, month, year)
|
|
filePath, err := bs.BuildReport(report, period, month, year)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.ServeFile(w, r, filePath)
|
|
}
|
|
}
|