From c3d2e09715a656aeb144a87520e0901c6525ea2b Mon Sep 17 00:00:00 2001 From: Vilen Topchii <32271530+vtopc@users.noreply.github.com> Date: Tue, 17 Sep 2024 20:14:49 +0300 Subject: [PATCH] WIP --- analytics.go | 56 +++++++++++++++++++++++++ analytics_request.go | 40 ++++++++++++++++++ analytics_response.go | 95 +++++++++++++++++++++++++++++++++++++++++++ analytics_test.go | 23 +++++++++++ 4 files changed, 214 insertions(+) create mode 100644 analytics.go create mode 100644 analytics_request.go create mode 100644 analytics_response.go create mode 100644 analytics_test.go diff --git a/analytics.go b/analytics.go new file mode 100644 index 00000000..c8eb4181 --- /dev/null +++ b/analytics.go @@ -0,0 +1,56 @@ +package mailgun + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/pkg/errors" +) + +// ListMetrics returns account metrics. +// Must be /v1 API. +// https://documentation.mailgun.com/docs/mailgun/api-reference/openapi-final/tag/Metrics/ +func (c *Client) ListMetrics(ctx context.Context, opts MetricsOptions) (*MetricsResponse, error) { + url := fmt.Sprintf("%s", metricsEndpoint) + mRequest, err := json.Marshal(opts) + if err != nil { + return nil, errors.Wrap(err, "while marshalling analytics metrics request") + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(mRequest)) + if err != nil { + return nil, errors.Wrap(err, "while creating analytics metrics request") + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, errors.Wrap(err, "while making analytics metrics request") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return nil, errors.Errorf("POST on '%s' returned %s", url, string(body)) + } + + var ret MetricsResponse + if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil { + return nil, errors.Wrap(err, "while decoding analytics metrics response") + } + + return &ret, nil +} + +type MetricsPagination struct { + // Colon-separated value indicating column name and sort direction e.g. 'domain:asc'. + Sort string `json:"sort"` + // The number of items to skip over when satisfying the request. To get the first page of data set skip to zero. Then increment the skip by the limit for subsequent calls. + Skip int64 `json:"skip"` + // The maximum number of items returned in the response. + Limit int64 `json:"limit"` + // The total number of items in the query result set. + Total int64 `json:"total"` +} diff --git a/analytics_request.go b/analytics_request.go new file mode 100644 index 00000000..f4a7952f --- /dev/null +++ b/analytics_request.go @@ -0,0 +1,40 @@ +package mailgun + +type MetricsOptions struct { + // A start date (default: 7 days before current time). + Start RFC2822Time `json:"start"` + // An end date (default: current time). + End RFC2822Time `json:"end"` + // A resolution in the format of 'day' 'hour' 'month'. Default is day. + Resolution Resolution `json:"resolution,omitempty"` + // A duration in the format of '1d' '2h' '2m'. + // If duration is provided then it is calculated from the end date and overwrites the start date. + Duration string `json:"duration,omitempty"` + // Attributes of the metric data such as 'time' 'domain' 'ip' 'ip_pool' 'recipient_domain' 'tag' 'country' 'subaccount'. + Dimensions []string `json:"dimensions,omitempty"` + // Name of the metrics to receive the stats for such as 'accepted_count' 'delivered_count' 'accepted_rate'. + Metrics []string `json:"metrics,omitempty"` + // Filters to apply to the query. + Filter MetricsFilterPredicateGroup `json:"filter,omitempty"` + // Include stats from all subaccounts. + IncludeSubaccounts bool `json:"include_subaccounts,omitempty"` + // Include top-level aggregate metrics. + IncludeAggregates bool `json:"include_aggregates,omitempty"` + // Attributes used for pagination and sorting. + Pagination MetricsPagination `json:"pagination,omitempty"` +} + +type MetricsLabeledValue struct { + Label string `json:"label"` + Value string `json:"value"` +} + +type MetricsFilterPredicate struct { + Attribute string `json:"attribute"` + Comparator string `json:"comparator"` + LabeledValues []MetricsLabeledValue `json:"values,omitempty"` +} + +type MetricsFilterPredicateGroup struct { + BoolGroupAnd []MetricsFilterPredicate `json:"AND,omitempty"` +} diff --git a/analytics_response.go b/analytics_response.go new file mode 100644 index 00000000..3c2a2337 --- /dev/null +++ b/analytics_response.go @@ -0,0 +1,95 @@ +package mailgun + +type MetricsResponse struct { + Start string `json:"start"` + End string `json:"end"` + Resolution Resolution `json:"resolution"` + Duration string `json:"duration"` + Dimensions []string `json:"dimensions"` + Pagination MetricsPagination `json:"pagination"` + Items []MetricsItem `json:"items"` + Aggregates MetricsAggregates `json:"aggregates"` +} + +type MetricsItem struct { + Dimensions []MetricsDimension `json:"dimensions"` + Metrics Metrics `json:"metrics"` +} + +type MetricsAggregates struct { + Metrics Metrics `json:"metrics"` +} + +type Metrics struct { + AcceptedIncomingCount *uint64 `json:"accepted_incoming_count"` + AcceptedOutgoingCount *uint64 `json:"accepted_outgoing_count"` + AcceptedCount *uint64 `json:"accepted_count"` + DeliveredSMTPCount *uint64 `json:"delivered_smtp_count"` + DeliveredHTTPCount *uint64 `json:"delivered_http_count"` + DeliveredOptimizedCount *uint64 `json:"delivered_optimized_count"` + DeliveredCount *uint64 `json:"delivered_count"` + StoredCount *uint64 `json:"stored_count"` + ProcessedCount *uint64 `json:"processed_count"` + SentCount *uint64 `json:"sent_count"` + OpenedCount *uint64 `json:"opened_count"` + ClickedCount *uint64 `json:"clicked_count"` + UniqueOpenedCount *uint64 `json:"unique_opened_count"` + UniqueClickedCount *uint64 `json:"unique_clicked_count"` + UnsubscribedCount *uint64 `json:"unsubscribed_count"` + ComplainedCount *uint64 `json:"complained_count"` + FailedCount *uint64 `json:"failed_count"` + TemporaryFailedCount *uint64 `json:"temporary_failed_count"` + PermanentFailedCount *uint64 `json:"permanent_failed_count"` + ESPBlockCount *uint64 `json:"esp_block_count"` + WebhookCount *uint64 `json:"webhook_count"` + PermanentFailedOptimizedCount *uint64 `json:"permanent_failed_optimized_count"` + PermanentFailedOldCount *uint64 `json:"permanent_failed_old_count"` + BouncedCount *uint64 `json:"bounced_count"` + HardBouncesCount *uint64 `json:"hard_bounces_count"` + SoftBouncesCount *uint64 `json:"soft_bounces_count"` + DelayedBounceCount *uint64 `json:"delayed_bounce_count"` + SuppressedBouncesCount *uint64 `json:"suppressed_bounces_count"` + SuppressedUnsubscribedCount *uint64 `json:"suppressed_unsubscribed_count"` + SuppressedComplaintsCount *uint64 `json:"suppressed_complaints_count"` + DeliveredFirstAttemptCount *uint64 `json:"delivered_first_attempt_count"` + DelayedFirstAttemptCount *uint64 `json:"delayed_first_attempt_count"` + DeliveredSubsequentCount *uint64 `json:"delivered_subsequent_count"` + DeliveredTwoPlusAttemptsCount *uint64 `json:"delivered_two_plus_attempts_count"` + + DeliveredRate string `json:"delivered_rate"` + OpenedRate string `json:"opened_rate"` + ClickedRate string `json:"clicked_rate"` + UniqueOpenedRate string `json:"unique_opened_rate"` + UniqueClickedRate string `json:"unique_clicked_rate"` + UnsubscribedRate string `json:"unsubscribed_rate"` + ComplainedRate string `json:"complained_rate"` + BounceRate string `json:"bounce_rate"` + FailRate string `json:"fail_rate"` + PermanentFailRate string `json:"permanent_fail_rate"` + TemporaryFailRate string `json:"temporary_fail_rate"` + DelayedRate string `json:"delayed_rate"` + + // usage metrics + EmailValidationCount *uint64 `json:"email_validation_count"` + EmailValidationPublicCount *uint64 `json:"email_validation_public_count"` + EmailValidationValidCount *uint64 `json:"email_validation_valid_count"` + EmailValidationSingleCount *uint64 `json:"email_validation_single_count"` + EmailValidationBulkCount *uint64 `json:"email_validation_bulk_count"` + EmailValidationListCount *uint64 `json:"email_validation_list_count"` + EmailValidationMailgunCount *uint64 `json:"email_validation_mailgun_count"` + EmailValidationMailjetCount *uint64 `json:"email_validation_mailjet_count"` + EmailPreviewCount *uint64 `json:"email_preview_count"` + EmailPreviewFailedCount *uint64 `json:"email_preview_failed_count"` + LinkValidationCount *uint64 `json:"link_validation_count"` + LinkValidationFailedCount *uint64 `json:"link_validation_failed_count"` + SeedTestCount *uint64 `json:"seed_test_count"` +} + +type MetricsDimension struct { + // The dimension + Dimension string `json:"dimension"` + // The dimension value + Value string `json:"value"` + // The dimension value in displayable form + DisplayValue string `json:"display_value"` +} diff --git a/analytics_test.go b/analytics_test.go new file mode 100644 index 00000000..0a96c7a4 --- /dev/null +++ b/analytics_test.go @@ -0,0 +1,23 @@ +package mailgun + +var mockAcceptedIncomingCount uint64 = 10 + +var expectedResponse = MetricsResponse{ + Start: "Mon, 15 Apr 2024 00:00:00 +0000", + Dimensions: []string{"time"}, + Items: []MetricsItem{ + { + Dimensions: []MetricsDimension{ + { + Dimension: "time", + Value: "Mon, 15 Apr 2024 00:00:00 +0000", + DisplayValue: "Mon, 15 Apr 2024 00:00:00 +0000", + }, + }, + Metrics: Metrics{ + AcceptedIncomingCount: &mockAcceptedIncomingCount, + ClickedRate: "0.8300", + }, + }, + }, +}