Skip to content

Commit

Permalink
Add query mode and Separate UA and GA4 Frontend (#87)
Browse files Browse the repository at this point in the history
* Add Query Mode(time series, table), Seperate UA, GA4 query editor

* Add error message at no time dimensions

* Fix CI
  • Loading branch information
lcc3108 authored Sep 17, 2023
1 parent 863f375 commit f325c04
Show file tree
Hide file tree
Showing 10 changed files with 384 additions and 22 deletions.
19 changes: 12 additions & 7 deletions pkg/gav4/analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,28 @@ func (ga *GoogleAnalytics) Query(ctx context.Context, config *setting.Datasource
return nil, fmt.Errorf("failed to read query: %w", err)
}

if len(queryModel.AccountID) < 1 {
log.DefaultLogger.Error("Query", "error", "Required AccountID")
return nil, fmt.Errorf("Required AccountID")
}

if len(queryModel.WebPropertyID) < 1 {
if len(queryModel.WebPropertyID) == 0 {
log.DefaultLogger.Error("Query", "error", "Required WebPropertyID")
return nil, fmt.Errorf("Required WebPropertyID")
}

if len(queryModel.Dimensions) == 0 && len(queryModel.Metrics) == 0 {
log.DefaultLogger.Error("Query", "error", "Required Dimensions or Metrics")
return nil, fmt.Errorf("Required Dimensions or Metrics")
}

if queryModel.Mode == "time series" && len(queryModel.TimeDimension) == 0 {
log.DefaultLogger.Error("Query", "error", "TimeSeries query need TimeDimension")
return nil, fmt.Errorf("TimeSeries query need TimeDimensions")
}

report, err := client.getReport(*queryModel)
if err != nil {
log.DefaultLogger.Error("Query", "error", err)
return nil, err
}

return transformReportsResponseToDataFrames(report, queryModel.RefID, queryModel.Timezone)
return transformReportsResponseToDataFrames(report, queryModel.RefID, queryModel.Timezone, queryModel.Mode)

}

Expand Down
17 changes: 9 additions & 8 deletions pkg/gav4/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,20 @@ func (client *GoogleClient) getReport(query model.QueryModel) (*analyticsdata.Ru
// Create the DateRange object.
{StartDate: query.StartDate, EndDate: query.EndDate},
},
Metrics: Metrics,
Dimensions: Dimensions,
Offset: offset,
OrderBys: []*analyticsdata.OrderBy{
Metrics: Metrics,
Dimensions: Dimensions,
Offset: offset,
KeepEmptyRows: true,
}
if len(query.Dimensions) > 0 {
req.OrderBys = []*analyticsdata.OrderBy{
{
Dimension: &analyticsdata.DimensionOrderBy{
DimensionName: query.TimeDimension,
DimensionName: query.Dimensions[0],
},
},
},
KeepEmptyRows: true,
}
}

log.DefaultLogger.Debug("Doing GET request from analytics reporting", "req", req)
// Call the BatchGet method and return the response.
report, err := client.analyticsdata.Properties.RunReport(query.WebPropertyID, &req).Do()
Expand Down
52 changes: 49 additions & 3 deletions pkg/gav4/grafana.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,44 @@ func transformReportToDataFrameByDimensions(columns []*model.ColumnDefinition, r
}

// <--------- primary secondary --------->
var timeDimensions []string = []string{"dateHourMinute", "gdateHour", "date", "firstSessionDate"}
var timeDimensions []string = []string{"dateHourMinute", "dateHour", "date", "firstSessionDate"}

func transformReportToDataFramesTableMode(report *analyticsdata.RunReportResponse, refId string, timezone string) ([]*data.Frame, error) {
// return nil,nil
otherDimensions := make([]*analyticsdata.MetricHeader, 0)
for _, dimension := range report.DimensionHeaders {
otherDimensions = append([]*analyticsdata.MetricHeader{
{
Name: dimension.Name,
Type: "STRING",
},
}, otherDimensions...)
}
report.MetricHeaders = append(otherDimensions, report.MetricHeaders...)

for _, row := range report.Rows {
for _, dimensionValue := range row.DimensionValues {
row.MetricValues = append([]*analyticsdata.MetricValue{
{
Value: dimensionValue.Value,
},
}, row.MetricValues...)
row.DimensionValues = nil
}
}

var frames = make([]*data.Frame, 0)
columns := getColumnDefinitions(report.MetricHeaders)
frame, err := transformReportToDataFrameByDimensions(columns, report.Rows, refId, "")
if err != nil {
log.DefaultLogger.Error("transformReportToDataFrameByDimensions", "error", err.Error())
return nil, err
}

frames = append(frames, frame)

return frames, nil
}

