mirror of
https://github.com/rjNemo/rentease.git
synced 2026-06-06 02:36:49 +00:00
77 lines
2 KiB
Go
77 lines
2 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"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
|
|
}
|
|
|
|
doc, err := bs.CreateInvoice(r.Context(), b, hc)
|
|
if err != nil {
|
|
if errors.Is(err, booking.ErrInvoiceStorageNotConfigured) {
|
|
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
slog.Error("failed to build invoice", slog.Any("error", err))
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.Redirect(w, r, doc.ShareURL, http.StatusTemporaryRedirect)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|