pdf service

This commit is contained in:
Ruidy 2024-02-16 12:38:03 +01:00
parent 72d0212316
commit 1f86cbf3ed
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
4 changed files with 116 additions and 80 deletions

109
internal/pdf/service.go Normal file
View file

@ -0,0 +1,109 @@
package pdf
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"github.com/labstack/gommon/log"
)
type PdfService struct {
invoicePath string
projectId string
url string
apiKey string
}
func NewPdfService() *PdfService {
return &PdfService{
invoicePath: "index.html",
projectId: os.Getenv("HTMLDOCS_PROJECT_ID"),
url: os.Getenv("HTMLDOCS_URL"),
apiKey: os.Getenv("HTMLDOCS_KEY"),
}
}
func (ps PdfService) BuildInvoice() error {
data := struct {
Context map[string]any `json:"context"`
Path string `json:"path"`
ProjectId string `json:"projectId"`
}{
Context: map[string]any{},
Path: ps.invoicePath,
ProjectId: ps.projectId,
}
payload, err := json.Marshal(data)
if err != nil {
log.Warnf("Error marshalling JSON:", err)
return err
}
// build request to third-party API
req, err := http.NewRequest("POST", ps.url, bytes.NewBuffer(payload))
if err != nil {
log.Warnf("Error creating request:", err)
return err
}
req.Header.Set("Authorization", "Bearer "+ps.apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Warnf("Error sending request:", err)
return err
}
defer resp.Body.Close()
res := new(struct {
Url string `json:"url"`
Error string `json:"error"`
})
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, res)
if err != nil {
log.Warnf("error decoding response: %s", err)
return err
}
if res.Error != "" {
log.Warnf("error building pdf file %s", err)
return errors.New(res.Error)
}
resp, err = http.Get(res.Url)
if err != nil {
log.Warnf("Error retrieving file")
return err
}
defer resp.Body.Close()
file, err := os.Create("tmp.pdf")
if err != nil {
log.Fatal(err)
}
defer file.Close()
body, err = io.ReadAll(resp.Body)
if err != nil {
return err
}
_, err = file.Write(body)
if err != nil {
log.Error("Error copying file content")
return err
}
return nil
}

View file

@ -1,13 +1,8 @@
package server
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
@ -18,6 +13,7 @@ import (
"github.com/rjNemo/rentease/constants"
"github.com/rjNemo/rentease/internal/domains/booking"
"github.com/rjNemo/rentease/internal/pdf"
"github.com/rjNemo/rentease/internal/views"
myTime "github.com/rjNemo/rentease/pkg/time"
)
@ -272,82 +268,10 @@ func (s Server) handleComputeReport() echo.HandlerFunc {
}
}
func (s Server) handleCreateInvoicePdf() echo.HandlerFunc {
func handleCreateInvoicePdf(ps *pdf.PdfService) echo.HandlerFunc {
return func(c echo.Context) error {
data := struct {
Context map[string]any `json:"context"`
Path string `json:"path"`
ProjectId string `json:"projectId"`
}{
Context: map[string]any{},
Path: "index.html", // TODO: put in a variable
ProjectId: os.Getenv("HTMLDOCS_PROJECT_ID"),
}
payload, err := json.Marshal(data)
err := ps.BuildInvoice()
if err != nil {
log.Warnf("Error marshalling JSON:", err)
return err
}
req, err := http.NewRequest("POST", os.Getenv("HTMLDOCS_URL"), bytes.NewBuffer(payload))
if err != nil {
log.Warnf("Error creating request:", err)
return err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("HTMLDOCS_KEY"))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Warnf("Error sending request:", err)
return err
}
defer resp.Body.Close()
log.Warnf("Response Status:", resp.Status)
res := new(struct {
Url string `json:"url"`
Error string `json:"error"`
})
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, res)
if err != nil {
log.Warnf("error decoding response: %s", err)
return err
}
if res.Error != "" {
log.Warnf("error building pdf file %s", err)
return errors.New(res.Error)
}
resp, err = http.Get(res.Url)
if err != nil {
log.Warnf("Error retrieving file")
return err
}
defer resp.Body.Close()
file, err := os.Create("tmp.pdf")
if err != nil {
log.Fatal(err)
}
defer file.Close()
body, err = io.ReadAll(resp.Body)
if err != nil {
return err
}
_, err = file.Write(body)
if err != nil {
log.Error("Error copying file content")
return err
}
return c.Attachment("tmp.pdf", "tmp.pdf")

View file

@ -32,5 +32,5 @@ func (s Server) MountHandlers() {
s.Router.POST(fmt.Sprintf("%s/:id/items", constants.RouteBooking), s.handleCreateItem())
s.Router.GET(constants.RouteReports, s.handleReportsPage())
s.Router.GET(fmt.Sprintf("%s/do", constants.RouteReports), s.handleComputeReport())
s.Router.GET("/pdf", s.handleCreateInvoicePdf())
s.Router.GET("/pdf", handleCreateInvoicePdf(s.ps))
}

View file

@ -14,12 +14,14 @@ import (
"gorm.io/gorm"
"github.com/rjNemo/rentease/internal/domains/booking"
"github.com/rjNemo/rentease/internal/pdf"
)
type Server struct {
Router *echo.Echo
db *gorm.DB
bs *booking.Service
ps *pdf.PdfService
addr string
}
@ -28,6 +30,7 @@ func New(db *gorm.DB) *Server {
Router: echo.New(),
db: db,
bs: booking.NewService(db),
ps: pdf.NewPdfService(),
addr: fmt.Sprintf("0.0.0.0:%s", os.Getenv("PORT")),
}
}