Skip to content

Commit 2c6543b

Browse files
authored
Merge pull request #51 from cbullinger/docsp-46497-hist-invoices
DOCSP-46497 & DOCSP-46233: Add historical and line item billing examples to Go SDK project
2 parents 721c3dc + 56f18b1 commit 2c6543b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+3729
-949
lines changed

generated-usage-examples/go/atlas-sdk-go/main.snippet.get-logs.go

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,57 +5,67 @@ import (
55
"context"
66
"fmt"
77
"log"
8-
"os"
9-
"path/filepath"
10-
"time"
118

12-
"github.com/joho/godotenv"
13-
"go.mongodb.org/atlas-sdk/v20250219001/admin"
14-
15-
"atlas-sdk-go/internal"
169
"atlas-sdk-go/internal/auth"
1710
"atlas-sdk-go/internal/config"
11+
"atlas-sdk-go/internal/errors"
12+
"atlas-sdk-go/internal/fileutils"
1813
"atlas-sdk-go/internal/logs"
14+
15+
"github.com/joho/godotenv"
16+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
1917
)
2018

2119
func main() {
22-
_ = godotenv.Load()
20+
if err := godotenv.Load(); err != nil {
21+
log.Printf("Warning: .env file not loaded: %v", err)
22+
}
23+
2324
secrets, cfg, err := config.LoadAll("configs/config.json")
2425
if err != nil {
25-
log.Fatalf("config load: %v", err)
26+
errors.ExitWithError("Failed to load configuration", err)
2627
}
2728

28-
sdk, err := auth.NewClient(cfg, secrets)
29+
client, err := auth.NewClient(cfg, secrets)
2930
if err != nil {
30-
log.Fatalf("client init: %v", err)
31+
errors.ExitWithError("Failed to initialize authentication client", err)
3132
}
3233

3334
ctx := context.Background()
35+
36+
// Fetch logs with the provided parameters
3437
p := &admin.GetHostLogsApiParams{
3538
GroupId: cfg.ProjectID,
3639
HostName: cfg.HostName,
3740
LogName: "mongodb",
3841
}
39-
ts := time.Now().Format("20060102_150405")
40-
base := fmt.Sprintf("%s_%s_%s", p.HostName, p.LogName, ts)
41-
outDir := "logs"
42-
os.MkdirAll(outDir, 0o755)
43-
gzPath := filepath.Join(outDir, base+".gz")
44-
txtPath := filepath.Join(outDir, base+".txt")
42+
rc, err := logs.FetchHostLogs(ctx, client.MonitoringAndLogsApi, p)
43+
if err != nil {
44+
errors.ExitWithError("Failed to fetch logs", err)
45+
}
46+
defer fileutils.SafeClose(rc)
4547

46-
rc, err := logs.FetchHostLogs(ctx, sdk.MonitoringAndLogsApi, p)
48+
// Prepare output paths
49+
outDir := "logs"
50+
prefix := fmt.Sprintf("%s_%s", p.HostName, p.LogName)
51+
gzPath, err := fileutils.GenerateOutputPath(outDir, prefix, "gz")
52+
if err != nil {
53+
errors.ExitWithError("Failed to generate GZ output path", err)
54+
}
55+
txtPath, err := fileutils.GenerateOutputPath(outDir, prefix, "txt")
4756
if err != nil {
48-
log.Fatalf("download logs: %v", err)
57+
errors.ExitWithError("Failed to generate TXT output path", err)
4958
}
50-
defer internal.SafeClose(rc)
5159

52-
if err := logs.WriteToFile(rc, gzPath); err != nil {
53-
log.Fatalf("save gz: %v", err)
60+
// Save compressed logs
61+
if err := fileutils.WriteToFile(rc, gzPath); err != nil {
62+
errors.ExitWithError("Failed to save compressed logs", err)
5463
}
5564
fmt.Println("Saved compressed log to", gzPath)
5665

57-
if err := logs.DecompressGzip(gzPath, txtPath); err != nil {
58-
log.Fatalf("decompress: %v", err)
66+
// Decompress logs
67+
if err := fileutils.DecompressGzip(gzPath, txtPath); err != nil {
68+
errors.ExitWithError("Failed to decompress logs", err)
5969
}
6070
fmt.Println("Uncompressed log to", txtPath)
6171
}

generated-usage-examples/go/atlas-sdk-go/main.snippet.get-metrics-dev.go

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,33 @@ import (
77
"fmt"
88
"log"
99

10-
"github.com/joho/godotenv"
11-
"go.mongodb.org/atlas-sdk/v20250219001/admin"
12-
1310
"atlas-sdk-go/internal/auth"
1411
"atlas-sdk-go/internal/config"
12+
"atlas-sdk-go/internal/errors"
1513
"atlas-sdk-go/internal/metrics"
14+
15+
"github.com/joho/godotenv"
16+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
1617
)
1718

1819
func main() {
19-
_ = godotenv.Load()
20+
if err := godotenv.Load(); err != nil {
21+
log.Printf("Warning: .env file not loaded: %v", err)
22+
}
23+
2024
secrets, cfg, err := config.LoadAll("configs/config.json")
2125
if err != nil {
22-
log.Fatalf("config load: %v", err)
26+
errors.ExitWithError("Failed to load configuration", err)
2327
}
2428

25-
sdk, err := auth.NewClient(cfg, secrets)
29+
client, err := auth.NewClient(cfg, secrets)
2630
if err != nil {
27-
log.Fatalf("client init: %v", err)
31+
errors.ExitWithError("Failed to initialize authentication client", err)
2832
}
2933

3034
ctx := context.Background()
35+
36+
// Fetch disk metrics with the provided parameters
3137
p := &admin.GetDiskMeasurementsApiParams{
3238
GroupId: cfg.ProjectID,
3339
ProcessId: cfg.ProcessID,
@@ -36,13 +42,16 @@ func main() {
3642
Granularity: admin.PtrString("P1D"),
3743
Period: admin.PtrString("P1D"),
3844
}
39-
40-
view, err := metrics.FetchDiskMetrics(ctx, sdk.MonitoringAndLogsApi, p)
45+
view, err := metrics.FetchDiskMetrics(ctx, client.MonitoringAndLogsApi, p)
4146
if err != nil {
42-
log.Fatalf("disk metrics: %v", err)
47+
errors.ExitWithError("Failed to fetch disk metrics", err)
4348
}
4449

45-
out, _ := json.MarshalIndent(view, "", " ")
50+
// Output metrics
51+
out, err := json.MarshalIndent(view, "", " ")
52+
if err != nil {
53+
errors.ExitWithError("Failed to format metrics data", err)
54+
}
4655
fmt.Println(string(out))
4756
}
4857

generated-usage-examples/go/atlas-sdk-go/main.snippet.get-metrics-prod.go

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,35 @@ import (
77
"fmt"
88
"log"
99

10-
"github.com/joho/godotenv"
11-
"go.mongodb.org/atlas-sdk/v20250219001/admin"
10+
"atlas-sdk-go/internal/errors"
1211

1312
"atlas-sdk-go/internal/auth"
1413
"atlas-sdk-go/internal/config"
14+
15+
"github.com/joho/godotenv"
16+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
17+
1518
"atlas-sdk-go/internal/metrics"
1619
)
1720

1821
func main() {
19-
_ = godotenv.Load()
22+
if err := godotenv.Load(); err != nil {
23+
log.Printf("Warning: .env file not loaded: %v", err)
24+
}
25+
2026
secrets, cfg, err := config.LoadAll("configs/config.json")
2127
if err != nil {
22-
log.Fatalf("config load: %v", err)
28+
errors.ExitWithError("Failed to load configuration", err)
2329
}
2430

25-
sdk, err := auth.NewClient(cfg, secrets)
31+
client, err := auth.NewClient(cfg, secrets)
2632
if err != nil {
27-
log.Fatalf("client init: %v", err)
33+
errors.ExitWithError("Failed to initialize authentication client", err)
2834
}
2935

3036
ctx := context.Background()
37+
38+
// Fetch process metrics with the provided parameters
3139
p := &admin.GetHostMeasurementsApiParams{
3240
GroupId: cfg.ProjectID,
3341
ProcessId: cfg.ProcessID,
@@ -42,12 +50,16 @@ func main() {
4250
Period: admin.PtrString("P7D"),
4351
}
4452

45-
view, err := metrics.FetchProcessMetrics(ctx, sdk.MonitoringAndLogsApi, p)
53+
view, err := metrics.FetchProcessMetrics(ctx, client.MonitoringAndLogsApi, p)
4654
if err != nil {
47-
log.Fatalf("process metrics: %v", err)
55+
errors.ExitWithError("Failed to fetch process metrics", err)
4856
}
4957

50-
out, _ := json.MarshalIndent(view, "", " ")
58+
// Output metrics
59+
out, err := json.MarshalIndent(view, "", " ")
60+
if err != nil {
61+
errors.ExitWithError("Failed to format metrics data", err)
62+
}
5163
fmt.Println(string(out))
5264
}
5365

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// See entire project at https://github.com/mongodb/atlas-architecture-go-sdk
2+
package main
3+
4+
import (
5+
"context"
6+
"fmt"
7+
"log"
8+
"time"
9+
10+
"atlas-sdk-go/internal/auth"
11+
"atlas-sdk-go/internal/billing"
12+
"atlas-sdk-go/internal/config"
13+
"atlas-sdk-go/internal/data/export"
14+
"atlas-sdk-go/internal/errors"
15+
"atlas-sdk-go/internal/fileutils"
16+
17+
"github.com/joho/godotenv"
18+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
19+
)
20+
21+
func main() {
22+
if err := godotenv.Load(); err != nil {
23+
log.Printf("Warning: .env file not loaded: %v", err)
24+
}
25+
26+
secrets, cfg, err := config.LoadAll("configs/config.json")
27+
if err != nil {
28+
errors.ExitWithError("Failed to load configuration", err)
29+
}
30+
31+
client, err := auth.NewClient(cfg, secrets)
32+
if err != nil {
33+
errors.ExitWithError("Failed to initialize authentication client", err)
34+
}
35+
36+
ctx := context.Background()
37+
p := &admin.ListInvoicesApiParams{
38+
OrgId: cfg.OrgID,
39+
}
40+
41+
fmt.Printf("Fetching historical invoices for organization: %s\n", p.OrgId)
42+
43+
// Fetch invoices from the previous six months with the provided options
44+
invoices, err := billing.ListInvoicesForOrg(ctx, client.InvoicesApi, p,
45+
billing.WithViewLinkedInvoices(true),
46+
billing.WithIncludeCount(true),
47+
billing.WithDateRange(time.Now().AddDate(0, -6, 0), time.Now()))
48+
if err != nil {
49+
errors.ExitWithError("Failed to retrieve invoices", err)
50+
}
51+
52+
if invoices.GetTotalCount() > 0 {
53+
fmt.Printf("Total count of invoices: %d\n", invoices.GetTotalCount())
54+
} else {
55+
fmt.Println("No invoices found for the specified date range")
56+
return
57+
}
58+
59+
// Export invoice data to be used in other systems or for reporting
60+
outDir := "invoices"
61+
prefix := fmt.Sprintf("historical_%s", p.OrgId)
62+
63+
exportInvoicesToJSON(invoices, outDir, prefix)
64+
exportInvoicesToCSV(invoices, outDir, prefix)
65+
}
66+
67+
func exportInvoicesToJSON(invoices *admin.PaginatedApiInvoiceMetadata, outDir, prefix string) {
68+
jsonPath, err := fileutils.GenerateOutputPath(outDir, prefix, "json")
69+
if err != nil {
70+
errors.ExitWithError("Failed to generate JSON output path", err)
71+
}
72+
if err := export.ToJSON(invoices.GetResults(), jsonPath); err != nil {
73+
errors.ExitWithError("Failed to write JSON file", err)
74+
}
75+
fmt.Printf("Exported invoice data to %s\n", jsonPath)
76+
}
77+
78+
func exportInvoicesToCSV(invoices *admin.PaginatedApiInvoiceMetadata, outDir, prefix string) {
79+
csvPath, err := fileutils.GenerateOutputPath(outDir, prefix, "csv")
80+
if err != nil {
81+
errors.ExitWithError("Failed to generate CSV output path", err)
82+
}
83+
84+
// Set the headers and mapped rows for the CSV export
85+
headers := []string{"InvoiceID", "Status", "Created", "AmountBilled"}
86+
err = export.ToCSVWithMapper(invoices.GetResults(), csvPath, headers, func(invoice admin.BillingInvoiceMetadata) []string {
87+
return []string{
88+
invoice.GetId(),
89+
invoice.GetStatusName(),
90+
invoice.GetCreated().Format(time.RFC3339),
91+
fmt.Sprintf("%.2f", float64(invoice.GetAmountBilledCents())/100.0),
92+
}
93+
})
94+
if err != nil {
95+
errors.ExitWithError("Failed to write CSV file", err)
96+
}
97+
98+
fmt.Printf("Exported invoice data to %s\n", csvPath)
99+
}
100+

0 commit comments

Comments
 (0)