rentease/internal/server/handle_pdf.go

72 lines
1.6 KiB
Go

package server
import (
"fmt"
"log"
"net/http"
"strconv"
"github.com/labstack/echo/v4"
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) echo.HandlerFunc {
return func(c echo.Context) error {
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
log.Println(err)
return err
}
b := bs.One(id)
filePath, err := bs.BuildInvoice(b, hc)
if err != nil {
log.Println(err)
return err
}
return c.File(filePath)
}
}
func handlePdfCreateReport(bs *booking.Service) 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.Report(period, month, year)
filePath, err := bs.BuildReport(report, period, month, year)
if err != nil {
return err
}
return c.File(filePath)
}
}