-
Notifications
You must be signed in to change notification settings - Fork 1
/
invoice_command.go
78 lines (64 loc) · 1.85 KB
/
invoice_command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"time"
"github.com/urfave/cli/v2"
"github.com/appuio/appuio-cloud-reporting/pkg/db"
"github.com/appuio/appuio-cloud-reporting/pkg/invoice"
)
type invoiceCommand struct {
DatabaseURL string
Year int
Month time.Month
}
var invoiceCommandName = "invoice"
func newInvoiceCommand() *cli.Command {
command := &invoiceCommand{}
return &cli.Command{
Name: invoiceCommandName,
Usage: "Run a invoice for a query in the given period",
Before: command.before,
Action: command.execute,
Flags: []cli.Flag{
newDbURLFlag(&command.DatabaseURL),
&cli.IntFlag{Name: "year", Usage: "Year to generate the report for.",
EnvVars: envVars("YEAR"), Destination: &command.Year, Required: true},
&cli.IntFlag{Name: "month", Usage: "Month to generate the report for.",
EnvVars: envVars("MONTH"), Destination: (*int)(&command.Month), Required: true},
},
}
}
func (cmd *invoiceCommand) before(context *cli.Context) error {
if cmd.Month < 1 || cmd.Month > 12 {
return fmt.Errorf("unknown month %q", cmd.Month)
}
return LogMetadata(context)
}
func (cmd *invoiceCommand) execute(cliCtx *cli.Context) error {
ctx := cliCtx.Context
log := AppLogger(ctx).WithName(invoiceCommandName)
log.V(1).Info("Opening database connection", "url", cmd.DatabaseURL)
rdb, err := db.Openx(cmd.DatabaseURL)
if err != nil {
return fmt.Errorf("could not open database connection: %w", err)
}
defer rdb.Close()
log.V(1).Info("Begin transaction")
tx, err := rdb.BeginTxx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
return err
}
defer tx.Rollback()
invoices, err := invoice.Generate(ctx, tx, cmd.Year, cmd.Month)
if err != nil {
return err
}
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", "\t")
enc.Encode(invoices)
return enc.Encode(invoices)
}