package main
import (
"context"
"fmt"
"net/http"
"sort"
"time"
pb "code.hackerspace.pl/hscloud/bgpwtf/invoice/proto"
"code.hackerspace.pl/hscloud/go/mirko"
"code.hackerspace.pl/hscloud/go/statusz"
"github.com/golang/glog"
)
const invoicesFragment = `
{{ .Msg }}
Number |
Created/Issued |
Customer |
Amount (net) |
Actions |
{{ range .Invoices }}
{{ if eq .State 2 }}
{{ else }}
{{ end }}
{{ .FinalUid }} |
{{ .DatePretty.Format "2006/01/02 15:04:05" }} |
{{ index .Data.CustomerBilling 0 }} |
{{ .TotalNetPretty }} |
{{ if eq .State 2 }}
View
{{ else }}
Preview (en) |
Preview (pl)
{{ end }}
|
{{ end }}
`
type templateInvoice struct {
*pb.Invoice
TotalNetPretty string
DatePretty time.Time
}
func (s *service) setupStatusz(m *mirko.Mirko) {
statusz.AddStatusPart("Invoices", invoicesFragment, func(ctx context.Context) interface{} {
var res struct {
Invoices []templateInvoice
Msg string
}
invoices, err := s.m.getInvoices(ctx)
res.Invoices = make([]templateInvoice, len(invoices))
for i, inv := range invoices {
res.Invoices[i] = templateInvoice{
Invoice: inv,
TotalNetPretty: fmt.Sprintf("%.2f %s", float64(inv.TotalNet)/100, inv.Unit),
DatePretty: time.Unix(0, inv.Date),
}
}
if err != nil {
glog.Errorf("Could not get invoices for statusz: %v", err)
res.Msg = fmt.Sprintf("Could not get invoices: %v", err)
}
sort.Slice(res.Invoices, func(i, j int) bool { return res.Invoices[i].Date > res.Invoices[j].Date })
return res
})
m.HTTPMux().HandleFunc("/debug/view", func(w http.ResponseWriter, r *http.Request) {
rendered, err := s.invoicePDF(r.Context(), r.URL.Query().Get("id"), r.URL.Query().Get("language"))
if err != nil {
fmt.Fprintf(w, "error: %v", err)
}
w.Header().Set("Content-type", "application/pdf")
w.Write(rendered)
})
}