Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Parse scientific notation in GA import

Uku Tahted871e7a0bd6
diff --git a/lib/plausible/imported/site.ex b/lib/plausible/imported/site.ex
index c9370f96ce..43bc7208a2 100644
--- a/lib/plausible/imported/site.ex
+++ b/lib/plausible/imported/site.ex
@@ -23,14 +23,22 @@ defmodule Plausible.Imported do
end
end
+ defp parse_number(nr) do
+ # Scientific notation
+ if String.contains?(nr, "E") do
+ {float, ""} = Float.parse(nr)
+ float
+ else
+ {int, ""} = Integer.parse(nr)
+ int
+ end
+ end
+
defp new_from_google_analytics(site_id, "imported_visitors", %{
"dimensions" => [date],
"metrics" => [%{"values" => values}]
}) do
- [visitors, pageviews, bounces, visits, visit_duration] =
- values
- |> Enum.map(&Integer.parse/1)
- |> Enum.map(&elem(&1, 0))
+ [visitors, pageviews, bounces, visits, visit_duration] = values |> Enum.map(&parse_number/1)
%{
site_id: site_id,
diff --git a/test/plausible/imported/imported_test.exs b/test/plausible/imported/imported_test.exs
index d211d2215e..b603f2ace8 100644
--- a/test/plausible/imported/imported_test.exs
+++ b/test/plausible/imported/imported_test.exs
@@ -602,5 +602,40 @@ defmodule Plausible.ImportedTest do
%{"name" => "GNU/Linux", "visitors" => 2, "percentage" => 40}
]
end
+
+ test "Can import visit duration with scientific notation", %{conn: conn, site: site} do
+ populate_stats(site, [
+ build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),
+ build(:pageview, timestamp: ~N[2021-01-31 00:00:00])
+ ])
+
+ assert :ok =
+ Plausible.Imported.from_google_analytics(
+ [
+ %{
+ "dimensions" => ["20210101"],
+ "metrics" => [%{"values" => ["1", "1", "0", "1", "1.391607E7"]}]
+ },
+ %{
+ "dimensions" => ["20210131"],
+ "metrics" => [%{"values" => ["1", "1", "1", "1", "60"]}]
+ }
+ ],
+ site.id,
+ "imported_visitors"
+ )
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/main-graph?period=month&date=2021-01-01&with_imported=true"
+ )
+
+ assert %{"top_stats" => top_stats} = json_response(conn, 200)
+
+ visit_duration = Enum.find(top_stats, fn stat -> stat["name"] == "Visit duration" end)
+
+ assert visit_duration["value"] == 3_479_033
+ end
end
end