rentease/internal/server/handle_pdf.go
2024-03-03 14:25:36 +01:00

69 lines
1.6 KiB
Go

package server
import (
"fmt"
"net/http"
"strconv"
"github.com/labstack/echo/v4"
"github.com/rjNemo/rentease/config"
"github.com/rjNemo/rentease/internal/booking"
"github.com/rjNemo/rentease/internal/pdf"
u "github.com/rjNemo/underscore"
)
func handleCreateInvoicePdf(bs *booking.Service, ps *pdf.PdfService, hc *config.Host) echo.HandlerFunc {
return func(c echo.Context) error {
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
return err
}
b := bs.One(id)
err = ps.BuildInvoice(b, hc)
if err != nil {
return err
}
return c.Attachment("tmp.pdf", "tmp.pdf")
}
}
func handleCreateReportPdf(bs *booking.Service, ps *pdf.PdfService) echo.HandlerFunc {
return func(c echo.Context) error {
period := c.QueryParam("period")
if !u.Contains([]string{"month", "year"}, period) {
return &echo.HTTPError{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("%q is not a valid period", period),
}
}
monthStr := c.QueryParam("month")
month, err := strconv.Atoi(monthStr)
if err != nil || month < 1 || month > 12 {
return &echo.HTTPError{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("%q is not a valid month", month),
}
}
yearStr := c.QueryParam("year")
year, err := strconv.Atoi(yearStr)
if err != nil {
return &echo.HTTPError{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("%q is not a valid year", year),
}
}
report := bs.BuildReport(period, month, year)
err = ps.BuildReport(report, period, month, year)
if err != nil {
return err
}
return c.Attachment("tmp.pdf", "tmp.pdf")
}
}