func transformReportToDataFrames(report *analyticsdata.RunReportResponse, refId string, timezone string) ([]*data.Frame, error) {
// return nil,nil
Expand Down Expand Up @@ -167,10 +204,19 @@ func transformReportToDataFrames(report *analyticsdata.RunReportResponse, refId
return frames, nil
}

func transformReportsResponseToDataFrames(reportsResponse *analyticsdata.RunReportResponse, refId string, timezone string) (*data.Frames, error) {
func transformReportsResponseToDataFrames(reportsResponse *analyticsdata.RunReportResponse, refId string, timezone string, mode string) (*data.Frames, error) {
var frames = make(data.Frames, 0)
// for _, report := range reportsResponse.Rows {
frame, err := transformReportToDataFrames(reportsResponse, refId, timezone)
var transformReportToDataFramesFn func(*analyticsdata.RunReportResponse, string, string) ([]*data.Frame, error)
switch mode {
case "time series":
transformReportToDataFramesFn = transformReportToDataFrames
case "table":
transformReportToDataFramesFn = transformReportToDataFramesTableMode
default:
transformReportToDataFramesFn = transformReportToDataFramesTableMode
}
frame, err := transformReportToDataFramesFn(reportsResponse, refId, timezone)
if err != nil {
return nil, err
}
Expand Down
4 changes: 3 additions & 1 deletion pkg/gav4/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ func GetQueryModel(query backend.DataQuery) (*model.QueryModel, error) {

model.StartDate = query.TimeRange.From.In(timezone).Format("2006-01-02")
model.EndDate = query.TimeRange.To.In(timezone).Format("2006-01-02")
model.Dimensions = append([]string{model.TimeDimension}, model.Dimensions...)
if model.TimeDimension != "" {
model.Dimensions = append([]string{model.TimeDimension}, model.Dimensions...)
}
// model.TimeRange = query.TimeRange
// model.MaxDataPoints = query.MaxDataPoints
return model, nil
Expand Down
1 change: 1 addition & 0 deletions pkg/model/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ type QueryModel struct {
Timezone string `json:"timezone,omitempty"`
FiltersExpression string `json:"filtersExpression,omitempty"`
Offset int64 `json:"offset,omitempty"`
Mode string `json:"mode,omitempty"`
// Not from JSON
// TimeRange backend.TimeRange `json:"-"`
// MaxDataPoints int64 `json:"-"`
Expand Down
26 changes: 26 additions & 0 deletions src/QueryEditorCommon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { QueryEditorProps } from '@grafana/data';
import { DataSource } from 'DataSource';
import { QueryEditorGA4 } from 'QueryEditorGA4';
import { QueryEditorUA } from 'QueryEditorUA';
import React, { PureComponent } from 'react';
import { GADataSourceOptions, GAQuery } from 'types';

type Props = QueryEditorProps<DataSource, GAQuery, GADataSourceOptions>;


export class QueryEditorCommon extends PureComponent<Props> {
constructor(props: Readonly<Props>) {
super(props);
this.props.query.version = props.datasource.getGaVersion()
}
render() {
console.log("common")
const { query, datasource, onChange, onRunQuery } = this.props;
const { version } = query
if (version === "v4") {
return <QueryEditorGA4 datasource={datasource} onChange={onChange} onRunQuery={onRunQuery} query={query}></QueryEditorGA4>
} else {
return <QueryEditorUA datasource={datasource} onChange={onChange} onRunQuery={onRunQuery} query={query}></QueryEditorUA>
}
}
}
Loading

0 comments on commit f325c04

Please sign in to comment.