Compare commits

...

632 Commits

Author SHA1 Message Date
Adrian Gruntkowski a7603c9e49
Improve import procedure to ensure no time range overlaps (#3970)
* Always scope import ID by site as well

* Do not schedule new import job if there are any site imports in progress

* Disable import buttons when any import is in progress

* Simplify `schedule_job/4` (h/t @RobertJoonas)
3 years ago
Adrian Gruntkowski cffff0340c
Handle Google API timeouts gracefully during imports (#3975) 3 years ago
Adrian Gruntkowski 33eed9d7db
Delete imports which have no stats (#3972) 3 years ago
Marko Saric e5b7f1afd0
Changing the copy of the locked screen (#3967)
changing the copy here as I think that in some situations the "we're still counting stats" message is now shown even to those dashboards where we've stopped counting stats so best to avoid that
3 years ago
Uku Taht f966419a4a
Update ua_inspector (#3957)
Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 f9f0407d68
Remove `experimtnal_hostname_filter` and keep it on by default (#3973)
* Remove `experimental_hostname_filter` and keep it on by default

* Catch up with changes done via e5b56dbe6
3 years ago
RobertJoonas e5b56dbe62
Refactor VisitorGraph (#3936)
* Give a more semantic name to a function

* Make the LineGraph component thinner

* Move LineGraph into a separate file

* Move interval logic into interval-picker.js

This commit also fixes a bug where the interval name displayed inside
the picker component flickers the default interval when the graph is
loading.

The problem was that we were counting on graphData for returning us the
current interval: `let currentInterval = graphData?.interval`

We should always know the default interval before making the main-graph
request. Sending graphData to IntervalPicker component does not make
sense anyway.

* extract data fetching functions out of VisitorGraph component

* Return graph_metric key from Top Stats API

This commit introduces no behavioral changes - only starts returning an
additional field, allowing us to avoid the following logic in React:

1. Finding the metric names, given a stat display name. E.g.
   `Unique visitors (last 30 min) -> visitors`

2. Checking if a metric is graphable or not

* Move metric state into localStorage

This commit gets rid of the internal `metric` state in the VisitorGraph
component and starts using localStorage for that instead.

This commit also chains the main-graph request into the top-stats request
callback - meaning that we'll always fetch new graph data after top stats
are updated. And we do it all in a single function.

Doing so simplifies the loading state significantly, and also helps to
make it clear, that at all times, existing top stats are required before
we can fetch the graph. That's because the metric is determined by which
Top stats are returned (for example, we can't be sure whether revenue
metrics will be returned or not).

* Make sure graph tooltip says "Converted Visitors"

* Extract a StatsExport function component

Again, instead of relying on `graphData?.interval` we can read it from
localStorage, or default to the largest interval available. The export
should not be dependant on the graph.

* Extract SamplingNotice function component

* Extract WithImportedSwitch function component

* Stop "lazy-loading" the graph and top stats

Since the container is always on top on the page, it will be visible on
the first render in any case - no matter the screen size.

* Turn VisitorGraph into a function component

* Display empty container until everything has loaded

* Do not display loading spinner on realtime ticks

* Turn Top Stats into a fn component

* fetch top stats and graph async

* Make sure revenue metrics can remain on the graph

* Add an extra check to canMetricBeGraphed

* fix typo

* remove redundant double negation
3 years ago
Karl-Aksel Puulmann 3115c6e7a8
Reducing JOINs in queries (#3966)
* Move experimental_session_count? logic to within query object

* WIP new querying system for deciding what tables to query

* both -> either

* Include sample_percent in both tables

* Remove a hanging TODO

* Allow filtering by visit props on event queries if flag is on

* Make default sessions join more conditional

* Simplify events_join_sessions?

* Add some TODOs

* Fix assignment

* Handle entry/exit page visit props separately from props stored in events table

* Update test which created sessions/events differently from everyone else

* Make query_events private

* Dont filter by session properties on events table if querying sessions and joining in events

* Handle visits, pageviews, events and visitors metrics from other table

* both -> either

* events, pageviews are strictly event metrics

* Add support for (plain) breakdowns deciding which table to use

* Run tests with experimental_reduced_joins as a separate job

Also refactor which tests are run with postgres:15 to reduce number of jobs

* moduledocs for TableDecider

* Fix matrix

* Custom build name

* Move TEST_EXPERIMENTAL_REDUCED_JOINS check

* Handle percentage separately from other metrics

* Remove debug code

* TableDecider tests

* both => sample_percent

* Improve naming

* Simplify code

* Breakdowns retain old behavior if getting metric visitors

* Unify behavior of entry/exit page hostnames with rest

* Fix test naming
3 years ago
hq1 6af80dd246
Filter by hostnames (#3963)
* CH Migration: exit/entry hostnames in sessions_v2

* Leave only exit_page_hostname, we already record hostnames

* Use ClickHouse DDL in favour of ecto so that cluster is included

* Compress with ZSTD(3)

* Expose Hostname filter in the dashboard dropdown

* Add `exit_page_hostname` to ClickHouse `sessions_v2` schema

* Start tracking hostname changes in sessions

* Implement hostname filter suggestions

* Enable filtering by `event:hostname`

* Add tests for filtering by hostnames

* Ensure filter suggestions work for exit pages too

* Allow overriding hostnames with `send_pageview` mix task

* Remove `:window_time_on_page` flag

It seems that we can remove it after all?

* Initialize `experimental_hostname_filter` query parameter

* Rewrite cache store behaviour with regards to session hostnames

* Work around inconsistent session merging

So that `populate_stats` can get closer to actual ingestion

* Improve top stats test

* Make it possible to filter sessions by entry/exit hostnames

* Update pages tests

* Expose `experimental_hostname_filtering` temporarily in the UI

* Untested yet: also apply experimental filtering to sources

* Introduce `hostname_filter` feature flag

* Format

* Test top sources with hostname filter + experimental flag
3 years ago
Adrian Gruntkowski e6d83e946f
Populate new columns in imports and exports (#3969)
* Extend `Imported*` schemas with newly added columns

* Populate newly added `Imported*` fields in GA4 imports

* Extend exports with newly added fields

* Extend CSV importer to ingest new fields

* Fix alias shadowing error

* Add more extensive GA4 import fixtures

* Apply rounding and casting to sampled visits
3 years ago
RobertJoonas bd73fc8266
CH Migration - add more imported metrics and properties (#3949)
* add migration

* add utm_source to imported_sources

* quickfix

* satisfy credo

* Revert "satisfy credo"

This reverts commit bb0b228164.

* Revert "quickfix"

This reverts commit ab6f70c79e.

---------

Co-authored-by: ruslandoga <67764432+ruslandoga@users.noreply.github.com>
3 years ago
ruslandoga 2ba4988c95
specify insert columns in import from s3 (#3968)
Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
hq1 1f778e0c11
CH Migration: exit page hostname on sessions_v2 (#3953)
* CH Migration: exit/entry hostnames in sessions_v2

* Leave only exit_page_hostname, we already record hostnames

* Use ClickHouse DDL in favour of ecto so that cluster is included

* Compress with ZSTD(3)
3 years ago
Adrian Gruntkowski 9f27fa303c
Fix dry run mode in `DataMigration.SiteImports` (#3965) 3 years ago
Adrian Gruntkowski 23a3699dd7
Improve import stats toggle and `with_imported` flag computation (#3960)
* Check import presence across all imports and not just the first one

Also, simplify imported data toggle rendering to not explicitly
refer to the earliest import source.

* Change imported stats toggle icon in dashboard

* Test `Imported.get_imports_date_range/1`

* Simplify failed UA/GA import email copy
3 years ago
Adrian Gruntkowski 71fe541359
Implement script for backfilling legacy site import entries and adjusting end dates of site imports (#3954)
* Always select and clear import ID 0 when referring to legacy imports

* Implement script for adding site import entries and adjusting end dates

* Log cases where end date computation is using fallback

* Don't log queries when running the migration to reduce noise
3 years ago
Adrian Gruntkowski 5bf59d1d8a
Implement adjusting imported date range to actual and existing stats (#3943)
* Implement adjusting imported date range to actual and existing stats

* Drop redundant prefix from import list entries

* Make pageview numbers in imports list formatted for readability

* Test and improve date range cropping

* DRY UA and GA4 stats start and end date API calls

* Extend UA/GA import controller tests and improve error handling

* refactor finding longest open range without existing data

* Fix typo in test description

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>

* Rename `open_ranges` to `free_ranges`

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
ruslandoga c263df5805
CSV imports (UI) (#3845)
* add basic ui

* remove TODO

* credo

* allow folder upload

* redirect external

* mention folder, use folder icon for file picker

* back to multiple file upload

* mention zip

* escape dots in archive filename
3 years ago
hq1 b31433a7bf
Ensure all the react container attributes are strings (#3948) 3 years ago
hq1 edf70d14b6
Use sessionStorage for "dashboard first launch" banner tracking (#3892)
* Use sessionStorage for offer e-mail report banner tracking

Keeping it within the cookie is problematic, as the banners don't
expire and overflow the cookie with data when enough new sites
are added.

Ref https://github.com/plausible/analytics/issues/3762

* Update changelog

* Extract a component

* Make is_dbip evaluate to quoted boolean
3 years ago
hq1 7523abe93e
Add metrics to ingestion pipeline (#3927)
* Add metrics to ingestion pipeline

* Format

* Format

* Update buckets

* Credo
3 years ago
Karl-Aksel Puulmann 604bf88451
Add github action to validate whether migrations and app change at the same time (#3945) 3 years ago
Karl-Aksel Puulmann 4af7019011
Ignore sessions without entry/exit pages when breaking down entry/exit pages (#3933)
* Ignore sessions without entry/exit pages when breaking down entry/exit pages

* Update stats controller tests to have more realistic test data (pageview followed by event)
3 years ago
hq1 2fae0146a4
Reapply 3918 (#3940)
* Reapply "Pages shield (#3918)"

This reverts commit 33b5c10654.

* Make the FF check work against the site actor
3 years ago
hq1 9989ce6927
Migration for 3918 (#3939)
* Revert "Pages shield (#3918)"

This reverts commit 53f94a9f82.

* Migration: Shield page rules
3 years ago
hq1 53f94a9f82
Pages shield (#3918)
* Migration: Shield page rules

* Add Ecto schema for Page Rules

* Add Page Rule cache

* Fix typo

* BTW: Use already imported function

* Extend Shields context interface + split existing tests

* Ingestion: filter matching patches + refactor shield actions

* Add LV section for adding Page Rules

* Validate max page path length

* Put Pages Shield behind a feature flag

* Update CHANGELOG

* Update docs link anchor

As per https://github.com/plausible/docs/pull/477

* Update lib/plausible/shields.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update lib/plausible_web/live/shields/page_rules.ex

Co-authored-by: ruslandoga <doga.ruslan@gmail.com>

* Update lib/plausible_web/live/shields/page_rules.ex

Co-authored-by: ruslandoga <doga.ruslan@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
Co-authored-by: ruslandoga <doga.ruslan@gmail.com>
3 years ago
Adrian Gruntkowski ba5b80a8c0
Add label to site imports and populate it (#3914) 3 years ago
Uku Taht 1d017e86a1
Fix escaping of source filters (#3930)
* Fix escaping of source filters

* CHANGELOG

* Fix typo

Co-authored-by: Karl-Aksel Puulmann <macobo@users.noreply.github.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
Co-authored-by: Karl-Aksel Puulmann <macobo@users.noreply.github.com>
3 years ago
Adrian Gruntkowski 52c226c428
Add `label` column to `site_imports` schema (#3926) 3 years ago
RobertJoonas fb61f0b425
Capitalize Total Conversions in graph tooltip (#3934) 3 years ago
RobertJoonas d6e1e8bebd
Put total conversions on the graph + goal-filtered CSV export improvements (#3929)
* Add validation for the events metric in main_graph

* Test the already existing events metric support in main-graph

* Put total conversions on the graph

* extract main_graph_csv function (refactor only)

* add total_conversions and conversion_rate to goal-filtered visitors.csv

* update changelog
3 years ago
Uku Taht 561dcd821e
Mask pathanme in filter menu event (#3932) 3 years ago
Uku Taht fd879eeb16
Store referrers from android apps (#3715)
* Store referrers from android apps

* Add test for unknown referrer protocol

* Store android referrer protocol
3 years ago
Uku Taht 8992c8ee07
Add tracking to filter button (#3928) 3 years ago
RobertJoonas c32779a3e5
Timeseries for conversion rate (#3919)
* add conversion rate to Stats API timeseries

* make sure CR can be queried as the only metric

* add a test asserting zeros are returned

* add tests for filtering by other properties at the same time

* Remove unnecessary validation of params

1. It doesn't make to validate `interval` (and its granularity) in all
   endpoints. It's only relevant for the main graph.

2. The plug (renamed to `date_validation_plug`) already makes sure that
   the dates are validated. No need to call the same function again in
   Top Stats and Funnel endpoints.

* add metric validation to main graph

* Add tests for main graph API

* put conversion rate on the graph

* update changelog

* Add revenue metrics into metrics.ex

* make fn private

* avoid setting graph metric to visitors in goal-filtered view
3 years ago
Adrian Gruntkowski d6e81670e4
Unify UA and GA4 import flow into one (#3888)
* Unify GA4 and UA import flow into one

* Clean up property and view data retrieval via Google HTTP APIs

* Turn `Map.get` into `Map.fetch!` in API response processing code

* Bump list account summaries page size limit to max of 200

* Show only views in legacy flow and fix legacy redirect after import start

* Move google analytics import actions tests to a separate module

* Extend Google Analytics controller tests

* DRY up `property?` predicate (h/t @RobertJoonas)
3 years ago
ruslandoga 5f9465614b
Include domain and dates in zip archive filename (#3921)
* include domain and dates in zip archive filename

* adapt to comments
3 years ago
Karl-Aksel Puulmann 32ab138301
Fix issue with name clash (#3925)
Unexpectedly, table.name caused a name clash after CR refactor, so using a unique name
for the output column

Sentry issue: https://sentry.plausible.io/organizations/sentry/issues/5612
3 years ago
Karl-Aksel Puulmann c219652dae
Re-apply Move conversion_rate logic from elixir to clickhouse (#3924)
* Revert "Revert "Move conversion_rate logic from elixir to clickhouse (#3887)"…"

This reverts commit 253fb5d67d.

* Fix issue with missing columns

The issue came from refactoring event:goal UNION ALL logic and trying to move
name select from first to last. If any other tables were joined, the incorrect
item would be used as an array index, causing this issue.

Added a relevant test.
3 years ago
Karl-Aksel Puulmann 253fb5d67d
Revert "Move conversion_rate logic from elixir to clickhouse (#3887)" (#3923)
This reverts commit 1909743b90.
3 years ago
Karl-Aksel Puulmann 1909743b90
Move conversion_rate logic from elixir to clickhouse (#3887)
* Separate out query building from pagination/execution logic.

* Refactor pageview_goals breakdown query, removing index column from results

* Remove zip_columns logic

* Use common pagination util

* Do everything in a single query for breakdowns for goals

* Order in DB

* Make sure column order is identical

* Calculate CR within the goal breakdown query

* Calculate CR for property breakdowns

* WIP: Calculate group CR

* CR with order_by

* Compatibility fix

* Import Ecto.Query and cleanup

* handle total_visitors the same way as add_percentage

* Handle conversion_rate in aggregate.ex

* Solve rebase fail

* Simplify maybe_add_group_conversion_rate

* Add conversion_rate defaults to 0 test

* Add test for conversion_rate should not be calculated with imported data (failing here and on master)

* Dont include imported data when breakdown by prop or goal

* Remove revenue_nils
3 years ago
ruslandoga 64f35bf8f6
make robots.txt restrictive by default (#3905)
* make robots.txt restrictive by default

* add note about cloud robots.txt
3 years ago
ruslandoga 279e89c693
CSV imports (no UI) (#3895)
* encode/decode date range in filenames

* Update lib/plausible/imported/csv_importer.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update lib/plausible/imported/csv_importer.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* drop unused functions

* send failure email if there is no data to export

* use PlausibleWeb.Email.mailer_email_from()

* ensure we get dates from minmax date query

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
ruslandoga 4242b52be4
Allow importing extra config (#3906)
* allow importing extra config

* changelog

* fix typo

* add test
3 years ago
ruslandoga dfcc8d794a
Add space after logo on the index page (#3825) 3 years ago
Karl-Aksel Puulmann 02d2256483
Set exit_page only on pageviews (#3870)
* Set exit_page only on pageviews

* Update tests

* Update entry_page on first pageview

* Update CHANGELOG.md
3 years ago
ruslandoga 07b714a143
Update Sentry (#3843)
* update Sentry

* Sentry.HTTPClient.child_spec is now optional

* Sentry.EventFilter is deprecated

* update sentry to 10.2.0

* fix dialyzer warnings
3 years ago
ruslandoga c08aa29ad8
Remove DISABLE_AUTH deprecation warning (#3904)
* remove DISABLE_AUTH deprecation warning

* changelog
3 years ago
ruslandoga 0a0c7ce165
Remove init-admin.sh (#3903)
* remove init-admin.sh

* changelog
3 years ago
ruslandoga 8c0e94f72c
Fix manual embed width (#3910)
* fix manual embed width

* changelog
3 years ago
ruslandoga 4ae00540dc
Split Elixir CI jobs (#3898)
* split elixir tests

* more understandable matrix

* add unused deps in mix.lock check

* get all deps for static checks
3 years ago
ruslandoga 5e74b1cf74
CSV exports (UI) (#3875)
* ui

* fix redirect link

* improve make minio

* use implicit button form for csv export

* add exports_bucket helper

* read S3_EXPORTS_BUCKET

* supply s3_bucket in export_csv job args

* make plausible_minio use unprotected port

* move s3_csv_export queue to base queues

* Update lib/plausible_web/controllers/site_controller.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Karl-Aksel Puulmann d3586a81e3
UX improvement: don't autofocus on Custom properties on dashboard (#3872)
* UX improvement: don't autofocus on Custom properties on dashboard

Currently when you visit the dashboard with a certain configuration,
it will automatically scroll to the bottom, which is annoying.

To reproduce:
1. localStorage.clear() in console
2. Refresh, open properties at the very bottom
3. Refresh again

Expected behavior:
1. Dashboard shows

Actual behavior:
1. Dashboard scrolls to the bottom

* Changelog entry
3 years ago
hq1 59afa20955
Reapply #3878 + bugfix hit rate tracking (#3891)
* Reapply "Replace caching engine (#3878)" (#3883)

This reverts commit c5881cdc6d.

* Ensure hit rate is tracked on `get_or_store`

* Remove :wx and :observer

* Remove unused deps

* Use `:set` table type
3 years ago
RobertJoonas e8f3946dde
Fix division by zero in imported queries (#3890)
* prevent division by 0 in merge_imported queries

* Revert "fix bounce_rate change bug (#3886)"

This reverts commit 6eef32a8ff.

After 02aa0b2, we can keep on assuming that bounce rate is always numeric.
3 years ago
Adrian Gruntkowski 4d7d88cfec
Implement basics of GA4 import (#3851)
* Implement LV date input using flatpickr

* Implement basics of GA4 import (very dirty WIP)

* Split Google HTTP API into UA and GA4 specific parts

* Add a quick way to record GA4 API responses

* Add first GA4 import fixtures with GA4 Data API responses

* Extract GA4 and UA specific logic form Google API

* Extract UA and GA4 specific actions to distinct controllers

* Add integration test for GA4 importer

* Update GA4 fixtures

* Test GA4 API

* Add debug logging and fix paginating through API results in in GA4 import

* Revert "Implement LV date input using flatpickr"

This reverts commit c696f8ee39d5702f27015c09a4f079ca124cc7bb.

* Fix note
3 years ago
ruslandoga f2350b5165
Add `/tmp/` to .gitignore and simplify s3 cleanups in tests (#3889) 3 years ago
ruslandoga 5a3072ca21
CSV exports (no UI) (#3836)
* csv exports

* use ex_unit's tmp_dir
3 years ago
RobertJoonas 6eef32a8ff
fix bounce_rate change bug (#3886) 3 years ago
RobertJoonas 7641c66a2b
Stats api time on page (#3858)
* add metric validation + support in aggregate

* add a test ensuring comparison works

* disallow time_on_page with a goal filter

* Return time_on_page as `nil` from aggregate API

In case time_on_page cannot be calculated, we'll return it as `nil` from
the Stats API.

This is to make the behaviour consistent between breakdown and aggregate
endpoints. As for the UI, we'll still continue to report time_on_page as
0 - not changing any UI behaviour as discussed with Marko.

* add tests for time_on_page in event:page breakdown

* update changelog

* invalidate time_on_page with event:name filter

* add the ability to only query time_on_page in page breakdown

We'll need the visitors metric to get the list of pages to calculate the
time_on_page for.
3 years ago
Cenk Kücük dea9287d74
Revert "Temporarily disable tzdata auto-updating (#3873)" (#3885)
This reverts commit 11368e5143.
3 years ago
hq1 c5881cdc6d
Revert "Replace caching engine (#3878)" (#3883)
This reverts commit 437a3350ff.
3 years ago
Marko Saric ca7edd47cb
removing target="_blank" from blog link (#3882) 3 years ago
hq1 437a3350ff
Replace caching engine (#3878)
* Dependencies: swap Cachex for ConCache

* Implement Cache adapter wrapping ConCache

* Implement cache stats tracker, for metrics

* Use Cache.Adapter in Plausible.Cache

Marking the test as not slow anymore

* Use Cache Adapter when tracking sessions

* Use Cache Adapter for UA parsing

* Rename child identifiers - cachex is obsolete now

* Test stats tracking

* Update grafana metrics

* Put all caches under common child specification

* Try less

* Shorten the function delegation path
3 years ago
hq1 bb8a272a36
Fix margins in help guides section (#3881) 3 years ago
hq1 b68e3aa6a2
changes to the in-app footer (clean) (#3880)
* changes to the in-app footer

changes to the in-app footer to focus on product usage links rather than marketing pages

* Format

---------

Co-authored-by: Marko Saric <34340819+metmarkosaric@users.noreply.github.com>
3 years ago
ruslandoga 83a46fb47e
Dockerfile and co updates (#3811)
* wip

* more env, setup user before packages to avoid them picking our uid

* make entrypoint.sh executable by all again

* apparently it's a best practice to have executables be owned by root

* make entrypoint executable in COPY

* stop writing to /app, write to /tmp if needed

* fewer changes

* system user

* keep same style for multiline commands

* fewer changes

* add changelog entry

* fix group assignment for plausible user

* use gid=999

* no home

* no home

* add gecos

* add plausible user to nogroup instead of creating a custom one

* eh

* fewer changes

* fewer changes

* fewer changes

* use PERSISTENT_CACHE_DIR instead of STORAGE_DIR

* ignore more

* cleanup

* remove hex timeout env var

* use ERL_FLAGS=+JMsingle true in public builds

* fallback to /tmp and nest under /tzdata_data/ for tzdata

---------

Co-authored-by: Cenk Kücük <cenk@plausible.io>
3 years ago
Karl-Aksel Puulmann 11368e5143
Temporarily disable tzdata auto-updating (#3873)
This can cause issues as 1 day after a deploy the tzdata list is updated
from 2021 to 2024. Selecting a timezone thats not supported in 2021 can
then break dashboards temporarily following a deploy.

This can be reverted after https://github.com/plausible/analytics/pull/3811
3 years ago
Karl-Aksel Puulmann a9d3c03782
Validate the same metric isnt queried multiple times in external stats API (#3871)
* Validate the same metric isnt queried multiple times in external stats API

Issue: https://3.basecamp.com/5308029/buckets/35611491/card_tables/cards/7161347855

* Changelog entry

* Make credo happy
3 years ago
Karl-Aksel Puulmann 26d41ddbb9
Mutation to populate event session columns (#3844)
* WIP mutation to populate event session columns

* Remove duplication

* report errors, allow_nondeterministic_updates

* use right columns

* Update existing columns instead of session_* ones

* Make dialyzer happy

* Fix issue with passing pre-existing params in

* Logger -> IO.puts

* Use IngestRepo.config for connection settings

* Make dictionary options configurable

* Move allow_nondeterministic_mutations to within the migration

* Solve credo warning about too deep nesting

* Missed logger call

* Pattern matching in function head
3 years ago
Karl-Aksel Puulmann 0cdba7d407
Fix broken tests (#3867) 3 years ago
Karl-Aksel Puulmann c6d98397a8
Move `add_percentage` logic into clickhouse (#3854)
* Remove `add_percentage`, calculate percentages in clickhouse queries

This simplifies querying logic and avoids doing extra queries and avoids
race conditions.

* Remove special none handling from breakdowns, handling percentages correctly

* Add (failing) test showing expected add_percentage behavior for user making multiple sessions

* Update add_percentage behavior to use separate subqueries
3 years ago
Karl-Aksel Puulmann c60a2faee4
Write event table session columns (#3865)
* Write event table session columns

* Update testing factory rig
3 years ago
Karl-Aksel Puulmann 70d21f1b69
Improve compression of event table session columns (#3864) 3 years ago
Karl-Aksel Puulmann 8d977e0f76
Tests: session properties without the prefixes (#3863)
* Undo event session attributes renaming

* Rename session_ attributes in tests
3 years ago
Cenk Kücük fecd665c19
Push private images to GHCR (#3859) 3 years ago
Karl-Aksel Puulmann d5048fd6b4
Stop writing session properties into events table (#3800)
* Refactor: Explicitly add field names to INSERT

This avoids issues when code schema is out of sync with real schema

* Dont write session parameters to events

These would only be stored on first event anyways. Work remains to be done
on tests which have their own helper

* Remove writes to country_code in a test

* Remove old columns from being accessible in elixir code

* Update most tests to use new way of adding session props to events

* Update testing harness

* Update stats controller test

* Update for shield rules

* update breakdown tests

* Fix typing of state for dialyzer

* Drop support for old session attributes code

* Update remaining tests

* cond -> if
3 years ago
hq1 5eb9d724e5
Plugins API: mark data_domain as nullable in capabilities schema (#3840)
* Plugins API: mark data_domain as nullable in capabilities schema

* fixup
3 years ago
Karl-Aksel Puulmann ea38b45685
Ecto migration to move sessions_v2 to VersionedCollapsingMergeTree (#3809)
This migration will noop in staging/production as it already has been run. It also leaves
behind a backup table that initially takes no extra space but will need to be cleaned up
manually
3 years ago
Adrian Gruntkowski 39aa81a16f
Implement UI for multiple imports (#3727)
* Create a stub of site settings section for imports and exports

* Use legacy site import indication to determine UA import handling

* Add provisional logos for upcoming import sources

* Stub basics of import page

* Add very rudimentary support for multiple UA imports

* Implement imports list as live view

* Add support for opening LV modal from backend and closing from frontend

* Introduce notion of themes to `button` and `button_link` components

* Add confirmation modal on deleting import

* Swap GA4 logo

* Implement disabled state support for `button_link` component

* Disable export and non-implemented import sources

* Use native starts start date for upper boundary of import time range

* Ensure integrations view uses legacy UA import flow

* Remove unnecessary preload in SiteController

* Remove unnecessary exception for legacy imports

* Move API controller stats tests under PlausibleWeb

* Test listing imports

* Add test for explicit listener setup

* Add tests for legacy flag state in UA importer

* Add test for purging legacy import data

* Add tests for `Sites.native_stats_start_date`

* Test forgetting imports

* Add `Stats.Clickhouse.imported_pageview_counts/1` and fix test flakiness

* Show page view counts on imports list

* Add tests for static imports and exports view

* Adjust button look slightly

* Use `case` instead of `cond`

* Make feature flag customisable per site

* Fix buttons and empty state styling

* Add another import to seeds

* Use JS confirm dialog instead of modal for deletion confirmations

* Revert "Add support for opening LV modal from backend and closing from frontend"

This reverts commit 260e6c753032b451542e24be9edc2118790b5a00.

* Default `legacy` to false when inserting new import jobs

* Drop `method` attribute from `button_link` and `unstyled_link` components
3 years ago
Adrian Gruntkowski fdbe4cc0a4
Add `legacy` flag column to `site_imports` schema (#3842) 3 years ago
Marko Saric 0fe5682f91
Change the CTA to upgrade now rather than contact (#3837) 3 years ago
hq1 316148e788
Fix settings options mobile (#3838)
* Fix settings options on mobile view

* Fix settings options selected item on mobile

* Format
3 years ago
ruslandoga f3423aefec
Add csv importer (#3795)
* add csv importer

* make table validation explicit

* update some docs

* improve docs

* add minio container to ci

* more tests

* eh

* continue

* add passing test

* add failing test

* add config test

* add minio to Makefile

* testcontainers

* remove extra whitespace

* explain the implementation a bit

* account for async deletes in tests

* bounces is UInt32

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
ruslandoga 31cf3e54f8
Add Bamboo.Mua (#3654) 3 years ago
hq1 f1b6a672d4
Fix `added_by` not saving on adding country rules (#3835)
* Fix `added_by` not saving on adding country rules

* Format

* Remove dupe attr
3 years ago
hq1 518cdb3307
Shield: Country Rules (#3828)
* Migration: add country rules

* Add CountryRule schema

* Implement CountryRule cache

* Add country rules context interface

* Start country rules cache

* Lookup country rules on ingestion

* Remove :shields feature flag from test helpers

* Add nested sidebar menu for Shields

* Fix typo

* IP Rules: hide description on mobile view

* Prepare SiteController to handle multiple shield types

* Seed some country shield

* Implement LV for country rules

* Remove "YOU" indicator from country rules

* Fix small build

* Format

* Update typespecs

* Make docs link point at /countries

* Fix flash on top of modal for Safari

* Build the rule struct with site_id provided up-front

* Clarify why we're messaging the ComboBox component

* Re-open combobox suggestions after pressing Escape

* Update changelog

* Fix font size in country table cells

* Pass `added_by` via rule add options

* Display site's timezone timestamps in rule tooltips

* Display formatted timestamps in site's timezone

And simplify+test Timezone module; an input timestamp converted
to UTC can never be ambiguous.

* Remove no-op atom

* Display the maximum number of rules when reached

* Improve readability of remove button tests

* Credo

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
hq1 b7b5dcf4c9
Migration: add country rules (#3834)
* Migration: add country rules

* Make `country_code` not nullable
3 years ago
Cenk Kücük 8a8df685a7
Update country code for anonymising VPN services (#3766)
* Update country code for anonymising VPN services

* Update to latest
3 years ago
RobertJoonas dd428430f5
Query imported data for views_per_visit (#3830)
* query imported data for views_per_visit

* changelog update
3 years ago
Cenk Kücük cc867396b2
Update elixir.yml (#3831)
Only test against the last 2 major versions
3 years ago
ruslandoga bea8ceeffb
use newer postgres versions in the ci (#3821) 3 years ago
hq1 c822f8de1e
Hide user name overlay on mobile (#3829) 3 years ago
Karl-Aksel Puulmann c6e06359c6
Avoid changing Custom properties tab automatically every time filter changes (#3777)
Follow-up to https://github.com/plausible/analytics/pull/3719

The previous behavior was predicated on:
- Allowing a single custom property filter
- Allowing breaking down only by the chosen custom property filter

Now these restrictions are removed the previous auto-switching just becomes annoying
3 years ago
Marko Saric 19ce62db61
Update README.md 3 years ago
Uku Taht a1fedb751b Update license hash 3 years ago
Cenk Kücük 0f0f604d2e
Branding stuff (#3816)
* Replace footer text

* add COPYING.txt file

* Add new logos

* Use new logos in all layouts

* New logos

* Check license key on startup

* Bypass license check when Mix.env == :dev

* Use new logos with smaller wordmarks

* Add generic logo_path/1 function

* Use new favicons everywhere

* Bypass license check in test env

* Use sha256 for license key hash

* Mix.env -> config_env()

* Use Mix.evn at compile time rather than runtime

* Mix format

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
3 years ago
Cenk Kücük bdaf80c05d
Publish community edition under plausible/community-edition on GHCR and dockerhub (#3815) 3 years ago
Karl-Aksel Puulmann acd4f33c8e
Migration to improve compression options of sessions_v2 and events_v2 tables (#3803)
Part of https://3.basecamp.com/5308029/buckets/35611491/messages/7061875211
Based on work in https://3.basecamp.com/5308029/buckets/35611491/messages/6949640880#__recording_7015576045
3 years ago
hq1 bca617d0bf
`String.to_atom/1` is safe to do at compile-time (#3813)
otherwise random compile-time errors may occur
3 years ago
RobertJoonas 52f584efa9
Group `os_version` by `os` (#3806)
* improve test

* add os to os_version breakdown

...and add operating_system_versions.csv to the CSV export

* fix conversion rate for os_version breakdown

* update changelog

* fix existing CSV tests

* use case instead of cond
3 years ago
Karl-Aksel Puulmann 8ba2b934b3
Add data migration for moving sessions_v2 table to VersionedCollapsingMergeTree (#3802)
* Add data migration for moving to VersionedCollapsingMergeTree

This has been tested locally and partially on staging. Still requires a bit of work to verify.

Verification query:

```
SELECT main._partition_id, tmp.count, main.count
FROM (
SELECT _partition_id, count() AS count
FROM sessions_v2_tmp_versioned
GROUP BY _partition_id
) AS tmp
FULL OUTER JOIN (
SELECT _partition_id, count() AS count
FROM sessions_v2
GROUP BY _partition_id
) AS main
ON (tmp._partition_id == main._partition_id)
ORDER BY main._partition_id
```

* Add an early exit to migration

* cluster? extract common code
3 years ago
RobertJoonas d74b1d5e60
Reapply conversion rate into Stats API + bugfixes (#3805)
* Revert "Revert api conversion rate (#3789)"

This reverts commit 8e8790dd30.

* fix browser_version CR breakdown bug

* changelog bugfix

* inspect data structures before sending to sentry
3 years ago
hq1 6035618213
Add `GET /capabilities` to Plugins API (#3808)
* Add `GET /capabilities` to Plugins API

It aims to:

 - help the client verify the data-domain the token is associated with
 - list all the features available for the site's owner
   (and therefore determine availability of the subset of those for the current
   Plugins API caller)

The endpoint does not require authentication, in the sense that it'll
always respond with 200 OK. However when the token is provided,
a verification lookup is made.

* Remove IO.inspect() call

* Credo

* Aesthetics

* s/send_resp/send_error/

* Call preload just once
3 years ago
hq1 23b9032148
Allow site deletion with IP Rules stored (#3804)
* Allow site deletion with IP Rules stored

* drop_if_exists
3 years ago
Karl-Aksel Puulmann 5cdca6f408
Remove code that updates session browser/geo/OS attributes (#3796)
This will makes it impossible to store session attributes on events.

Looking at production data also revealed no cases where these updates
are effective.
3 years ago
hq1 eceac8afd5
Allow inviting users who are members already (#3797)
* Allow e-mail exclusion in team members quota

* Exclude invitee from quota on invitation create

* Enable invitation submission but report errors on quota violation

* Use a single interface for team members quota

* Check the `Keyword.validate/2` result

* Update test/plausible_web/controllers/site/membership_controller_test.exs

Co-authored-by: Uku Taht <Uku.taht@gmail.com>

---------

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
3 years ago
Adrian Gruntkowski e96a52c588
Revert "push docker images to ghcr.io (#3787)" (#3790)
This reverts commit c430274d7e.
3 years ago
RobertJoonas 8e8790dd30
Revert api conversion rate (#3789)
* Revert "Unify percentage change for CR and bounce_rate (#3781)"

This reverts commit a6b1a6ebc7.

* Revert "Bring Stats API up to speed: Add `conversion_rate` to Aggregate and Breakdown (#3739)"

This reverts commit 672d682e95.
3 years ago
Cenk Kücük c430274d7e
push docker images to ghcr.io (#3787) 3 years ago
RobertJoonas a6b1a6ebc7
Unify percentage change for CR and bounce_rate (#3781)
* Fix conversion rate change calculation

The change in conversion rate should be calculated similar to bounce rate.
For example, an increase of 25% -> 50% should not be a 100% change, but
a 25% change instead.

* Use the same comparison function in Stats API and dashboard API

This commit fixes a bug where the percentage change reported by the Stats
API is different from the one returned by the internal dashboard API.

* changelog update
3 years ago
hq1 926de4dd10
Experimental session count (#3786)
* WIP

* Allow `experimetnal_session_count` request serialization

* Extend `Plausible.Stats.Query` with `experimental_session_count` flag

* Add `FunWithFlags` actor implementation for `Site`

* Change the way sessions are retrieved

* Remove redundant test

* Format

* Update the test

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
3 years ago
RobertJoonas 672d682e95
Bring Stats API up to speed: Add `conversion_rate` to Aggregate and Breakdown (#3739)
* disable event metric with include_imported in every case

* add missing test for metric validation

* refactor metric validation functions

* implement conversion_rate metric validation

* move calculate_cr function into Stats.Util

* Refactor: Move aggregate CR logic into Stats.aggregate

* define atoms to exist

* Ensure that CR does not depend on visitors being queried

If 'visitors' are already queried, we'll use that value. Otherwise we'll
need to make another query to fetch it.

* confirm Stats API aggregate supports CR (tests only)

* small refactor

This is the only 'event_property' left after pattern matching on all
others in the function clauses defined above.

* Make it possible to optionally query conversion_rate

...in breakdown queries (excluding goal and custom prop breakdown)

* A little refactor asking for revenue metrics

1. The `@revenue_metrics` module attribute is an empty list on full build
   anyway
2. We don't need to query for revenue metrics if there are no revenue goals
   returned in the given query (even if revenue goals exist in site.goals)
3. Revenue metrics are already dropped in prop breakdown without a goal
   filter via (get_revenue_tracking_currency/3)

* Make it possible to optionally query conversion_rate (continuation)

... also from a custom prop and goal breakdown

* Frontend adjustments to the Locations report

* Display conversion rate in Regions and Cities (ListReport view)
* Display total conversions, conversions (visitors), and CR in the
  "Details" modals of Countries, Regions, and Cities
* Move the percentage into a separate column in the Countries details table

* confirm Stats API breakdown supports conversion_rate (tests only)

* small refactor: extract maybe_add_time_on_page function

* Make it possible to query cr alone

... (without the visitors metric). Already supported in aggregate, this
commit only implements it for the breakdown API.

* Reuse Stats.Util helper functions from b02db88 for aggregate API

We can follow the same logic as with breakdown for manually adding
`visitors` into the metrics list and taking it out of the response
later on.

That way we don't have to make another query, e.g. in a case where
only pageviews and conversion rate is queried. Also keeps things
consistent.

* changelog update

* fix test after resolving merge conflict

* Use explicit string->atom mapping instead of casting

* alias Util module instead of importing it

* use Enum.empty instead of Enum.any

* improve readability

* rename special_metrics to computed_metrics and explain with a comment

* rename visitors_without_event_filters to total_visitors

* keep a single function for removing unwanted metrics

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Karl-Aksel Puulmann 0065cd3052
Support using matches/contains for most filters (#3721)
* Support using matches/contains for most filters

* Change behavior where we auto-zoom to specific browser/os/source to only do so if filtering on a single value

* No contains filtering on `location`

* Update CHANGELOG.md

* Fix merge conflict
3 years ago
Karl-Aksel Puulmann ac7da6a9d4
Set materialized_views_ignore_errors (#3784)
We had an incident where a stray materialized view caused inserts to fail. This setting
causes stray mv errors to silently fail, which is okay for our current usecases.

Further reading: https://clickhouse.com/docs/en/sql-reference/statements/create/view#materialized-view
3 years ago
ruslandoga 423f72a0ad
safe(r) Oban telemetry (#3743)
* safe telemetry

* use try/catch instead

* add some tests

* cleanup tests

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
Adrian Gruntkowski f8b4d5066a
Add multiple imports per site (#3724)
* Clean up references to no longer active `google_analytics_imports` Oban queue

* Stub CSV importer

* Add SiteImport schema

* Rename `Plausible.Imported` module file to match module name

* Add `import_id` column to `Imported.*` CH schemas

* Implement Importer behavior and manage imports state using new entities

* Implement importer callbacks and maintain site.imported_data for UA

* Keep imports in sync when forgetting all imports

* Scope imported data queries to completed import IDs

* Mark newly imported data with respective import ID

* Clean up Importer implementation a bit

* Test querying legacy and new imported data

* Send Oban notifications on import worker failure too

* Fix checking for forgettable imports and remove redundant function

* Fix UA integration test

* Change site import source to atom enum and add source label

* Add typespecs and reduce repetition in `Plausible.Imported`

* Improve documentation and typespecs

* Add test for purging particular import

* Switch email notification templates depending on import source

* Document running import synchronously

* Fix UA importer args parsing and ensure it's covered by tests

* Clear `site.stats_start_date` on complete import to force recalculation

* Test Oban notifications (h/t @ruslandoga)

* Purge stats on import failure right away to reduce a chance of leaving debris behind

* Fix typos

Co-authored-by: hq1 <hq@mtod.org>

* Fix another typo

* Refactor fetching earliest import and earliest stats start date

* Use `Date.after?` instead of `Timex.after?`

* Cache import data in site virtual fields and limit queried imports to 5

* Ensure always current `stats_start_date` is used

* Work around broken typespec in Timex

* Make `SiteController.forget_imported` action idempotent

* Discard irrecoverably failed import tasks

* Use macros for site import statuses

There's also a fix ensuring only complete imports are considered
where relevant - couldn't isolate it as it was in a common hunk

* Use `import_id` as worker job uniqueness criterion

* Do not load imported stats data in plugins API context

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
Adrian Gruntkowski 6915dd5e78
Add table migrations for supporting multiple imports per site (#3785)
* Add migration deleting jobs from legacy analytics import queue

* Add `site_imports` table

* Add `import_id` column to imported_* CH tables

* Extend one of `site_imports` indexes
3 years ago
Marko Saric 05adf5d83c
copy changes to the CTA on the top of a new dashboard (#3783)
* Update stats.html.eex

* Update stats.html.eex
3 years ago
Karl-Aksel Puulmann f5e15941de
Add migration for minmax indexes on session timestamps (#3772) 3 years ago
Karl-Aksel Puulmann f3509f2a17
Refactor spike detection top sources query (#3770)
* ORDER BY referrer_source for spikes job

This is more consistent with the rest of the queries

* Refactor top_sources -> top_sources_for_spike

* Remove more dead code

* Remove unused arguments

* Remove unused select arguments

* Add a test to top_sources_for_spike
3 years ago
Karl-Aksel Puulmann d1fe184cb7
Remove ORDER BY min(session.start) (#3771)
This adds a needless performance overhead. Note that all queries already
sort by the _name_ of the breakdown value besides the session start.
3 years ago
hq1 494ffbd622
Shields behind a FF (#3780) 3 years ago
hq1 99fe03701e
IP Block List (#3761)
* Add Ecto.Network dependency

* Migration: Add ip block list table

* If Cachex errors out, mark the cache as not ready

* Add IPRule schema

* Seed IPRules

* Add Shields context module

* Implement IPRuleCache

* Start IPRuleCache

* Drop blocklisted IPs on ingestion

* Cosmetic rename

* Add settings sidebar item

* Consider IPRuleCache readiness on health checks

* Fix typo

* Implement IP blocklist live view

* Update moduledocs

* Extend contextual module tests

* Convert IPRules LiveView into LiveComponent

* Keep live flashes on the tabs view

* Update changelog

* Format

* Credo

* Remove garbage

* Update drop reason typespecs

* Update typespecs for cache keys

* Keep track of who added a rule and when

* Test if adding via LV prefills the updated_by tooltip

* Update ecto_network dependency

* s/updated_by/added_by

* s/drop_blocklist_ip/drop_shield_rule_ip

* Add docs link

* s/Updated/Added
3 years ago
hq1 bc467996ab
Shields IP blocklist: migration (#3779) 3 years ago
hq1 6a2d7fc0f5
Merge `Plugins.API.Router` into main one (#3767)
* Merge `Plugins.API.Router` into main one

In order to get grafana metrics reported
See: https://github.com/akoutmos/prom_ex/issues/224

* Format
3 years ago
hq1 f5129f1b0d
Turn Revenue Goals into Custom Events if the plan doesn't support them (#3768)
* Turn Revenue Goals into Custom Events if the plan runs out

* Tag test with full_build
3 years ago
Karl-Aksel Puulmann 499be9f0b3
Add more custom properties to be tracked (#3778)
We just released support for multiple custom property filters, but our demo/live setup
does not have many useful custom properties. This PR adds a few more to allow
better slicing-and-dicing.
3 years ago
Karl-Aksel Puulmann 1cb7982cd9
Filtering by multiple custom properties (#3719)
* WIP: PropFilterRow

* Get multi-behavior working

* Render multiple prop filters in one

* Modal reads from query string correctly

* Backend support for multiple custom property filters

* Add backend tests for multiple custom property filters

* Disable already selected options in property keys

We can't allow choosing the same property multiple times without changing the request
params, which we decided against

* Allow choosing any property under Behaviors > Custom props even if custom prop filter applied

This was a limitation (I believe) introduced by using ARRAY JOINs to query custom properties

* CHANGELOG.md

* Solve credo warning about too deep nesting

* Update assets/js/dashboard/stats/modals/prop-filter-modal.js

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>

* Refactor internal function for clarity

* Add another step -> Add another

* Solve 500 error

* Separate boxes per property filter

* Retain other filters in props table

* removeFilter behavior for props

* matches_member support for custom props

* filter_suggestions for prop keys should account for prop filter

* find over filter

* refactor appliedFilters

* FILTER_TYPES => FILTER_OPERATIONS

* Make add another link not wrap the whole page

* Unique keys

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
dependabot[bot] c8b25347ed
Bump buildjet/cache from 3 to 4 (#3753)
Bumps [buildjet/cache](https://github.com/buildjet/cache) from 3 to 4.
- [Changelog](https://github.com/BuildJet/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/buildjet/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: buildjet/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Cenk Kücük <cenk@plausible.io>
3 years ago
hq1 9f2f894421
Fix flashing on reapplying theme (#3760)
* Fix flashing on reapplying theme

This seem to be making a difference on staging

* Add `blocking="rendering"` attribute
3 years ago
hq1 6ce4d19931
Fix flaky test: wait till ets is emptied (#3755)
* Fix flaky test: wait till ets is emptied

* fixup
3 years ago
hq1 9ad5ecebc2
Improve print dashboard css (#3754)
* Improve print dashboard CSS

* More improvements
3 years ago
Marko Saric 03e1224693
improvements to the email copy (#3756)
* Update yearly_expiration_notification.html.eex

* Update yearly_renewal_notification.html.eex
3 years ago
RobertJoonas 51f0e406a0
improve stats api upgrade required error message (#3747) 3 years ago
Karl-Aksel Puulmann 625b2a2946
Use parallel_hash for joins in clickhouse (#3741) 3 years ago
Adrian Gruntkowski 3738cd9578
Parse referrer filter value when passed separately (#3742)
* Parse referrer filter value when passed separately

* Remove unnecessary test setup
3 years ago
hq1 e28793a45a
Make `hello@plausible.io` clickable (#3746)
* Make `hello@plausible.io` clickable

* Format

* ...
3 years ago
hq1 9fb4ea0c3e
Bugfix: available features for expired trials, no subscriptions (#3740)
* Reorganize how subscriptions/trials are evaluated

* Bugfix: expired trial+no subscriptions should not have access to extra features

* Make self-hosted users always on trial

* Seed secondary user with password

* Format

* Fix docs

* Fix small_test run

* Run the test only on full_build

* More tweaks to small builds

* Allow [Goals] for expired trials with no subscription
3 years ago
dependabot[bot] 85c9771d11
Bump @playwright/test from 1.40.1 to 1.41.1 in /tracker (#3744)
Bumps [@playwright/test](https://github.com/microsoft/playwright) from 1.40.1 to 1.41.1.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.40.1...v1.41.1)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 63c4c1d07b
Bump eslint from 8.55.0 to 8.56.0 in /tracker (#3640)
Bumps [eslint](https://github.com/eslint/eslint) from 8.55.0 to 8.56.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.55.0...v8.56.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] c86959ef9e
Bump ex_money from 5.15.2 to 5.15.3 (#3696)
Bumps [ex_money](https://github.com/kipcole9/money) from 5.15.2 to 5.15.3.
- [Release notes](https://github.com/kipcole9/money/releases)
- [Changelog](https://github.com/kipcole9/money/blob/main/CHANGELOG.md)
- [Commits](https://github.com/kipcole9/money/compare/v5.15.2...v5.15.3)

---
updated-dependencies:
- dependency-name: ex_money
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 931161f693
Generalize Cache/Warmers - extract only specifics to `Site.Cache` (#3716)
* Simplify caches config

The intervals were proven to never change really,
and previous shape made them not very discoverable either.
We'll look into a more declarative setup.

* Aim for more declarative supervision tree setup

* Generalize `Plausible.Cache`

This makes the `Site.Cache` module implement the specifics,
leaving the common bits reusable for upcoming cache processes.

* Generalize `Plausible.Cache` warmers

* Fix typos
3 years ago
ruslandoga d5818a63f7
update Ch (#3733) 3 years ago
dependabot[bot] 3c9062a1dd
Bump actions/cache from 3 to 4 (#3734)
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Cenk Kücük <cenk@plausible.io>
3 years ago
hq1 18ddf1e7a0
Re enable accept traffic until notifications (#3737)
* Revert "Remove 0-sized queue"

This reverts commit 6d229b3f70.

* Revert "Temporarily remove notification cron worker (#3732)"

This reverts commit 447e3929cb.

* Revert "Temporarily disable accept_traffic_until actions (#3730)"

This reverts commit 58afe3376f.

* Send accept_traffic_until notifications at 8 UTC rather than 5

* Add option for dry-run

* Expose dry_run in a dedicated function
3 years ago
hq1 ee6d16d44f
Shift accepted_traffic_until for possibly delayed notifications (#3738) 3 years ago
hq1 8f6ec252e9
Backfill accepted_traffic_until for active subscriptions (#3736)
* Backfill accepted_traffic_until for active subscriptions

* Narrow the results
3 years ago
RobertJoonas 04b9067591
Add `event:goal` property to Stats API (#3718)
* add tests for filtering by goal in timeseries and aggregate

* refactor filter parsing

* stop returning custom props in event:goal breakdown

* test breaking down wildcard pageview goals

* extract filter utils

* parse more goal filter options

* add passing tests for new filter types

* do not allow querying session metrics with a goal filter

* remove unused page_match property

* test that non-configured goals are not returned in breakdown

* enforce filtered goals configured

* update changelog

* Allow simple filtering by revenue goals

This does not mean that revenue metrics are supported. If a revenue goal
is filtered by, we treat it like a simple custom event goal in the API.

* use List.wrap
3 years ago
Adam Rutkowski 6d229b3f70 Remove 0-sized queue 3 years ago
Adam Rutkowski 00ef386356 Revert "Bump actions/cache from 3 to 4 (#3707)"
This reverts commit 100e89370f.
3 years ago
hq1 447e3929cb
Temporarily remove notification cron worker (#3732)
* Temporarily remove notification cron worker

* Format
3 years ago
hq1 712f60f37f
Update `accept_traffic_until` on payment succeeded notification (#3731)
* Update `accept_traffic_until` on payment succeeded notification

* full build only
3 years ago
hq1 58afe3376f
Temporarily disable accept_traffic_until actions (#3730)
* Temporarily disable accept_traffic_until actions

* Remove commented code
3 years ago
dependabot[bot] 100e89370f
Bump actions/cache from 3 to 4 (#3707)
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Cenk Kücük <cenk@plausible.io>
3 years ago
hq1 0fa7f3c1e1
Make subsequent query boundaries idempotent (#3723)
* Make subsequent query boundaries idempotent

This should prevent time-sensitive race conditions
on subsequent `Plausible.Stats.*` calls for the same query.
Not sure if there are more places where now() is
dynamic relative to query life cycle, but it's a start.

* Format

* Update lib/plausible/stats/query.ex

Co-authored-by: Wojtek Mach <wojtekmach@users.noreply.github.com>

* Match on `Query.now` in a test

---------

Co-authored-by: Wojtek Mach <wojtekmach@users.noreply.github.com>
3 years ago
Adrian Gruntkowski 822483c37c
Extract Universal Analytics import logic (#3700)
* Move imported tables schemas to separate modules outside Google ns

* Move buffer for imports to Imported ns

* fix schema newlines

* Extract UA import processing and persistence

* Decouple analytics worker implementation from UA

* Rename env variable for import buffer size

* Preserve old import queue until release
3 years ago
Karl-Aksel Puulmann 11c5d3b251
Remove ARRAY JOINs (#3708)
* Use array indexing instead of left joins

This has multiple benefits:
- Allows us to more easily add support for multiple custom property
  filters
- Performance: Increased performance of some queries by ~20%

Work left to do:
- Check tests coverage
- Create macros for repeated fragments
- Quote and refer to right tables in fragments/macros

* Use macros to clean up code

* Use existing atoms to avoid memory leaks
3 years ago
Karl-Aksel Puulmann e2eb861799
Github Actions: Run tests on all PRs (#3709)
Chained PRs (like https://github.com/plausible/analytics/pull/3708)
don't currently run tests. This PR fixes that.
3 years ago
RobertJoonas 041b0ab779
trace aggregate and timeseries queries too (#3712) 3 years ago
hq1 36a8b36382
CombBox bugfix: stale spinner on creatable options selection (#3713) 3 years ago
RobertJoonas 6ca4eaf5e2
Improve query tracing (#3704)
* Enable breakdown property tracing for event:goal

This is currently overwritten by event:name. The queries for event:name
will still be tracked if queried specifically.

* Add filters tracing to Query.trace/1

* make sure breakdown metrics are sorted and joined

* check opts skip tracing directly without passing it
3 years ago
hq1 8965ac40a7
Decorate site settings sidebar with heroicons (#3711)
* Decorate site settings sidebar with heroicons

* Capitalize "Danger Zone"

* Capitalize "Danger Zone"
3 years ago
Karl-Aksel Puulmann 1b95433d6e
Support `contains`/`matches` for custom properties (#3687)
* Allow `matches` operator to work in BE for custom props

Note: No FE support yet, needs further testing

* feat: allow choosing `contains` for property filters in the UI

* no autocomplete on prop values if `contains` for consistency

* CHANGELOG.md

* Fix: Handle (none) property in property breakdowns when using matching

When matching we should always exclude (none)
3 years ago
hq1 0a124e69e7
Actually enforce proper WordPress spelling (#3710) 3 years ago
Uku Taht 730c8edc4a
Update ref_inspector database (#3697)
* Update ref_inspector database

* Use random referrer input
3 years ago
Uku Taht 024efd1fc1
Update ua_inspector database (#3698)
* Update ua_inspector source

* Downloan device detector updates
3 years ago
Marko Saric fb80847d7e
capital P in WordPress (#3703) 3 years ago
Arkadiusz Plichta 4ec86abeac
update clickhouse docker image (#3701) 3 years ago
Uku Taht a5e0619053
Escape special regex characters (#3634)
* Escape special regex characters

* Add changelog entry
3 years ago
dependabot[bot] cba5f55ba1
Bump ex_doc from 0.31.0 to 0.31.1 (#3693)
Bumps [ex_doc](https://github.com/elixir-lang/ex_doc) from 0.31.0 to 0.31.1.
- [Release notes](https://github.com/elixir-lang/ex_doc/releases)
- [Changelog](https://github.com/elixir-lang/ex_doc/blob/main/CHANGELOG.md)
- [Commits](https://github.com/elixir-lang/ex_doc/compare/v0.31.0...v0.31.1)

---
updated-dependencies:
- dependency-name: ex_doc
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
hq1 7deffcdeee
Prefer example.com in tests (#3690) 3 years ago
Cenk Kücük 44fca0c95d
Prioritize X-Plausible-IP header over everything else (#3689) 3 years ago
RobertJoonas 0a29679afa
Stop expecting `trial_expiry_date` to exist on upgrade (#3688)
* stop expecting trial_expiry_date to exist on upgrade

* add test
3 years ago
RobertJoonas d3094ffdb7
Prevent upgrades that would leave the customer locked (#3683)
* Remove allowance_required field from grace_period

Since we are now preventing customers from subscribing to a plan that
does not accommodate their pageview usage, there is no need for an extra
check on removing the grace period after a successful upgrade.

This extra check is the reason why the automatic unlocks have recently
failed in several cases.

* refactor outgrown subscription notices

* make a test actually test the described functionality

* Apply greater pageview allowance margin only for trial upgrades

...in order to prevent cancelled or paused subscriptions from subscribing
to plans that would still leave their account locked.

* Mark the entire ChoosePlanTest module full build only

* remove account locking guide

This is irrelevant for self-hosters, and the internal knowledge base is
a better place for this document. Moved it there.

* refactor Keyword get clause

* add a pattern matching assertion in code
3 years ago
RobertJoonas 7536f0285c
Fix weekly interval bug (#3686)
* Fix a bug

This commit fixes a bug where the timeseries weekly interval query for a
month returned 0 visitors for the first week.

This happened because the start of the month defining the first week was
missing the UTC -> site.timezone conversion.

* Update test/plausible_web/controllers/api/stats_controller/main_graph_test.exs

Remove dot from test description

Co-authored-by: Karl-Aksel Puulmann <macobo@users.noreply.github.com>

---------

Co-authored-by: Karl-Aksel Puulmann <macobo@users.noreply.github.com>
3 years ago
Adrian Gruntkowski eaa7020230
Latency-friendly LV modal implementation and Goals form refactor (#3649)
* Make modal for goal settings trigger without BE roundtrip

* Turn goal form into a live component and extract modal into a wrapper

* Further extract modal component and handle reset action

* Make ComboBox selection callback more flexible

* Add rudimentary loading state to dialog

* Make form unaware of being put inside a modal

* Make modal a live component and completely reset contents on open server-side

* Try to avoid race condition

* Fix race condition

* Remove unnecessary conditional on socket assigns

* Add typespecs and fix formatting

* Make goals form high latency friendly

* Fix tests to account for goal settings form becoming live component

* Fix goal settings form live component declaration

* Add documentation for modal

* Fix small build test

* Fix typo

Co-authored-by: hq1 <hq@mtod.org>

* Revert no longer necessary test changes from 46f65d9

* Fix and clean up modal styling

* Keep focus on dialog when open and show only spinner on backdrop when loading

* Adjust corners and shadows and implement open/close transitions

* Lock body scroll when modal is open

* Make modal top-aligned again to avoid jumping around on variable content height

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
Adrian Gruntkowski 954b70c79b
Run SiteLocker right after site ownership transfer (#3684)
* Run SiteLocker right after site ownership transfer

* Put site unlocking behind full build flag

* Tag regression tests as full build only
3 years ago
dependabot[bot] fae6c07fad
Bump oban from 2.17.1 to 2.17.2 (#3685)
Bumps [oban](https://github.com/sorentwo/oban) from 2.17.1 to 2.17.2.
- [Release notes](https://github.com/sorentwo/oban/releases)
- [Changelog](https://github.com/sorentwo/oban/blob/v2.17.2/CHANGELOG.md)
- [Commits](https://github.com/sorentwo/oban/compare/v2.17.1...v2.17.2)

---
updated-dependencies:
- dependency-name: oban
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
hq1 63dec378c2
Remove `connection` and `OAuther` dependencies (#3681)
* Remove `connection` dependency

https://github.com/elixir-ecto/connection

* Remove OAuther dependency

Some remnant from https://github.com/plausible/analytics/pull/27/files
3 years ago
hq1 32456d4348
Upgrade stack (deps, elixir 1.16, OTP 26.2.1) (#3678)
* Bump asdf erlang & elixir

* Bump erlang/elixir in the dockerfile

* Remove Oban.Stager config as per https://github.com/sorentwo/oban/blob/main/guides/upgrading/v2.14.md

* Configure Oban for tests as per https://github.com/sorentwo/oban/blob/main/guides/upgrading/v2.14.md

* Mark sampling hint clause with unsafe fragment

Any other/recommended way to do that? cc @ruslandoga

* Address String.slice/2 deprecation

* Update deps

* Address 0.0 matching warning

* Make funnel settings work

although this is probably not the best way to do it.
Needs revisiting, not sure what broke it - could not find
any breaking changes in related dependencies.

* Migrate oban as per https://github.com/sorentwo/oban/blob/main/guides/upgrading/v2.17.md

* Update credo

* Bump CI cache

* Use `Bypass.pass` to avoid exit shutdown message
3 years ago
hq1 c1a1d697a4
Partially revert #3661 - just keep the real errors wrapped, but don't display anything to the user (#3677)
* Revert "Remove unused RocketIcon"

This reverts commit c5e8d0c172.

* Revert "Display either hash or actual error message"

This reverts commit 0c091ab35f.

* Revert "Use ApiErrorNotice in funnels"

This reverts commit 5929de248e.

* Revert "Don't render "No data yet" when there's a NetworkError for example"

This reverts commit 70bee07632.

* Revert "Show the sinking shuttle notice whenever an API error occurs"

This reverts commit 9a62c8af2b.

* Revert "Add Hahash dependency"

This reverts commit b94207ea0a.

* Remove support hash
3 years ago
RobertJoonas 403f559b35
Limit Custom Properties access in Stats API (#3670)
* add new function and doc for allowed_props

* limit props access in Stats API queries

* use dot syntax instead
3 years ago
hq1 24a8aa2821
Reapply sentry context (#3675)
* Reapply "Sentry context in live views (#3672)"

This reverts commit 5449fead160064b8a0081c458cc5dcd34399eb0b.

* Make sure `:selection_made` is handled in `GoalSettings.Form`

That was a bit unepexcted.. normally `handle_info` is injected
by the LiveView use macro and it discards any message gracefully.
After switching to `use PlausibleWeb, :live_view` we're also
using `PlausibleWeb.Live.Flash` that happens to inject its own receive
clause for closing the flash. Which then renders the original,
overridable, `handle_info` catch-all obsolete.

* Update LV SentryContext only on connected sockets

(first mount already has the right context coming from Sentry plug)

* Make sure Live.ChoosePlan passes `current_user_id` session key
3 years ago
hq1 c87b165aef
Revert "Sentry context in live views (#3672)" (#3673)
This reverts commit 9bb2dc00d0.
3 years ago
hq1 9bb2dc00d0
Sentry context in live views (#3672)
* Add common LiveView macro to PlausibleWeb

* Keep peer data, URI and UA in /live websocket metadata

* Use new PlausibleWeb macro in existing LiveViews

* Implement adding some basic Sentry context `on_mount`

* Format

* Use macro in Live.FunnelSettings

* Update FunnelSettings.Form
3 years ago
Adrian Gruntkowski aa139a73b8
Fix calendar picker for comparisons on small screens (#3669) 3 years ago
Adrian Gruntkowski 1021942863
Fix props availability check when listing stats filters in dropdown (#3671) 3 years ago
hq1 dc8210dd84
Use tags rather than context to annotate support hashes in Sentry (#3668) 3 years ago
hq1 9cb44291f7
Rate limit e-mail changes (#3667) 3 years ago
hq1 5c8f39ac4c
Prevent crashes on ambiguity when casting timezones (#3663)
* Fall back to UTC when timezone gap found

* bugfix 1

* bugfix 2

* Apply safe tz conversion to all cases where it's done on a ts other than now

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
hq1 72b4e05bbf
Always enable e-mail verification on full build (#3666)
* Always enable e-mail verification on full build

* s/change/set

* Update lib/plausible/auth/user.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
hq1 4569ac09c1
Don't leak internal server errors, use support hash (#3661)
* Add Hahash dependency

* Don't leak internal server error details to the user

* Show the sinking shuttle notice whenever an API error occurs

* Don't render "No data yet" when there's a NetworkError for example

* Use ApiErrorNotice in funnels

* Display either hash or actual error message

The reason "internal-server-error" doesn't work well as a fallback
hash is that e.g. `NetworkError when attempting to fetch resource`
might be completely at client's fault. In such cases it's better
to display the whole thing still.

* Remove unused RocketIcon
3 years ago
dependabot[bot] a769447dcc
Bump actions/github-script from 6 to 7 (#3534)
Bumps [actions/github-script](https://github.com/actions/github-script) from 6 to 7.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vinicius Brasil 9e5d63ed96
Display premium features tabs on the dashboard (#3646)
* Display premium features tabs on the dashboard

This commit makes the funnels and props tab on the dashboard visible
even when the site owner's plan does not have access to that feature.
This is to raise awareness of those features, and if the site owner does
not want to see that tab, they can still click "Hide this report" to
hide it.

Previously, when the plan did not support a feature, the feature module
`enabled/1` function returned `false`, regardless of the
`sites.feature_enabled` toggle. This commit creates a new function
called `opted_out/1` to differentiate access from explicitly opting out
a feature.

* Remove unused data-conversions-enabled attribute

* DRY Plausible.Billing.Feature.check_availability/1 function

* Allow opting out features the user doesn't have access to

* add upgrade CTA to FeatureSetupNotice

* fix JS linting errors

* simplify notice.js

* fix behaviour when deleting funnels saved to localstorage

In case some other funnel exists, we will use that as the default
selected one. If not, a feature setup notice will be displayed again.

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
RobertJoonas 155a7a56a7
Fix goal filter inconsistency (#3658)
* remove unused code

* add e.name == "pageview" condition to pageview goals

This fixes the weird behavior where filtering by a pageview goal would
also return custom events and vice versa.

* update changelog
3 years ago
hq1 7755d4fd29
Lock traffic data backfill (#3648)
* WIP snapshot

* Don't assume that subscription and trial can't co-exist 🤷

* Don't look up subscription status if payment is overdue
3 years ago
hq1 b6a2acb57a
Update accept_traffic_until notifications (#3665)
* Update accept_traffic_until notifications:

  - extend has_stats to 48h
  - ensure the user is properly greeted

* Clarify the structure passed to email template function
3 years ago
Adrian Gruntkowski af9b34a1c6
Revert "Prevent scrollbar click to close modal (#3651)" (#3664)
This reverts commit 75a7ef5241.
3 years ago
hq1 21bbd3835a
Disallow funny business on timezone entry (#3662)
* Disallow funny business on timezone entry

* Add external API test
3 years ago
Marko Saric 7efa253e3f
Add a note about site settings being available on the locked screen (#3650)
* Add a note about site settings being available on the locked screen

some people are not aware that they can access site settings when the dashboard is locked. i've tried to add that to the note here as it should improve the user experience and minimize the number of people reaching out to support

* Adjust markup a bit

* Convert view to HEEx and apply predefined components

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
RobertJoonas 1342135908
Add `custom_props.csv` back to CSV export for Growth plans (#3656)
* restore special props access for growth plans

* format

* refactor if condition

Co-authored-by: hq1 <hq@mtod.org>

* format

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 8be9397199
Skip breakdown of imported pages with pageviews=0 (#3655)
* Skip breakdown of imported pages with pageviews=0

* Fixup

* Prove good impoted records are merged
3 years ago
hq1 73923404b0
Improve approaching accept_traffic_until e-mail (#3660)
* Improve approaching accept_traffic_until e-mail

* fixup

* format
3 years ago
Vinicius Brasil 75a7ef5241
Prevent scrollbar click to close modal (#3651)
This commit replaces the `mousedown` event for `click` to close a modal,
such as the detail dialog. This allows the scrollbar to be clicked
without firing an event, and right clicks too.

Closes #2872
3 years ago
ruslandoga af6b578dc5
format extra (#3657) 3 years ago
hq1 f755b20569
Lock traffic notifications (#3641)
* Update communication

* Remove an unreachable function (mistyped)

* [migration] Make accept_traffic_until a date

* Fix typo

* Set `accept_traffic_until` when creating a site

* Update sites `accept_traffic_until` on subscription change

* Add a note to yearly cancellation notification

* Rephrase annual e-mail for clarity

* Pass the small build test

* Add email notifications

* Fixup

* Implement `accept_traffic_until` notification worker

* Fixup - no need to test this for small build

* Update moduledoc

* Move moduletag

* s/sent_at/sent_on

* Use WHERE NOT EXISTS instead of LEFT JOIN

* Use upsert when tracking notifications sent

* Store sent marker before actually sending notification

* Prefer to keep `accept_traffic_until` on the user record

This gives us a single source of truth, addresses cases like
ownership transparently, simplifies the code and enables CRM toggles.
The only downside is that there's another join performed in the
Sites.Cache full refresh - in this case, small refreshes are
skipped - but this is fine, since the traffic will be let in
anyway.

* Expose `accepted_traffic_until` in the CRM

* Update lib/plausible/auth/user.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Preload owner in CRM

* Use the offset parameter in trial over e-mail contents

* Format

* Harden cache test

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Adrian Gruntkowski 66d4b3a966
Fix SiteLocker for case of user without trial expiry date but with active subscription (#3652) 3 years ago
RobertJoonas d2270f3c35
Small bugfix + refactor email reports (#3642)
* use more convenient testing functions

* do not display + sign with 0% change in emails

* Rename module/file/function names

before, `weekly_report` was also used for monthly reports and that was a
bit confusing to read in code.

* Refactor send_email_report.ex

This commit improves readability by refactoring the code into smaller
functions and reducing the number of arguments given to functions.

But more importantly, it stops making duplicate stats queries for every
email recipient by moving the queries out of the for loop.

* Refactor: move querying logic out of the worker module

and merge all stats information under a single `stats` assign.
3 years ago
Marko Saric 2bbc063b6c
adding data centers to the comparison 3 years ago
Cenk Kücük 147597cd98
Drop events when classified as datacenter IP (#3647) 3 years ago
Adrian Gruntkowski 9d97dc1912
Move limit enforcement to accepting site ownership transfer (#3612)
* Move limit enforcement to accepting site ownerhsip transfer

* enforce pageview limit on ownership transfer accept

* Refactor plan limit check logic

* Extract `ensure_can_take_ownership` to `Invitations` context and refactor

* Improve styling of exceeded limits notice in invitation dialog and disable button

* styling improvements to notice

* make transfer_ownership return transfer to self error

* do not allow transferring to user without active subscription WIP

* Add missing typespec and improve existing ones

* Fix formatting

* Explicitly label direct match on function argument for clarity

* Slightly refactor `CreateInvitation.bulk_transfer_ownership_direct`

* Exclude quota enforcement tests from small build test suite

* Remove unused return type from `invite_error()` union type

* Do not block plan upgrade when there's pending ownership transfer

* Don't block and only warn about missing features on transfer

* Remove `x-init` attribute used for debugging

* Add tests for `Quota.monthly_pageview_usage/2`

* Test and improve site admin ownership transfer actions

* Extend tests for `AcceptInvitation.transfer_ownership`

* Test transfer ownership controller level accept action error cases

* Test choosing plan by user without sites but with a pending ownership transfer

* Test invitation x-data in sites LV

* Remove sitelocker trigger in invitation acceptance code and simplify logic

* Add Quota test for `user.allow_next_upgrade_override` being set

* ignore pageview limit only when subscribing to plan

* Use sandbox Paddle instance for staging

* Use sandbox paddle key for staging and dev

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
hq1 1678fa10f4
Migrations for #3641 (#3644)
* Migrations for #3641

* Fix typo
3 years ago
Uku Taht 222de719ea
Fix dropdown highlighting for comparisons (#3643) 3 years ago
Uku Taht a3e365b01b
Remove onClick handler from details link (#3636) 3 years ago
RobertJoonas 22ecbe7bc7
Refactor: Split up the choose_plan LV code (#3637)
* move format_price to Plausible.Billing

* move PlausibleWeb.Components.Billing file to subfolder

* extract new Notice module

* rename test file and module name

* move growth_grandfathered notice to notice.ex

* extract a PlanBenefits module

* extract PlanBox component

* extract PageviewSlider component

* fix plan benefits text color
3 years ago
RobertJoonas 77ca5abbc8
fix theme applying based on the 'theme' query param (#3639) 3 years ago
hq1 9e783ebb41
Set CLICKHOUSE_MAX_BUFFER_SIZE_BYTES to 1M on dev (#3635)
Completes full `mix ecto.reset` in around 30s 🤘
3 years ago
dependabot[bot] 0a49511052
Bump eslint-plugin-playwright from 0.19.0 to 0.20.0 in /tracker (#3621)
Bumps [eslint-plugin-playwright](https://github.com/playwright-community/eslint-plugin-playwright) from 0.19.0 to 0.20.0.
- [Release notes](https://github.com/playwright-community/eslint-plugin-playwright/releases)
- [Changelog](https://github.com/playwright-community/eslint-plugin-playwright/blob/main/CHANGELOG.md)
- [Commits](https://github.com/playwright-community/eslint-plugin-playwright/compare/v0.19.0...v0.20.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-playwright
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vinicius Brasil 7f51928338
Remove business tier feature flag (#3632)
* Remove business tier feature flag

This commit removes all code branches related to the business tier
feature flag, as we're not flipping this flag off anymore. It also
removes unused routes, e.g. /billing/change-plan and /billing/upgrade

* remove unused billing templates

* refactor with clause to case instead

* assert on the url in email tests

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
ruslandoga 6639d6af63
Flush Clickhouse buffers faster by encoding early (#3623)
* encode early

* rename: CLICKHOUSE_MAX_BUFFER_SIZE -> CLICKHOUSE_MAX_BUFFER_SIZE_BYTES

* deprecate CLICKHOUSE_MAX_BUFFER_SIZE

* cleanup

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
Uku Taht 17ba44e8db
Fix darkmode flash (#3625)
* Inline theme script to layout

* Extract theme_script as Heex component

* Remove unused function

* Reference assigns directly

* Clean up current user

* Clean up theme javascript

* Use new theme script in focus.html layout

* Use `assigns` instead of `@conn.assigns` in `focus.html.heex` template too

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
RobertJoonas ab54a66a43
Fix `class` in `styled_link` and remove existing uses of `class` (#3631)
Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
hq1 5a01624f03
Fix link styling regression introduced via #3572 (#3629)
* Fix link styling regression introduced via #3572

* Justify external links in user dropdown

* Format

* Use assigns.new_tab to justify justification 🤡
3 years ago
hq1 8d85c38047
Add `:payment_required` policy to `GateKeeper` (#3628)
* Migration: Add `accept_traffic_until` to "sites"

* Drop traffic from sites where `accept_traffic_until` is passed
3 years ago
hq1 3f5eecf15f
Migration: Add `accept_traffic_until` to "sites" (#3627) 3 years ago
hq1 d161ad7667
Fix flaky test (#3626) 3 years ago
RobertJoonas 686ffa6ef3
Clean up legacy trials code + displaying limits (#3620)
* remove unused functionality

We can now safely delete all the logic around users who are on trial and
signed up *before* the business tiers release, since that's no longer
possible

* add monthly_pageview_limit fn clause that takes a user

* make Quota.site_limit return enterprise site limit

...not `:unlimited`, as we still need to display it
in the account settings.

* make `team_member_limit/1` return :unlimited on small_build

* improve team_member_usage/1 function doc

* stop displaying unlimited symbol in usage section

These unlimited limits include:

* `monthly_pageview_limit` for trials
* `team_member_limit` for old enterprise plans
* `site limit` for old accounts (before 2021-05-05)

* format

* small refactor case clause + move mod vars

* review suggestions
3 years ago
Uku Taht 677b4f2e79
Use dropdown component in /sites page (#3572)
* Use dropdown component in sites page

* Add x- attributes to globals

* Update tests

* Prevent default on click

* Fix compile warning

* Add conditional rendering back in

* Remove $id magic
3 years ago
ruslandoga 95e7a2b1f6
add session collapse order test (#3622) 3 years ago
RobertJoonas e85ee417ab
Prevent invited users without sites from subscribing (#3600)
* prevent invited users without sites from subscribing

* always setup a site in choose_plan_test context

* change trial_expiry_date=nil condition to no sites owned
3 years ago
hq1 8ba851d27f
Protect against custom props payloads breaking event insertions (#3617)
* Protect against custom props payloads breaking event insertions

* Use two traversals instead of three

* Reorganize invalid props filtering
3 years ago
hq1 b96319321c
Add Browser/Version breakdown to CSV (#3599)
* Add csv for browser versions

* add changelog

* Fixup - ensure the dashboard browser version breakdown still works

* Update CHANGELOG

---------

Co-authored-by: Ekaterina Krivich <ekaterinak@heathmont.net>
3 years ago
dependabot[bot] 906b06ae84
Bump eslint from 8.54.0 to 8.55.0 in /tracker (#3586)
Bumps [eslint](https://github.com/eslint/eslint) from 8.54.0 to 8.55.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.54.0...v8.55.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vinicius Brasil 45a763ab2b
Add data retention to the choose plan page (#3605)
* Add data retention field to plans

* Display data retention as benefit when choosing plan

* Split fields in two module attributes

* Remove extra whitespace

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
ruslandoga 26809bfd2e
Fix flaky rate_limit test (#3615) 3 years ago
hq1 7b5c20db17
Revert "experiment in improving throughput of write buffers (#3511)" (#3614)
This reverts commit 16bfb11701.
3 years ago
Adam Rutkowski 69579272d6 Revert "dump buffer on invalid insert (#3613)"
This reverts commit 7a4cafac16.
3 years ago
ruslandoga 7a4cafac16
dump buffer on invalid insert (#3613)
* dump buffer on invalid insert

* dump to PERSISTENT_CACHE_DIR

* fix warning

* ensure dir is not nil
3 years ago
ruslandoga 16bfb11701
experiment in improving throughput of write buffers (#3511)
* wip

* fewer length/1 calls

* encode early

* cleanup

* add micro benchmark

* extract types at compilation

* remove specs to make credo happier

* cleanup is_bounce

* cleanup :D

* add eprof to buffer insert+flush benchmark

* add ci/bench.yml

* rm state.schema from write buffer

* rm noisy logs

* rm benches

* add :source to insert

* make CLICKHOUSE_MAX_BUFFER_SIZE mean bytes

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
Vinicius Brasil e4230db2d9
Improve subscription status checking code (#3598)
* Improve subscription status checking code

This commit improves the subscription status checking in code, and
creates convinience functions to work with it, including nil-checking
and in?/2 function.

* Change in?/2 to macro
3 years ago
Adrian Gruntkowski 12f786810c
Remove `two_factor` feature flag (#3597)
* Remove `two_factor` feature flag

* Avoid compilation warnings in small build
3 years ago
ruslandoga 0eedf9aa98
rm Hammer (#3571) 3 years ago
Marko Saric 0b00762591
Changes to the emails as discussed (#3540)
* Update over_limit.html.eex

* Update dashboard_locked.html.eex

* Update dashboard_locked.html.eex

* Update over_limit.html.eex

* Update dashboard_locked.html.eex

* fix tests

* stop querying owned_site_ids three times

... when querying for billing cycles. Adds an optional `owned_site_ids`
argument to the `usage_cycle` function.

* add penultimate billing cycle info to emails

This commit also refactors some code and adds unit tests to email templates

* use delimit_integer instead of large_number_format

... to display usage with exact numbers such as 1,099,999 instead of 1M

* add penultimate cycle date ranges and linebreaks

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
hq1 615b6aef7d
Plugins API exentsions (custom props, bulk goal delete, goal creation => ListResponse always) (#3593)
* End polymorphic response in goals create

Being part of the v3 spec, this isn't well
(or at all) supported by OpenAPI generators.

Always respond with `Goal.ListResponse`

* Implement `PUT /custom_props`

* Implement bulk `DELETE /goals`

* Expose API for (bulk-)disabling custom props

* Add controller typespecs

* Delegate list wrapping to `Plausible.API.*`
3 years ago
Adrian Gruntkowski da0fa6c355
Implement UI for 2FA setup and verification (#3541)
* Add 2FA actions to `AuthController`

* Hook up new `AuthController` actions to router

* Add `qr_code` to project dependencies

* Implement generic `qr_code` component rendering SVG QR code from text

* Implement enabled and disabled 2FA setting state in user settings view

* Implement view for initiating 2FA setup

* Implement view for verifying 2FA setup

* Implement view for rendering generated 2FA recovery codes

* Implement view for verifying 2FA code

* Implement view for verifying 2FA recovery code

* Improve `input_with_clipboard` component

* Improve view for initiating 2FA setup

* Improve verify 2FA setup view

* Implement `verify_2fa_input` component

* Improve view for verifying 2FA setup

* Improve view rendering generated 2FA recovery codes

* Use `verify_2fa_input` component in verify 2FA view

* Do not render PA contact on self-hosted instances

* Improve flash message phrasing on generated recovery codes

* Add byline with a warning to disable 2FA modal

* Extract modal to component and move 2FA components to dedicated module

* First pass on loading state for "generate new codes"

* Adjust modal button logic

* Fix button in verify_2fa_input component

* Use button component in activate view

* Implement wait states for recovery code related actions properly

* Apply rate limiting to 2FA verification

* Log failed 2FA code input attempts

* Add ability to trust device and skip 2FA for 30 days

* Improve styling in dark mode

* Fix waiting state under Chrome and Safari

* Delete trust cookie when disabling 2FA

* Put 2FA behind a feature flag

* Extract 2FA cookie deletion

* ff fixup

* Improve session management during 2FA login

* Extract part of 2FA controller logic to a separate module and clean up a bit

* Clear 2FA user session when rate limit hit

* Add id to form in verify 2FA setup view

* Add controller tests for 2FA actions and login action

* Update CHANGELOG.md

* Use `full_build?()` instead of `@is_selfhost` removed after rebase

* Update `Auth.TOTP` moduledoc

* Add TOTP token management and make `TOTP.enable` more test-friendly

* Use TOTP token for device trust feature

* Use zero-deps `eqrcode` instead of deps-heavy `qr_code`

* Improve flash messages copy

Co-authored-by: hq1 <hq@mtod.org>

* Make one more copy improvement

Co-authored-by: hq1 <hq@mtod.org>

* Fix copy in remaining spots

* Change redirect after login to accept URLs from #3560 (h/t @aerosol)

* Add tests checking handling login_dest on login and 2FA verification

* Fix regression in email activation form submit button behavior

* Rename `PlausibleWeb.TwoFactor` -> `PlausibleWeb.TwoFactor.Session`

* Move `qr_code` component under `Components.TwoFactor`

* Set domain and secure options for new cookies

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
RobertJoonas 4566e6b530
New admin route for displaying usage (#3577)
* add a new crm usage route for admins

* add a test for admin route authorization

* add full_build_only tag
3 years ago
RobertJoonas 7212d336ae
add migration (#3590) 3 years ago
Adrian Gruntkowski cc18423369
Add `totp_token` string field to `users` (#3592) 3 years ago
Adrian Gruntkowski af363bf294 Remove test which is no longer conformant with current biz plan logic 3 years ago
Adrian Gruntkowski d42c6927d5
Use autocomplete=new-password for shared link password field (#3589) 3 years ago
Uku Taht 032823e112
Add last_bill_date to new subscriptions (#3588)
* Add last_bill_date to new subscriptions

* Remove leftover test code

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
Uku Taht 44d71c8c0e
Fix domains that start with UTF character (#3560)
* Avoid redirect in site settings

* Fix unicode in SiteController existing tests

* Fix various tests

* Add CHANGELOG

* Make sure test site is example.com

* Use Route helpers in site_controller

* Fix UTF redirect in change domain submit action

* Fix UTF site domain in reset stats action
3 years ago
hq1 c4eea9f8d5
`s/warn/warning` (`warn` is deprecated) (#3587) 3 years ago
hq1 74675f0cbc
Move dogfooding to full build (#3576)
* Move dogfooding to `extra/`

* Remove unused view functions
3 years ago
dependabot[bot] 466958ea60
Bump eslint-plugin-playwright from 0.18.0 to 0.19.0 in /tracker (#3578)
Bumps [eslint-plugin-playwright](https://github.com/playwright-community/eslint-plugin-playwright) from 0.18.0 to 0.19.0.
- [Release notes](https://github.com/playwright-community/eslint-plugin-playwright/releases)
- [Changelog](https://github.com/playwright-community/eslint-plugin-playwright/blob/main/CHANGELOG.md)
- [Commits](https://github.com/playwright-community/eslint-plugin-playwright/compare/v0.18.0...v0.19.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-playwright
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vinicius Brasil 5e6033e261
Move input range bubble to JavaScript (#3569)
* Move input range bubble to JavaScript

This commit switches the input range bubble on the choose plan page from
LiveView to JavaScript. The reason for this change is the input range
is a regular HTML input rendered by the browser, not LV, therefore
bubble was not in sync when sliding the input.

* Apply suggestions from code review
3 years ago
hq1 3905e27d40
Pin https://github.com/docker/metadata-action/ (#3575)
Ref: https://github.com/docker/metadata-action/pull/352#issuecomment-1833733738
3 years ago
hq1 7bf1e2a6ed
Reapply "Define a better monthly pageview usage (#3564)" (#3574)
This reverts commit c739b8878d.
3 years ago
hq1 5278c23965
Revert and extract migration (#3573)
* Revert "Define a better monthly pageview usage (#3564)"

This reverts commit 57188a402a.

* Extract migration from 57188a402a/priv/repo/migrations/20231129103158_add_allow_next_upgrade_override_to_users.exs
3 years ago
RobertJoonas 57188a402a
Define a better monthly pageview usage (#3564)
* refactor asking for the monthly pageview usage

* add tests for usage and limits section in account settings

* display pageview usage per billing cycle for active subscribers

* disable cycle tabs if no usage

* make current billing cycle whole

...instead of capping it at today's date

* run queries for different cycles concurrently

* fix linebreak bug

* add calculate usage action into CRM

* change some names of assigns

* block subscribing to a plan by pageview usage

Depending on whether the customer has already subscribed or not, checking
their pageview usage is different:

* If they're not subscribed yet, we allow them to subscribe to a plan If
  it their last 30 days usage does not exceed the plan pageview limit by
  more than 15% (30% for when subscribing to a 10k plan)

* For existing subscribers, we'll use the exact same mechanism that we're
  using for locking sites - the last two billing cycles usage. If both
  cycles exceed the plan limit by more than 10% - we don't allow them to
  subscribe to the plan

* apply credo suggestion

* prevent highlight bar overflow

* move disabled classes to button element

* optimize for darkmode

* unify link and text styling on the same horizontal line

'Upgrade' & 'Update billing details' links + billing interval text were
positioned on the same line. The font size was similar, but not the same

* improve exceeded_limits function readability

* Refactor some tests and remove code duplication

* override allow upgrade when limits exceeded

In cases where limits are exceeded, we can set the boolean flag
`allow_next_upgrade_override` to `true` in the CRM. This will allow
the user to upgrade to any plan they want. After they've upgraded or
changed their plan - the flag will automatically reset to `false`.

* only apply upgrade override for exceeded pageview limit

* fix tests on the CI

* make current_cycle usage always displayed by default

* make pageview allowance margin more clear

* add comment
3 years ago
hq1 bd7deb5631
Update dockerfile for build options (#3567)
* Update dockerfile for build options

* Start permanent on small

* Default to small

* Default to small fixup
3 years ago
Vinicius Brasil 8dfaad56f0
Match choose plan styling with landing page (#3568)
* Match choose page styling with landing page

Related: https://github.com/plausible/website/pull/507

* Fix tests

* Apply suggestions from code review
3 years ago
dependabot[bot] 736baa25d8
Bump @playwright/test from 1.40.0 to 1.40.1 in /tracker (#3565)
Bumps [@playwright/test](https://github.com/microsoft/playwright) from 1.40.0 to 1.40.1.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.40.0...v1.40.1)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
hq1 a4b9c3b8ba
Remove custom domains support + update build options (#3559)
* Disable super-admin checks on small build

* Mute a test writing to stdout

* Move sampling outside of small build

* Convert waiting_first_pageview to heex and stop relying on env vars

* Set site limit unlimited on small build

* Stop relying on app env to get trial expiry

* Remove custom domains - including migration

* Remove is_selfhosted from layout view

* Quota fixup

* Stop relying on app env for self hosted registration

* Stop relying on app env for pass reset success

* Apply on_trial? check only on full build

* Update templates relying on app env

* Adjusts auth controller tests for small build

* Trial fixup

* Fixup

* Stop relying on app env

* Rest of the fsckn owl

* Update typespecs

* Fix dialyzer warning

* Remove unused module

* Credo + format

* GeoIP is not, for full build

* Use `small_build?()` where applicable

* Implement bypassing FirstLaunchPlug without insertions

* Get Marko's patch de58a18a85

* Test is-dbip=false presence

* Fix typespec

* Remove future hardcodes

* Handle `nil` from `Plausible.Geo.database_type()`

* Remove XXX marker

* Use one typespec for two clauses

* Introduce `MIX_ENV=small_dev`

* Revert "Use one typespec for two clauses"

This reverts commit 8d8cd21764.
3 years ago
Adrian Gruntkowski 86b9d1680d
Simplify TOTP core logic and add email notifications (#3563)
* Modify API of `Auth.TOTP` to work with simplified flow

* Send email when 2FA is enabled and disabled

* Add tests for `initiated?/1`

* Add tests for email submission and improve recipient address composition

* Fix email tags

* Rename email templates to HEEx

* Fix formatting in email templates
3 years ago
RobertJoonas ff2c3346d2
Bugfix: Allow breakdown by internally used prop keys for Growth plans (#3562)
* fix bug - allow internally used prop key breakdown for Growth plans

* use case instead of with
3 years ago
Marko Saric be48ca2826
Update SECURITY.md 3 years ago
Marko Saric de58a18a85
Keeping footers consistent 3 years ago
Marko Saric 276461e4ea
Comparison updated to keep it consistent with the site 3 years ago
hq1 0f577a998c
Update credo config + extras (#3547)
* Disable CyclomaticComplexity checks

* Move AuhtorizeSitesAPI plug under extra
3 years ago
hq1 88e1d9dc28
Small build updates (#3546)
* Sites API

* Extract Revenue react api helpers

* !fixup

* Extract JS Money module to /extra

* Extract Revenue full build extras (tests pass for full)

* Update MIX_ENV=small mix test

* Remove dead code

* Add moduledocs

* Add credo config

* Trick dialyzer

* DRY revenue metrics

* Use more concise version of on_full_build macro

* Disable credo check
3 years ago
Vinicius Brasil af0b97e68a
Move Mix.Task.DumpPlans to Plausible.Release (#3544)
This commit moves the dump_plans Mix task to the Plausible.Release
module so it can run in production.

Usage: `./bin/plausible eval Plausible.Release.dump_plans`
3 years ago
dependabot[bot] f01b76cc41
Bump eslint from 8.53.0 to 8.54.0 in /tracker (#3533)
Bumps [eslint](https://github.com/eslint/eslint) from 8.53.0 to 8.54.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.53.0...v8.54.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vinicius Brasil b35096bbc8
Dump plan information to PostgreSQL (#3543)
* Use Ecto.Schema for casting plans from JSON files

* Dump plans to internal database table
3 years ago
Adrian Gruntkowski 65cc8980e0
Implement core logic for TOTP support (#3525)
* Add `nimble_totp`, `cloak` and `cloak_ecto` to project dependencies

* Setup Cloak-based secrets vault and create a dedicated Ecto type

* Add `totp_enabled|secret|last_used_at` fields to `User` schema

* Implement schema and stateless logic for TOTP recovery codes

* Implement core logic of TOTP auth

* Fix typos and improve style of doc comments

Co-authored-by: hq1 <hq@mtod.org>

* Fix moduledoc alignment

* Use more compact conditional expression

Co-authored-by: hq1 <hq@mtod.org>

* Disambiguate `I` as `7` when generating recovery codes (h/t @hq1)

* Fix a typo in runtime config error message

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 819449f19a
Include extra in docker image (#3537) 3 years ago
hq1 b9ec38038c
Add small build option (#3536)
* Update applications

* Clone community config

* Move modules to experimental dir

* Update runtime config

* Apply first set of compile-time conditionals

* Move funnel schemas to experimental

* Make funnel schema-less build compile

* Use experimental/lib for elixir code

* Move JS funnels to experimental

* Clean up conditional rendering

* Tidy up the pipeline

* Make two builds pass tests without warnings

* Reuse existing dotenvs

* Do a bunch of renames

* Clean up naming

* Run secondary CI

* Update router

* Remove RewriteFunnelDupes migration

Tests were disabled already and it was a one-off shot

* Fixup quota mixins

* Add moduledoc

* Change MIX_ENV for seconary test run

* Skip crm on small

* !fixup

* Exclude flags pipeline

* Update lib/plausible_web/controllers/stats_controller.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Adrian Gruntkowski 2512f3cbe2
Create migration adding TOTP fields to `users` and recovery codes table (#3535) 3 years ago
Adrian Gruntkowski 9b0a6e6e7d
Improve LiveView flash messages (#3523)
* Cancel existing flash timer before setting a new one

* Abstract flash logic across live views

* Render flash messages one after another
3 years ago
ruslandoga 4586e091a5
Update PromEx to fix a memory leak in benchmarks (#3532) 3 years ago
RobertJoonas 02a1271ee4
Bugfix site transfers (#3531)
* Bugfix: allow ownership transfers when premium features enabled but not used

Fields like `props_enabled` and `funnels_enabled` are true by default,
and these fields do not indicate whether the user/site is actually using
these features or not.

* allow site transfers if they will be at limit after transfer

* small refactor
3 years ago
Vinicius Brasil 0175158e81
List only premium features on the CRM (#3530) 3 years ago
Cenk Kücük f4d7ba70e8
drop IPs classified as datacenter (#3522)
* drop IPs classified as datacenter

* process event and increment counter instead of dropping
3 years ago
dependabot[bot] a2c9ba191e
Bump @playwright/test from 1.39.0 to 1.40.0 in /tracker (#3528)
Bumps [@playwright/test](https://github.com/microsoft/playwright) from 1.39.0 to 1.40.0.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.39.0...v1.40.0)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Márton Salomváry 555eb25d20
Allow custom event timeseries in stats API (#3505)
* Allow custom event timeseries in stats API

* Fix linting error

---------

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
3 years ago
Vinicius Brasil cfaa5be8f4
Configurable limits for enterprise plans (#3527) 3 years ago
RobertJoonas d66322e12d
Limit grandfathering to *active* subscribers and trials (#3524)
* refactor asserting plan generation in plans_test.exs

* stop grandfathering old expired trials

For users who registered before the business tiers release, we want to
offer a chance to subscribe to a grandfathered plan. However, if they
let their trial expire and don't subscribe in the next 10 days, they'll
lose that opportunity.

* stop grandfathering expired subscriptions

* remove default title and icon from Generic.notice

* fix bug with dismissable notice

classList is null when dismissable_id is not given

* alias Plausible.Auth.User

* Refactor Generic.notice component

Make it easy to apply different colors

* move subscription_cancelled_notice across the app

And remove from user settings > subscription box. Also, include a note
about losing grandfathered status when letting the subscription expire.

* allow full width in Generic.notice

* use Generic.notice for subscription_past_due_notice

* use Generic.notice for subscription_paused_notice

* prevent two notices clashing into each other with gap-y-2

* define attrs for phx components

* optimize for light mode

* make subscription cancelled notice dismissable

but if it's dismiss, show it in the place where it was before in the
account settings > subscription box

* make function private

* replace function doc with regular comment to avoid compile warning

* use array for classnames

Co-authored-by: Vinicius Brasil <vini@hey.com>

* fix typos in function doc

---------

Co-authored-by: Vinicius Brasil <vini@hey.com>
3 years ago
ruslandoga 13055aafc0
use windows in 'time on page' queries (#3446)
* use windows in 'time on page' query

* add imported time on page back

* join imported_pages instead of extra query

* don't forget aggregated time on page!

* eh?

* no need for separate window clause

* use dynamic_filter_condition in aggregate_time_on_page

* it's avg, not total

* fix dynamic_filter_condition call

* tests pass

* fewer changes

* fewer changes + feature flag

* base quickfix

* fewer changes

* fewer changes?

* fewer changes!

* replace coalesce with if(empty(),etc)

* make window_aggregate_time_on_page return same result as neighbor_

* breakdown as well

* add failing test

* more info

* more info

* format example

* add failing aggregate.ex test

* fix breakdown.ex windowing time_on_page calculation

* fix aggregate.ex windowing time_on_page calculation
3 years ago
dependabot[bot] dc5ab2e407
Bump hashicorp/setup-terraform from 2 to 3 (#3489)
Bumps [hashicorp/setup-terraform](https://github.com/hashicorp/setup-terraform) from 2 to 3.
- [Release notes](https://github.com/hashicorp/setup-terraform/releases)
- [Changelog](https://github.com/hashicorp/setup-terraform/blob/main/CHANGELOG.md)
- [Commits](https://github.com/hashicorp/setup-terraform/compare/v2...v3)

---
updated-dependencies:
- dependency-name: hashicorp/setup-terraform
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 53e4d64195
Bump eslint from 8.52.0 to 8.53.0 in /tracker (#3488)
Bumps [eslint](https://github.com/eslint/eslint) from 8.52.0 to 8.53.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.52.0...v8.53.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vinicius Brasil e541f1a55f
Hide premium feature notice for trials (#3509) 3 years ago
ruslandoga f2a8809fd1
unlock unused deps (#3518) 3 years ago
RobertJoonas af979d02c7
Bugfix: Allow cancelled subscriptions to subscribe (#3517)
* extract set_slider function in choose_plan_test

* allow cancelled subscriptions to subscribe even before expired
3 years ago
RobertJoonas fdf1462c04
Notice across the app about Funnels and Revenue goals private preview end (#3510)
* change upgrade CTA notice message for enterprise and business plans

* add dismissable option to Generic.notice

* more general notice about losing premium features in X days

* save notice dismissed per user

... more than one Plausible account can use the same device, so we should
scope the fact that the notice has been dismissed by user id.

* fix bug applying classes to Generic.notice

* apply shadow to the new notice on light mode

* use Heroicons.x_mark instead of raw SVG

* use Enum.filter instead of list comprehension
3 years ago
Cenk Kücük 0c2e6b8751
Integrate ingestion monitoring data into instatus (#3515) 3 years ago
Adrian Gruntkowski 3ba57a04fc
Make OpenTelemetry sampler ratio configurable via env (#3514) 3 years ago
hq1 671904aefd
Enable JSON log formatting (#3512)
* Enable JSON log formatting

if `LOG_FORMAT=json` is set, the app will start logging
JSON-formatted messages. By the way, the Repo :loggers configration
was removed since it's been already deprecated by Ecto v3
(https://hexdocs.pm/ecto/changelog.html#deprecations-4).

* Update changelog
3 years ago
hq1 c64ab6b6ee
Fix bug showing invitation popups (#3513)
Apparently using the `<p>` element breaks x-show/styles cascading.
Swapping it with `<div>` renders `x-show` correctly including
children elements.
3 years ago
Adrian Gruntkowski f464ceae88
Implement pinned sites (#3469)
* Revert "Remove site pins for now"

This reverts commit 5eccf4eaf6.

* Implement basic site pin schema level logic within user specific preferences

* Add vertical ellipsis menu markup

* Implement basic changesets for user preferences

* Implement pin toggling

* Try to fix pin sorting

* Implement pin toggling in LV

* Adjust moduledocs for new schema(s)

* Remove unnecessary `distinct` from query

* Use `button` for pin/unpin action

* Generalize preference setting

* Rename schema and fields for clarity

* Rename `list_type` -> `entry_type`

* Safeguard setting options

* Test `set_option/4` and `toggle_pin/2`

* Add test for listing pinned sites via `Sites.list`

* Disallow pinning sites outside page explicitly

* Test pinning in LV

* Test conditional rendering of site settings in /sites

* Remove unnecessary TODO comment

* Safeguard `Sites.set_option/4` against invalid user/site combo

* Handle pinned sites in dashboard site picker

* Clear flashes upon (un)pinning sites

* Update CHANGELOG

* Prevent blinking of hamburger menu items on first paint

* Highlight hamburger handle on hover in /sites

* Start showing hotkeys in site picker again

* Sort pinned sites in the order they were pinned

* Update sites list order immediately after pin/unpin toggle

* Refactor and split `Sites.list/3`, extracting `Sites.list_with_invitations/3`

* Cap number of pinned sites at 9 per user

* First pass on visual indication of site cards (dis)appearing

* Apply ellipsis gradient+shadow on card hover

* Fix responsive padding of site cards

* Sort by invitations first, pinned sites second and then the rest

* Revert "Apply ellipsis gradient+shadow on card hover"

This reverts commit 0608796612639030ccbb12df639709f78edc1434.

* Apply more subtle hover effect on the ellipsis menu

* Make error and success flash LV boxes use separate component containers

* Promote `pinned_at` in table migration to a column

* Switch logic to using `pinned_at` as a standard schema field

* Refactor `Sites.list*` getting rid of subquery (h/t @ukutaht)

* Remove migration which is already merged upstream

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
3 years ago
RobertJoonas 26d9e16d7d
Fixing Business Tier related bugs (#3504)
* fix underlined blank space in upgrade link

* Add :if clause to site limit notice

* Change test description

* Move growth? and trial? conditionals to CTA function

* Improve wording in billing notices

---------

Co-authored-by: Vinicius Brasil <vini@hey.com>
3 years ago
hq1 af87a63cab
Fix disabled invitation form on business tier (#3508)
ref https://github.com/plausible/analytics/pull/3493
3 years ago
Adrian Gruntkowski 2d2ea1a2a3
Implement trace ID ratio-based sampling for OpenTelemetry (#3499)
* Implement trace ID ratio-based sampling for OpenTelemetry

* Make `decide` more resilient
3 years ago
Adrian Gruntkowski 8698b8770b
Create `site_user_preferences` table and apply LV fix (#3506)
* Create `site_user_preferences` table

* Do not trigger querying on filter text change when there's no change
3 years ago
Marko Saric 69d21d59b1
Update README.md 3 years ago
Vini Brasil b5000cc247
Fix private preview notice typo (#3503)
* Fix private preview notice typo

* fix link to choose-plan instead of upgrade

* do not display premium feature notice if legacy feature access

* register trial message

* change enterprise contact us copy

* fix test

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
Vini Brasil 2578391be2
Display private preview for non business accounts (#3502)
* Display private preview for non business accounts

* Update lib/plausible_web/components/billing.ex

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
RobertJoonas 7036332db2
Business tier bug smash (#3493)
* price formatting

* fix space underlined

* add a redirect from :upgrade to :choose_plan

* Add premium feature notice to revenue goals

* add the number of API request to plan benefits

* be more explicit about Stats API requests

* start linking to the new upgrade page if FF enabled

* add redirect to :upgrade_to_enterprise_plan from :choose_plan

This commit intends to keep the existing behaviour of redirecting users
directly to the enterprise upgrade page when they click on an upgrade
link in an email and have an enterprise plan configured.

Hence, we can also simplify the /settings template and only link to
'/billing/choose-plan', even for enterprise plans.

* deprecate /billing/change-plan route based on FF

* Move new site template to HEEX

* Move new team member invitation template to HEEX

* Standardize exceeded limits error message

* Fix failing tests

* Limit Stats API access to unlimited trials

---------

Co-authored-by: Vinicius Brasil <vini@hey.com>
3 years ago
Vini Brasil c9bf5827e9
Prepare business tier for release (#3464)
* Change limits for trials

* Keep legacy trial limits for users that registered before the business tier

* Change private preview notice for release

* Run formatter

* Add countdown to private preview notice
3 years ago
hq1 38b1834b3f
Tidy up openapi schema (#3498)
* Tidy up OpenAPI schema

* Remove `items` from object schema
3 years ago
Uku Taht 058d8cc6c9
Extract button component (#3474)
* Add button component

* Use new button in settings screen

* Use button component in registration screens

* Use new button component for Billing.upgrade_link

* Separate .button and .button_link

* Add attr definiton for disabled

* Fix funnels test
3 years ago
ruslandoga 2917cfaf65
add tests for time_on_page edge cases (#3494) 3 years ago
RobertJoonas f977351ae2
Fix upgrade page for legacy trials + bug fixes (#3486)
* allow using Stats API and Props for free_10k subscriptions

* return v3 plans for legacy trials

* do not display grandfathering notice for legacy trials

* set a more accurate BT release date

* fix bug on dev env

Allow the `find/1` function to find sandbox plans

* add error handling and tests for change_plan_preview

* fix feature warning bug

* fix credo warnings

* fix tests

* set BT release date further into the future

* rename function and some vars

* bugfix with limit exceeding

* fix test
3 years ago
hq1 a8fa05706b
Add loading state to site cards (#3483)
* Show loading state for mini plots

* Dark mode

* Don't render no change in green

* Fix loading placeholders for mobile/desktop view

* Fixup test

* Make loading state background color for light theme one step brighter

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
RobertJoonas 8f26b9a034
Allow subscribing to a plan when exceeding its pageview limit on the new upgrade page (#3481)
* still allow subscribing to a plan when exceeding its pageview limit

* format
3 years ago
hq1 08bd10614f
Fixups sites (#3482)
* Revert "Fix sites query invitation left join lookup (#3480)"

This reverts commit 6e6508a359.

* Revert "Revert "Fix sites query invitation left join lookup (#3480)""

This reverts commit f5cc831d7a.

* Revert "Fix sites query invitation left join lookup (#3480)"

This reverts commit 6e6508a359.

* Fix sites listing
3 years ago
RobertJoonas df44f549d8
Recommending a plan (#3476)
* use a different article in the email copies

... for recommending a plan, since the user can choose between Growth
and Business.

* small refactoring improvement

Rename `Plans.available_plans_with_prices` to `Plans.available_plans_for`,
taking an optional `with_prices` argument.

* highlight recommended tier for trial users on the ugprade page

* review suggestion
3 years ago
hq1 6e6508a359
Fix sites query invitation left join lookup (#3480) 3 years ago
hq1 30b4dc2872
Show 0% change on the small plot (#3478)
* Show 0% change on the small plot

* Fix more cut-off

* ws
3 years ago
hq1 6148f4ad61
Fix /sites cut-off for 0 visitors plot (#3477) 3 years ago
Adrian Gruntkowski 07cab27fef
Implement new sites view (#3463)
* Implement complete basics of LV sites

* Reimplement everything in LV except pagination

* Implement basic search capability

* PoC: plot visitors on sites index

* Add rudimentary clipped gradient in minicharts

* Fix clipping gradient, define once

* Format

* Add moduledoc to visitors component

* Move paginator helpers to the top core namespace

* Fix typespec of `Plausible.Sites.list`

* Split sites component into subcomponents

* Add function to uniformly calculate 24h intervals
and visitor totals across multiple sites.

* Integrate batch 24h interval query with plots on sites view

* Don't confuse heex compiler with alpine @ shorthands

* Make linear gradient svg definition truly invisible

* Implement basic pagination

* Extract `site_stats` from site and invitation cards

* Improve pagination

* Tweak css

* Improve filtering on pagination and make WSS fail graceful

* Test `last_24h_visitors_hourly_intervals/2`

* Replace /sites with LV implementation

* Add debounce to search filter

* Fix typespecs

* Fix styling

* Fix mini graph scaling factor calculation

* Fix search consuming itself

* Minimal tweaks to the plots

* Fixup

* Remove magic numbers from the plot

* Create `site_pins` table

* Add `SitePin` schema

* Implement listing invitations, sites and pins in a single query

* Add FIXME note

* Remove site pins for now

* Add tests for `Plausible.Sites.list/3`

* Add a couple more tests to sites dead view

* Remove unnecessary FIXME

* Add LV tests for Sites

* Calculate and display 24h visitors change

* Render the change in bold

* Add clarfying comment on virtual field in `Site` schema

* Remove unnecessary function from Invitations API

* Remove unused list opt from type definition in `Sites`

* Improve joins in list query slightly

* Add comment on manually computing sites list total

* Start searching from a singly character in domain field

* Add typespec to `last_24h_visitors_hourly_intervals`

* Extend moduledoc in visitors component

* Simplify loading sites in LV

* Simplify assigns in LV

* Add missing group for shadow under site card

* Make invitation modal render

* Make HTML in sites LV semantically correct

* Remove autofocus and focus search on `/`

* Remove shadow from search input

* Make search cancel on escape

* Fix tests relying on outdated HTML structure

* Make visitor chart color scheme consistent with dashboard chart

* Update styling of trend labels

* Fix empty state and improve search blur/focus handling

* Use live navigation for pagination

* Implement spinner on load from search

* Remove unused `Plausible.Stats.Clickhouse.last_24h_visitors/1`

* Calculate uniques correctly across hour boundaries

* Swap inlined svg for Heroicons component in invitation modal

* Add order by to base query in 24h hourly intervals

* Revert "Add order by to base query in 24h hourly intervals"

This reverts commit a6be5e3026.

* Query clickhouse 24h visitors only on second mount

* Remove redundant sign from percentage change when negative

* Switch to offset-based pagination

  - offset seems easier to deal with for when actions on
    paginated list will be performed such as site pinning;
    tracking cursor data makes some entries disappear in
    edge cases. The data set is still fairly small and
    static, even for large customers.
  - we're removing Phoenix.Pagination as it doesn't really
    fir any use case, and it was only used to limit the number
    of sites in the site picker
  - site picker is now limited to 9 sites (future: pinned
    sites will be prioritized there)
  - no need to re-query for total count any more
  - BTW, the old /sites template was removed

* Refine the plot queries; Tests pass snapshot

* Add PromEx plugin for LiveView

* Fix tiny plot cut-off at the top

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
3 years ago
Marko Saric 3e77621d81
Fixing the broken GSC settings link in the dashboard (#3473)
* Fixing the broken GSC settings link in the dashboard

* Update google-keywords.js
3 years ago
Uku Taht ee0ef52a5f
Fix dark mode race condition (#3472)
* Ensure app.js is loaded before dashboard.js

* Use non-deprecated eventListener format
3 years ago
Uku Taht 9bf7497d4b Fix asset path for docs 3 years ago
Uku Taht cfe81d6d3f
Simplify asset building (#3459)
* Add tailwind and esbuild

* Remove unused images

* Move unprocessed assets to priv directory

* Fix applyTheme script

* Remove autoprefixer

* Update bundlemon

* Remove babel config

* Revert "Remove autoprefixer"

This reverts commit fc60c31c73.

* Make dashboard react file work

* Fix app.css imports

* Remove autoprefixer

* Add back in robots.txt

* Go back to css/ and js/ folders as opposed to assets/

* Bundle embed.host.js and embed.content.js

* Add components folder to live reload paths

* Remove bundlemon

* Use mix assets task in Dockerfil

* Add assets setup to CONTRIBUTING.md
3 years ago
ruslandoga 463697661c
remove action=register_form check (#3466) 3 years ago
dependabot[bot] 65021f9304
Bump eslint from 8.51.0 to 8.52.0 in /tracker (#3462)
Bumps [eslint](https://github.com/eslint/eslint) from 8.51.0 to 8.52.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.51.0...v8.52.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] b298e0e1b5
Bump actions/setup-node from 3 to 4 (#3468)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 3 to 4.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vini Brasil 3b28a8d418
Warn user about Stats API when downgrading (#3471)
* Warn user about Stats API when downgrading

* Update test/plausible/billing/quota_test.exs

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
RobertJoonas 3c76053c3f
ignore only pv limit exceeded on subscribe (#3470) 3 years ago
RobertJoonas 8cc7bce689
Restrict subscribing to a plan when exceeding its limits + warning for losing feature access (#3461)
* fix the styling of the red text notice under checkout link

* avoid some code repetition

* simplify rendering the change_plan_link

* refactor disabling checkout link and showing disabled message

* disable change plan and upgrade link when exceeding pageview limit

* disable checkout when exceeding team member limit

* disable checkout when site limit exceeded

* extract checkout related code in a separate function

* stick to a single order of features

* losing features warning

* fix back link from change-plan-preview

* create Quota.exceeded_limits function

* restrict subscribing with exceeded limits on the API level too

* use with instead of case

Co-authored-by: Vini Brasil <vini@hey.com>

* use :map type instead of :any for user

Co-authored-by: Vini Brasil <vini@hey.com>

* create Quota.usage function

---------

Co-authored-by: Vini Brasil <vini@hey.com>
3 years ago
dependabot[bot] 0c8b3d7992
Bump postcss from 8.4.29 to 8.4.31 in /assets (#3398)
Bumps [postcss](https://github.com/postcss/postcss) from 8.4.29 to 8.4.31.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.4.29...8.4.31)

---
updated-dependencies:
- dependency-name: postcss
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 7312598b4b
Bump @babel/traverse from 7.21.5 to 7.23.2 in /assets (#3431)
Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.21.5 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse)

---
updated-dependencies:
- dependency-name: "@babel/traverse"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] f4cbefbcb4
Bump eslint-plugin-playwright from 0.16.0 to 0.18.0 in /tracker (#3451)
Bumps [eslint-plugin-playwright](https://github.com/playwright-community/eslint-plugin-playwright) from 0.16.0 to 0.18.0.
- [Release notes](https://github.com/playwright-community/eslint-plugin-playwright/releases)
- [Changelog](https://github.com/playwright-community/eslint-plugin-playwright/blob/main/CHANGELOG.md)
- [Commits](https://github.com/playwright-community/eslint-plugin-playwright/compare/v0.16.0...v0.18.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-playwright
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vini Brasil ad05af08a4
Check for limits and features used by site before transferring ownership (#3445)
* Simplify team_member_usage query

* Check limits before transferring ownership

* Extract invite creation to dedicated service module

* Simplify team member usage query

* Remove unnecessary distinct clause

* Delegate CreateInvitation via Memberships
3 years ago
RobertJoonas a226773da1
Legacy plans (#3455)
* replace unlisted plans with legacy plans

...and add a legacy plan that has an existing subscriber in Paddle. All
legacy plans are considered generation 1 - meaning that when a user on
one of these plans and they'll go to the upgrade page, then the listed
plans will be v1 for Growth and v3 for Business.

* remove redundant plans_sandbox function

* remove the unused 'scope' argument from Plans.find

* remove unused plan

* add basic test coverage for legacy plans

* add another plan with an existing active subscriber (fix another bug)
3 years ago
Marko Saric 9798a80a5a
Copy changes (#3460) 3 years ago
Uku Taht c075a1b149
Fix feedback link (#3452) 3 years ago
hq1 117eef000d
Upgrade Erlang/Elixir stack (#3454)
* Bump deps

* Bump stack

* Fix deprecation warnings

* Fix VCR cassettes mismatch due to OTP-18414

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Format & fix flaky tests

* Handle raw IPv4 hostnames; test public suffix TLD

* Configure locus db cache_dir

So that maxmind unavailability doesn't affect
application startup. PERSISTENT_CACHE_DIR env var is used
to point locus at the GeoIP DB file.

* WIP: Remove ExVCR

* Fix test env config

* Fixup exvcr

* Remove exvcr from deps

* Add convert script

* Remove exvcr cassettes

* Remove convert script

* Rename test

* Update moduledoc

* Update dockerfile

* Bump CI cache

* Tag more slow tests, why not?

* Use charlist for locus cache option

* Pin nodejs

* Merge google tests, make them async

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
RobertJoonas 2ada3d700f
List plan benefits on the new upgrade page (#3444)
* change team member limits for new v4 plans

* duplicate business plans with unlimited team members

We need to do this because we want grandfathered users to have unlimited
team members on business plans as well. Otherwise we'd have to build
overrides on the subscription level when checking the limit.

* refactor generating plan structs

* move Plan module into a separate file

* remove not needed conditions

* add generation field to plans

* sync the sanbox plan limits and features with plan generations

* implement displaying plan benefits

* add grandfathering notice

* plug in the real v3 business plan IDs

* optimize N/A text color for darkmode

* use String.to_existing_atom instead

Co-authored-by: Vini Brasil <vini@hey.com>

* Remove the unnecessary part of a comment

Co-authored-by: Vini Brasil <vini@hey.com>

* make the Plan.new function simpler

* use exlamation marks

---------

Co-authored-by: Vini Brasil <vini@hey.com>
3 years ago
hq1 957138a8ec
Plugins API: handle Revenue Goals creation wrt Business Tier (#3440)
* Plugins API: handle Revenue Goals creation wrt Business Tier

* Update bulk goal creation

* Update test/plausible_web/plugins/api/controllers/goals_test.exs

Co-authored-by: Vini Brasil <vini@hey.com>

* Use growth_subscription factory

---------

Co-authored-by: Vini Brasil <vini@hey.com>
3 years ago
hq1 19b2239eb9
Track tokens usage (#3438)
* Migration: track last seen usage for Plugins API Tokens

* Track and interpret Token.last_seen_at

* Display last used

* Order tokens by inserted date, rather than UUID :clown:

* s/Last seen/Last used in the UI

* Test for "Last used" column presence

* Fix table layout for very long descriptions

* Update lib/plausible/plugins/api/tokens.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update lib/plausible/plugins/api/token.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update test/plausible/plugins/api/token_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* s/last_seen_at/last_used_at

* Update lib/plausible_web/live/plugins/api/settings.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* fixup

* Document reasoning behind 5m windows

* s/last_seen/last_used

* Mute credo

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
hq1 2cc80ebd7a
Integrations Settings section (#3427)
* Extend the Tokens context module

* Extract GA Import to separate component

* Extract Search Console settings to separate component

* Remove Search Console from the router

* Stop counting imported pageviews in general settings

* Remove search console controller action

* Add settings_integrations controller action

* Fix remaining redirects

* Add Integrations route

* Replace SC sidebar item with Integrations

* Update site controller tests

* Implement Plugins API Tokens LV

* Apply universal heroicon to docs info links

* Add flash on token creation

* Update CHANGELOG

* Redirect to integrations upon forgetting GA import

* Update moduledocs

* Remove unnecessary wildcards

* WIP: attempt at fixing broken oauth flow

* Fix post-import redirect

* Fixup missing attribute

* Format

* Seed random google auth

* Use example.com for seeded e-mails

* Tweak Google integrations layout

* Remove dangling IO.inspect

* Bugfix: copy to clipboard breaking LV form bindings

* Update lib/plausible/plugins/api/tokens.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update lib/plausible_web/controllers/site_controller.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update lib/plausible_web/live/plugins/api/settings.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update test/plausible/plugins/api/tokens_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Adrian Gruntkowski 127a9ef9ba
Document reasoning behind disabling deduplication in import tables (#3439) 3 years ago
Vini Brasil 3b0322670b
Update plans_v4.json with new plans IDs (#3436)
* Update plans_v4.json with new plans IDs

* Fix failing tests

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
RobertJoonas 7674c94ace
Refactor: Add 'goals' feature to JSON plan files (#3435)
* fix text color in dark mode

* rename a function

* use aliases in quota.ex

* rename a function

* make Goals a similar feature to others but with a free option

* rename a function

* mix format
3 years ago
hq1 52d5fac362
Fixup 4cdf843ad: (#3434)
- migration is irreversible for now,
    likely due to https://github.com/plausible/ecto_ch/issues/81#issuecomment-1624754909
    or maybe https://github.com/plausible/ecto_ch/pull/58/files
  - IO.inspect call removed
3 years ago
Marko Saric ff66e9b1e4
changing the link to the feedback board 3 years ago
Marko Saric 9e13e20567
fixing the link for feature requests 3 years ago
Vini Brasil 896d78d8fd
Apply feature gates to dashboard queries (#3424)
* Read feature status from Billing.Feature instead of %Site{}

This commit changes data attributes passed to React. Previously the
controller read feature statuses directly from the %Site{} schema. The
Billing.Feature context is aware of the user plan and the features
available.

* Limit funnels internal API based on site owner plan

* Limit props internal API based on site owner plan

* Use site factory in QueryTest

* Limit custom property filter based on site owner plan

* Limit revenue goals queries based on site owner plan
3 years ago
hq1 9b912f3d89
Fix liveview (#3433) 3 years ago
Adrian Gruntkowski 4cdf843ade
Disable deduplication for improted_* tables in CH (#3429)
* Disable deduplication for improted_* tables in CH

* Make migration cluster-aware

* Bump cache to avoid problems

* Fix cache dump

* Remove cache bump
3 years ago
Uku Taht fd8a9529f9
Choose plan styling (#3399)
* Update styling for Choose Plan page

* Make it look good on mobile

* Update tests

* Remove unnecessary assign

* Optimize for dark mode

* Change order or interval picker and slider on mobile

* Format

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
hq1 e12ea9701d
Fix master build (#3432) 3 years ago
Uku Taht d7cd719d4f
Use default Phoenix.LiveView.Socket (#3404)
* Use default Phoenix.LiveView.Socket

* Pull socket definition highed in Endpoint config

* Simplify runtime plug session
3 years ago
Uku Taht 97b24c0492
Nolt sso (along with a better nav dropdown) (#3395)
* Add SSO link with signed JWT token

* Falls back to Nolt URL without SSO if token cannot be generated

* Add profile image (gravatar) to Nolt SSO link

* Improve navbar dropdown

* Add 'contact support' link to nav dropdown

* Add CSS rule to prevent horizontal jumps

* Dark mode styling

* Close dropdown when link is clicked

* Clarify links in dropdown

* Clarify CSS comment

* Use Alpine.data() over window

* Rename suggestions_dropdown -> combo-box

* Mix format

* Make logout link look good on dark mode

* Use proxy for gravatar

* Do not use Gravatar proxy in self-hosted

* Changelog

* Add Github Repo link to nav dropdown

* Make dialyzer happy

* Add proxy for Gravatar

* Update assets/css/app.css

Co-authored-by: hq1 <hq@mtod.org>

* Update lib/plausible_web/controllers/avatar_controller.ex

Co-authored-by: hq1 <hq@mtod.org>

* Fix alpine <> Liveview integration

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 99efb93082
No longer require domain to seek Plugins API Tokens (#3409)
* No longer require domain to seek Plugins API Tokens

* Accept raw token only
3 years ago
Adrian Gruntkowski 70c001099d
Improve and simplify email verification codes generation (#3407)
* Refactor email verification codes generation to avoid predictability

* Improve `Site.Memberships.any?` slightly

* Update tests

* Fix seeds

* Use `expired?` predicate for checking verification code validity in tests

* Store verification code as string in database to avoid unnecessary int casting
3 years ago
Adrian Gruntkowski 87f7729cf9
Add `email_activation_codes` table (#3426)
* Add email_activation_codes table

* Change code column in migration to string
3 years ago
Marko Saric d338980dc5
new copy for the cancellation email (#3422)
* Update cancellation_email.html.eex

* changing the subject too

* Fix broken test

---------

Co-authored-by: Vinicius Brasil <vini@hey.com>
3 years ago
dependabot[bot] d6b5b2939b
Bump @playwright/test from 1.37.1 to 1.39.0 in /tracker (#3415)
Bumps [@playwright/test](https://github.com/microsoft/playwright) from 1.37.1 to 1.39.0.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.37.1...v1.39.0)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Adrian Gruntkowski f0c749ad70
Implement direct site ownership transfer without invite via CRM (#3416) 3 years ago
RobertJoonas 313bfa0558
remove wrong FF condition (#3417) 3 years ago
Vini Brasil c0fe2a3996
Implement Stats API feature gate (#3411)
* Include ApiKey functions in Auth context

* Make feature notice work without %Site{}

Previously the extra feature notice required a %Site{} in order to check
the owner plan. However, not every feature is scoped by site, for
example the Stats API. For features like this, a %User{} is required,
and not a %Site{}.

This commit replaces the `:site` param with `:billable_user`, which is
common to both site and user-scoped features.

* Add stats_api to the list of extra features

* Limit API Key creation based on user plan
3 years ago
Adrian Gruntkowski 192aefc493
Fix email update flow for selfhosted setup with verification disabled (#3408) 3 years ago
Vini Brasil 303b3509f7
Feature gates (#3401)
This pull request implements limits to funnels, revenue goals and custom props based on the site owner plan. It extends the current "premium feature" notice to account for the new plans, trials and the on-going private preview. Stats API is not in the context of this pull request, but will be implemented likewise.
3 years ago
Marko Saric 90cb7cdef8
Some changes to the onboarding email copy (#3392)
* Update site_setup_success_email.html.eex

* Update check_stats_email.html.eex

* Update trial_one_week_reminder.html.eex

---------

Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
3 years ago
dependabot[bot] 6c018f884a
Bump eslint from 8.48.0 to 8.51.0 in /tracker (#3402)
Bumps [eslint](https://github.com/eslint/eslint) from 8.48.0 to 8.51.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.48.0...v8.51.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Adrian Gruntkowski 439c5014d4
Trigger email reverification on change (#3388)
* Implement PoC for email reverification flow on update

* Improve user settings form and email change validation

* Expose `previous_email` in Kaffy CRM

* Improve plugs setup and remove dead action from AuthController

* Fix seeds

* Extract predicate query functions from AuthController

* Add tests

* Update CHANGELOG.md

* Rename `has_any_sites?` to `Memberships.any?` and `has_any_memberships?`

* Improve flash message on cancelling email change

* Cover one more test case for email update
3 years ago
Adrian Gruntkowski 33b5e69c64
Add `previous_email` column to `users` (#3406) 3 years ago
RobertJoonas 3d2f356ba7
Refactor enterprise plan upgrade and change-plan actions (#3397)
* rename enterprise?/1 function

* change link text to Upgrade when subscription deleted

* extract paddle_button and paddle_script components

* create a new upgrade-to-enterprise-plan page

* extract upgrade_link component

* rename function

* link to enterprise plan upgrade page from settings

...if the user has an enterprise plan configured

* fetch enterprise plan price on the new page

* add change_enterprise_plan functionality on the new page

* render existing change_enterprise_plan_contact_us.html

...when subscribed to latest configured enterprise plan

* rename vars and extract resumable? fn

* remove dead billing route

* small test refactor: extract convenience fn

* add tests for...

...restricting paused and past_due subscription access to the new
enterprise plan page.

1. redirect to /settings from the controller action
2. hiding the change-plan link from the user settings

* implement redirect to /settings

* hide the enterprise upgrade/change-plan link

* add tests for a deleted enterprise subscription

* plug in the new controller action and delete dead code

* optimize for dark mode

* fix compile warning

* credo fix

* display N/A instead of crash when price nil

* change subscription.status type to Ecto.Enum

Also, create a new `Subscription.Status` module that exposes macros to
return the used atom values (prevent typos at compiletime).

* fix bug (@conn not available anymore)

* use Routes.billing_path where applicable

* add a status() type

* silence credo

* refactor suggestion from review

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Remove the __using__ macro from Subscription.Status

... instead be explicit about requires and aliases and also order
the use, import, require, and alias clauses according to
https://github.com/christopheradams/elixir_style_guide#module-attribute-ordering

* drop the virtual Enteprise 'price_per_interval' field

* apply review suggestion to make the code more DRY

* use dot syntax to fetch current user in new controller actions

* fix formatting

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Adrian Gruntkowski dec193e904
Make FixBrokenGoals migration idempotent (#3405)
* Make FixBrokenGoals migration idempotent

The migration in question was renamed in order to fix order of executing migrations when run
from the ground up (via https://github.com/plausible/analytics/pull/3378).

As a side effect, it's executed again on databases that had it applied earlier, with
a different timestamp prefix.

As this migration is safe to run multiple times, it was modified to make forward
migration work gracefully when constraint already exists.

* Add `pending-migrations.sh` release script
3 years ago
Adrian Gruntkowski 21297b666f
Add constraint enforcing at most one owner membership per site (#3403) 3 years ago
Adrian Gruntkowski 842bbb7995
Fix invalid subscription preload in SiteLocker email submission routine (#3400) 3 years ago
hq1 0007c0c108
Plugins API: 2nd pass with Goals resource + SharedLinks schema changes (#3396)
* Remove "Context" namespace level

* Change Goal string representation

* Alias Schemas in Plugin API Test Case template

* Update schema & tests for SharedLink resource

* Update Goals interface

- make it possible to create revenue goals
- extract "for site" query to a standalone function

* Fixup typespecs

* Alias Errors module in OpenAPI controllers

* Add missing goals test

* Implement Goals Plugins API resource

* Add extra test to confirm changeset error propagation

* Mute credo

* Fix typos

* Handle changeset traversal in `Errors`

* Use upserts in `Goals.find_or_create`

* Extract touch_site! to Site.Cache, address credo, improve code docs

* Apply formatting

* Remove unused inner join

* Update test/plausible_web/plugins/api/controllers/goals_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update test/plausible_web/plugins/api/controllers/goals_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update test/plausible_web/plugins/api/controllers/goals_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update test/plausible_web/plugins/api/controllers/goals_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update test/plausible_web/plugins/api/controllers/goals_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update error message on revenue goal currency clash

* Remove unused code

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Adrian Gruntkowski d608fec903
Improve domain cleanup on site creation (#3393) 3 years ago
Adrian Gruntkowski 296637dc18
Ensure that `User.password_strength/1` always returns a value (#3389) 3 years ago
RobertJoonas 8bc86d165f
Use Phoenix LiveView for the upgrade page (#3382)
* add a new upgrade page liveview behind a FF

* Create plans_v4.json file

* Add the upgrade page UI template and some basic functionalities

* different content based on subscription plan existing or not
* pageview slider
* monthly/yearly switch

* fix tests

* split into 2 separate functions

* rename variables

* implement volume slider + read default interval/volume from plan

* organize choose-plan.ex better

* remove unused vars from tests

* make monthly_cost and yearly_cost nil by default

The actual prices for all plans are stored in Paddle. We don't need to
keep the duplicates in the JSON files.

* add fetch_prices/1 to PaddleApi

* make v4 business ID's differ from growth ones

* render actual price information from plans

...and make the prices in both growth and business plan boxes change
dynamically when the pageview slider or interval is changed.

* highlight current subscription plan box

* add test describe block for business tier subscription

* connect to live socket only on the specific LV page using focus.html

* only wrap the input slider inside the form

* little readability improvement

* add v4 team_member_limits (after rebase with master)

* extract monthly_quota_box function in user_settings

When the business_tier FF is enabled, this section is different and
links to the new upgrade page.

* document subscription statuses

* change _notice.html.eex to .heex

* extract subscription status notice components

* add failed payment notices to upgrade page

* create class_of_element/2 convenience function for testing

* add cancel_subscription mix task

* implement checkout buttons

* mix format

* get all available plans with prices through plans.ex

* use more suitable function for fetching usage

* avoid double db lookups on mount

* rename variable

* separate functions for getting plan by product_id vs subscription

* separate subscription status docs into context module

* consider cancelled subscriptions

* default volume by usage if no subscription plan

* add enterprise-level volume option to slider

* optimize for darkmode

* UI improvements

* display 2 months free notice for yearly billing
* VAT excluded notice
* note about having a business subscription in user settings
* make the page pop and fit plans on screen on first render

* optimize for mobile and remove background containers

* change default price tag to simply 'N/A'

* fix tests

* Change Paddle.js integration to use JavaScript directly
* rename many variables

* allow users on v1 and v2 plan subscribe to 20M and 50M tiers

* add a test for two months free label

* make it work with a free_10k subscription

* small test improvement and formatting

* change other upgrade link in user settings if FF enabled

* dialyzer

* fix typo

* add test for free_10k user

* silence credo

* mix format

* credo - add moduledoc

* credo - another moduledoc

* handle calls to sentry on the api level

* refactor getting regular subscription plan for LiveView

* post review code style tweaks

* remove unused aliases

* credo - add @moduledoc false to Subscriptions

* crash in cancel_subscription task when Repo update fails

* readability improvements (review suggestions)

* add comment about 'external_resource' module attr

---------

Co-authored-by: Vinicius Brasil <vini@hey.com>
3 years ago
Adrian Gruntkowski 16ce0f1ea8
Handle missing or expired token in password reset action and LV gracefully (#3387)
This change addresses two problems:

* controller action crashing missing "token" param - it's handled gracefully
  now and will not pollute Sentry anymore with http://sentry.plausible.io/organizations/sentry/issues/4319
* LiveView receives email extracted from token on initial page load instead
  of reverifying token on every re-mount (which can happen when somebody
  leaves form open for an extended period of time; rare but happens and
  needlessly pollutes Sentry as well)
3 years ago
Adrian Gruntkowski e67850c11d
Fix and refactor invitation logic (#3376)
* Make membership creation and role updates more explicit in terms of changesets

* Extract invitation accept flow logic and refactor it slightly

* Improve acceptation logic

* Update moduledoc

* Improve SiteLocker API and add typespecs

* Stop naming function not returning a boolean like a predicate

* Refactor rest of invitation actions and safeguard against rogue requests

* Update code docs slightly

* Extend `Billing.check_needs_update/1` tests

* Parametrize selfhost flag and toggle SiteLocker logic on it

* Add tests for newly extracted services

* Add test case and a fix for locking site on grace period ended

* Make invitation controller tests async as there's no more env patching

* Add test cases for self-invites and fix one bug

* Add and refactor tests for rejecting and removing invitations

* Prevent issuing ownership transfer to existing owner

* Improve name of the test

* Improve `Billing.check_needs_to_upgrade/1` return value

* Improve `Billing.SiteLocker.update_sites_for/1` and its tests

* Fix typos

Co-authored-by: hq1 <hq@mtod.org>

* Make invitation removal and rejection resilient to races

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 082ec91c63
OpenAPI: first pass on Plugins API - Shared Links (#3378)
* Update depenedencies: OpenAPISpex + cursor based pagination

* Update formatter config

* Add internal server error implementation

* Test errors

* Implement pagination interface

* Implement Plugins API module macros

* Implement Public API base URI

(to be used with path helpers once called from within
forwarded router's scope)

* Implement OpenAPI specs + schemas

* Implement Shared Links context module

* Add pagination and error views

* Add Shared Link view

* Implement Shared Link controller

* Expose SharedLink.t() spec

* Implement separate router for the Plugins API

* Update moduledocs

* Always wrap resource objects with `data`

* Update moduledoc

* Use https://github.com/open-api-spex/open_api_spex/pull/425

due to https://github.com/open-api-spex/open_api_spex/issues/92

* Rely on BASE_URL for swagger-ui server definition

* Fixup goals migration

* Migrate broken goals before deleting dupes

* Remove bypassing test rate limiting for which there's none anyway

* Move the context module under `Plausible.` namespace

* Bring back conn assignment to PluginsAPICase template

* Update test/plausible_web/plugins/api/controllers/shared_links_test.exs

Co-authored-by: Uku Taht <Uku.taht@gmail.com>

* Update renamed aliases

* Seed static token for development purposes

* Delegate Plugins API 500s to a familiar shape

* Simplify with statement

---------

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
3 years ago
Cenk Kücük 5339db7152
Move back to GitHub managed actions runner (#3383)
This fixes CI for PRs coming from external repos/contributors
3 years ago
Adrian Gruntkowski 777b4b3741
Improve forms (#3380)
* Make client-facing user changesets accept only editable fields

* Add controller test
3 years ago
Uku Taht aee6f105c2
Fix dogfooding (#3377)
* Track funnels and custom props settings

* Send dogfood script events to ingest.plausible.io

* Mix format
3 years ago
Marko Saric b7b7cbc0a3
Fixing the link (#3379) 3 years ago
Marko Saric fe492ce7fe
Further copy changes 3 years ago
Marko Saric 59ebcc2d35
Update to keep the copy consistent with the main site 3 years ago
hq1 755345f4ba
Implement Plugins API authorization (#3373)
* Implement Plugins API Token schema

* Work with domain change grace period

* Do not cast internal data, extend schema with hints

* Implement Plugins API authorization

* Test no authorization header passed

* Preload authorized site

* Fixup typespecs
3 years ago
hq1 311d66b341
Implement Plugins API Token schema (#3370)
* Implement Plugins API Token schema

* Work with domain change grace period

* Do not cast internal data, extend schema with hints
3 years ago
Adrian Gruntkowski dbdbfb1144
Redirect to People Settings after removing pending invitation (#3371) 3 years ago
Adrian Gruntkowski 51c1138d0d
Implement better user password validation (#3344)
* Add zxcvbn dependency

* Change password length range requirement from 6-64 to 12-128

* Reimplement register form in LV

* Implement server-side check for password strength

* Add rudimentary strength meter

* Make password input with strength a separate component and improve it

* Fix existing tests to provide strong enough password

* Apply formatting

* Replace existing registration form with new one

* Hide built-in label in `.input` component when none provided

* Crop password to first 32 chars for analysis by zxcvbn

* Add tests for new form components

* Integrate hCaptcha into LV

* Fix existing AuthController tests

* Add tests for Live.RegisterForm

* Hide strength meter when password input is empty

* Randomize client IP in headers during tests to avoid hitting rate limit

* Apply auxilliary formatting fixes to AuthController

* Integrate registration from invitation into LV registration logic

* Fix existing password set and reset forms

* Make `password_length_hint` component more customizable

* Optimize `Auth.User.set_password/2`

* Remove unnecessary attribute from registration form

* Move password set and reset forms to LV

* Add tests for SetPasswordForm LV component

* Add tests for password checks in `Auth.User`

* Document code a bit

* Implement simpler approach to hCaptcha integration

* Update CHANGELOG.md

* Improve consistency of color scheme

* Introduce debounce across all text inputs in registration and password forms

* Fix email input background in register form

* Ensure only single error is rendered for empty password confirmation case

* Remove `/password` form entirely in favor of preferred password reset

* Remove unnecessary `router` option from `live_render` calls

* Make expensive assigns in LV with `assign_new` (h/t @aerosol)

* Accept passwords longer than 32 bytes uniformly as very strong

* Avoid displaying blank error side by side with weak password error

* Make register actions handle errors gracefully

* Render only a single piece of feedback to reduce noise

* Make register and password reset forms pw manager friendly (h/t @cnkk)

* Move registration forms to live routes

* Delete no longer used deadviews

* Adjust registration form in accordance to changes in #3290

* Reintroduce dogfood page path for invitation form from #3290

* Use alternative approach to submitting plausible metrics from LV form

* Rename metrics events and extend tests to account for them
3 years ago
Cenk Kücük b1ade191eb
remove healthcheck for custom.plausible.io (#3364) 3 years ago
Marko Saric 2c9c1590e4
Adding a note about WordPress plugin (#3358)
* Adding a note about WP plugin

* Make it pretty

* Add component for link in new tab

* Adjust link styling for dark mode

* Update Subscription.free (for testing purposes)

* More natural interface for syled_link

* Use <.styled_link> helper in change_domain.html.heex

* Mix format

* Fix warning

* Fix credo warning

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
3 years ago
ruslandoga c3910ae201
log mailer errors (#3336)
* log mailer errors

* update sentry to fix logger metadata bug

* update changelog
3 years ago
Uku Taht be1a679933
Dogfooding improvements (#3290)
* Simplify tracking script template

* Track dashboard pages with anonymized URLs

* Track embedded dashboards as domain embed. + base_domain

* Add dogfood page ids for dashboard settings

* Add tracking to invitation form

* Start tracking register-via-invitation flow with custom event

* Remove leftover code

* Track logged-in status

* Add verified routes

* Inline dogfood routes

* Path -> Url

* Mix format

* Remove verified routes

* Inline dogfood_path
3 years ago
hq1 8c605865b6
Enforce goals unique (#3343)
* Enforce goals unique

* Remove unnecessary alias

* Skip tests that can no longer run anymore

To run, make sure the migration from
priv/repo/migrations/20230914071245_goals_unique.exs
is rolled back.

* Use separate transactions for the migration

* Update priv/repo/migrations/20230914071245_goals_unique.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
hq1 542385feab
Data Migration: rewrite funnels that contain duplicate goals (#3361)
* Add `RewriteFunnelDupes` data fix

To rewrite funnels referencing goals whose names
are the same. This enables us to enforce all goals
within the site unique later on.

* Credo

* Update priv/data_migrations/FunnelDupeGoals/sql/list-funnels-with-dupe-goal-ids.sql.eex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Revert unrelated changes

* Remove dead code

* Update lib/plausible/data_migration/rewrite_funnel_dupes.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update lib/plausible/data_migration/rewrite_funnel_dupes.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Cenk Kücük 1a9dd0de90
Update Workflow Concurrency (#3359)
Ensures that only one workflow is running per branch at a time.

If you are working on a branch and push several commits in succession, any workflows in progress will be cancelled and only the last one will run.
3 years ago
Marko Saric 7bf16639b8
Open docs links in new window (#3360)
* Some fixes

* Open link in new window

* open in new window

* Open in new window
3 years ago
hq1 a5bac43981
[migration] Data fix: rewrite goals for which `event_name` and `page_path` both exist (#3357)
* Rewrite goals for which both event_name and page_path exist.

This might've happened due to the old form only hiding form
fields from the viewport, allowing to submit both values in
certain cases when switching tabs. The tabs behaviour has
been changed as of #3293 but no proper constraints existed.

* Add new check constraint to the goals schema

* Use NOT VALID option for adding the CHECK constraint

* Skip wrapping migration in a single transaction
3 years ago
hq1 8c077513ac
Fix Add Property button font weight (#3356) 3 years ago
dependabot[bot] 9601d81501
Bump docker/setup-buildx-action from 2 to 3 (#3354)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2 to 3.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 3ef93d4c41
Bump docker/metadata-action from 4 to 5 (#3353)
Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 4 to 5.
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Upgrade guide](https://github.com/docker/metadata-action/blob/master/UPGRADE.md)
- [Commits](https://github.com/docker/metadata-action/compare/v4...v5)

---
updated-dependencies:
- dependency-name: docker/metadata-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] a901333c2c
Bump docker/build-push-action from 4 to 5 (#3352)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 4 to 5.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v4...v5)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] c0bd78724d
Bump docker/login-action from 2 to 3 (#3355)
Bumps [docker/login-action](https://github.com/docker/login-action) from 2 to 3.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 3464d2c890
Bump docker/setup-qemu-action from 2 to 3 (#3351)
Bumps [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) from 2 to 3.
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] ce4c9fced5
Bump actions/checkout from 3 to 4 (#3338)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
hq1 a9bfaed70f
Get rid of the funnels flag completely (#3341) 3 years ago
hq1 43be271836
Funnel Settings UI tweaks (to match Custom Props/Goals) (#3323)
* Add hint to creatable ComboBoxes without suggestions available

* Load external resources once in funnel settings

* Load external resources once in goal settings

* Make Custom Props Settings UI match Goal Settings

* Remove unnecessary goals query

This should be done only once in the live view

* Remove funnels feature flag

* fixup

* Make the modal scrollable

* By default, focus first suggestion for creatables

* Update StaticSearch

So it's capable of casting custom data structures
into weighted items. Missing tests added.

* Add Search + modal to funnel settings

* Add sample props to seeds

* Load all suggestions asynchronously, unless `Mix.env == :test`

* ComboBox: Fix inconsistent suggestions

We require "Create ..." element to be only focused
when there are no suggestions available.
This causes some issues, depending on the state,
the least focusable index might be either 0 ("Create...")
or 1. This patch addresses all the quirks with focus.

* Fix ComboBox max results message

So that AlpineJS doesn't think it's a focusable
option.

* Keep the state up to date when changing props

* Add hint to creatable ComboBoxes without suggestions available

* Load external resources once in funnel settings

* Load external resources once in goal settings

* Make Custom Props Settings UI match Goal Settings

* Remove unnecessary goals query

This should be done only once in the live view

* Remove funnels feature flag

* fixup

* Make the modal scrollable

* By default, focus first suggestion for creatables

* Add sample props to seeds

* Load all suggestions asynchronously, unless `Mix.env == :test`

* ComboBox: Fix inconsistent suggestions

We require "Create ..." element to be only focused
when there are no suggestions available.
This causes some issues, depending on the state,
the least focusable index might be either 0 ("Create...")
or 1. This patch addresses all the quirks with focus.

* Fix ComboBox max results message

So that AlpineJS doesn't think it's a focusable
option.

* Keep the state up to date when changing props

* Fixup site_id

* Fix typo

* fixup
3 years ago
hq1 0822bc61df
Props Settings UI to match Goals Settings (#3322)
* Add hint to creatable ComboBoxes without suggestions available

* Load external resources once in funnel settings

* Load external resources once in goal settings

* Make Custom Props Settings UI match Goal Settings

* Remove unnecessary goals query

This should be done only once in the live view

* Remove funnels feature flag

* fixup

* Make the modal scrollable

* By default, focus first suggestion for creatables

* Add sample props to seeds

* Load all suggestions asynchronously, unless `Mix.env == :test`

* ComboBox: Fix inconsistent suggestions

We require "Create ..." element to be only focused
when there are no suggestions available.
This causes some issues, depending on the state,
the least focusable index might be either 0 ("Create...")
or 1. This patch addresses all the quirks with focus.

* Fix ComboBox max results message

So that AlpineJS doesn't think it's a focusable
option.

* Keep the state up to date when changing props

* Update seeds with sensible prop names

* Make escape work for closing combobox suggestions

Co-authored-by: Uku Taht <Uku.taht@gmail.com>

* Revert "Make escape work for closing combobox suggestions"

This reverts commit 306866d2a1.

@ukutaht unfortunately this makes it impossible to select
an suggestion.

* Revert "Revert "Make escape work for closing combobox suggestions""

This reverts commit 4844857812.

* Make ESC great again

* Improve readability

---------

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
3 years ago
Uku Taht 7cb2c6bfa3
Allow admins to initiate ownership transfer from the CRM (#3340)
* Allow admins to initiate ownership transfer from the CRM

* Add stronger assertion for bulk invite action

* Fix compile warning

* Move bulk transfer logic to Sites module

* Replaces unused variables with _

* Add typespec for `bulk_transfer_ownership`

* Extract from keywordlist options instead of matching

* Fix and extend bulk transfer tests

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
3 years ago
Adrian Gruntkowski 27a11fc5b7
Filter out empty entries when listing stats for UTM props (#3339)
* Filter out empty entries when listing stats for UTM props

* Update test fixtures removing noref entries in UTM CSV stat exports

* Update external API tests to account for lack of noref records for UTM stats

* Filter out entries with empty UTM props from imported GA stats

* Remove unreachable GA utm_source dim clause in imported stats logic
3 years ago
Vini Brasil 9b029c1558
Improve ownership transfers (#3326)
* Move inline functions to module

* Extend invite/4 for ownership transfers

* Verify inviter has sufficient permissions

* Ensure ownership transfers don't count as team member

This commit changes the team member usage query to exclude ownership
transfer invitations. Previously, when an ownership transfer was
pending, the team member usage was incremented.

* Draw attention to payment notice when transferring ownership

* Remove duplicate mail sending from membership_controller

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
3 years ago
Cenk Kücük 45ed56b4d5
Add monitoring for ingest.plausible.io (#3334)
* Add monitoring for ingest.plausible.io

* fix deprecation warning

* fmt
3 years ago
Vini Brasil e30ba8b27f
Silence undefined plan Sentry log for trials (#3332) 3 years ago
Uku Taht 275335071b
Update Tailwind to latest v3.3.3 (#3320)
* Update Tailwind to latest v3.3.3

* Upgrade autoprefixer and postcss

* Move tailwindcss plugins to devDependencies

* Remove unused tailwind rules

* Remove obsolete 'transform' rules

Ref: https://tailwindcss.com/docs/upgrade-guide#automatic-transforms-and-filters

* Use the current yellow, update gray to slate

* Move webpack to devdependencies

* Go more minimal with package.json changes

* Update autoprefixer version

* Update postcss version

* Adjust dark style colors

* Use proper node version is asdf config
3 years ago
hq1 ae0019afe5
Render keybinding hints in the range picker (#3325)
* Render keybinding hints in the range picker

There was a regression in #3321 - some keybinding
hints stopped appearing due to exact string matching.

* Switch casing
3 years ago
hq1 29d0f82182
Apply unified capitalization to buttons and titles (#3321) 3 years ago
hq1 5ff8526844
Fix custom domain showing up for the wrong reason (#3324) 3 years ago
hq1 a1be27eea6
s/superadmin/super_admin (#3318)
* s/superadmin/super_admin

* Add test
3 years ago
hq1 46f1149e3b
s/superuser/superadmin (#3317) 3 years ago
hq1 b2df714bdb
Bugfix: ComboBox navigation with creatable on top (#3316)
* Bugfix: ComboBox navigation with creatable on top

* !fixup

* !fixup

* !fixup

* !fixup
3 years ago
Vini Brasil d22c011aa3
Implement limits for team members (#3305)
* Refactor MembershipController.invite_member/2

This commit refactors the controller action used for creating new
invitations. It moves the code to Plausible.Sites.invite/4 and replaces
`ifs` and `cases` with `with`.

* Add team_member_limit to plan definition

* Create usage and limits functions for team members

* Apply team member limit when inviting new users

* Add team members to Usage & Limits section

* Change invite function to receive email address instead of %User{}

* Wrap invite function in a DB transaction

* Remove unnecessary joins from team member usage query

* Replace UNION ALL with UNION to remove duplicates
3 years ago
hq1 b3ff695797
Improve goal settings UX (#3293)
* Add Heroicons dependency

* Add name_of/1 html helper

Currently with Floki there's no way to query for
`[name=foo[some]]` selector

* Update changelog

* Make goal deletion possible with only goal id

* Remove stale goal controllers

* Improve ComboBox component

- make sure the list options are always of the parent input width
- allow passing a suggestion function instead of a module

* Stale fixup

* Update routes

* Use the new goals route in funnel settings

* Use a function in the funnel combo

* Use function in the props combo

* Remove old goals form

* Implement new goal settings

* Update moduledoc

* Fix revenue switch in dark mode

* Connect live socket on goal settings page

* Fixup

* Use Heroicons.trash icon

* Tweak goals search input

* Remove unused alias

* Fix search/button alignment

* Fix backspace icon alignment

* Delegate :superadmin check to get_for_user/3

I'll do props settings separately, it's work in progress
in a branch on top of this one already. cc @ukutaht

* Rename socket assigns

* Fixup to 5c9f58e

* Fixup

* Render ComboBox suggestions asynchronously

This commit:
  - prevents redundant work by checking the socket connection
  - allows passing no options to the ComboBox component,
    so that when combined with the `async` option, the options
    are asynchronously initialized post-render
  - allows updating the suggestions asynchronously with the
    `async` option set to `true` - helpful in case of DB
    queries used for suggestions

* Update tests

* Throttle comboboxes

* Update tests

* Dim the search input

* Use debounce=200 in ComboBox component

* Move creatable option to the top

* Ensure there's always a leading slash for goals

* Test pageview goals with leading / missing

* Make the modal scrollable on small viewports
3 years ago
dependabot[bot] f740cc899f
Bump eslint-plugin-playwright from 0.15.3 to 0.16.0 in /tracker (#3312)
Bumps [eslint-plugin-playwright](https://github.com/playwright-community/eslint-plugin-playwright) from 0.15.3 to 0.16.0.
- [Release notes](https://github.com/playwright-community/eslint-plugin-playwright/releases)
- [Changelog](https://github.com/playwright-community/eslint-plugin-playwright/blob/main/CHANGELOG.md)
- [Commits](https://github.com/playwright-community/eslint-plugin-playwright/compare/v0.15.3...v0.16.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-playwright
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Marko Saric b0d99c5935
Update weekly_report.mjml.eex (#3313) 3 years ago
dependabot[bot] 691f4d36a5
Bump eslint from 8.46.0 to 8.48.0 in /tracker (#3302)
Bumps [eslint](https://github.com/eslint/eslint) from 8.46.0 to 8.48.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.46.0...v8.48.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
RobertJoonas 5ba21c04fe
Remove Props FF (#3242)
* stop returning prop_names from /conversions

* remove the old prop-breakdown API route and CSV export

* remove allowed_event_props from CRM

* remove DeprecatedConversions

* remove props FF

* update changelog
3 years ago
Vini Brasil 43a926bdb3
Create new sandbox plans based on V4 (#3308) 3 years ago
Cenk Kücük 4ae0c68397
verify tls connection to clickhouse and postgres (#3254) 3 years ago
hq1 93a7cd5d49
Connect to live socket only on specific pages (#3292)
* Connect to live socket only on specific pages

And disable the "server blip" message on non-dev
environments. It's non actionable to our customers.

* Simplify meta tags rendering
3 years ago
dependabot[bot] dbc3b91a4b
Bump @playwright/test from 1.37.0 to 1.37.1 in /tracker (#3275)
Bumps [@playwright/test](https://github.com/Microsoft/playwright) from 1.37.0 to 1.37.1.
- [Release notes](https://github.com/Microsoft/playwright/releases)
- [Commits](https://github.com/Microsoft/playwright/compare/v1.37.0...v1.37.1)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vini Brasil 5d9d05c1f6
Usage & Limits section (#3291)
* Update user_settings template to HEEX

* Move site_limit function to Billing.Quota

* Create Billing.Quota.site_usage function

* Move monthly_pageview_limit function to Billing.Quota

* Create Billing.Quota.monthly_pageview_usage function

* Add "Usage & Limits" section to user settings page

* Apply suggestions from code review
3 years ago
Uku Taht 8c870f7c6b Increase sampling test delta to reduce flakyness 3 years ago
Uku Taht ab4eb75109
Inflate sampled results in Stats.Funnel.funnel/3 (#3270)
* Inflate sampled results in Stats.Funnel.funnel/3

* Add test for sampling

* Update test/plausible/funnels_test.exs

Co-authored-by: hq1 <hq@mtod.org>

* Ignore unused binding

* Use bang version of hash function

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 df19fad046
Set SECURE_COOKIE=false for local dev (#3289)
Safari won't allow to set it even for localhost
3 years ago
Uku Taht da3d4366f6
Add login link to 404 page (#3288)
* Add login link to 404 page

* Fix 404 test

* Fix another test
3 years ago
hq1 b9fb6fd1a7
Revert "Revert "Reconfigure session cookie (#3274)" (#3284)" (#3285)
This reverts commit 65f7b4c5cc.
3 years ago
Uku Taht cc60f1c942
Add new priority email template (#3283)
* Add new priority email template?

* Allow priority email to be sent with not layout

* Use priority email template for priority transactional emails

* Test for postmark message stream
3 years ago
ruslandoga 98d6bf3a4f
fix changelog (#3280)
* fix changelog

* use correct issue link
3 years ago
hq1 65f7b4c5cc
Revert "Reconfigure session cookie (#3274)" (#3284)
This reverts commit 63fabcbb5f.
3 years ago
Vini Brasil dad787cb4b
Rename allowance to monthly_pageview_limit (#3273)
* Remove unused site_limit_exempt list

* Rename allowance to monthly_pageview_limit
3 years ago
Vini Brasil 48b02c1396
Avoid suggesting plan for trials switching to enterprise plans (#3282)
This commit fixes a bug where the SendTrialNotifications job tried to
suggest a plan for users switching to enterprise plans, resulting in the
exception below:

```
UndefinedFunctionError: function :enterprise.volume/0 is undefined (module :enterprise is not available)
  Module "enterprise", in :enterprise.volume/0
  File "lib/plausible_web/templates/email/trial_upgrade_email.html.eex", line 5, in PlausibleWeb.EmailView."trial_upgrade_email.html"/1
  File "lib/phoenix_view.ex", line 381, in Phoenix.View.render_within/3
  File "lib/phoenix_view.ex", line 557, in Phoenix.View.render_to_iodata/3
  File "lib/phoenix_view.ex", line 564, in Phoenix.View.render_to_string/3
  File "lib/bamboo_phoenix.ex", line 291, in Bamboo.Phoenix.render_text_or_html_email/1
  File "lib/workers/send_trial_notifications.ex", line 67, in Plausible.Workers.SendTrialNotifications.send_today_reminder/1
  File "lib/workers/send_trial_notifications.ex", line 36, in anonymous fn/2 in Plausible.Workers.SendTrialNotifications.perform/1
```
3 years ago
hq1 63fabcbb5f
Reconfigure session cookie (#3274)
* Reconfigure session cookie

* Allow configure secure cookie (#3277)

* Update config/runtime.exs

Co-authored-by: ruslandoga <doga.ruslan@gmail.com>

* fix runtime conf

* Revert "fix runtime conf"

This reverts commit ff37e479e4.

* Revert "Update config/runtime.exs"

This reverts commit 5d9b310b02.

* Revert "Allow configure secure cookie (#3277)"

This reverts commit 7401a2ad3f.

* Read SECURE_COOKIE with defaults per cloud/selfhost

* Include environment in cookie name

* Remove redundant option

* Format

* s/Map.replace/Map.put

* up

* One more try

* Prevent browser refreshes on socket connection error

We'll keep the log and don't make the page look dumb
even if there's some misconfiguration going on.

---------

Co-authored-by: ruslandoga <doga.ruslan@gmail.com>
3 years ago
dependabot[bot] d6d4d3dd75
Bump @playwright/test from 1.36.2 to 1.37.0 in /tracker (#3255)
Bumps [@playwright/test](https://github.com/Microsoft/playwright) from 1.36.2 to 1.37.0.
- [Release notes](https://github.com/Microsoft/playwright/releases)
- [Commits](https://github.com/Microsoft/playwright/compare/v1.36.2...v1.37.0)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vini Brasil 34f1ddfc8c
Refactor Plausible.Billing.Plans module (#3268)
This pull request introduces a series of improvements to Plausible.Billing.Plans, including:

* Tag the JSON file with the plan version
* Rename the JSON field limit to monthly_pageview_limit
* Move site_limit function to Billing.Plans
* Refactor subscription_interval, allowance and site_limit functions
* Remove unused AnalyzePlans task
3 years ago
Uku Taht 3f9ca35d58
Actually ignore unkown device type (#3267) 3 years ago
Uku Taht a6bf951852
Ignore unkown device type (#3266) 3 years ago
RobertJoonas 9e9555f719
Improvements to the Properties feature (#3261)
* automatic CONVERSIONS -> PROPS navigation

In the Behaviours section, we'll navigate from Goal Conversions > Properties,
when a goal filter is applied by clicking on an entry in the Goal Conversions
list. This navigation does not happen for pageview goals or special goals (e.g.
'Outbound Link: Click', 'File Download', etc.)

The Behaviours component will remember that the navigation happened in order
to return the user to the previous view when the goal filter is removed.

* ability to store prop_keys per goal in localStorage

* pass the onclick handler to the Details view too

This makes sure that when a  listItem is clicked in the Details view,
the same behaviour (such as changing the Locations tab from 'Countries'
to 'Regions') is called.

* bugfix - always escape pipes when applying goal/prop filters

* disable propkey selection when prop filter applied

* make the propkey selector take up all the width
3 years ago
hq1 e59cda5d93
Fix filter suggestions (#3265)
* Fix filter suggestions

* Mute credo for now
3 years ago
hq1 20d31a8d0d
Bump ua_inspector/matomo db (#3263)
* Bump ua_inspector/matomo db

* Update changelog

* Bump matomo to master

* Pin matomo sha
3 years ago
hq1 49a29d86e8
Make stats controller tests synchronous (#3264) 3 years ago
hq1 bc650c213a
Fix breakdown pagination when filtering by goals (#3251)
* Add a failing test

* Bugfix: breakdown by goal pagination

* Update changelog

* Apply comment about comment
3 years ago
Vini Brasil 059df171bc
Refactor Plausible.Billing.Plans module (#3249)
This commit introduces a series of improvements on the Plans module including function renaming, documentation and readability. This is the groundwork for billing plans.

There should be no actual changes with this commit, therefore no changes in tests either.
3 years ago
Cenk Kücük ec747ad401
add dockerhub creds optional 3 years ago
hq1 ae3a003d31
Fix filter labels when filtering on clicks from ModalTable (#3247) 3 years ago
hq1 e467324c5a
Disallow small intervals on large ranges (#3245)
* Update interval dropdown based on custom range selection

* Add `monthsBetweenDates` function

* Reassign interval for custom "period" based on local storage

* Generate intervals by period based on stats_start_date

* Account for "custom" and "all" period intervals dynamically
3 years ago
RobertJoonas eeca63ff4c
Some fixes to the Custom Props feature (#3241)
* rename Properties to Custom Properties in Site Settings

* fix docs link for custom props

* add back the external links for special goal URLs and 404 paths

* grandfathering note
3 years ago
Ёkaterina Krivich 9e26ea2cdf
Add `referrers.csv` to CSV export (#2624) (#3002)
* Add referrers to csv (#2624)

* Change CHANGELOG

* add missing files

* fix tests

* revert package files changes

* fix typo

* format

* rename
3 years ago
Vini Brasil 8c3b541971
Allow internal prop keys in queries (#3231)
* Remove `Plausible.Sites.set_allowed_event_props/2` function

This commit removes the `Plausible.Sites.set_allowed_event_props/2`
function in favor of `Plausible.Props.allow/2`.

* Allow internal prop keys in queries

This commit allows internal prop keys by default in queries. I decided
not to include internal keys in the database, because they might change
and we'd need to migrate it again.

* remove redundant 'props.' from behaviours/index.js

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
Vini Brasil 1fedaf18c3
Remove allowed props list from dashboard data attribute (#3230)
This commit removes the allowed props list from the data attribute
passed to React. The list was used for checking whether props configured
or not. This commit adds a new `hasProps` attribute, and removes the
list.
3 years ago
RobertJoonas 373b8e8201
UI tweaks to Properties and Conversions (#3226)
* fix conversions fetchData limit to the right number

* make Goal Conversions metric column width match Properties

* add more top-margin to Details links in ListReport

* add special handling for url prop in Conversions

* change 'Details' button to 'More' when no additional details

* fix CI

* breakdown by 'path' prop instead for 404 pages

* change the 'MORE' button back to 'DETAILS'

But keep the option of not showing the button when there are less
than 9 list entries.

* capture special props in an object instead (review suggestion)

* Add cloaked link to special goals list

---------

Co-authored-by: Vinicius Brasil <vini@hey.com>
3 years ago
Vini Brasil 59a82288e1
Remove url and path prop keys from suggestions (#3228)
* Remove url prop key from suggestions

This commit prevents the `url` prop key from being suggested by the
props settings page. This prop is used internally for file downloads and
outbound link clicks, and doesn't need to be manually allowed.

* Document Props module
3 years ago
dependabot[bot] c9f683aaee
Bump handlebars from 4.7.7 to 4.7.8 in /tracker (#3218)
Bumps [handlebars](https://github.com/handlebars-lang/handlebars.js) from 4.7.7 to 4.7.8.
- [Release notes](https://github.com/handlebars-lang/handlebars.js/releases)
- [Changelog](https://github.com/handlebars-lang/handlebars.js/blob/v4.7.8/release-notes.md)
- [Commits](https://github.com/handlebars-lang/handlebars.js/compare/v4.7.7...v4.7.8)

---
updated-dependencies:
- dependency-name: handlebars
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
hq1 054d0655af
[pg migration] Delete account with multiple subscriptions (#3220)
* Migrate user deletion

So that subscriptions, google

* Make CRM deletion functional

* Preload subscriptions in an uniform manner
3 years ago
hq1 92a7e01df5
Trim long URLs, paths and other list items uniformly (#3221)
* Trim long URLs and paths uniformly

* Update
3 years ago
Vini Brasil 06305cce95
Hide creatable option when input matches suggestion (#3217)
This commit fixes a bug where the `Create "apple"` combo box option
would show up even when `apple` was in the suggestions list.
3 years ago
RobertJoonas 232bdd34a1
Conversions listreport (#3215)
* rename conversions.js to deprecated-conversions.js

* add a new Conversions component and switch by props FF

* add a Details view to the new Conversions component

* allow querying conversions with pagination

...and keep the current behaviour for DeprecatedConversions, always returning
page=1 and limit=100

* hide some columns on mobile

* prevent ListReport first column header overflow
3 years ago
RobertJoonas 8ac166b447
Add revenue metrics to Properties report (#3209)
* extract add_exit_rate function

* Change internal API metric names for /entry-pages & /exit-pages

* `unique_entrances` -> `visitors`,
* `total_entrances` -> `visits`,
* `unique_exits` -> `visitors`,
* `total_exits` -> `visits`,

This is just a consistency improvement - the `visitors` metric always means
one thing and there's no need to call it different for entry pages internally.

This commit does not change any noticable behavior. The UI labels are kept
the same and the column headers in the CSV export will also remain the same.

* Change internal API metric names for /conversions

* `unique_conversions` -> `visitors`,
* `total_conversions` -> `events`,

* return revenue metrics from /custom-prop-values (backend)

* be more explicit about which metric is plotted with Bar

* validate that ListReport input metrics actually exist in the API response

* display revenue metrics in the dashboard Properties section

* limit the number of columns shown on mobile

* add revenue metrics to Properties > Details

* review suggestions

* define hiddenOnMobile per metric instead of keeping the first 3

* rewrite if-else block

---------

Co-authored-by: Vini Brasil <vini@hey.com>
3 years ago
Wojtek Mach 26373b2726
Remove unused lib/plausible/mailer_test.exs (#3214)
Seems this file was accidentally placed in lib/ and thus never getting
compiled (cause it's .exs) nor getting mix tested (cause it's not in
test/).
3 years ago
dependabot[bot] 43103b27a9
Bump eslint from 8.45.0 to 8.46.0 in /tracker (#3211)
Bumps [eslint](https://github.com/eslint/eslint) from 8.45.0 to 8.46.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.45.0...v8.46.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
RobertJoonas 17b9e36a19
Refactor: Standardize API metrics used internally (#3208)
* extract add_exit_rate function

* Change internal API metric names for /entry-pages & /exit-pages

* `unique_entrances` -> `visitors`,
* `total_entrances` -> `visits`,
* `unique_exits` -> `visitors`,
* `total_exits` -> `visits`,

This is just a consistency improvement - the `visitors` metric always means
one thing and there's no need to call it different for entry pages internally.

This commit does not change any noticable behavior. The UI labels are kept
the same and the column headers in the CSV export will also remain the same.

* Change internal API metric names for /conversions

* `unique_conversions` -> `visitors`,
* `total_conversions` -> `events`,
3 years ago
RobertJoonas 7b39328d6c
Props details view (#3196)
* make (none) value in custom prop breakdown add +1 to pagination limit

This is needed because the (none) value is always added to the
breakdown_results **after** fetching those from ClickHouse.

* only include (none) values on the first page of results

* fix percentage metric calculation for paginated results

Instead of summing up the number of visitors from the breakdown results
to get the total, we have to make a separate query to `Stats.aggregate`.
Otherwise, the percentages for each results page will wrongly add up to 100%.

Since imported data for aggregated visitors and other properties (such as
browsers, OSs, etc) live in different tables, we have to tweak the tests to
also include the same number of visitors in the `imported_visitors` table.

* add details view for props

* changelog

* exclude imported data from total
3 years ago
Kris Buist 7c5ebab2c6
Fix the interval selection in the all time view (#3110)
Previously, the interval was always overwritten with the default value, which is determined based on the age of the site.
It should not be overwritten when the interval is explicitly passed by the user
3 years ago
Vini Brasil d49d68af8f
Create props settings page (#3191) 3 years ago
dependabot[bot] d47908046f
Bump @playwright/test from 1.35.1 to 1.36.2 in /tracker (#3195)
Bumps [@playwright/test](https://github.com/Microsoft/playwright) from 1.35.1 to 1.36.2.
- [Release notes](https://github.com/Microsoft/playwright/releases)
- [Commits](https://github.com/Microsoft/playwright/compare/v1.35.1...v1.36.2)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 66bbef36bb
Bump timex from 3.7.8 to 3.7.11 (#3198)
Bumps [timex](https://github.com/bitwalker/timex) from 3.7.8 to 3.7.11.
- [Release notes](https://github.com/bitwalker/timex/releases)
- [Changelog](https://github.com/bitwalker/timex/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bitwalker/timex/commits)

---
updated-dependencies:
- dependency-name: timex
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
hq1 2f9103fe1b
Fix unique constraint validation on weekly/monthly reports (#3200)
* Fix unique constraint validation on weekly/monthly reports

* Undo this annoying lsp formatter race condition
3 years ago
hq1 9f0e7d54f8
Fix flaky log assertion (#3199) 3 years ago
hq1 82f356f387
Add debug_replay_info context to Sentry Stats reports (#3189)
* Add debug_replay_info context to Sentry Stats reports

* Test limit
3 years ago
dependabot[bot] eb3222f840
Bump phoenix_ecto from 4.4.0 to 4.4.2 (#3194)
Bumps [phoenix_ecto](https://github.com/phoenixframework/phoenix_ecto) from 4.4.0 to 4.4.2.
- [Changelog](https://github.com/phoenixframework/phoenix_ecto/blob/main/CHANGELOG.md)
- [Commits](https://github.com/phoenixframework/phoenix_ecto/compare/v4.4.0...v4.4.2)

---
updated-dependencies:
- dependency-name: phoenix_ecto
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Cenk Kücük e26efdb7c0
remove dockerhub credentials from pull (#3188)
I previously introduced using the dockerhub credentials when pulling images from dockerhub. But this leads to problems when creating PRs from a fork.
And it is not so clear if we really need to use the dockerhub creds, as it seems that there were no problems before.
3 years ago
ruslandoga 1c17e89b65
add transport_opts to data migration (#3179)
* add transport_opts to data migration

* add changelog entry

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
dependabot[bot] d89dc466e6
Bump eslint from 8.44.0 to 8.45.0 in /tracker (#3186)
Bumps [eslint](https://github.com/eslint/eslint) from 8.44.0 to 8.45.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.44.0...v8.45.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 15daa0222f
Bump ex_doc from 0.29.4 to 0.30.3 (#3187)
Bumps [ex_doc](https://github.com/elixir-lang/ex_doc) from 0.29.4 to 0.30.3.
- [Changelog](https://github.com/elixir-lang/ex_doc/blob/main/CHANGELOG.md)
- [Commits](https://github.com/elixir-lang/ex_doc/compare/v0.29.4...v0.30.3)

---
updated-dependencies:
- dependency-name: ex_doc
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
RobertJoonas 37b33d1dbe
read FF status per user, not only global (#3185) 3 years ago
RobertJoonas 51cad4c0ec
Props into CSV export (#3167)
* move set_allowed_event_props into context module

* extract parse_csv fn

* add custom_props.csv to CSV export (under FF)

* add test for custom prop export with a prop filter

* add test for goal filtered scenario

* mix format

* fix flaky test

* extract breakdown_custom_prop_values function

* Revert "fix flaky test"

This reverts commit 256b9bb2e7. The flaky
test was already fixed in 86557b1878

* make set_allowed_event_props a bang function

* test that all files are included in the CSV export
3 years ago
dependabot[bot] 2144eb1116
Bump word-wrap from 1.2.3 to 1.2.4 in /assets (#3159)
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Vini Brasil <vini@hey.com>
3 years ago
ruslandoga f3a1a9d599
derive jason encoder for request (#3182)
* derive jason encoder for request

* test didn't test

---------

Co-authored-by: hq1 <hq@mtod.org>
3 years ago
hq1 928691158f
Fix test flakiness due to shared state in asynchronous run (#3184)
* Fix flaky test

* Prevent this in the future
3 years ago
hq1 b606fc1809
Fix long URLs in outbound breakdown (#3183)
* Truncate breakdown URLs

* Update seeds with Outbound Links

* Update changelog

Fixes https://github.com/plausible/analytics/issues/3158
3 years ago
dependabot[bot] 79274480aa
Bump ex_money from 5.12.4 to 5.15.0 (#3177)
Bumps [ex_money](https://github.com/kipcole9/money) from 5.12.4 to 5.15.0.
- [Release notes](https://github.com/kipcole9/money/releases)
- [Changelog](https://github.com/kipcole9/money/blob/master/CHANGELOG.md)
- [Commits](https://github.com/kipcole9/money/compare/v5.12.4...v5.15.0)

---
updated-dependencies:
- dependency-name: ex_money
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Vini Brasil <vini@hey.com>
3 years ago
Vini Brasil 60e418b357
Refine ComboBox.StaticSearch (#3172)
This commit makes static search more strict by rejecting matches with a score less than 0.6. Here's an example of suggestion that was matching with a 0.5 score that should not be suggested. This makes the suggestion list smaller and more reasonable.

Co-authored by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
ruslandoga a9603a44c9
inspect request in sentry context (#3180) 3 years ago
hq1 7ba0863bc2
Fix UTM Campaigns filtering regression from #3153 (#3181) 3 years ago
Vini Brasil 16846b16c8
Add creatable option to ComboBox (#3169)
* Add creatable option to ComboBox

This commit changes the ComboBox component to allow a `creatable`
option. This option enables users to create new options along with
choosing existing options.

* Test ComboBox class parameter

* Use display_value instead of input

* Change scroll block to nearest to prevent glitches
3 years ago
RobertJoonas 9ed79542f2
List props frontend (#3126)
* add the props section in behaviors

* update listReport when keyLabel (=propKey) changes

* make column min-width configurable and increase for props

* add rendering condition to limit container height

* fix filter link

* fix tests

* disable clear for single-option combobox

* improve single-option combobox styling

* fix fetchPropKeyOptions fn update on query change

* BUGFIX: searching for prop_values in property filter modal

* change the order of funnels and props section pickers

* change props section Bar color from gray to light-red

* remove disabled options from combobox dropdown (multi & single)

* display percentage metric values without a % sign

* change metric labels in goal filter view to Visitors and Events

* fix realtime update timer
3 years ago
RobertJoonas b9d122c0c7
Refactor: Use ListReport component in Sources (#3153)
* refactor SourceList to use ListReport

* refactor SourceList into a fn comp

* change referrer-drilldown API response format and remove dead code

* use ListReport in referrer-list

* fix CI

* fix flaky test

* remove IO.inspect
3 years ago
hq1 dfa5bbf4a0
Render funnel name in bold only when funnels tab active (#3163) 3 years ago
hq1 edd2757531
Expose 9000 for native clickhouse protocol (dev mode) (#3162)
* Expose 9009 for native clickhouse protocol (dev mode)

* s/9009/9000
3 years ago
hq1 bf84c043ce
Allow arbitrary suggestion modules in Live ComboBox component (#3154)
* Move ComboBox under Live.Components namespace

* Make suggestions module injectable through component API

* Reorganize tests

* Test ComboBox in isolation

* Allow external suggestion limit option

* Funnels editor: bugfix propagating suggestions over limit

* Update docs & typespecs
3 years ago
RobertJoonas 34fbc3d5bc
New private API to return custom prop values (#3111)
* copy prop_breakdown tests into a separate file

* add a new endpoint for custom props

Duplicate existing goal prop breakdown as a building base for the
new endpoint

* stick to original metric names + CR definitions

We currently use CR with two different definitions, which is inconsistent
and should be changed. This commit just documents the difference for the
time being.

* basic prop breakdown without goal filter

* increase % metric precision to one decimal place

* add some tests without goal filter

* silence credo for TODO comment

* use events metric instead of pageviews

* review feedback

* inline add_cr_a instead
3 years ago
hq1 e6996ccfda
Fix weekly/monthly report e-mails (MJML) (#3150)
* Render weekly/monthly reports with MJML

* Update changelog

* Fix APP-2NA (#3119)
3 years ago
hq1 4b9b3abafd
Respond with early 400 on malformed export request (#3151)
* Respond with early 400 on malformed export request

* credo
3 years ago
Vini Brasil 35107e2b8f
Add revenue metrics to prop breakdown (#3140)
* Extract <Money> React component

* Unhide prop breakdown for revenue goals

* Query revenue metrics on prop breakdown API
3 years ago
RobertJoonas 626dcba0c5
fix CR undefined bug (#3141) 3 years ago
dependabot[bot] 19914112c4
Bump floki from 0.32.1 to 0.34.3 (#3135)
Bumps [floki](https://github.com/philss/floki) from 0.32.1 to 0.34.3.
- [Release notes](https://github.com/philss/floki/releases)
- [Changelog](https://github.com/philss/floki/blob/main/CHANGELOG.md)
- [Commits](https://github.com/philss/floki/compare/v0.32.1...v0.34.3)

---
updated-dependencies:
- dependency-name: floki
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
RobertJoonas 49a2a14237
refactor LazyLoader and fix bug (#3121) 3 years ago
Uku Taht c550a87e01
Add webhook alert from Checkly -> Instatus (#2840)
* Add webhook alert from Checkly -> Instatus

* `terraform fmt`

* Send api healthcheck failures to TF

---------

Co-authored-by: Cenk Kücük <cenk@plausible.io>
3 years ago
ruslandoga 6fa558b651
release v2.0.0 (#3030) 3 years ago
Vini Brasil fd01a67a5f
Plot revenue metrics on main graph (#3112)
* Move money cast function to Stats.Util

* Add revenue metrics to main graph API

* Plot revenue metrics on the main graph

* Return plain numbers instead of a map

* Fix Credo issues

* Fix canMetricBeGraphed function

* Revert canMetricBeGraphed function changes
3 years ago
Cenk Kücük 36bfdb35f5
upgrade github runner (#3114) 3 years ago
dependabot[bot] eb8bc062d5
Bump eslint-plugin-playwright from 0.15.0 to 0.15.3 in /tracker (#3129)
Bumps [eslint-plugin-playwright](https://github.com/playwright-community/eslint-plugin-playwright) from 0.15.0 to 0.15.3.
- [Release notes](https://github.com/playwright-community/eslint-plugin-playwright/releases)
- [Changelog](https://github.com/playwright-community/eslint-plugin-playwright/blob/main/CHANGELOG.md)
- [Commits](https://github.com/playwright-community/eslint-plugin-playwright/compare/v0.15.0...v0.15.3)

---
updated-dependencies:
- dependency-name: eslint-plugin-playwright
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 8058a06d2d
Bump phoenix_live_view from 0.19.0 to 0.19.4 (#3131)
Bumps [phoenix_live_view](https://github.com/phoenixframework/phoenix_live_view) from 0.19.0 to 0.19.4.
- [Changelog](https://github.com/phoenixframework/phoenix_live_view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/phoenixframework/phoenix_live_view/compare/v0.19.0...v0.19.4)

---
updated-dependencies:
- dependency-name: phoenix_live_view
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Kris Buist c4316d61c6
Fix the country filter label when clicking on a country on the map (#3109) 3 years ago
hq1 e6e7f07915
Revert "Bump stylelint from 14.1.0 to 15.10.1 in /assets (#3115)" (#3125)
This reverts commit efe0d63b74.
3 years ago
dependabot[bot] efe0d63b74
Bump stylelint from 14.1.0 to 15.10.1 in /assets (#3115)
Bumps [stylelint](https://github.com/stylelint/stylelint) from 14.1.0 to 15.10.1.
- [Release notes](https://github.com/stylelint/stylelint/releases)
- [Changelog](https://github.com/stylelint/stylelint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/stylelint/stylelint/compare/14.1.0...15.10.1)

---
updated-dependencies:
- dependency-name: stylelint
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] f1c89a28f5
Bump eslint from 8.38.0 to 8.44.0 in /tracker (#3103)
Bumps [eslint](https://github.com/eslint/eslint) from 8.38.0 to 8.44.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.38.0...v8.44.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 50eb97d679
Bump semver from 5.7.1 to 5.7.2 in /assets (#3124)
Bumps [semver](https://github.com/npm/node-semver) from 5.7.1 to 5.7.2.
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/v5.7.2/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v5.7.1...v5.7.2)

---
updated-dependencies:
- dependency-name: semver
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 2dbba5d724
Bump webpack from 5.38.1 to 5.88.1 in /assets (#3093)
Bumps [webpack](https://github.com/webpack/webpack) from 5.38.1 to 5.88.1.
- [Release notes](https://github.com/webpack/webpack/releases)
- [Commits](https://github.com/webpack/webpack/compare/v5.38.1...v5.88.1)

---
updated-dependencies:
- dependency-name: webpack
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 5b960426f9
Bump @tailwindcss/aspect-ratio from 0.2.1 to 0.4.2 in /assets (#2263)
Bumps [@tailwindcss/aspect-ratio](https://github.com/tailwindlabs/tailwindcss-aspect-ratio) from 0.2.1 to 0.4.2.
- [Release notes](https://github.com/tailwindlabs/tailwindcss-aspect-ratio/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss-aspect-ratio/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss-aspect-ratio/compare/v0.2.1...v0.4.2)

---
updated-dependencies:
- dependency-name: "@tailwindcss/aspect-ratio"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 4615866c13
Bump phoenix_live_reload from 1.3.3 to 1.4.1 (#2849)
Bumps [phoenix_live_reload](https://github.com/phoenixframework/phoenix_live_reload) from 1.3.3 to 1.4.1.
- [Release notes](https://github.com/phoenixframework/phoenix_live_reload/releases)
- [Changelog](https://github.com/phoenixframework/phoenix_live_reload/blob/main/CHANGELOG.md)
- [Commits](https://github.com/phoenixframework/phoenix_live_reload/compare/v1.3.3...v1.4.1)

---
updated-dependencies:
- dependency-name: phoenix_live_reload
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
risson 50fa1b059b
Allow optional IPv6 for clickhouse repo (#2970)
* Allow optional IPv6 for clickhouse repo

Signed-off-by: Marc 'risson' Schmitt <marc.schmitt@risson.space>

* remove trailing comma

---------

Signed-off-by: Marc 'risson' Schmitt <marc.schmitt@risson.space>
Co-authored-by: ruslandoga <rusl@n-do.ga>
3 years ago
Cenk Kücük 13a38aee14
upgrade clickhouse (#3113) 3 years ago
ruslandoga 7e2627ae4c
array join (#3021) 3 years ago
hq1 2be9020460
Fix APP-46E: accept invitation 2nd click (#3120)
* Fix APP-46E: accept invitation 2nd click

* :LspStop

* Update lib/plausible_web/controllers/invitation_controller.ex

Co-authored-by: Vini Brasil <vini@hey.com>

---------

Co-authored-by: Vini Brasil <vini@hey.com>
3 years ago
hq1 cf5cc8de94
Filter out GA imported data with no visitors recorded (#3123) 3 years ago
hq1 9debcdee24
Fix APP-2NA (#3119) 3 years ago
hq1 fea9bb32ee
Prevent robots from looking too much into public dashboards (#3118)
* Add noindex,nofollow to dashboard pages

* Implement NoRobots plug

* Enable NoRobots plug in the router

* Fixup internal route

* Fix double slash in the router

* Add special bot treatment to plausible.io live demo page

* Revert aggressive protection with agent detection
3 years ago
Roj fd3c9ecc7b
Add missed space (#3116) 3 years ago
RobertJoonas 0541098330
Make the ListReport component more flexible (#3078)
* refactor ListReport

Pass a 'getFilterFor' function instead of a 'filter' object to ListReport

* Keep the statsBoxClass in one place only

* add classname prop to MoreLink

* define metric structs as ListReport inputs

* Fix a bug

If the query changes, we also want to reset the eventListener function.
Otherwise we keep calling an outdated function that fetches old data.

* fix CI
3 years ago
hq1 01fba1f34b
Bump funnel max size to 8 steps (#3094)
* Bump max funnel size to 8 steps

* Improve chart rendering for small screens/large funnels
3 years ago
hq1 ade437c085
Evaluate ephemeral funnels before saving (#3097)
* PoC: evaluate funnel on step selection

* Adjust test to actually _select_ steps

* Throttle and test ephemeral funnel evaluation

* Format compact percentages server-side

At this point it's pointless to duplicate this;
all the primitives exist in the API in case the client
wants a different representation.
3 years ago
hq1 e98a16141e
Enable superadmin access to funnel settings (#3104) 3 years ago
Cenk Kücük f374650330
Postgres upgrade (#3062)
* Update list to the last 3 versions of postgres

* Update postgres prod version
3 years ago
hq1 34c053ed12
Fix spacing between two notices in funnel settings (#3092)
* Fix spacing between two notices in funnel settings

* Fixup
3 years ago
hq1 21a968ef2c
Set socket interval for hearbeats to 10s (#3091) 3 years ago
hq1 ff11b3f26d
Bugfix: funnel deletion (#3090)
Somewhere along the way of rebasing the feature,
the integration tests for deletion were lost.

j/k they were never written 🤡
3 years ago
hq1 eb397a6c25
Dynamically set up session domain (#3089)
* Dynamically configure session domain

* Fix up error message in runtime config
3 years ago
hq1 4ac83b6e5d
Reconfigure live websocket (#3087)
* Dynamically set :domain for the live socket

Ref: https://github.com/phoenixframework/phoenix_live_view/pull/2715

* Make runtime config raise before the user ends up in a reconnect loop

* hall of shame: remove console.info remnant

* Check origin on live websocket

* Get rid of single pipe
3 years ago
hq1 db5488efa6
Put live view meta tags behind a FF (#3083) 3 years ago
hq1 0c77b01a99
Allow configurable websocket URL for live view (#3082) 3 years ago
hq1 bbedeff683
Implement Funnels view on dashboard (#3066)
* Add Funnel react component

assets/js/dashboard/stats/behaviours/funnel.js - restored from:

98a76cbd Remove console.info calls
d94db99d Convert Funnel class component into a functional one
028036ad Review comments
3067a940 Stop doing maths in react
73407cc3 Fix error handling when local storage gets corrupted
e8c6fc52 Format numbers on funnel labels
c815709f Reorganize component responsibility
7a88fe44 Outline basic error handling
94caed7c Chart styling updates
4514608a Add percentages to funnel
d622c32d Add funnel picker

Co-authored-by: Uku Taht <uku.taht@gmail.com>

* Pass funnels list to react via data-funnels

* Implement Funnels react API

lib/plausible_web/controllers/api/stats_controller.ex - restored from:

f36ad234 Adjust to Plausible.Stats interface
9b532273 Test funnel stats controller
028036ad Review comments
bea3725f Remove IO.inspect
7a88fe44 Outline basic error handling
c8ae3eaf Move Funnels to StatsController and use base query
667cf222 Put private functions at the bottom

* Tweak funnel presentation

* Handle errors at the top

* Do not register DataLabels plugin globally

or else all the existing charts are affected

* Calculate drop-off percentage evaluating funnels

* Tweak dark mode + implement nicer tooltips

* Make currently selected funnel bold in the picker

* Count user_ids not session_ids when evaluating funnels

So if a visitor goes:

1. Start session
2. Complete funnel step 1
3. Inactive for 30 minutes
4. Complete funnel step 2

We would not be able to track this funnel completion because of the session timeout.
We like to o measure this as funnel completion even though the session expired in the middle.

cc @ukutaht

* Add extra properties to the funnels API

cc @ukutaht

* Improve tooltips so that step to data is rendered

* Change tooltip number formatting

* Remove debugging remnants

* Quick & dirty mobile view

* Fix mobile view: tweak dark mode & funnel switching

* Ignore DOMException: the operation was aborted

Otherwise this sometimes flashes the space shuttle
screen when navigating quickly via a keyboard.

* Format percentages on the main chart

* Close missing tag 🙈

* Revert "Close missing tag 🙈"

This reverts commit 9c2f970e22fd7e2980503242b414f42ce8bce1d2.

* Use jsx to render funnel tooltip

To get markup validated via lsp mostly...

* Fixup: s/class/className

* Fix className interpolation

* Add a ruler to the tooltip

* Tweak funnel chart style

* Fix font distortion issue on chart/canvas labels

* s/class/className

* Put "Set up funnels" link behind a feature flag

* Refactor internal selection storage

Getting ready for live funnel evaluation

* Don't try to connect LV socket if there's no CRSF token set up

This is perfectly okay for some of the templates/layouts.

* Fix up funnel creation typespecs

Unfortunately we can't define a type with literal string keys,
hence this must suffice.

* Use uniq over count/distinct

* Revert JSX in tooltips

Ref: https://github.com/plausible/analytics/pull/3066#discussion_r1241891155

* Remove the extra query for counting all visitors

cc @ukutaht

* Add premium notice

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
3 years ago
Vini Brasil a8daac5e03
Add notice to revenue goals UI (#3069)
This pull request changes the UI for revenue goals, replaces the select box with a toggle, and adds a notice. It also polishes up the goal creation UI in general to have the same font sizes and weights compared to the rest of the page.
3 years ago
Vini Brasil b97290b5cf
Add revenue metrics to top stats (#3059)
This commit adds revenue data to top stats. Average and total are displayed when filtering by a revenue goal (or many if they have the same currency set).
3 years ago
hq1 d8543c81cc
Funnel site settings (#3039)
* Update formatter config

* Install LiveView JS integration & hooks

* Temporarily update endpoint/session config

* Optionally allow preloading funnels for goals

* Site controller

* Implement funnel settings

lib/plausible_web/live/funnel_settings/combo_box.ex - restored from:

054de6e2 Fix the tab/blur bug again
20da4c89 Rename InputPicker to ComboBox

lib/plausible_web/live/funnel_settings/form.ex - restored from:

9bedda3b Remove potential FIXME
20da4c89 Rename InputPicker to ComboBox
028036ad Review comments
aea4ebc4 Access Funnel min/max steps via the __using__/1 macro
0dde27fd Remove inspect call
eed588a7 Start testing the funnel editor
0e95228b Extract funnel settings test module
7b16ace5 Leverage aplinejs to deal with the tyranny
8dc6a3e7 wip
cf228630 wip
30a43fd1 wip
89f10ecb wip
950a18d9 Dirty funnel save
298a6a53 wip
7690d50f wip
639c6238 fixup
aa59adeb wip
ff75c00b wip

lib/plausible_web/live/funnel_settings/list.ex - restored from:

4eae122c Fix data-confirm attr interpolation
51f0397d Implement deleting funnels
1f6fe25d Add number of steps to funnels list
298a6a53 wip
ff75c00b wip

test/plausible_web/live/funnel_settings/funnel_settings/combo_box_test.exs - restored from:

20da4c89 Rename InputPicker to ComboBox

test/plausible_web/live/funnel_settings/funnel_settings_test.exs - restored from:

34822ff4 Bootstrap InputPicker tests

lib/plausible_web/live/funnel_settings.ex - restored from:

028036ad Review comments
acd9c4f2 Prepare ephemeral funnel definitions so that users can test funnels
51f0397d Implement deleting funnels
0e95228b Extract funnel settings test module
8dc6a3e7 wip
89f10ecb wip
950a18d9 Dirty funnel save
298a6a53 wip
aa59adeb wip
ff75c00b wip

test/plausible_web/controllers/error_report_controller_test.exs - restored from:

34822ff4 Bootstrap InputPicker tests

test/support/html.ex - restored from:

0a53979d Improve InputPicker tests - include AlpineJS assertions
34822ff4 Bootstrap InputPicker tests

lib/plausible_web/views/layout_view.ex - restored from:

b490403b !ifxup

lib/plausible_web/templates/site/settings_funnels.html.eex - restored from:

51f0397d Implement deleting funnels
ea1315f3 Test funnels list in settings
7b16ace5 Leverage aplinejs to deal with the tyranny
ff75c00b wip
4da25c35 Fixup

lib/plausible_web/templates/layout/app.html.eex - restored from:

ff75c00b wip

* Add funnel settings route

* Warn about funnels deletion when deleting goals

lib/plausible_web/templates/site/settings_goals.html.eex - restored from:

fdd9bcd0 Fixup
f1e6364d Merge remote-tracking branch 'origin/master' into funnels-rebase
9d0b7c6d Fix markup error
4a4ddbdc Optionally preload funnels for goals and stub funnel-goal deletion
ebdc4333 Extend the prompt in case of funnel-goal deletion
639c6238 fixup
aa59adeb wip

* Split new JS LiveView additions

* Put funnels behind a feature flag

* Integrate dashboard feature toggle

* Update signing salt for live view

* Update moduledocs

* Update live reloader config

* Use Phoenix.HTML.Safe for goal names

* Workaround to get flashes working in embedded liveview

* Keep feature toggles idempotent, rename property to setting

We'll still retain the ability to flip bools on a lower level.

* Update moduledocs

* Make live flash disappear after 5s

* Tailwind: purge .heex files too

* Update docs link

* Add live components to tailwind purge config

* Update another flaky test

Ref f0bdf872
cc @vinibrsl

* Fix combobox input length w/ WebKit

* Intoduce generic notice component

* Revert "Fix combobox input length w/ WebKit"

This reverts commit 3c653a6d85d5000167631e10ef45a93c13b41ed1.

* Fix combobox input length on webkit

* Make whole combobox item clickable, not only text

* Fix glitch moving Save button on activation

* Tweak dark mode

* Show funnel form without waiting for funnel name input

* Tweak dark mode

* Include static Phoenix components in tailwind purge

* Tune funnels form into a liveview of its own

This is so that ComboBoxes can publish their selections
and unavailable choices can be propagated to other siblings.

* Push less data over websocket

* Undo Lsp/formatter race condition

* Fixup typespecs

* Bust CI cache
3 years ago
dependabot[bot] 086045bde8
Bump eslint-plugin-playwright from 0.12.0 to 0.15.0 in /tracker (#3061)
Bumps [eslint-plugin-playwright](https://github.com/playwright-community/eslint-plugin-playwright) from 0.12.0 to 0.15.0.
- [Release notes](https://github.com/playwright-community/eslint-plugin-playwright/releases)
- [Changelog](https://github.com/playwright-community/eslint-plugin-playwright/blob/main/CHANGELOG.md)
- [Commits](https://github.com/playwright-community/eslint-plugin-playwright/compare/v0.12.0...v0.15.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-playwright
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
Vini Brasil 81444f077d
Remove revenue metrics from pageview goal query (#3040)
This commit fixes a bug where performing a breakdown by goal with
revenue metrics would return data for both event goals and pageview
goals. However, revenue data is only applicable for event goals as they
hold currency data.

To fix the bug, this commit removes revenue metrics from the pageview
breakdown query.
3 years ago
hq1 cf4fee33c2
Pin alpine versions to 3.18.0 (#3057)
* Revert "Bump alpine from 3.18.0 to 3.18.2 (#3044)"

This reverts commit c19a51efb0.

* Pin both images to alpine 3.18.0
3 years ago
Vini Brasil 67be43b6e6
Add tagged events support for revenue goals (#3038)
* Add tagged events support for revenue goals

This commit adds two special classes for tracking revenue with tagged
events. The following example sends an event with revenue data when the
tracker script has revenue and tagged-events script extensions:

```html
<button class="plausible-event-revenue-amount=10.29 plausible-event-revenue-currency=EUR"></button>
```

* Rename special revenue tracking class name
3 years ago
Cenk Kücük 94591a5a20
Update loadbalancer url (#3056) 3 years ago
Vini Brasil 41c88c4fa0
Add unique names to cache supervisors in tests (#3055)
This commit fixes a flaky test where a supervisor with that same name
was already started.
3 years ago
Vini Brasil 5012e0c0ec
Set with_imported=false in realtime mode (#3053)
This commit fixes a bug where timeseries queries - such as the main
graph - would fail with imported data in realtime mode. Realtime mode
`date` field is not actually a date, but minutes from now. This would
cause the imported tables join to fail with this error:

```
(Ch.Error Code: 53. DB::Exception: Can't infer common type for joined
columns: date: Int64 at left, s1.date: Date at right. There is no
supertype for types Int64, Date because some of them are
Date/Date32/DateTime/DateTime64 and some of them are not.
(TYPE_MISMATCH)
```

This commit removes imported data from realtime queries, as it doesn't
make sense to include it. Imported data does not have time precision,
and would only appear in the first day the data was imported anyways.
3 years ago
Vini Brasil f0bdf872b5
Add eventually/1 call to flaky test (#3054) 3 years ago
dependabot[bot] 02783885c7
Bump @playwright/test from 1.32.2 to 1.35.1 in /tracker (#3043)
Bumps [@playwright/test](https://github.com/Microsoft/playwright) from 1.32.2 to 1.35.1.
- [Release notes](https://github.com/Microsoft/playwright/releases)
- [Commits](https://github.com/Microsoft/playwright/compare/v1.32.2...v1.35.1)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] 8cb9878ba4
Bump actions/checkout from 2 to 3 (#3050)
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
dependabot[bot] c19a51efb0
Bump alpine from 3.18.0 to 3.18.2 (#3044)
Bumps alpine from 3.18.0 to 3.18.2.

---
updated-dependencies:
- dependency-name: alpine
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3 years ago
hq1 aabde0a7b9
Update gitignore with docker volume dirs (#3029) 3 years ago
Vini Brasil 8834486a19
Pass cached site struct down the ingestion pipeline (#3027)
* Pass cached site struct down the ingestion pipeline

Revenue goals need the cached site struct during ingestion to get the
goals name and currency. This cache lookup is not necessary as
`GateKeeper.check/1`, which is called first in the ingestion pipeline,
could already return the site struct from the cache.

This commit changes `GateKeeper.check/1` to return the site struct
instead of the site ID. Moreover, this commit changes the ingestion
pipeline to avoid calling the sites cache twice.

Related: https://github.com/plausible/analytics/pull/2957#discussion_r1203921549

* Remove revenue_goals unnecessary fallback

* Change duplicate child_id in cache test

* Remove revenue goal condition from cache query

* Remove Plausible.DataCase.reload/1
3 years ago
Uku Taht 98055d2f1c
Fix queries with wildcard goals (#3015)
* Fix queries with wildcard goals

* Changelog
3 years ago
Vini Brasil 8f6224b5de
Revenue tracking: goal conversions and tracker script (#3019)
* Add revenue average and total to Goal Conversions

* Add revenue option to tracker script

* Simplify revenue tracker script
3 years ago
ruslandoga fd15853965
disable registration by default in self-hosted setups (#3014)
* disable registration by default in self-hosted setups

* add changelog entry

* add error flash
3 years ago
Vini Brasil 2c4cea6dce
Add revenue metrics in StatsController instead of Stats.Breakdown (#3028)
This commit makes total_revenue and average_revenue first-class metrics
instead of adding them magically in `Plausible.Stats.Breakdown`. To
keep the same behavior, revenue metrics are added in StatsController.

Related: https://github.com/plausible/analytics/pull/2957#pullrequestreview-1475017620
3 years ago
hq1 a356009af8
Implement backend core for funnels (#3023)
* Implement Funnel schema

* Implement Funnels context module

lib/plausible/funnels.ex - restored from:

dca93621 Mark Vini's suggestion applied
7d1eec75 Update lib/plausible/funnels.ex
028036ad Review comments
b694ccd5 Express the guard nicely
acd9c4f2 Prepare ephemeral funnel definitions so that users can test funnels
aea4ebc4 Access Funnel min/max steps via the __using__/1 macro
51f0397d Implement deleting funnels
cf228630 wip
1f6fe25d Add number of steps to funnels list
89f10ecb wip
950a18d9 Dirty funnel save
e62bfce5 Refactor funnel result evaluation
88e38a33 Update funnel tests
bf47f654 Calculate conversion rate/dropoff in the backend
9e62ffb1 Make existing tests pass
7a88fe44 Outline basic error handling
c8ae3eaf Move Funnels to StatsController and use base query
2929bfd4 Minor rework
b490403b !ifxup
ae44db77 Add Funnels.list/1 function
4f3216b3 Unique steps
6e0c3efc Ensure step ordering works
cea93ba1 It works I think
c50ac0c2 WIP
a466ec4c Dirty wip
fbd14e23 Absolute dirty wip
3ddd15ad wip
34ceb3f5 dirty wip

test/plausible_web/controllers/api/stats_controller/funnels_test.exs - restored from:

9b532273 Test funnel stats controller

Co-authored-by: Uku Taht <uku.taht@gmail.com>

* Update Goals implementation

lib/plausible/goal/schema.ex - restored from:

028036ad Review comments
acd9c4f2 Prepare ephemeral funnel definitions so that users can test funnels
4a4ddbdc Optionally preload funnels for goals and stub funnel-goal deletion
fbd14e23 Absolute dirty wip

lib/plausible/goals.ex - restored from:

aea4ebc4 Access Funnel min/max steps via the __using__/1 macro
a418c039 Implement funnel reduction logic on goal deletion
4a4ddbdc Optionally preload funnels for goals and stub funnel-goal deletion
ebdc4333 Extend the prompt in case of funnel-goal deletion
950a18d9 Dirty funnel save
f06c3fcf wip

test/plausible/goals_test.exs - restored from:

a418c039 Implement funnel reduction logic on goal deletion
4a4ddbdc Optionally preload funnels for goals and stub funnel-goal deletion
dee5bc9e Fixup tests

* Update seeds

* Split funnel schema modules

* Add moduledoc to Funnel schema

* Update Funnel.Step moduledoc

* Add typespecs to Plausible.Funnels

* Implement Phoenix.HTML.Safe for Funnel schema

* Fixup a test after ordering goals by desc:id

test/plausible_web/controllers/api/stats_controller/conversions_test.exs - restored from:

26a493cb Fixup a test after ordering goals by desc:id

* Annotate Goal schema with type t()

* Reword schema module docs

* Fix up typespecs

* Stop tagging Funnels.get/2 result

* Nuke Goals.by_id!/2

* Test Funnels module

test/plausible/funnels_test.exs - restored from:

b7a6d3ad ya, rly
028036ad Review comments
acd9c4f2 Prepare ephemeral funnel definitions so that users can test funnels
51f0397d Implement deleting funnels
1f6fe25d Add number of steps to funnels list
dee5bc9e Fixup tests
950a18d9 Dirty funnel save
88e38a33 Update funnel tests
bf47f654 Calculate conversion rate/dropoff in the backend
9e62ffb1 Make existing tests pass
2929bfd4 Minor rework
b490403b !ifxup
ae44db77 Add Funnels.list/1 function
4f3216b3 Unique steps
6e0c3efc Ensure step ordering works
cea93ba1 It works I think
c50ac0c2 WIP
a466ec4c Dirty wip
34ceb3f5 dirty wip

Co-authored-by: Uku Taht <uku.taht@gmail.com>

* Apply changes related to 242081e5

* Evaluate funnels through `Stats.funnel/3` entry point

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
3 years ago
hq1 c7b8a8ef27
Bugfix for #3005 (#3025)
* Revert "Revert "UI groundwork: Conversions to Behaviors (#3005)" (#3024)"

This reverts commit dc0853bac7.

* Move ref back to LazyLoader container
3 years ago
hq1 dc0853bac7
Revert "UI groundwork: Conversions to Behaviors (#3005)" (#3024)
This reverts commit ba19f9530e.
3 years ago
hq1 3dce3142bf
Migration: add funnel related tables (#3022)
priv/repo/migrations/20230417095029_init_funnels.exs - restored from:

aa59adeb wip
4d039ba2 Make funnel names unique
4f3216b3 Unique steps
e55edf8e Rename funnel_goals->funnel_steps
34ceb3f5 dirty wip
3 years ago
RobertJoonas ba19f9530e
UI groundwork: Conversions to Behaviors (#3005)
* copy relevant files from b2ace16540

* make it work and set site.funnels to empty list

* make Behaviours a functional component

* add UI for a setup hint and always display conversions by default

* cherry-pick migration commit

* update site schema with new fields

* backend: implement disable-feature action

* switch between tabs in the behaviors section

Introduces template components to build props and funnels on. Both
only show a setup notice atm, and both are behind feature flags.

* extend API for disabling props and funnels

* render feature setup note directly from the Behaviours component

* fix UI behavior when features are hidden

* update setup notices

* add conversions feature switch to Site Settings > Goals

* mix format

* remove IO.inspect

* change setup notice - use buttons + popup confirmation

* optimize for light mode

* restrict access to setup notices

* some styling improvements

* allow super-admins to enable/disable features

* only show conversions (last 30min) in realtime mode

* use shorter display names for tabs

* optimize for mobile screens

* note about sending custom events

* changelog update + fix CI

* change HTTP verb for the disable-feature action

* change UI label for show/hide goals
3 years ago
Vini Brasil e4d4f7d954
Revenue tracking: Ingestion and breakdown queries (#2957)
* Add revenue fields to ClickHouse events

This commit adds 4 fields to the ClickHouse events_v2 table:

* `revenue_source_amount` and `revenue_source_currency` store revenue in
  the original currency sent during ingestion

* `revenue_reporting_amount` and `revenue_reporting_currency` store
  revenue in a common currency to perform calculations, and this
  currency is defined by the user when setting up the goal

The type of amount fields is `Nullable(Decimal64(3))`. That covers all
fiat currencies and allows us to store huge amounts. Even though
ClickHouse does not suggest using `Nullable`, this is a good use case,
because otherwise additional work would have to be done to
differentiate missing values from real zeroes.

I ran a benchmark with the data pattern we expect in production, where
we have more missing values than real decimals. I created 100 million
records where 90% of decimals are missing. The difference between the
tables in storage is just 0.4Mb.

* Add revenue parameter to Events API

This commit adds support for sending revenue data in ingestion using the
`revenue` parameter - aliased to `$`.

* Add revenue parameter to mix send_pageview

* Add average and total revenue to breakdown queries
3 years ago
Vini Brasil d98242895b
Add revenue fields to events_v2 (#3018) 3 years ago
RobertJoonas 5162da473c
add migration (#2988) 3 years ago
ruslandoga b0c0214b6b fix twitter link 3 years ago
Vini Brasil c559370201
Trim prop list to 30 items during ingestion (#3009)
This commit adds an upper bound limit to custom props. It fails silently
and trims the list instead of dropping the event.
4 years ago
ruslandoga 131c99c69e
remove custom_dimension_filter feature and views_per_visit_metric flags (#2996)
* remove custom_dimension_filter feature flag

* add changelog entry

* fix shouldLinkToFilterModal removal

* remove views_per_visit_metric flag
4 years ago
Uku Taht 995556e86f
Enable sampling in the Stats API (#2985) 4 years ago
hq1 49ca6b859a
Prepare base for the funnel PRs merge (#2993)
* Update dependencies as per the funnels branch

Co-authored-by: Uku Taht <uku.taht@gmail.com>

* Mute sigil_E deprecation errors

* Use Phoenix.Component in PlausbileWeb

* Add tooltip to react/no-unknown-property whitelist

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
Co-authored-by: Vinicius Brasil <vini@hey.com>
4 years ago
ruslandoga 54f5718ac8
remove fetch.min.js shim from waiting_first_pageview page (#2999) 4 years ago
Uku Taht fc918081b5
Fix event name validation (#2975)
* Fix event name validation

* Add @moduledoc

* Move tests to Ingestion.RequestTest

* Remove comment
4 years ago
ruslandoga 25f95ae84e
add landing page (#2989)
* add landing page

* cont.

* add redirect to /sites test

* add changelog entry

* adapt for mobile
4 years ago
RobertJoonas 6c907cbf42
Fix favicon request URLS (#2976)
Also use the favicon.ex proxy in referrer drilldown
4 years ago
ruslandoga 40e95ffd3d
add LOG_FAILED_LOGIN_ATTEMPTS (#2936)
* add failed login logs

* put failed login attempt logs behind a config option

* add changelog entry

* add config test

* add auth_controller tests

* move tests to separate non-async test module

---------

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
4 years ago
ruslandoga ce7401dd83
add MAILER_NAME (#2937)
* add MAILER_NAME

* add mailer test

---------

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
4 years ago
Uku Taht e4b1aa64d1
Fix tailwind safelist (#2966) 4 years ago
ruslandoga 7b22aff11c
add MAILGUN_BASE_URI (#2935)
* add MAILGUN_BASE_URI support

* add changelog entry
4 years ago
ruslandoga f489d96251
skip v1 table drop in self-host (#2945) 4 years ago
ruslandoga 447ed12155
use ecto_ch (#2890)
* use ecto_ch

* use Ch type in BoolUInt8

* update ecto_ch and ch to latest versions
4 years ago
RobertJoonas dafb60164a
Allow setting sample_threshold in dashboard API queries (#2958)
* refactor Query.from/2

* allow specifying sample_threshold number in query
4 years ago
Uku Taht 6be67bc6c2
Carry _sample_factor from right side to left in join (#2962) 4 years ago
Uku Taht 1a94456586
Wrap user deletion in DB transaction (#2964) 4 years ago
Uku Taht 3b1e0101d8
Limit width of embedded dashboards by default (#2965) 4 years ago
Vini Brasil 10d9e3b083
Revenue tracking: Add currency field to goal creation (#2948)
* Add revenue goal option to goal creation

This commit adds a currency field to the goals form. Goals that have a
currency set are now revenue goals, and are cached with sites to later
be used during ingestion.

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>

* Enable feature flag in tests

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
4 years ago
Vini Brasil 3a07487c05
Add currency field to goals table (#2955) 4 years ago
Uku Taht ca3e2e5121
Add unique constraint to api keys (#2931)
* Add unique constraint to api keys

* Fix test

* Remove `user_id` from api key index
4 years ago
Marko Saric 3482337348
link to the WP plugin and the integration guides (#2927) 4 years ago
Marko Saric 1723d3ca68
Keep the in-app footer consistent with the main site (#2944) 4 years ago
Uku Taht 2259651b21
Ignore missing subscription on update (#2930) 4 years ago
RobertJoonas e27e29250b
Fix tracker bug - call callback function when ignoring event (#2947)
* call callback function when ignoring event

* update changelog
4 years ago
Harry Vangberg 34a6b984c7
Escape domain when creating URL for favicon (#2942)
* Escape domain when constructing favicon URL

A domain may include a slash, and in that case the domain must be
escaped, before it is used as an attribute for the image tag.

* match with 'conn.request_path' instead + test

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
4 years ago
RobertJoonas fa54efbc6d
Support `with_imported=true` in Stats API aggregate (#2919)
* default to source_query.include_imported before true

This fixes a bug where a Stats API aggregate query was trying
to query current period *without imported data* but previous
period *with imported data*.

* remove __internal_visits at a better time

As soon as we have made the db query, we don't need it anymore

* disallow events metric with imported data

* update changelog

* keep default in a better place

* remove unused option

* update test description

Co-authored-by: Vini Brasil <vini@hey.com>

---------

Co-authored-by: Vini Brasil <vini@hey.com>
4 years ago
Vini Brasil f29d07a49e
Add tracking back to upgrade-success page (#2938) 4 years ago
Vini Brasil 4ca2e26b9c
Limit ingestion payload size (#2904)
This pull request adds constraints on user input values during ingestion. The purpose of this PR is to filter out unrealistic or invalid inputs. More comments about each limit inline.
4 years ago
RobertJoonas 00d05b2edd
Fix a bug with query bindings (#2932) 4 years ago
Marko Saric 42f88be12a
Tweaks to the email copy (#2933)
* Removing the spike line

* Update dashboard_locked.html.eex
4 years ago
Uku Taht e954f946e1
Adds `nofollow` to X-Robots-Tag header in stats page (#2929) 4 years ago
RobertJoonas db359c2a6f
Filter out garbage props by `site.allowed_event_props` (#2907)
* add migration

* add not null constraint

* remove not null constraint and default value

* add site schema change

* filter garbage props for prop_key suggestions

* filter garbage props returned by StatsController.conversions/2

* add crm action to set prop allowlist

* use nullable allowed_event_props field instead

* filter garbage props in db query instead

* implement suggestion dealing with string input

* refactor the allowlist condition in db query

* improve test
4 years ago
Uku Taht eec842c46b
Remove `visits_metric` feature flag (#2898)
* Remove `visits_metric` feature flag

* Fix credo warning
4 years ago
Vini Brasil 257fa16cdc
Simplify Phoenix error template (#2913)
* Simplify Phoenix error template

* Test tracking script is not included in error pages

* Test tracking script is not rendered in error templates

* Rename error layout and remove unnecessary HTML boilerplate

* Add layout setting to errors rendered without exceptions

* Add skip_plausible_tracking option to more pages
4 years ago
dependabot[bot] 16c4b9e3eb
Bump docker/build-push-action from 2 to 4 (#2918)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 2 to 4.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v2...v4)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
4 years ago
dependabot[bot] 007ff2c729
Bump docker/setup-buildx-action from 1 to 2 (#2916)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 1 to 2.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v1...v2)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
4 years ago
dependabot[bot] 6ab1cfc319
Bump actions/setup-node from 2 to 3 (#2917)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 2 to 3.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
4 years ago
dependabot[bot] 42022fcb29
Bump actions/cache from 2 to 3 (#2915)
Bumps [actions/cache](https://github.com/actions/cache) from 2 to 3.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
4 years ago
Cenk Kücük a69719c498
Keep github actions up to date with dependabot (#2914) 4 years ago
dependabot[bot] d437d17777
Bump alpine from 3.17.0 to 3.18.0 (#2910)
Bumps alpine from 3.17.0 to 3.18.0.

---
updated-dependencies:
- dependency-name: alpine
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
4 years ago
hq1 57af1f19ec
Drop events/sessions tables after V2 migration (#2908) 4 years ago
RobertJoonas 412bf1959e
Postgres migration to add `allowed_event_props` field to `site` (#2894)
* add migration

* add not null constraint

* remove not null constraint and default value
4 years ago
RobertJoonas d161c1be0b
Upgrade phoenix (#2902)
* upgrade phoenix

Co-authored-by: Vini Brasil <vini@hey.com>

* fix a test (flash message)

The flash message in focus.html.eex was not covered by any test. This
commit fixes also fixes that.

* change function name

* remove unnecessary formatter and format

* update CI cache

* fix dialyzer error

---------

Co-authored-by: Vini Brasil <vini@hey.com>
4 years ago
hq1 6a831d9898
Harden API input validation (#2869)
* Reject invalid country codes early

* Validate all date parameters early

* Ensure request JSON parses to a map

* Re-arrange function calls

* Extend malicious filter validation
4 years ago
Vini Brasil 30465aaaf4
Add percentage difference back to default view (#2895)
This commit brings back percentage arrows to default view. These were
removed by the recent comparisons work, and we've had reports of people
missing it. As we haven't noticed any difference in performance, I've
decided to revert that change.
4 years ago
ruslandoga 885ccaa7ab
fix qemu arm64 builds (#2879)
* fix qemu arm64 builds

* unpin final image
4 years ago
Vini Brasil fecbc8b455
Fix conversions top stats bug when comparing (#2893)
This commit fixes a bug where unique conversions and the unique visitors
of the previous period in comparison view were always the same.

First reported at: https://github.com/plausible/analytics/discussions/532#discussioncomment-5760187
4 years ago
Vini Brasil eb6baa92a3
Show imported icon only when querying imported ranges (#2892)
This commit updates the imported 'G' icon, so that it appears only when
querying or comparing a range with imported data. By hiding the icon in
all other cases, users will see it only when they can actually click on
it.
4 years ago
RobertJoonas 7d935b79bf
Treat page filter as entry page filter only for bounce rate (#2874)
* add entry page filter condition to bounce rate

* Fix select_merge with dynamic

* fix tests and add one test

* generalize page_filter_condition function

* use dynamic_filter_condition for session filters too

* disable views_per_visit with a page filter

* update changelog

* disable credo for complex function

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
4 years ago
Vini Brasil 990447ff74
Ensure comparison line Y axis scale matches main plot (#2884)
Previously, the comparison line could sometimes be displayed with a
different scale than the main plot due to the maxTicksLimit option not
being fixed and changing based on the data. This commit fixes the issue
by setting the maxTicksLimit value to 8 in the graph settings instead of
for each individual axis.

Additionally, a callback that attempted to dynamically change the Y axis
ticks while resizing has been removed. As the graph has a fixed height,
dynamically resizing the Y axis no longer makes sense.
4 years ago
RobertJoonas caeff41932
Prop filter modal (#2841)
* Add PropFilterModal (only UI)

* small variable refactor

* allow selecting prop value filter type

* allow selecting only one prop_key

* allow selecting many prop_values only when prop_key selected

* handle submitting filter

* get applied filters from query + remove option

* change prop filter label format

* support member and not_member filter types for pageview props

* show (none) value in filter suggestions

* refactor zip_results/4 and remove unused code

* fix displaying (none) values in goals section prop breakdown

* remove unnecessary functionality

* fix bug: returning prop names for goal :member filter

* fix bug: submitting regular filter modal with Enter key

* bugfix: disallow opening prop filter modal when feature flag disabled

* mix format

* break selected combobox values into multiple lines

* fix useEffect behavior for focusing on prop_key field

* support submitting prop filter with Enter key

* refactor getFormState in PropFilterModal

* separate fetchPropKey and fetchPropValue functions

* Allow querying props for pageview goals

* Make the internal props API only return a list of props (not map)
* Separate function for fetching all props in Stats API goal breakdown (this returns a map as before)

* ditch state for keeping search bar visible

* group by event_name in db query
4 years ago
RobertJoonas 020e155fdf
Improve tagged events (#2880)
* allow '--' in addition to '=' in the classnames

* changelog update
4 years ago
Vini Brasil 8dc8423319
Prepare Comparisons for release (#2873)
This pull request removes the comparisons feature flag, making it visible to all users. It also removes percentages from top stats in default view, leaving those for the comparison view only.
4 years ago
Vini Brasil 8ec3dd402f
Prevent overwriting with_imported when comparing (#2871)
This commit fixes a bug where comparisons would not work with imported data. This is because comparisons copies the source query and modifies the dates only, where it should reevaluate if there is imported data for the new comparison date range.

Closes #2870

Co-authored-by: Adam <hq@mtod.org>
4 years ago
Uku Taht cc5c795fd6
Add more spacing for graph controls (#2878) 4 years ago
hq1 09687c0c14
Add .iex.exs with common aliases/imports (#2877) 4 years ago
Vini Brasil 0cfbcedd84
Fix date picker shifting day bug (#2848)
* Fix date picker shifting day bug

This commit fixes a bug where picking a specific date in custom range
takes you to the stats of the day before.

This was caused because Flatpickr returns a Date instance, and we were
trying to parse this Date instance into day.js using the `utc` function,
assuming it was a ISO-8601 string.

This commit fixes it by casting Date into dayjs using the `dayjs`
function instead of `utc`.

* Fix invalid date Flatpickr bug

This commit fixes a bug where the Flatpickr was not setting the minDate
correctly based on statsBegin. This was failing because parseUTCDate is
now returning a day.js instance, and Flatpickr cannot handle that type.

* Hide dayjs usage in util/date
4 years ago
Vini Brasil 70dc8d71c0
Improve comparisons UI for mobile devices (#2847)
* Hide arrows when comparing on smaller devices

* Hide "vs." label when comparing on smaller devices
4 years ago
hq1 71ef0bd043
Clean up after V2 migration (#2868)
* Clean up after V2 migration

This PR removes all the leftovers and alternative code
branching after v2 migration.

The self-hosted release is being drafted at:

https://github.com/plausible/hosting/issues/68

Refs:
  - https://github.com/plausible/analytics/pull/2865
  - https://github.com/plausible/analytics/pull/2825
  - https://github.com/plausible/analytics/pull/2780

* !fixup
4 years ago

@ -0,0 +1,205 @@
# This file contains the configuration for Credo and you are probably reading
# this after creating it with `mix credo.gen.config`.
#
# If you find anything wrong or unclear in this file, please report an
# issue on GitHub: https://github.com/rrrene/credo/issues
#
%{
#
# You can have as many configs as you like in the `configs:` field.
configs: [
%{
#
# Run any config using `mix credo -C <name>`. If no config name is given
# "default" is used.
#
name: "default",
#
# These are the files included in the analysis:
files: %{
#
# You can give explicit globs or simply directories.
# In the latter case `**/*.{ex,exs}` will be used.
#
included: [
"lib/",
"test/",
"extra/"
],
excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"]
},
#
# Load and configure plugins here:
#
plugins: [],
#
# If you create your own checks, you must specify the source files for
# them here, so they can be loaded by Credo before running the analysis.
#
requires: [],
#
# If you want to enforce a style guide and need a more traditional linting
# experience, you can change `strict` to `true` below:
#
strict: false,
#
# To modify the timeout for parsing files, change this value:
#
parse_timeout: 5000,
#
# If you want to use uncolored output by default, you can change `color`
# to `false` below:
#
color: true,
#
# You can customize the parameters of any check by adding a second element
# to the tuple.
#
# To disable a check put `false` as second element:
#
# {Credo.Check.Design.DuplicatedCode, false}
#
checks: %{
enabled: [
#
## Consistency Checks
#
{Credo.Check.Consistency.ExceptionNames, []},
{Credo.Check.Consistency.LineEndings, []},
{Credo.Check.Consistency.ParameterPatternMatching, []},
{Credo.Check.Consistency.SpaceAroundOperators, []},
{Credo.Check.Consistency.SpaceInParentheses, []},
{Credo.Check.Consistency.TabsOrSpaces, []},
#
## Design Checks
#
# You can customize the priority of any check
# Priority values are: `low, normal, high, higher`
#
{Credo.Check.Design.AliasUsage,
[priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]},
# You can also customize the exit_status of each check.
# If you don't want TODO comments to cause `mix credo` to fail, just
# set this value to 0 (zero).
#
{Credo.Check.Design.TagTODO, [exit_status: 2]},
{Credo.Check.Design.TagFIXME, []},
#
## Readability Checks
#
{Credo.Check.Readability.AliasOrder, []},
{Credo.Check.Readability.FunctionNames, []},
{Credo.Check.Readability.LargeNumbers, []},
{Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]},
{Credo.Check.Readability.ModuleAttributeNames, []},
{Credo.Check.Readability.ModuleDoc, []},
{Credo.Check.Readability.ModuleNames, []},
{Credo.Check.Readability.ParenthesesInCondition, []},
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
{Credo.Check.Readability.PipeIntoAnonymousFunctions, []},
{Credo.Check.Readability.PredicateFunctionNames, []},
{Credo.Check.Readability.PreferImplicitTry, []},
{Credo.Check.Readability.RedundantBlankLines, []},
{Credo.Check.Readability.Semicolons, []},
{Credo.Check.Readability.SpaceAfterCommas, []},
{Credo.Check.Readability.StringSigils, []},
{Credo.Check.Readability.TrailingBlankLine, []},
{Credo.Check.Readability.TrailingWhiteSpace, []},
{Credo.Check.Readability.UnnecessaryAliasExpansion, []},
{Credo.Check.Readability.VariableNames, []},
{Credo.Check.Readability.WithSingleClause, []},
#
## Refactoring Opportunities
#
{Credo.Check.Refactor.Apply, []},
{Credo.Check.Refactor.CondStatements, []},
{Credo.Check.Refactor.CyclomaticComplexity, false},
{Credo.Check.Refactor.FunctionArity, []},
{Credo.Check.Refactor.LongQuoteBlocks, []},
{Credo.Check.Refactor.MatchInCondition, []},
{Credo.Check.Refactor.MapJoin, []},
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
{Credo.Check.Refactor.NegatedConditionsWithElse, false},
{Credo.Check.Refactor.Nesting, []},
{Credo.Check.Refactor.UnlessWithElse, []},
{Credo.Check.Refactor.WithClauses, []},
{Credo.Check.Refactor.FilterFilter, []},
{Credo.Check.Refactor.RejectReject, []},
{Credo.Check.Refactor.RedundantWithClauseResult, []},
#
## Warnings
#
{Credo.Check.Warning.ApplicationConfigInModuleAttribute, []},
{Credo.Check.Warning.BoolOperationOnSameValues, []},
{Credo.Check.Warning.ExpensiveEmptyEnumCheck, []},
{Credo.Check.Warning.IExPry, []},
{Credo.Check.Warning.IoInspect, []},
{Credo.Check.Warning.OperationOnSameValues, []},
{Credo.Check.Warning.OperationWithConstantResult, []},
{Credo.Check.Warning.RaiseInsideRescue, []},
{Credo.Check.Warning.SpecWithStruct, []},
{Credo.Check.Warning.WrongTestFileExtension, []},
{Credo.Check.Warning.UnusedEnumOperation, []},
{Credo.Check.Warning.UnusedFileOperation, []},
{Credo.Check.Warning.UnusedKeywordOperation, []},
{Credo.Check.Warning.UnusedListOperation, []},
{Credo.Check.Warning.UnusedPathOperation, []},
{Credo.Check.Warning.UnusedRegexOperation, []},
{Credo.Check.Warning.UnusedStringOperation, []},
{Credo.Check.Warning.UnusedTupleOperation, []},
{Credo.Check.Warning.UnsafeExec, []}
],
disabled: [
#
# Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`)
#
# Controversial and experimental checks (opt-in, just move the check to `:enabled`
# and be sure to use `mix credo --strict` to see low priority checks)
#
{Credo.Check.Consistency.MultiAliasImportRequireUse, []},
{Credo.Check.Consistency.UnusedVariableNames, []},
{Credo.Check.Design.DuplicatedCode, []},
{Credo.Check.Design.SkipTestWithoutComment, []},
{Credo.Check.Readability.AliasAs, []},
{Credo.Check.Readability.BlockPipe, []},
{Credo.Check.Readability.ImplTrue, []},
{Credo.Check.Readability.MultiAlias, []},
{Credo.Check.Readability.NestedFunctionCalls, []},
{Credo.Check.Readability.SeparateAliasRequire, []},
{Credo.Check.Readability.SingleFunctionToBlockPipe, []},
{Credo.Check.Readability.SinglePipe, []},
{Credo.Check.Readability.Specs, []},
{Credo.Check.Readability.StrictModuleLayout, []},
{Credo.Check.Readability.WithCustomTaggedTuple, []},
{Credo.Check.Refactor.ABCSize, []},
{Credo.Check.Refactor.AppendSingleItem, []},
{Credo.Check.Refactor.DoubleBooleanNegation, []},
{Credo.Check.Refactor.FilterReject, []},
{Credo.Check.Refactor.IoPuts, []},
{Credo.Check.Refactor.MapMap, []},
{Credo.Check.Refactor.ModuleDependencies, []},
{Credo.Check.Refactor.NegatedIsNil, []},
{Credo.Check.Refactor.PipeChainStart, []},
{Credo.Check.Refactor.RejectFilter, []},
{Credo.Check.Refactor.VariableRebinding, []},
{Credo.Check.Warning.LazyLogging, []},
{Credo.Check.Warning.LeakyEnvironment, []},
{Credo.Check.Warning.MapGetUnsafePass, []},
{Credo.Check.Warning.MixEnv, []},
{Credo.Check.Warning.UnsafeToAtom, []}
# {Credo.Check.Refactor.MapInto, []},
#
# Custom checks can be created using `mix credo.gen.check`.
#
]
}
}
]
}

@ -0,0 +1,73 @@
# This file excludes paths from the Docker build context.
#
# By default, Docker's build context includes all files (and folders) in the
# current directory. Even if a file isn't copied into the container it is still sent to
# the Docker daemon.
#
# There are multiple reasons to exclude files from the build context:
#
# 1. Prevent nested folders from being copied into the container (ex: exclude
# /assets/node_modules when copying /assets)
# 2. Reduce the size of the build context and improve build time (ex. /build, /deps, /doc)
# 3. Avoid sending files containing sensitive information
#
# More information on using .dockerignore is available here:
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
.dockerignore
# Ignore git, but keep git HEAD and refs to access current commit hash if needed:
#
# $ cat .git/HEAD | awk '{print ".git/"$2}' | xargs cat
# d0b8727759e1e0e7aa3d41707d12376e373d5ecc
.git
!.git/HEAD
!.git/refs
# Common development/test artifacts
/cover/
/doc/
/test/
/tmp/
.elixir_ls
plausible-report.xml
.env
.idea
*.iml
*.log
*.code-workspace
.vscode
# Mix artifacts
/_build/
/deps/
*.ez
# Generated on crash by the VM
erl_crash.dump
# If NPM crashes, it generates a log, let's ignore it too.
npm-debug.log
# Static artifacts - These should be fetched and built inside the Docker image
/assets/node_modules/
/tracker/node_modules/
/priv/static/cache_manifest.json
/priv/static/css
/priv/static/js
/priv/version.json
# Auto-generated tracker files
/priv/tracker/js/*.js
# Dializer
/priv/plts/*.plt
/priv/plts/*.plt.hash
# Geolocation databases
/priv/geodb/*.mmdb
/priv/geodb/*.mmdb.gz
# Docker volumes
.clickhouse_db_vol*
plausible_db*

@ -1,5 +1,6 @@
[
import_deps: [:ecto, :phoenix],
inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"],
subdirectories: ["priv/*/migrations"]
plugins: [Phoenix.LiveView.HTMLFormatter],
import_deps: [:ecto, :ecto_sql, :phoenix],
subdirectories: ["priv/*/migrations"],
inputs: ["*.{heex,ex,exs}", "{config,lib,test,extra}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"]
]

@ -10,7 +10,7 @@ body:
[Our docs](https://plausible.io/docs) are a great place for most answers, but if you can’t find your answer there, you can [contact our customer support](https://plausible.io/contact).
Have a feature request? Please search the ideas [on our forum](https://github.com/plausible/analytics/discussions/categories/feature-requests) to make sure that the feature has not yet been requested. If you cannot find what you had in mind, please [submit your feature request here](https://github.com/plausible/analytics/discussions/new).
Have a feature request? Please check our [feedback board](https://feedback.plausible.io).
Have an issue with your self-hosted install? Self-hosted is community supported and you can ask in [our self-hosted forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support).

@ -4,8 +4,8 @@ contact_links:
url: https://github.com/plausible/analytics/discussions/categories/self-hosted-support
about: Please use the self-hosted community forum for any self-hosted issues and questions
- name: 💡 Feature requests and ideas
url: https://github.com/plausible/analytics/discussions/categories/feature-requests
about: Please vote for and post new feature ideas in the community forum
url: https://feedback.plausible.io
about: Please vote for and post new feature ideas on our feedback board
- name: 📖 Documentation
url: https://plausible.io/docs
about: A great place to find instructions and answers on how to get the most out of your Plausible experience

@ -20,3 +20,7 @@ updates:
schedule:
interval: "daily"
open-pull-requests-limit: 1
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"

@ -0,0 +1,67 @@
name: Build Private Images GHCR
on:
push:
branches: [master, stable]
tags: ['r*']
pull_request:
types: [synchronize, labeled]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
if: ${{ github.event_name == 'push' || contains(github.event.pull_request.labels.*.name, 'deploy-to-staging') }}
runs-on: buildjet-16vcpu-ubuntu-2204
permissions:
contents: read
packages: write
steps:
- name: Docker meta
id: meta
uses: docker/metadata-action@v5.0.0
with:
images: ghcr.io/plausible/analytics/ee
tags: |
type=ref,event=pr
type=ref,event=branch
type=ref,event=tag
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v5
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
MIX_ENV=prod
BUILD_METADATA=${{ steps.meta.outputs.json }}
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
- name: Notify team on failure
if: ${{ failure() }}
uses: fjogeleit/http-request-action@v1
with:
url: ${{ secrets.BUILD_NOTIFICATION_URL }}
method: 'POST'
customHeaders: '{"Content-Type": "application/json"}'
data: '{"content": "<a href=\"https://github.com/plausible/analytics/actions/workflows/build-private-images.yml\">Build failed</a>"}'

@ -5,18 +5,21 @@ on:
branches: [master, stable]
tags: ['r*']
pull_request:
branches: [master]
types: [synchronize, labeled]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
if: ${{ github.event_name == 'push' || contains(github.event.pull_request.labels.*.name, 'deploy-to-staging') }}
runs-on: buildjet-4vcpu-ubuntu-2004
runs-on: buildjet-16vcpu-ubuntu-2204
steps:
- name: Docker meta
id: meta
uses: docker/metadata-action@v4
uses: docker/metadata-action@v5.0.0
with:
images: plausible/analytics-private
tags: |
@ -25,17 +28,17 @@ jobs:
type=ref,event=tag
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
uses: docker/build-push-action@v5
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
@ -43,6 +46,7 @@ jobs:
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
MIX_ENV=prod
BUILD_METADATA=${{ steps.meta.outputs.json }}
- name: Image digest

@ -0,0 +1,68 @@
name: Build Public Images GHCR
on:
push:
tags: ['v*']
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
runs-on: buildjet-16vcpu-ubuntu-2204
permissions:
contents: read
packages: write
steps:
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/plausible/community-edition
tags: |
type=semver,pattern={{version}},prefix=v
type=semver,pattern={{major}}.{{minor}},prefix=v
type=semver,pattern={{major}},prefix=v
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v5
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64, linux/arm64
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
MIX_ENV=small
BUILD_METADATA=${{ steps.meta.outputs.json }}
ERL_FLAGS=+JPperf true
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
- name: Notify team on failure
if: ${{ failure() }}
uses: fjogeleit/http-request-action@v1
with:
url: ${{ secrets.BUILD_NOTIFICATION_URL }}
method: 'POST'
customHeaders: '{"Content-Type": "application/json"}'
data: '{"content": "<a href=\"https://github.com/plausible/analytics/actions/workflows/build-public-images.yml\">Build failed</a>"}'

@ -4,36 +4,40 @@ on:
push:
tags: ['v*']
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
runs-on: buildjet-4vcpu-ubuntu-2004
runs-on: buildjet-16vcpu-ubuntu-2204
steps:
- name: Docker meta
id: meta
uses: docker/metadata-action@v4
uses: docker/metadata-action@v5
with:
images: plausible/analytics
images: plausible/community-edition
tags: |
type=semver,pattern={{version}},prefix=v
type=semver,pattern={{major}}.{{minor}},prefix=v
type=semver,pattern={{major}},prefix=v
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
uses: docker/build-push-action@v5
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
@ -42,7 +46,9 @@ jobs:
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
MIX_ENV=small
BUILD_METADATA=${{ steps.meta.outputs.json }}
ERL_FLAGS=+JMsingle true
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}

@ -1,23 +1,42 @@
name: Elixir CI
on:
push:
branches: [master, stable]
pull_request:
push:
branches: [master, stable]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
CACHE_VERSION: v7
PERSISTENT_CACHE_DIR: cached
jobs:
build:
name: Build and test
runs-on: buildjet-4vcpu-ubuntu-2004
name: "Build and test (${{ matrix.mix_env }}, ${{ matrix.postgres_image }}${{ matrix.test_experimental_reduced_joins == '1' && ', experimental_reduced_joins' || '' }})"
runs-on: ubuntu-latest
strategy:
matrix:
postgres_version: [12, 13, 14]
mix_env: ['test', 'small_test']
postgres_image: ['postgres:16']
test_experimental_reduced_joins: ['0']
include:
- mix_env: 'test'
postgres_image: 'postgres:15'
test_experimental_reduced_joins: '0'
- mix_env: 'test'
postgres_image: 'postgres:16'
test_experimental_reduced_joins: '1'
env:
MIX_ENV: ${{ matrix.mix_env }}
TEST_EXPERIMENTAL_REDUCED_JOINS: ${{ matrix.test_experimental_reduced_joins }}
services:
postgres:
image: postgres:${{ matrix.postgres_version }}
image: ${{ matrix.postgres_image }}
ports:
- 5432:5432
env:
@ -27,9 +46,8 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
clickhouse:
image: clickhouse/clickhouse-server:22.8.13.20-alpine
image: clickhouse/clickhouse-server:23.3.7.5-alpine
ports:
- 8123:8123
env:
@ -38,41 +56,91 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: marocchino/tool-versions-action@v1
id: versions
- uses: erlef/setup-beam@v1
with:
elixir-version: ${{ steps.versions.outputs.elixir }}
otp-version: ${{ steps.versions.outputs.erlang }}
- uses: actions/cache@v4
with:
path: |
deps
_build
tracker/node_modules
priv/tracker/js
${{ env.PERSISTENT_CACHE_DIR }}
key: ${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-${{ hashFiles('**/mix.lock') }}
restore-keys: |
${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-
${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-refs/heads/master-
- name: Check for changes in tracker/**
uses: dorny/paths-filter@v3
id: changes
with:
filters: |
tracker:
- 'tracker/**'
- name: Check if priv/tracker/js/plausible.js exists
run: |
if [ -f priv/tracker/js/plausible.js ]; then
echo "HAS_BUILT_TRACKER=true" >> $GITHUB_ENV
else
echo "HAS_BUILT_TRACKER=false" >> $GITHUB_ENV
fi
- run: npm install --prefix ./tracker
if: steps.changes.outputs.tracker == 'true' || env.HAS_BUILT_TRACKER == 'false'
- run: npm run deploy --prefix ./tracker
if: steps.changes.outputs.tracker == 'true' || env.HAS_BUILT_TRACKER == 'false'
- run: mix deps.get --only $MIX_ENV
- run: mix compile --warnings-as-errors --all-warnings
- run: mix do ecto.create, ecto.migrate
- run: mix run -e "Tzdata.ReleaseUpdater.poll_for_update"
- run: mix test --include slow --include minio --max-failures 1 --warnings-as-errors
if: env.MIX_ENV == 'test'
- run: mix test --include slow --max-failures 1 --warnings-as-errors
if: env.MIX_ENV == 'small_test'
static:
name: Static checks (format, credo, dialyzer)
env:
MIX_ENV: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Read .tool-versions
uses: marocchino/tool-versions-action@v1
- uses: marocchino/tool-versions-action@v1
id: versions
- name: Set up Elixir
uses: erlef/setup-beam@v1
- uses: erlef/setup-beam@v1
with:
elixir-version: ${{steps.versions.outputs.elixir}}
otp-version: ${{ steps.versions.outputs.erlang}}
- name: Restore dependencies cache
uses: actions/cache@v2
elixir-version: ${{ steps.versions.outputs.elixir }}
otp-version: ${{ steps.versions.outputs.erlang }}
- uses: actions/cache@v4
with:
path: |
deps
_build
priv/plts
key: ${{ runner.os }}-mix-v3-${{ hashFiles('**/mix.lock') }}
restore-keys: ${{ runner.os }}-mix-v3-
- name: Install dependencies
run: mix deps.get && npm install --prefix ./tracker
- name: Check Formatting
run: mix format --check-formatted
- name: Check Compile Warnings
run: mix compile --warnings-as-errors --all-warnings
- name: Generate tracker files
run: npm run deploy --prefix ./tracker
- name: Check Credo Warnings
run: mix credo diff --from-git-merge-base origin/master
- name: Run tests
run: mix test --include slow --max-failures 1 --warnings-as-errors
- name: Check Dialyzer
run: mix dialyzer
env:
MIX_ENV: test
key: static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-${{ hashFiles('**/mix.lock') }}
restore-keys: |
static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-
static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-refs/heads/master-
- run: mix deps.get
- run: mix compile --warnings-as-errors --all-warnings
- run: mix format --check-formatted
- run: mix deps.unlock --check-unused
- run: mix credo diff --from-git-merge-base origin/master
- run: mix dialyzer

@ -0,0 +1,28 @@
name: Validate migrations
on:
pull_request:
paths:
- 'priv/repo/migrations/**'
- 'priv/ingest_repo/migrations/**'
jobs:
validate:
name: App code does not change at the same time
runs-on: ubuntu-latest
steps:
- uses: dorny/paths-filter@v3
id: changes
with:
list-files: json
filters: |
lib:
- 'lib/**'
- 'extra/**'
- 'config/**'
- if: steps.changes.outputs.lib == 'true'
run: |
echo "::error file=${{ fromJSON(steps.changes.outputs.lib_files)[0] }}::Code and migrations shouldn't be changed at the same time"
exit 1

@ -4,7 +4,10 @@ on:
push:
branches: [master, stable]
pull_request:
branches: [master, stable]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
@ -12,22 +15,16 @@ jobs:
runs-on: buildjet-4vcpu-ubuntu-2004
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Read .tool-versions
uses: marocchino/tool-versions-action@v1
id: versions
- name: Set up Node
uses: actions/setup-node@v2
uses: actions/setup-node@v4
with:
node-version: ${{steps.versions.outputs.nodejs}}
- run: npm install --prefix ./assets
- run: npm install --prefix ./tracker
- run: npm run lint --prefix ./assets
- run: npm run check-format --prefix ./assets
- run: npm run deploy --prefix ./assets
- run: npm run deploy --prefix ./tracker
- name: Run BundleMon
run: npm run bundlemon --prefix ./assets
env:
BUNDLEMON_PROJECT_ID: "619e0b6ad4a54a00089861ac"
CI_COMMIT_SHA: ${{github.event.pull_request.head.sha || github.sha}} # important!

@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Read .tool-versions
uses: marocchino/tool-versions-action@v1
@ -35,7 +35,7 @@ jobs:
otp-version: ${{ steps.versions.outputs.erlang}}
- name: Restore Elixir dependencies cache
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: |
deps

@ -4,14 +4,16 @@ on:
push:
branches:
- master
paths:
- 'test/e2e/**.tf'
paths:
- 'test/e2e/**.tf'
pull_request:
branches:
- master
paths:
- 'test/e2e/**.tf'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
jobs:
terraform:
concurrency: terraform_checkly
@ -25,10 +27,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
uses: hashicorp/setup-terraform@v3
with:
cli_config_credentials_token: ${{ secrets.TF_CLOUD_CHECKLY_API_TOKEN }}
@ -39,7 +41,7 @@ jobs:
- name: Terraform Init
id: init
run: terraform init
- name: Terraform Validate
id: validate
run: terraform validate -no-color
@ -50,7 +52,7 @@ jobs:
run: terraform plan -no-color
continue-on-error: true
- uses: actions/github-script@v6
- uses: actions/github-script@v7
if: github.event_name == 'pull_request'
env:
PLAN: "terraform\n${{ steps.plan.outputs.stdout }}"

@ -6,13 +6,17 @@ on:
paths:
- 'tracker/**'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
timeout-minutes: 15
runs-on: buildjet-4vcpu-ubuntu-2004
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 16
- name: Install dependencies

11
.gitignore vendored

@ -19,6 +19,9 @@ erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Temporary files, for example, from tests.
/tmp/
# Ignore package tarball (built via "mix hex.build").
plausible-*.tar
@ -35,7 +38,8 @@ npm-debug.log
# Since we are building assets from assets/,
# we ignore priv/static. You may want to comment
# this depending on your deployment strategy.
/priv/static/
/priv/static/css
/priv/static/js
/priv/version.json
# Files matching config/*.secret.exs pattern contain sensitive
@ -54,6 +58,7 @@ plausible-report.xml
*.iml
*.log
*.code-workspace
.vscode
# Dializer
/priv/plts/*.plt
@ -67,3 +72,7 @@ plausible-report.xml
# Auto-generated tracker files
/priv/tracker/js/*.js
# Docker volumes
.clickhouse_db_vol*
plausible_db*

@ -0,0 +1,19 @@
alias Plausible.{Repo, ClickhouseRepo, IngestRepo}
alias Plausible.{Site, Sites, Goal, Goals, Stats}
import_if_available(Ecto.Query)
import_if_available(Plausible.Factory)
Logger.configure(level: :warning)
IO.puts(
IO.ANSI.cyan() <>
~S[
.*$$$$$$s.
*$$$$$$$$$$$,
:$$SSS#######S *$$$$/. $$ ** $$ l$:
,$$SSS#######. $$ ,$:$$ $$$$$ .S* $: $$@$* $% $$$$@s :$: s$@$s
.**$$$#####` $@$$$$' $l s-' $:.@* $| '$@s. $% $$ \$ :$:,$$ *$:
,***/` #$ `$$ %$$%$$ *$$$#`.*sss$ $% $#$$$' %$ *$sss,
,$$'] <> IO.ANSI.reset() <> "\n\n"
)

@ -1,4 +1,3 @@
erlang 25.2.3
elixir 1.14.3-otp-25
nodejs 16.3.0
python 3.9.12
erlang 26.2.1
elixir 1.16.0-otp-26
nodejs 21.0.0

@ -1,14 +1,104 @@
# Changelog
All notable changes to this project will be documented in this file.
## Unreleased
### Added
- Pages Block List in Site Settings
- Add `conversion_rate` to Stats API Timeseries and on the main graph
- Add `total_conversions` and `conversion_rate` to `visitors.csv` in a goal-filtered CSV export
- Ability to display total conversions (with a goal filter) on the main graph
- Add `conversion_rate` to Stats API Timeseries and on the main graph
- Add `time_on_page` metric into the Stats API
- County Block List in Site Settings
- Query the `views_per_visit` metric based on imported data as well if possible
- Group `operating_system_versions` by `operating_system` in Stats API breakdown
- Add `operating_system_versions.csv` into the CSV export
- Display `Total visitors`, `Conversions`, and `CR` in the "Details" views of Countries, Regions and Cities (when filtering by a goal)
- Add `conversion_rate` to Regions and Cities reports (when filtering by a goal)
- Add the `conversion_rate` metric to Stats API Breakdown and Aggregate endpoints
- IP Block List in Site Settings
- Allow filtering with `contains`/`matches` operator for Sources, Browsers and Operating Systems.
- Allow filtering by multiple custom properties
- Wildcard and member filtering on the Stats API `event:goal` property
- Allow filtering with `contains`/`matches` operator for custom properties
- Add `referrers.csv` to CSV export
- Add a new Properties section in the dashboard to break down by custom properties
- Add `custom_props.csv` to CSV export (almost the same as the old `prop_breakdown.csv`, but has different column headers, and includes props for pageviews too, not only custom events)
- Add `referrers.csv` to CSV export
- Improve password validation in registration and password reset forms
- Adds Gravatar profile image to navbar
- Enforce email reverification on update
- Add Plugins API Tokens provisioning UI
- Add searching sites by domain in /sites view
- Add last 24h plots to /sites view
- Add site pinning to /sites view
- Add support for JSON logger, via LOG_FORMAT=json environment variable
- Add support for 2FA authentication
- Add 'browser_versions.csv' to CSV export
- Add `CLICKHOUSE_MAX_BUFFER_SIZE_BYTES` env var which defaults to `100000` (100KB)
- Add alternative SMTP adapter plausible/analytics#3654
- Add `EXTRA_CONFIG_PATH` env var to specify extra Elixir config plausible/analytics#3906
- Add restrictive `robots.txt` for self-hosted plausible/analytics#3905
### Removed
- Removed the nested custom event property breakdown UI when filtering by a goal in Goal Conversions
- Removed the `prop_names` returned in the Stats API `event:goal` breakdown response
- Removed the `prop-breakdown.csv` file from CSV export
- Deprecated `CLICKHOUSE_MAX_BUFFER_SIZE`
- Removed `/app/init-admin.sh` that was deprecated in v2.0.0 plausible/analytics#3903
- Remove `DISABLE_AUTH` deprecation warning plausible/analytics#3904
### Changed
- A visits `entry_page` and `exit_page` is only set and updated for pageviews, not custom events
- Limit the number of Goal Conversions shown on the dashboard and render a "Details" link when there are more entries to show
- Show Outbound Links / File Downloads / 404 Pages / Cloaked Links instead of Goal Conversions when filtering by the corresponding goal
- Require custom properties to be explicitly added from Site Settings > Custom Properties in order for them to show up on the dashboard
- GA/SC sections moved to new settings: Integrations
- Replace `CLICKHOUSE_MAX_BUFFER_SIZE` with `CLICKHOUSE_MAX_BUFFER_SIZE_BYTES`
- Validate metric isn't queried multiple times
### Fixed
- Creating many sites no longer leads to cookie overflow
- Ignore sessions without pageviews for `entry_page` and `exit_page` breakdowns
- Using `VersionedCollapsingMergeTree` to store visit data to avoid rare race conditions that led to wrong visit data being shown
- Fix `conversion_rate` metric in a `browser_versions` breakdown
- Calculate `conversion_rate` percentage change in the same way like `bounce_rate` (subtraction instead of division)
- Calculate `bounce_rate` percentage change in the Stats API in the same way as it's done in the dashboard
- Stop returning custom events in goal breakdown with a pageview goal filter and vice versa
- Only return `(none)` values in custom property breakdown for the first page (pagination) of results
- Fixed weekly/monthly e-mail report [rendering issues](https://github.com/plausible/analytics/issues/284)
- Fix [broken interval selection](https://github.com/plausible/analytics/issues/2982) in the all time view plausible/analytics#3110
- Fixed [IPv6 problems](https://github.com/plausible/analytics/issues/3173) in data migration plausible/analytics#3179
- Fixed [long URLs display](https://github.com/plausible/analytics/issues/3158) in Outbound Link breakdown view
- Fixed [Sentry reports](https://github.com/plausible/analytics/discussions/3166) for ingestion requests plausible/analytics#3182
- Fix breakdown pagination bug in the dashboard details view when filtering by goals
- Update bot detection (matomo 6.1.4, ua_inspector 3.4.0)
- Improved the Goal Settings page (search, autcompletion etc.)
- Log mailer errors plausible/analytics#3336
- Allow custom event timeseries in stats API plausible/analytics#3505
- Fixes for sites with UTF characters in domain plausible/analytics#3560
- Fix crash when using special characters in filter plausible/analytics#3634
- Fix automatic scrolling to the bottom on the dashboard if previously selected properties tab plausible/analytics#3872
- Allow running the container with arbitrary UID plausible/analytics#2986
- Fix `width=manual` in embedded dashboards plausible/analytics#3910
- Fix URL escaping when pipes are used in UTM tags plausible/analytics#3930
## v2.0.0 - 2023-07-12
### Added
- Call to action for tracking Goal Conversions and an option to hide the section from the dashboard
- Add support for `with_imported=true` in Stats API aggregate endpoint
- Ability to use '--' instead of '=' sign in the `tagged-events` classnames
- 'Last updated X seconds ago' info to 'current visitors' tooltips
- Add support for more Bamboo adapters, i.e. `Bamboo.MailgunAdapter`, `Bamboo.MandrillAdapter`, `Bamboo.SendGridAdapter` plausible/analytics#2649
- Ability to change domain for existing site (requires numeric IDs data migration, instructions will be provided separately) UI + API (`PUT /api/v1/sites`)
- Add `LOG_FAILED_LOGIN_ATTEMPTS` environment variable to enable failed login attempts logs plausible/analytics#2936
- Add `MAILER_NAME` environment variable support plausible/analytics#2937
- Add `MAILGUN_BASE_URI` support for `Bamboo.MailgunAdapter` plausible/analytics#2935
- Add a landing page for self-hosters plausible/analytics#2989
- Allow optional IPv6 for clickhouse repo plausible/analytics#2970
### Fixed
- Fix tracker bug - call callback function even when event is ignored
- Make goal-filtered CSV export return only unique_conversions timeseries in the 'visitors.csv' file
- Stop treating page filter as an entry page filter
- City report showing N/A instead of city names with imported data plausible/analytics#2675
@ -22,18 +112,25 @@ All notable changes to this project will be documented in this file.
- Add error message in case a transfer to an invited (but not joined) user is requested plausible/analytics#2651
- Fix bug with [showing property breakdown with a prop filter](https://github.com/plausible/analytics/issues/1789)
- Fix bug when combining goal and prop filters plausible/analytics#2654
- Fix broken favicons when domain includes a slash
- Fix bug when using multiple [wildcard goal filters](https://github.com/plausible/analytics/pull/3015)
- Fix a bug where realtime would fail with imported data
- Fix a bug where the country name was not shown when [filtering through the map](https://github.com/plausible/analytics/issues/3086)
### Changed
- Treat page filter as entry page filter for `bounce_rate`
- Reject events with long URIs and data URIs plausible/analytics#2536
- Always show direct traffic in sources reports plausible/analytics#2531
- Stop recording XX and T1 country codes plausible/analytics#2556
- Device type is now determined from the User-Agent instead of window.innerWidth plausible/analytics#2711
- Add padding by default to embedded dashboards so that shadows are not cut off plausible/analytics#2744
- Update the User Agents database (https://github.com/matomo-org/device-detector/releases/tag/6.1.1)
- Disable registration in self-hosted setups by default plausible/analytics#3014
### Removed
- Remove Firewall plug and `IP_BLOCKLIST` environment variable
- Remove the ability to collapse the main graph plausible/analytics#2627
- Remove `custom_dimension_filter` feature flag plausible/analytics#2996
## v1.5.1 - 2022-12-06

@ -18,8 +18,9 @@ Make sure Docker, Elixir, Erlang and Node.js are all installed on your developme
4. Run `mix run priv/repo/seeds.exs` to seed the database. Check the [Seeds](#Seeds) section for more.
5. Run `npm ci --prefix assets` to install the required client-side dependencies.
6. Run `npm ci --prefix tracker` to install the required tracker dependencies.
7. Run `npm run deploy --prefix tracker` to generate tracker files in `priv/tracker/js`
8. Run `mix download_country_database` to fetch geolocation database
7. Run `mix assets.setup` to install Tailwind and Esbuild
8. Run `npm run deploy --prefix tracker` to generate tracker files in `priv/tracker/js`
9. Run `mix download_country_database` to fetch geolocation database
3. Run `make server` or `mix phx.server` to start the Phoenix server.
4. The system is now available on `localhost:8000`.

@ -2,20 +2,26 @@
# platform specific, it makes sense to build it in the docker
#### Builder
FROM hexpm/elixir:1.14.3-erlang-25.2.3-alpine-3.17.0 as buildcontainer
FROM hexpm/elixir:1.16.0-erlang-26.2.1-alpine-3.18.4 as buildcontainer
ARG MIX_ENV=small
# preparation
ENV MIX_ENV=prod
ENV MIX_ENV=$MIX_ENV
ENV NODE_ENV=production
ENV NODE_OPTIONS=--openssl-legacy-provider
# custom ERL_FLAGS are passed for (public) multi-platform builds
# to fix qemu segfault, more info: https://github.com/erlang/otp/pull/6340
ARG ERL_FLAGS
ENV ERL_FLAGS=$ERL_FLAGS
RUN mkdir /app
WORKDIR /app
# install build dependencies
RUN apk add --no-cache git nodejs yarn python3 npm ca-certificates wget gnupg make gcc libc-dev && \
npm install npm@latest -g && \
npm install -g webpack
npm install npm@latest -g
COPY mix.exs ./
COPY mix.lock ./
@ -35,38 +41,37 @@ COPY assets ./assets
COPY tracker ./tracker
COPY priv ./priv
COPY lib ./lib
COPY extra ./extra
RUN npm run deploy --prefix ./assets && \
npm run deploy --prefix ./tracker && \
RUN npm run deploy --prefix ./tracker && \
mix assets.deploy && \
mix phx.digest priv/static && \
mix download_country_database && \
# https://hexdocs.pm/sentry/Sentry.Sources.html#module-source-code-storage
mix sentry_recompile
mix sentry.package_source_code
WORKDIR /app
COPY rel rel
RUN mix release plausible
# Main Docker Image
FROM alpine:3.17.0@sha256:c0d488a800e4127c334ad20d61d7bc21b4097540327217dfab52262adc02380c
FROM alpine:3.18.4
LABEL maintainer="plausible.io <hello@plausible.io>"
ARG BUILD_METADATA={}
ENV BUILD_METADATA=$BUILD_METADATA
ENV LANG=C.UTF-8
ARG MIX_ENV=small
ENV MIX_ENV=$MIX_ENV
RUN apk upgrade --no-cache
RUN adduser -S -H -u 999 -G nogroup plausible -g 'Plausible Analytics'
RUN apk upgrade --no-cache
RUN apk add --no-cache openssl ncurses libstdc++ libgcc ca-certificates
COPY ./rel/docker-entrypoint.sh /entrypoint.sh
RUN chmod a+x /entrypoint.sh && \
adduser -h /app -u 1000 -s /bin/sh -D plausibleuser
COPY --from=buildcontainer --chmod=a+rX /app/_build/${MIX_ENV}/rel/plausible /app
COPY --chmod=755 ./rel/docker-entrypoint.sh /entrypoint.sh
COPY --from=buildcontainer /app/_build/prod/rel/plausible /app
RUN chown -R plausibleuser:plausibleuser /app
USER plausibleuser
USER 999
WORKDIR /app
ENV LISTEN_IP=0.0.0.0
ENTRYPOINT ["/entrypoint.sh"]

@ -15,13 +15,13 @@ install: ## Run the initial setup
server: ## Start the web server
mix phx.server
CH_FLAGS ?= --detach -p 8123:8123 --ulimit nofile=262144:262144 --name plausible_clickhouse
CH_FLAGS ?= --detach -p 8123:8123 -p 9000:9000 --ulimit nofile=262144:262144 --name plausible_clickhouse
clickhouse: ## Start a container with a recent version of clickhouse
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol:/var/lib/clickhouse clickhouse/clickhouse-server:22.9-alpine
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol:/var/lib/clickhouse clickhouse/clickhouse-server:latest-alpine
clickhouse-prod: ## Start a container with the same version of clickhouse as the one in prod
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol_prod:/var/lib/clickhouse clickhouse/clickhouse-server:22.8.13.20-alpine
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol_prod:/var/lib/clickhouse clickhouse/clickhouse-server:23.3.7.5-alpine
clickhouse-stop: ## Stop and remove the clickhouse container
docker stop plausible_clickhouse && docker rm plausible_clickhouse
@ -29,10 +29,19 @@ clickhouse-stop: ## Stop and remove the clickhouse container
PG_FLAGS ?= --detach -e POSTGRES_PASSWORD="postgres" -p 5432:5432 --name plausible_db
postgres: ## Start a container with a recent version of postgres
docker run $(PG_FLAGS) --volume=plausible_db:/var/lib/postgresql/data postgres:14-alpine
docker run $(PG_FLAGS) --volume=plausible_db:/var/lib/postgresql/data postgres:latest
postgres-prod: ## Start a container with the same version of postgres as the one in prod
docker run $(PG_FLAGS) --volume=plausible_db_prod:/var/lib/postgresql/data postgres:12
docker run $(PG_FLAGS) --volume=plausible_db_prod:/var/lib/postgresql/data postgres:15
postgres-stop: ## Stop and remove the postgres container
docker stop plausible_db && docker rm plausible_db
minio: ## Start a transient container with a recent version of minio (s3)
docker run -d --rm -p 10000:10000 -p 10001:10001 --name plausible_minio minio/minio server /data --address ":10000" --console-address ":10001"
while ! docker exec plausible_minio mc alias set local http://localhost:10000 minioadmin minioadmin; do sleep 1; done
docker exec plausible_minio mc mb local/dev-exports
docker exec plausible_minio mc mb local/dev-imports
minio-stop: ## Stop and remove the minio container
docker stop plausible_minio

@ -15,7 +15,7 @@
<br /><br />
</p>
[Plausible Analytics](https://plausible.io/) is a simple, lightweight (< 1 KB), open source and privacy-friendly alternative to Google Analytics. It doesn’t use cookies and is fully compliant with GDPR, CCPA and PECR. You can self-host or have us run Plausible for you in the cloud. Here's [the live demo of our own website stats](https://plausible.io/plausible.io). Made and hosted in the EU 🇪🇺
[Plausible Analytics](https://plausible.io/) is an easy to use, lightweight (< 1 KB), open source and privacy-friendly alternative to Google Analytics. It doesn’t use cookies and is fully compliant with GDPR, CCPA and PECR. You can self-host Plausible Community Edition or have us manage Plausible Analytics for you in the cloud. Here's [the live demo of our own website stats](https://plausible.io/plausible.io). Made and hosted in the EU 🇪🇺
We are dedicated to making web analytics more privacy-friendly. Our mission is to reduce corporate surveillance by providing an alternative web analytics tool which doesn’t come from the AdTech world. We are completely independent and solely funded by our subscribers.
@ -23,16 +23,17 @@ We are dedicated to making web analytics more privacy-friendly. Our mission is t
## Why Plausible?
Here's what makes Plausible a great Google Analytics alternative and why we're trusted by thousands of paying subscribers to deliver their website and business insights:
Here's what makes Plausible a great Google Analytics alternative and why we're trusted by 12,000+ paying subscribers to deliver their website and business insights:
- **Clutter Free**: Plausible Analytics provides [simple web analytics](https://plausible.io/simple-web-analytics) and it cuts through the noise. No layers of menus, no need for custom reports. Get all the important insights on one single page. No training necessary.
- **GDPR/CCPA/PECR compliant**: Measure traffic, not individuals. No personal data or IP addresses are ever stored in our database. We don't use cookies or any other persistent identifiers. [Read more about our data policy](https://plausible.io/data-policy)
- **Lightweight**: Plausible Analytics works by loading a script on your website, like Google Analytics. Our script is [45x smaller](https://plausible.io/lightweight-web-analytics), making your website quicker to load.
- **Lightweight**: Plausible Analytics works by loading a script on your website, like Google Analytics. Our script is [45x smaller](https://plausible.io/lightweight-web-analytics), making your website quicker to load. You can also send events directly to our [events API](https://plausible.io/docs/events-api).
- **Email or Slack reports**: Keep an eye on your traffic with weekly and/or monthly email or Slack reports. You can also get traffic spike notifications.
- **Open website stats**: You have the option to be transparent and open your web analytics to everyone. Your website stats are private by default but you can choose to make them public so anyone with your custom link can view them.
- **Define key goals and track conversions**: Set custom events or page URLs as your goals and see how they convert over time to understand and identify the trends that matter. Includes easy ways to track outbound link clicks and 404 error pages.
- **Invite team members and share stats**: You have the option to be transparent and open your web analytics to everyone. Your website stats are private by default but you can choose to make them public so anyone with your custom link can view them. You can [invite team members](https://plausible.io/docs/users-roles) and assign user roles too.
- **Define key goals and track conversions**: Create custom events with custom dimensions to track conversions and attribution to understand and identify the trends that matter. Includes easy ways to track outbound link clicks, file downloads and 404 error pages.
- **Search keywords**: Integrate your dashboard with Google Search Console to get the most accurate reporting on your search keywords.
- **SPA support**: Plausible is built with modern web frameworks in mind and it works automatically with any pushState based router on the frontend. We also support frameworks that use the URL hash for routing. See [our documentation](https://plausible.io/docs/hash-based-routing).
- **Smooth transition from Google Analytics**: There's a realtime dashboard, entry pages report and integration with Search Console. You can track your paid campaigns and conversions. You can invite team members. You can even [import your historical Google Analytics stats](https://plausible.io/docs/google-analytics-import). Learn how to [get the most out of your Plausible experience](https://plausible.io/docs/your-plausible-experience) and join thousands who have already migrated from Google Analytics.
Interested to learn more? [Read more on our website](https://plausible.io), learn more about the team and the goals of the project on [our about page](https://plausible.io/about) or explore [the documentation](https://plausible.io/docs).
@ -48,34 +49,32 @@ We choose the subscription business model rather than the business model of surv
## Getting started with Plausible
The easiest way to get started with Plausible is with [our official managed service in the cloud](https://plausible.io/#pricing). It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us.
The easiest way to get started with Plausible Analytics is with [our official managed service in the cloud](https://plausible.io/#pricing). It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us.
In order to be compliant with the GDPR and the Schrems II ruling, all visitor data for our managed service in the cloud is exclusively processed on servers and cloud infrastructure owned and operated by European providers. Your website data never leaves the EU.
Our managed hosting can save a substantial amount of developer time and resources. For most sites this ends up being the best value option and the revenue goes to funding the maintenance and further development of Plausible. So you’ll be supporting open source software and getting a great service!
### Can Plausible Analytics be self-hosted?
### Can Plausible be self-hosted?
Plausible is fully [open source web analytics](https://plausible.io/open-source-website-analytics) and we have a free as in beer [Plausible Analytics Self-Hosted](https://plausible.io/self-hosted-web-analytics) solution. It’s exactly the same product as our cloud solution with a less frequent release schedule (think of it as a long term support release).
Plausible is [open source web analytics](https://plausible.io/open-source-website-analytics) and we have a free as in beer and self-hosted solution called [Plausible Community Edition (CE)](https://plausible.io/self-hosted-web-analytics). Here are the differences between Plausible Analytics managed hosting in the cloud and the Plausible CE:
Bug fixes and new features are released to the cloud version several times per week. Features are battle-tested in the cloud which allows us to fix any bugs before the general self-hosted release. Every six months or so we combine all the changes into a new self-hosted release.
The main difference between the two is that the self-hosted version you have to install, host and manage yourself on your own infrastructure while the cloud version we manage everything for your ease and convenience. Here's the overview of all the differences:
| | Plausible Cloud | Self-Hosting |
| | Plausible Analytics Cloud | Plausible Community Edition |
| ------------- | ------------- | ------------- |
| Hosting | Easy and convenient. It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us. We manage everything so you don’t have to worry about anything and can focus on your stats. | You do it all yourself. You need to get a server and you need to manage your infrastructure. You are responsible for installation, maintenance, upgrades, server capacity, uptime, backup, security, stability, consistency, loading time and so on. |
| Storage | All visitor data is exclusively processed on EU-owned cloud infrastructure. We keep your site data on a secure, encrypted and green energy powered server in Germany. This ensures that your site data is protected by the strict European Union data privacy laws and ensures compliance with GDPR. Your website data never leaves the EU. | You have full control and can host your instance on any server in any country that you wish. Host it on a server in your basement or host it with any cloud provider wherever you want, even those that are not GDPR compliant. |
| Releases | Continuously developed and improved with new features and updates multiple times per week. | [It's a long term release](https://plausible.io/blog/building-open-source) published approximately twice per year so latest features won't be immediately available. You can see all the [currently unreleased features in the changelog](https://github.com/plausible/analytics/blob/master/CHANGELOG.md).|
| Raw data | You see all your site stats and metrics on our modern-looking, simple to use and fast loading dashboard. You can only see the stats aggregated in the dashboard. You can download the stats using the [CSV export](https://plausible.io/docs/export-stats), [stats API](https://plausible.io/docs/stats-api) or tools such as the [Data Studio Connector](https://plausible.io/docs/integration-guides#google-data-studio). | Do you want access to the raw data? Self-hosting gives you that option. You can take the data directly from the ClickHouse database. |
| Premium Support | Real support delivered by real human beings who build and maintain Plausible. | Premium support is not included. Self-hosting is community supported only. |
| Costs | There's a cost associated with providing an analytics service so we charge a subscription fee. We choose the subscription business model rather than the business model of surveillance capitalism. Your money funds further development of Plausible. | You need to pay for your server, CDN, backups and whatever other cost there is associated with running the infrastructure. You never have to pay any fees to us. Your money goes to 3rd party companies with no connection to us.|
| **Infrastructure management** | Easy and convenient. It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us. We manage everything so you don’t have to worry about anything and can focus on your stats. | You do it all yourself. You need to get a server and you need to manage your infrastructure. You are responsible for installation, maintenance, upgrades, server capacity, uptime, backup, security, stability, consistency, loading time and so on.|
| **Release schedule** | Continuously developed and improved with new features and updates multiple times per week. | [It's a long term release](https://plausible.io/blog/building-open-source) published twice per year so latest features and improvements won't be immediately available.|
| **Premium features** | All features available as listed in [our pricing plans](https://plausible.io/#pricing). | Selected premium features such as funnels and ecommerce revenue goals are not available as we aim to ensure a [protective barrier around our cloud offering](https://plausible.io/blog/community-edition).|
| **Bot filtering** | Advanced bot filtering for more accurate stats. Our algorithm detects and excludes non-human traffic patterns. We also exclude known bots by the User-Agent header and filter out traffic from data centers and referrer spam domains. | Basic bot filtering that targets the most common non-human traffic based on the User-Agent header and referrer spam domains.|
| **Server location** | All visitor data is exclusively processed on EU-owned cloud infrastructure. We keep your site data on a secure, encrypted and green energy powered server in Germany. This ensures that your site data is protected by the strict European Union data privacy laws and ensures compliance with GDPR. Your website data never leaves the EU. | You have full control and can host your instance on any server in any country that you wish. Host it on a server in your basement or host it with any cloud provider wherever you want, even those that are not GDPR compliant.|
| **Data portability** | You see all your site stats and metrics on our modern-looking, simple to use and fast loading dashboard. You can only see the stats aggregated in the dashboard. You can download the stats using the [CSV export](https://plausible.io/docs/export-stats), [stats API](https://plausible.io/docs/stats-api) or tools such as the [Data Studio Connector](https://plausible.io/docs/integration-guides#google-data-studio). | Do you want access to the raw data? Self-hosting gives you that option. You can take the data directly from the ClickHouse database. |
| **Premium support** | Real support delivered by real human beings who build and maintain Plausible. | Premium support is not included. CE is community supported only.|
| **Costs** | There's a cost associated with providing an analytics service so we charge a subscription fee. We choose the subscription business model rather than the business model of surveillance capitalism. Your money funds further development of Plausible. | You need to pay for your server, CDN, backups and whatever other cost there is associated with running the infrastructure. You never have to pay any fees to us. Your money goes to 3rd party companies with no connection to us.|
Interested in self-hosting Plausible on your server? Take a look at our [self-hosting installation instructions](https://plausible.io/docs/self-hosting).
Interested in self-hosting Plausible CE on your server? Take a look at our [Plausible CE installation instructions](https://github.com/plausible/community-edition/).
Plausible Self-Hosted is a community supported project and there are no guarantees that you will get support from the creators of Plausible to troubleshoot your self-hosting issues. There is a [community supported forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support) where you can ask for help.
Plausible CE is a community supported project and there are no guarantees that you will get support from the creators of Plausible to troubleshoot your self-hosting issues. There is a [community supported forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support) where you can ask for help.
Our only source of funding is our premium, managed service for running Plausible in the cloud. If you're looking for an alternative way to support the project, we've put together some sponsorship packages. If you choose to self-host Plausible you can [become a sponsor](https://github.com/sponsors/plausible) which is a great way to give back to the community and to contribute to the long-term sustainability of the project.
Our only source of funding is our premium, managed service for running Plausible in the cloud.
## Technology
@ -90,13 +89,14 @@ For anyone wishing to contribute to Plausible, we recommend taking a look at [ou
## Feedback & Roadmap
We welcome feedback from our community. We have a public roadmap driven by the features suggested by the community members. Take a look at our [feedback board](https://plausible.io/feedback) directly here on GitHub. Please let us know if you have any requests and vote on open issues so we can better prioritize.
We welcome feedback from our community. We have a public roadmap driven by the features suggested by the community members. Take a look at our [feedback board](https://plausible.io/feedback). Please let us know if you have any requests and vote on open issues so we can better prioritize.
To stay up to date with all the latest news and product updates, make sure to follow us on [X (formerly Twitter)](https://twitter.com/plausiblehq), [LinkedIn](https://www.linkedin.com/company/plausible-analytics/) or [Mastodon](https://fosstodon.org/@plausible).
To stay up to date with all the latest news and product updates, make sure to follow us on [Twitter](https://twitter.com/plausiblehq), [LinkedIn](https://www.linkedin.com/company/plausible-analytics/) or [Mastodon](https://fosstodon.org/@plausible).
## License & Trademarks
## License
Plausible CE is open source under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. You can [find it here](https://github.com/plausible/analytics/blob/master/LICENSE.md).
Plausible is open-source under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. You can [find it here](https://github.com/plausible/analytics/blob/master/LICENSE.md).
To avoid issues with AGPL virality, we've released the JavaScript tracker which gets included on your website under the MIT license. You can [find it here](https://github.com/plausible/analytics/blob/master/tracker/LICENSE.md).
The only exception is our JavaScript tracker which gets included on your website. To avoid issues with AGPL virality, we've
released the tracker under the MIT license. You can [find it here](https://github.com/plausible/analytics/blob/master/tracker/LICENSE.md).
Copyright (c) 2018-present Plausible Insights OÜ. Plausible Analytics name and logo are trademarks of Plausible Insights OÜ. Please see our [trademark guidelines](https://plausible.io/trademark) for info on acceptable usage.

@ -7,6 +7,8 @@ want be up to date on security patches, make sure your Plausible image is up to
## Reporting a Vulnerability
Our software is updated several times per week and we also have a way for you to [report any security vulnerabilities](https://plausible.io/vulnerability-disclosure-program). A more detailed overview about our security practices can be found on [plausible.io/security](https://plausible.io/security).
If you've found a security vulnerability with the Plausible codebase, you can disclose it responsibly by sending a summary to security@plausible.io.
We will review the potential threat and fix it as fast as we can.

@ -1,6 +0,0 @@
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}

@ -1,15 +0,0 @@
{
"baseDir": "../priv/",
"reportOutput": ["github"],
"files": [
{
"path": "static/js/*.js"
},
{
"path": "static/css/app.css"
},
{
"path": "tracker/js/plausible.js"
}
]
}

@ -25,7 +25,8 @@
"react/jsx-props-no-spreading": [0],
"jsx-a11y/click-events-have-key-events": [0],
"jsx-a11y/no-static-element-interactions": [0],
"react/no-did-update-set-state": [0]
"react/no-did-update-set-state": [0],
"react/no-unknown-property": [2, {"ignore": ["tooltip"]}]
},
"settings": {
"react": {

@ -1,15 +1,21 @@
/* purgecss start ignore */
@tailwind base;
@tailwind components;
/* purgecss end ignore */
@import "modal.css";
@import "loader.css";
@import "tooltip.css";
@import "flatpickr.css";
@import "tailwindcss/base";
@import "flatpickr/dist/flatpickr.min.css";
@import "./modal.css";
@import "./loader.css";
@import "./tooltip.css";
@import "./flatpickr.css";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
[x-cloak] { display: none; }
@media print {
canvas {
width: 100% !important;
height: auto !important;
}
}
.button {
@apply inline-flex justify-center px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md leading-5 transition hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500;
}
@ -22,6 +28,10 @@
@apply text-indigo-600 bg-transparent border border-indigo-600;
}
.button-outline:hover {
@apply text-white;
}
.button-sm {
@apply px-4 py-2 text-sm;
}
@ -37,13 +47,10 @@ html {
body {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width:100vw; /* Prevents content from jumping when scrollbar is added/removed due to vertical overflow */
overflow-x: hidden;
}
button:disabled {
cursor: default;
}
blockquote {
@apply px-4 py-2 my-4 border-l-4 border-gray-500;
}
@ -64,8 +71,6 @@ blockquote {
}
}
@tailwind utilities;
.light-text {
color: #F0F4F8;

@ -1,9 +1,24 @@
import "../css/app.css"
import "flatpickr/dist/flatpickr.min.css"
import "./polyfills/closest"
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
import "phoenix_html"
import 'alpinejs'
import Alpine from 'alpinejs'
import "./liveview/live_socket"
import comboBox from "./liveview/combo-box"
import dropdown from "./liveview/dropdown"
import "./liveview/phx_events"
Alpine.data('dropdown', dropdown)
Alpine.data('comboBox', comboBox)
Alpine.start()
if (document.querySelectorAll('[data-modal]').length > 0) {
window.addEventListener(`phx:close-modal`, (e) => {
document
.getElementById(e.detail.id)
.dispatchEvent(
new CustomEvent('close-modal', { bubbles: true, detail: e.detail.id })
)
})
}
const triggers = document.querySelectorAll('[data-dropdown-trigger]')
@ -34,36 +49,17 @@ if (triggers.length > 0) {
})
}
const registerForm = document.getElementById('register-form')
if (registerForm) {
registerForm.addEventListener('submit', function(e) {
e.preventDefault();
setTimeout(submitForm, 1000);
var formSubmitted = false;
function submitForm() {
if (!formSubmitted) {
formSubmitted = true;
registerForm.submit();
}
}
/* eslint-disable-next-line no-undef */
plausible('Signup', {callback: submitForm});
})
}
const changelogNotification = document.getElementById('changelog-notification')
if (changelogNotification) {
showChangelogNotification(changelogNotification)
fetch('https://plausible.io/changes.txt', {headers: {'Content-Type': 'text/plain'}})
fetch('https://plausible.io/changes.txt', { headers: { 'Content-Type': 'text/plain' } })
.then((res) => res.text())
.then((res) => {
localStorage.lastChangelogUpdate = new Date(res).getTime()
showChangelogNotification(changelogNotification)
})
})
}
function showChangelogNotification(el) {
@ -71,7 +67,7 @@ function showChangelogNotification(el) {
const lastChecked = Number(localStorage.lastChangelogClick)
const hasNewUpdateSinceLastClicked = lastUpdated > lastChecked
const notOlderThanThreeDays = Date.now() - lastUpdated < 1000 * 60 * 60 * 72
const notOlderThanThreeDays = Date.now() - lastUpdated < 1000 * 60 * 60 * 72
if ((!lastChecked || hasNewUpdateSinceLastClicked) && notOlderThanThreeDays) {
el.innerHTML = `
<a href="https://plausible.io/changelog" target="_blank">

@ -2,10 +2,10 @@ import React from 'react';
import ReactDOM from 'react-dom';
import 'url-search-params-polyfill';
import Router from './router'
import ErrorBoundary from './error-boundary'
import * as api from './api'
import * as timer from './util/realtime-update-timer'
import Router from './dashboard/router'
import ErrorBoundary from './dashboard/error-boundary'
import * as api from './dashboard/api'
import * as timer from './dashboard/util/realtime-update-timer'
timer.start()
@ -16,7 +16,16 @@ if (container) {
domain: container.dataset.domain,
offset: container.dataset.offset,
hasGoals: container.dataset.hasGoals === 'true',
hasProps: container.dataset.hasProps === 'true',
funnelsAvailable: container.dataset.funnelsAvailable === 'true',
propsAvailable: container.dataset.propsAvailable === 'true',
conversionsOptedOut: container.dataset.conversionsOptedOut === 'true',
funnelsOptedOut: container.dataset.funnelsOptedOut === 'true',
propsOptedOut: container.dataset.propsOptedOut === 'true',
revenueGoals: JSON.parse(container.dataset.revenueGoals),
funnels: JSON.parse(container.dataset.funnels),
statsBegin: container.dataset.statsBegin,
nativeStatsBegin: container.dataset.nativeStatsBegin,
embedded: container.dataset.embedded,
background: container.dataset.background,
isDbip: container.dataset.isDbip === 'true',

@ -1,4 +1,4 @@
import {formatISO} from './util/date'
import { formatISO } from './util/date'
let abortController = new AbortController()
let SHARED_LINK_AUTH = null
@ -36,14 +36,15 @@ function serializeFilters(filters) {
return JSON.stringify(cleaned)
}
export function serializeQuery(query, extraQuery=[]) {
export function serializeQuery(query, extraQuery = []) {
const queryObj = {}
if (query.period) { queryObj.period = query.period }
if (query.date) { queryObj.date = formatISO(query.date) }
if (query.from) { queryObj.from = formatISO(query.from) }
if (query.to) { queryObj.to = formatISO(query.to) }
if (query.filters) { queryObj.filters = serializeFilters(query.filters) }
if (query.with_imported) { queryObj.with_imported = query.with_imported }
if (query.period) { queryObj.period = query.period }
if (query.date) { queryObj.date = formatISO(query.date) }
if (query.from) { queryObj.from = formatISO(query.from) }
if (query.to) { queryObj.to = formatISO(query.to) }
if (query.filters) { queryObj.filters = serializeFilters(query.filters) }
if (query.experimental_session_count) { queryObj.experimental_session_count = query.experimental_session_count }
if (query.with_imported) { queryObj.with_imported = query.with_imported }
if (SHARED_LINK_AUTH) { queryObj.auth = SHARED_LINK_AUTH }
if (query.comparison) {
@ -58,11 +59,11 @@ export function serializeQuery(query, extraQuery=[]) {
return '?' + serialize(queryObj)
}
export function get(url, query={}, ...extraQuery) {
const headers = SHARED_LINK_AUTH ? {'X-Shared-Link-Auth': SHARED_LINK_AUTH} : {}
export function get(url, query = {}, ...extraQuery) {
const headers = SHARED_LINK_AUTH ? { 'X-Shared-Link-Auth': SHARED_LINK_AUTH } : {}
url = url + serializeQuery(query, extraQuery)
return fetch(url, {signal: abortController.signal, headers: headers})
.then( response => {
return fetch(url, { signal: abortController.signal, headers: headers })
.then(response => {
if (!response.ok) {
return response.json().then((msg) => {
throw new ApiError(msg.error, msg)
@ -71,3 +72,11 @@ export function get(url, query={}, ...extraQuery) {
return response.json()
})
}
export function put(url, body) {
return fetch(url, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
})
}

@ -6,7 +6,7 @@ import { ChevronDownIcon } from '@heroicons/react/20/solid'
import classNames from 'classnames'
import * as storage from './util/storage'
import Flatpickr from 'react-flatpickr'
import { formatISO, parseUTCDate, formatDateRange } from './util/date.js'
import { parseNaiveDate, formatISO, formatDateRange } from './util/date.js'
const COMPARISON_MODES = {
'off': 'Disable comparison',
@ -42,7 +42,6 @@ export const isComparisonEnabled = function(mode) {
}
export const toggleComparisons = function(history, query, site) {
if (!site.flags.comparisons) return
if (COMPARISON_DISABLED_PERIODS.includes(query.period)) return
if (isComparisonEnabled(query.comparison)) {
@ -67,8 +66,9 @@ function ComparisonModeOption({ label, value, isCurrentlySelected, updateMode, s
}
const render = ({ active }) => {
const buttonClass = classNames("px-4 py-2 w-full text-left font-medium text-sm dark:text-white cursor-pointer", {
const buttonClass = classNames("px-4 py-2 w-full text-left text-sm dark:text-white", {
"bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": active,
"font-medium": !isCurrentlySelected,
"font-bold": isCurrentlySelected,
})
@ -91,8 +91,9 @@ function MatchDayOfWeekInput({ history, query, site }) {
}
const buttonClass = (hover, selected) =>
classNames("px-4 py-2 w-full text-left font-medium text-sm dark:text-white cursor-pointer", {
classNames("px-4 py-2 w-full text-left text-sm dark:text-white cursor-pointer", {
"bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": hover,
"font-medium": !selected,
"font-bold": selected,
})
@ -112,7 +113,6 @@ function MatchDayOfWeekInput({ history, query, site }) {
}
const ComparisonInput = function({ site, query, history }) {
if (!site.flags.comparisons) return null
if (COMPARISON_DISABLED_PERIODS.includes(query.period)) return null
if (!isComparisonEnabled(query.comparison)) return null
@ -133,25 +133,31 @@ const ComparisonInput = function({ site, query, history }) {
const [uiMode, setUiMode] = React.useState("menu")
React.useEffect(() => {
if (uiMode == "datepicker" && calendar) calendar.current.flatpickr.open()
if (uiMode == "datepicker") {
setTimeout(() => calendar.current.flatpickr.open(), 100)
}
}, [uiMode])
const flatpickrOptions = {
mode: 'range',
showMonths: 1,
maxDate: 'today',
minDate: parseUTCDate(site.statsBegin),
minDate: site.statsBegin,
animate: true,
static: true,
onClose: ([from, to], _dateStr, _instance) => {
setUiMode("menu")
if (from && to) updateMode("custom", formatISO(parseUTCDate(from)), formatISO(parseUTCDate(to)))
if (from && to) {
[from, to] = [parseNaiveDate(from), parseNaiveDate(to)]
updateMode("custom", formatISO(from), formatISO(to))
}
}
}
return (
<>
<span className="pl-2 text-sm font-medium text-gray-800 dark:text-gray-200">vs.</span>
<span className="hidden md:block pl-2 text-sm font-medium text-gray-800 dark:text-gray-200">vs.</span>
<div className="flex">
<div className="min-w-32 md:w-48 md:relative">
<Menu as="div" className="relative inline-block pl-2 w-full">
@ -162,11 +168,11 @@ const ComparisonInput = function({ site, query, history }) {
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95">
<Menu.Items className="py-1 text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10" static>
{ Object.keys(COMPARISON_MODES).map((key) => ComparisonModeOption({ label: COMPARISON_MODES[key], value: key, isCurrentlySelected: key == query.comparison, updateMode, setUiMode })) }
{ query.comparison !== "custom" && <span>
@ -177,10 +183,9 @@ const ComparisonInput = function({ site, query, history }) {
</Transition>
{ uiMode == "datepicker" &&
<div className="h-0 absolute">
<div className="h-0 md:absolute">
<Flatpickr ref={calendar} options={flatpickrOptions} className="invisible" />
</div>
}
</div> }
</Menu>
</div>
</div>

@ -4,12 +4,10 @@ import { ChevronDownIcon } from '@heroicons/react/20/solid'
import debounce from 'debounce-promise'
import classNames from 'classnames'
function Option({isHighlighted, isDisabled, onClick, onMouseEnter, text, id}) {
const className = classNames('relative select-none py-2 px-3', {
'cursor-pointer': !isDisabled,
'text-gray-300 dark:text-gray-600': isDisabled,
'text-gray-900 dark:text-gray-300': !isDisabled && !isHighlighted,
'bg-indigo-600 text-white': !isDisabled && isHighlighted,
function Option({isHighlighted, onClick, onMouseEnter, text, id}) {
const className = classNames('relative cursor-pointer select-none py-2 px-3', {
'text-gray-900 dark:text-gray-300': !isHighlighted,
'bg-indigo-600 text-white': isHighlighted,
})
return (
@ -25,10 +23,10 @@ function Option({isHighlighted, isDisabled, onClick, onMouseEnter, text, id}) {
}
function scrollTo(wrapper, id) {
if (wrapper) {
const el = wrapper.querySelector('#' + id);
const el = wrapper.querySelector('#' + id)
if (el) {
el.scrollIntoView({block: 'center'});
el.scrollIntoView({block: 'center'})
}
}
}
@ -40,12 +38,12 @@ function optionId(index) {
export default function PlausibleCombobox(props) {
const [options, setOptions] = useState([])
const [loading, setLoading] = useState(false)
const [isOpen, setOpen] = useState(false);
const [input, setInput] = useState('');
const [highlightedIndex, setHighlightedIndex] = useState(0);
const searchRef = useRef(null);
const containerRef = useRef(null);
const listRef = useRef(null);
const [isOpen, setOpen] = useState(false)
const [input, setInput] = useState('')
const [highlightedIndex, setHighlightedIndex] = useState(0)
const searchRef = useRef(null)
const containerRef = useRef(null)
const listRef = useRef(null)
const visibleOptions = [...options]
if (props.freeChoice && input.length > 0 && options.every(option => option.value !== input)) {
@ -93,8 +91,10 @@ export default function PlausibleCombobox(props) {
}
}
function isDisabled(option) {
return props.values.some((val) => val.value === option.value)
function isOptionDisabled(option) {
const optionAlreadySelected = props.values.some((val) => val.value === option.value)
const optionDisabled = (props.disabledOptions || []).some((val) => val?.value === option.value)
return optionAlreadySelected || optionDisabled
}
function fetchOptions(query) {
@ -108,7 +108,7 @@ export default function PlausibleCombobox(props) {
})
}
const debouncedFetchOptions = useCallback(debounce(fetchOptions, 200), [])
const debouncedFetchOptions = useCallback(debounce(fetchOptions, 200), [fetchOptions])
function onInput(e) {
const newInput = e.target.value
@ -127,12 +127,15 @@ export default function PlausibleCombobox(props) {
}
function selectOption(option) {
if (isDisabled(option)) return
if (props.singleOption) {
props.onSelect([option])
} else {
searchRef.current.focus()
props.onSelect([...props.values, option])
}
props.onSelect([...props.values, option])
setOpen(false)
setInput('')
searchRef.current.focus()
}
function removeOption(option, e) {
@ -144,36 +147,130 @@ export default function PlausibleCombobox(props) {
}
const handleClick = useCallback((e) => {
if (containerRef.current && containerRef.current.contains(e.target)) return;
if (containerRef.current && containerRef.current.contains(e.target)) { return }
setInput('')
setOpen(false)
})
useEffect(() => {
document.addEventListener("mousedown", handleClick, false);
return () => { document.removeEventListener("mousedown", handleClick, false); }
document.addEventListener("mousedown", handleClick, false)
return () => { document.removeEventListener("mousedown", handleClick, false) }
}, [])
const matchesFound = !loading && visibleOptions.length > 0
const noMatchesFound = !loading && visibleOptions.length === 0
useEffect(() => {
if (props.singleOption && props.values.length === 0 && props.autoFocus) {
searchRef.current.focus()
}
}, [props.values.length === 0, props.singleOption, props.autoFocus])
return (
<div onKeyDown={onKeyDown} ref={containerRef} className="relative ml-2 w-full">
<div onClick={toggleOpen} className={classNames('pl-2 pr-8 py-1 w-full dark:bg-gray-900 dark:text-gray-300 rounded-md shadow-sm border border-gray-300 dark:border-gray-700 focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500', {'border-indigo-500 ring-1 ring-indigo-500': isOpen, '': !isOpen})}>
const searchBoxClass = 'border-none py-1 px-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm'
const containerClass = classNames('relative w-full', {
[props.className]: !!props.className,
'opacity-30 cursor-default pointer-events-none': props.isDisabled
})
function renderSingleOptionContent() {
const itemSelected = props.values.length === 1
const placeholder = itemSelected ? '' : props.placeholder
return (
<div className='flex items-center truncate'>
{ itemSelected && renderSingleSelectedItem() }
<input
className={searchBoxClass}
ref={searchRef}
value={input}
style={{backgroundColor: "inherit"}}
placeholder={placeholder}
type="text"
onChange={onInput}>
</input>
</div>
)
}
function renderSingleSelectedItem() {
if (input === '') {
return (
<span className="dark:text-gray-300 text-sm w-0">
{props.values[0].label}
</span>
)
}
}
function renderMultiOptionContent() {
return (
<>
{ props.values.map((value) => {
return (
<div key={value.value} className="bg-indigo-100 dark:bg-indigo-600 flex justify-between w-full rounded-sm px-2 py-0.5 m-0.5 text-sm">{value.label} <span onClick={(e) => removeOption(value, e)} className="cursor-pointer font-bold ml-1">&times;</span></div>
<div key={value.value} className="bg-indigo-100 dark:bg-indigo-600 flex justify-between w-full rounded-sm px-2 py-0.5 m-0.5 text-sm">
<span className='break-all'>{value.label}</span>
<span onClick={(e) => removeOption(value, e)} className="cursor-pointer font-bold ml-1">&times;</span>
</div>
)
})
}
<input className="border-none py-1 px-1 p-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm" ref={searchRef} value={input} style={{backgroundColor: "inherit"}} placeholder={props.placeholder} type="text" onChange={onInput}></input>
<input className={searchBoxClass} ref={searchRef} value={input} style={{backgroundColor: "inherit"}} placeholder={props.placeholder} type="text" onChange={onInput}></input>
</>
)
}
function renderDropDownContent() {
const matchesFound = visibleOptions.length > 0 && visibleOptions.some(option => !isOptionDisabled(option))
if (loading) {
return <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">Loading options...</div>
}
if (matchesFound) {
return visibleOptions
.filter(option => !isOptionDisabled(option))
.map((option, i) => {
const text = option.freeChoice ? `Filter by '${option.label}'` : option.label
return (
<Option
key={option.value}
id={optionId(i)}
isHighlighted={highlightedIndex === i}
onClick={() => selectOption(option)}
onMouseEnter={() => setHighlightedIndex(i)}
text={text}
/>
)
})
}
if (props.freeChoice) {
return <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">Start typing to apply filter</div>
}
return (
<div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">
No matches found in the current dashboard. Try selecting a different time range or searching for something different
</div>
)
}
const defaultBoxClass = 'pl-2 pr-8 py-1 w-full dark:bg-gray-900 dark:text-gray-300 rounded-md shadow-sm border border-gray-300 dark:border-gray-700 focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500'
const boxClass = classNames(props.boxClass || defaultBoxClass, {
'border-indigo-500 ring-1 ring-indigo-500': isOpen,
})
return (
<div onKeyDown={onKeyDown} ref={containerRef} className={containerClass}>
<div onClick={toggleOpen} className={boxClass }>
{props.singleOption && renderSingleOptionContent()}
{!props.singleOption && renderMultiOptionContent()}
<div className="cursor-pointer absolute inset-y-0 right-0 flex items-center pr-2">
{!loading && <ChevronDownIcon className="h-4 w-4 text-gray-500" />}
{loading && <Spinner />}
</div>
</div>
<Transition
{isOpen && <Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
@ -181,42 +278,11 @@ export default function PlausibleCombobox(props) {
show={isOpen}
>
<ul ref={listRef} className="z-50 absolute mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm dark:bg-gray-900">
{ loading && (
<div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">
Loading options...
</div>
)}
{ noMatchesFound && !props.freeChoice && (
<div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">
No matches found in the current dashboard. Try selecting a different time range or searching for something different
</div>
)}
{ noMatchesFound && props.freeChoice && (
<div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">
Start typing to apply filter
</div>
)}
{ matchesFound && (
visibleOptions.map((option, i) => {
const text = option.freeChoice ? `Filter by '${option.label}'` : option.label
return (
<Option
key={option.value}
id={optionId(i)}
isHighlighted={highlightedIndex === i}
isDisabled={isDisabled(option)}
onClick={() => selectOption(option)}
onMouseEnter={() => setHighlightedIndex(i)}
text={text}
/>
)
})
)}
{ renderDropDownContent() }
</ul>
</Transition>
</Transition>}
</div>
);
)
}
function Spinner() {

@ -1,6 +1,6 @@
import React, { Fragment } from "react";
import { FILTER_TYPES } from "../util/filters";
import { FILTER_OPERATIONS } from "../util/filters";
import { Menu, Transition } from "@headlessui/react";
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import { isFreeChoiceFilter, supportsIsNot } from "../util/filters";
@ -30,40 +30,46 @@ export default function FilterTypeSelector(props) {
)
}
const containerClass = classNames("w-full", {
'opacity-20 cursor-default pointer-events-none': props.isDisabled
})
return (
<Menu as="div" className="relative inline-block text-left">
{({ open }) => (
<>
<div className="w-24">
<Menu.Button className="inline-flex justify-between items-center w-full rounded-md border border-gray-300 dark:border-gray-500 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-850 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 dark:focus:ring-offset-gray-900 focus:ring-indigo-500">
{props.selectedType}
<ChevronDownIcon className="-mr-2 ml-2 h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" />
</Menu.Button>
</div>
<div className={containerClass}>
<Menu as="div" className="relative inline-block text-left w-full">
{({ open }) => (
<>
<div className="w-full">
<Menu.Button className="inline-flex justify-between items-center w-full rounded-md border border-gray-300 dark:border-gray-500 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-850 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 dark:focus:ring-offset-gray-900 focus:ring-indigo-500">
{props.selectedType}
<ChevronDownIcon className="-mr-2 ml-2 h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" />
</Menu.Button>
</div>
<Transition
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items
static
className="z-10 origin-top-left absolute left-0 mt-2 w-24 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none"
<Transition
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<div className="py-1">
{renderTypeItem(FILTER_TYPES.is, true)}
{renderTypeItem(FILTER_TYPES.isNot, supportsIsNot(filterName))}
{renderTypeItem(FILTER_TYPES.contains, isFreeChoiceFilter(filterName))}
</div>
</Menu.Items>
</Transition>
</>
)}
</Menu>
<Menu.Items
static
className="z-10 origin-top-left absolute left-0 mt-2 w-full rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none"
>
<div className="py-1">
{renderTypeItem(FILTER_OPERATIONS.is, true)}
{renderTypeItem(FILTER_OPERATIONS.isNot, supportsIsNot(filterName))}
{renderTypeItem(FILTER_OPERATIONS.contains, isFreeChoiceFilter(filterName))}
</div>
</Menu.Items>
</Transition>
</>
)}
</Menu>
</div>
)
}
}

@ -1,40 +1,22 @@
import React from 'react';
import React, { useEffect, useState } from 'react'
import { useInView } from 'react-intersection-observer'
export default class extends React.Component {
componentDidMount() {
if ('IntersectionObserver' in window) {
this.attachObserver()
} else {
this.props.onVisible && this.props.onVisible()
}
}
attachObserver() {
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.props.onVisible && this.props.onVisible()
this.observer.unobserve(this.element);
}
}, {
threshold: 0
});
export default function LazyLoader(props) {
const [hasBecomeVisibleYet, setHasBecomeVisibleYet] = useState(false)
const { ref, inView } = useInView({
threshold: 0,
})
this.observer.observe(this.element);
}
componentWillUnmount() {
this.observer && this.observer.unobserve(this.element);
}
useEffect(() => {
if (inView && !hasBecomeVisibleYet) {
setHasBecomeVisibleYet(true)
props.onVisible && props.onVisible()
}
}, [inView])
render() {
return (
<div
ref={(el) => { this.element = el }}
className={this.props.className}
style={this.props.style}
>
{this.props.children}
</div>
);
}
return (
<div ref={ref}>
{props.children}
</div>
)
}

@ -0,0 +1,56 @@
import React from "react"
import { sectionTitles } from "../stats/behaviours"
import * as api from '../api'
export function FeatureSetupNotice({ site, feature, title, info, callToAction, onHideAction }) {
const sectionTitle = sectionTitles[feature]
const requestHideSection = () => {
if (window.confirm(`Are you sure you want to hide ${sectionTitle}? You can make it visible again in your site settings later.`)) {
api.put(`/api/${encodeURIComponent(site.domain)}/disable-feature`, { feature: feature })
.then(response => {
if (response.ok) { onHideAction() }
})
}
}
function renderCallToAction() {
return (
<a href={callToAction.link} className="ml-2 sm:ml-4 button px-2 sm:px-4">
<p className="flex flex-col justify-center text-xs sm:text-sm">{callToAction.action}</p>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="ml-2 w-5 h-5">
<path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75" />
</svg>
</a>
)
}
function renderHideButton() {
return (
<button
onClick={requestHideSection}
className="inline-block px-2 sm:px-4 py-2 border border-gray-300 dark:border-gray-500 leading-5 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition ease-in-out duration-150">
Hide this report
</button>
)
}
return (
<div className="sm:mx-32 mt-6 mb-3" >
<div className="py-3">
<div className="text-center mt-2 text-gray-800 dark:text-gray-200">
{title}
</div>
<div className="text-justify mt-4 font-small text-sm text-gray-500 dark:text-gray-200">
{info}
</div>
<div className="text-xs sm:text-sm flex my-6 justify-center">
{renderHideButton()}
{renderCallToAction()}
</div>
</div>
</div>
)
}

@ -17,6 +17,7 @@ import {
isThisMonth,
isThisYear,
parseUTCDate,
parseNaiveDate,
isBefore,
isAfter,
formatDateRange
@ -24,6 +25,7 @@ import {
import { navigateToQuery, QueryLink, QueryButton } from "./query";
import { shouldIgnoreKeypress } from "./keybinding.js"
import { COMPARISON_DISABLED_PERIODS, toggleComparisons, isComparisonEnabled } from "../dashboard/comparison-input.js"
import classNames from "classnames"
function renderArrow(query, site, period, prevDate, nextDate) {
const insertionDate = parseUTCDate(site.statsBegin);
@ -38,19 +40,29 @@ function renderArrow(query, site, period, prevDate, nextDate) {
period
);
const leftClasses = `flex items-center px-1 sm:px-2 border-r border-gray-300 rounded-l
dark:border-gray-500 dark:text-gray-100 ${
disabledLeft ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900"
}`;
const rightClasses = `flex items-center px-1 sm:px-2 rounded-r dark:text-gray-100 ${
disabledRight ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900"
}`;
const isComparing = isComparisonEnabled(query.comparison)
const leftClass = classNames("flex items-center px-1 sm:px-2 border-r border-gray-300 rounded-l dark:border-gray-500 dark:text-gray-100", {
"bg-gray-300 dark:bg-gray-950": disabledLeft,
"hover:bg-gray-100 dark:hover:bg-gray-900": !disabledLeft,
})
const rightClass = classNames("flex items-center px-1 sm:px-2 rounded-r dark:text-gray-100", {
"bg-gray-300 dark:bg-gray-950": disabledRight,
"hover:bg-gray-100 dark:hover:bg-gray-900": !disabledRight,
})
const containerClass = classNames("rounded shadow bg-white mr-2 sm:mr-4 cursor-pointer dark:bg-gray-800", {
"hidden md:flex": isComparing,
"flex": !isComparing,
})
return (
<div className="flex rounded shadow bg-white mr-2 sm:mr-4 cursor-pointer dark:bg-gray-800">
<div className={containerClass}>
<QueryButton
to={{ date: prevDate }}
query={query}
className={leftClasses}
className={leftClass}
disabled={disabledLeft}
>
<svg
@ -69,7 +81,7 @@ function renderArrow(query, site, period, prevDate, nextDate) {
<QueryButton
to={{ date: nextDate }}
query={query}
className={rightClasses}
className={rightClass}
disabled={disabledRight}
>
<svg
@ -89,7 +101,7 @@ function renderArrow(query, site, period, prevDate, nextDate) {
);
}
function DatePickerArrows({site, query}) {
function DatePickerArrows({ site, query }) {
if (query.period === "year") {
const prevDate = formatISO(shiftMonths(query.date, -12));
const nextDate = formatISO(shiftMonths(query.date, 12));
@ -110,7 +122,7 @@ function DatePickerArrows({site, query}) {
return null
}
function DisplayPeriod({query, site}) {
function DisplayPeriod({ query, site }) {
if (query.period === "day") {
if (isToday(site, query.date)) {
return "Today";
@ -142,7 +154,7 @@ function DisplayPeriod({query, site}) {
return 'Realtime'
}
function DatePicker({query, site, history}) {
function DatePicker({ query, site, history }) {
const [open, setOpen] = useState(false)
const [mode, setMode] = useState('menu')
const dropDownNode = useRef(null)
@ -196,21 +208,21 @@ function DatePicker({query, site, history}) {
setOpen(false);
const keybindings = {
d: {date: false, period: 'day'},
e: {date: formatISO(shiftDays(nowForSite(site), -1)), period: 'day'},
r: {period: 'realtime'},
w: {date: false, period: '7d'},
m: {date: false, period: 'month'},
y: {date: false, period: 'year'},
t: {date: false, period: '30d'},
s: {date: false, period: '6mo'},
l: {date: false, period: '12mo'},
a: {date: false, period: 'all'},
d: { date: false, period: 'day' },
e: { date: formatISO(shiftDays(nowForSite(site), -1)), period: 'day' },
r: { period: 'realtime' },
w: { date: false, period: '7d' },
m: { date: false, period: 'month' },
y: { date: false, period: 'year' },
t: { date: false, period: '30d' },
s: { date: false, period: '6mo' },
l: { date: false, period: '12mo' },
a: { date: false, period: 'all' },
}
const redirect = keybindings[e.key.toLowerCase()]
if (redirect) {
navigateToQuery(history, query, {...newSearch, ...redirect})
navigateToQuery(history, query, { ...newSearch, ...redirect })
} else if (e.key.toLowerCase() === 'x') {
toggleComparisons(history, query, site)
} else if (e.key.toLowerCase() === 'c') {
@ -228,7 +240,7 @@ function DatePicker({query, site, history}) {
})
useEffect(() => {
if (mode === 'calendar' && open) {
if (mode === 'calendar' && open) {
openCalendar()
}
}, [mode])
@ -243,34 +255,18 @@ function DatePicker({query, site, history}) {
return () => { document.removeEventListener("mousedown", handleClick, false); }
}, [])
function setCustomDate(dates) {
if (dates.length === 2) {
const [from, to] = dates.map(parseUTCDate)
if (formatISO(from) === formatISO(to)) {
navigateToQuery(
history,
query,
{
period: 'day',
date: formatISO(from),
from: false,
to: false
}
)
function setCustomDate([from, to], _dateStr, _instance) {
if (from && to) {
[from, to] = [parseNaiveDate(from), parseNaiveDate(to)]
if (from.isSame(to)) {
navigateToQuery(history, query, { period: 'day', date: formatISO(from), from: false, to: false })
} else {
navigateToQuery(
history,
query,
{
period: 'custom',
date: false,
from: formatISO(from),
to: formatISO(to),
}
)
navigateToQuery(history, query, { period: 'custom', date: false, from: formatISO(from), to: formatISO(to) })
}
setOpen(false)
}
setOpen(false)
}
function toggle() {
@ -296,27 +292,17 @@ function DatePicker({query, site, history}) {
opts.date = opts.date ? formatISO(opts.date) : false;
const keybinds = {
'Today': 'D',
'Realtime': 'R',
'Last 7 days': 'W',
'Month to Date': 'M',
'Year to Date': 'Y',
'Last 12 months': 'L',
'Last 30 days': 'T',
'All time': 'A',
};
return (
<QueryLink
to={{from: false, to: false, period, ...opts}}
to={{ from: false, to: false, period, ...opts }}
onClick={() => setOpen(false)}
query={query}
className={`${boldClass } px-4 py-2 text-sm leading-tight hover:bg-gray-100 hover:text-gray-900
className={`${boldClass} px-4 py-2 text-sm leading-tight hover:bg-gray-100 hover:text-gray-900
dark:hover:bg-gray-900 dark:hover:text-gray-100 flex items-center justify-between`}
>
{text}
<span className='font-normal'>{keybinds[text]}</span>
{opts.keybindHint ? (<span className='font-normal'>{opts.keybindHint}</span>) : null}
</QueryLink>
);
}
@ -333,23 +319,23 @@ function DatePicker({query, site, history}) {
font-medium text-gray-800 dark:text-gray-200 date-options"
>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{renderLink("day", "Today")}
{renderLink("realtime", "Realtime")}
{renderLink("day", "Today", { keybindHint: 'D' })}
{renderLink("realtime", "Realtime", { keybindHint: 'R' })}
</div>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{renderLink("7d", "Last 7 days")}
{renderLink("30d", "Last 30 days")}
{renderLink("7d", "Last 7 Days", { keybindHint: 'W' })}
{renderLink("30d", "Last 30 Days", { keybindHint: 'T' })}
</div>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{ renderLink('month', 'Month to Date') }
{ renderLink('month', 'Last month', {date: lastMonth(site)}) }
{renderLink('month', 'Month to Date', { keybindHint: 'M' })}
{renderLink('month', 'Last Month', { date: lastMonth(site) })}
</div>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{renderLink("year", "Year to Date")}
{renderLink("12mo", "Last 12 months")}
{renderLink("year", "Year to Date", { keybindHint: 'Y' })}
{renderLink("12mo", "Last 12 months", { keybindHint: 'L' })}
</div>
<div className="py-1 date-option-group">
{renderLink("all", "All time")}
{renderLink("all", "All time", { keybindHint: 'A' })}
<span
onClick={() => setMode('calendar')}
onKeyPress={() => setMode('calendar')}
@ -362,11 +348,11 @@ function DatePicker({query, site, history}) {
aria-expanded="false"
aria-controls="calendar"
>
Custom range
Custom Range
<span className='font-normal'>C</span>
</span>
</div>
{ !COMPARISON_DISABLED_PERIODS.includes(query.period) && site.flags.comparisons &&
{!COMPARISON_DISABLED_PERIODS.includes(query.period) &&
<div className="py-1 date-option-group border-t border-gray-200 dark:border-gray-500">
<span
onClick={() => {
@ -374,10 +360,10 @@ function DatePicker({query, site, history}) {
setOpen(false)
}}
className="px-4 py-2 text-sm leading-tight hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer flex items-center justify-between">
{ isComparisonEnabled(query.comparison) ? 'Disable comparison' : 'Compare' }
{isComparisonEnabled(query.comparison) ? 'Disable comparison' : 'Compare'}
<span className='font-normal'>X</span>
</span>
</div> }
</div>}
</div>
</div>
);
@ -389,13 +375,14 @@ function DatePicker({query, site, history}) {
options={{
mode: 'range',
maxDate: 'today',
minDate: parseUTCDate(site.statsBegin),
minDate: site.statsBegin,
showMonths: 1,
static: true,
animate: true}}
animate: true
}}
ref={calendar}
className="invisible"
onChange={setCustomDate}
onClose={setCustomDate}
/>
</div>
)
@ -429,11 +416,11 @@ function DatePicker({query, site, history}) {
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
{renderDropDownContent()}
</Transition>

@ -0,0 +1,5 @@
Plausible copyright notice
This software is Copyright 2024 Plausible Insights OÜ
This repository is provided for informational purposes only, and no rights to use, distribute or otherwise exploit this software are granted to you. Our other repositories include software that is offered under the Affero GPL, but this repository is not. If you wish to discuss a license, or our hosted service that uses the software, please contact us at hello@plausible.io

@ -0,0 +1,85 @@
export default function FunnelTooltip(palette, funnel) {
return (context) => {
const tooltipModel = context.tooltip
const dataIndex = tooltipModel.dataPoints[0].dataIndex
const offset = document.getElementById("funnel").getBoundingClientRect()
let tooltipEl = document.getElementById('chartjs-tooltip')
if (!tooltipEl) {
tooltipEl = document.createElement('div')
tooltipEl.id = 'chartjs-tooltip'
tooltipEl.style.display = 'none'
tooltipEl.style.opacity = 0
document.body.appendChild(tooltipEl)
}
if (tooltipEl && offset && window.innerWidth < 768) {
tooltipEl.style.top = offset.y + offset.height + window.scrollY + 15 + 'px'
tooltipEl.style.left = offset.x + 'px'
tooltipEl.style.right = null
tooltipEl.style.opacity = 1
}
if (tooltipModel.opacity === 0) {
tooltipEl.style.display = 'none'
return
}
if (tooltipModel.body) {
const currentStep = funnel.steps[dataIndex]
const previousStep = (dataIndex > 0) ? funnel.steps[dataIndex - 1] : null
tooltipEl.innerHTML = `
<aside class="text-gray-100 flex flex-col">
<div class="flex justify-between items-center border-b-2 border-gray-700 pb-2">
<span class="font-semibold mr-4 text-lg">${previousStep ? `<span class="mr-2">${previousStep.label}</span>` : ""}
<span class="text-gray-500 mr-2">→</span>
${tooltipModel.title}
</span>
</div>
<table class="min-w-full mt-2">
<tr>
<th>
<span class="flex items-center mr-4">
<div class="w-3 h-3 mr-1 rounded-full ${palette.visitorsLegendClass}"></div>
<span>
${dataIndex == 0 ? "Entered the funnel" : "Visitors"}
</span>
</span>
</th>
<td class="text-right font-bold px-4">
<span>
${dataIndex == 0 ? funnel.entering_visitors.toLocaleString() : currentStep.visitors.toLocaleString()}
</span>
</td>
<td class="text-right text-sm">
<span>
${dataIndex == 0 ? funnel.entering_visitors_percentage : currentStep.conversion_rate_step}%
</span>
</td>
</tr>
<tr>
<th>
<span class="flex items-center">
<div class="w-3 h-3 mr-1 rounded-full ${palette.dropoffLegendClass}"></div>
<span>
${dataIndex == 0 ? "Never entered the funnel" : "Dropoff"}
</span>
</span>
</th>
<td class="text-right font-bold px-4">
<span>${dataIndex == 0 ? funnel.never_entering_visitors.toLocaleString() : currentStep.dropoff.toLocaleString()}</span>
</td >
<td class="text-right text-sm">
<span>${dataIndex == 0 ? funnel.never_entering_visitors_percentage : currentStep.dropoff_percentage}%</span>
</td>
</tr >
</table >
</aside >
`
}
tooltipEl.style.display = null
}
}

@ -0,0 +1,358 @@
import React, { useEffect, useState, useRef } from 'react'
import FlipMove from 'react-flip-move';
import Chart from 'chart.js/auto'
import FunnelTooltip from './funnel-tooltip.js'
import ChartDataLabels from 'chartjs-plugin-datalabels'
import numberFormatter from '../util/number-formatter'
import Bar from '../stats/bar'
import RocketIcon from '../stats/modals/rocket-icon'
import * as api from '../api'
import LazyLoader from '../components/lazy-loader'
export default function Funnel(props) {
const [loading, setLoading] = useState(true)
const [visible, setVisible] = useState(false)
const [error, setError] = useState(undefined)
const [funnel, setFunnel] = useState(null)
const [isSmallScreen, setSmallScreen] = useState(false)
const chartRef = useRef(null)
const canvasRef = useRef(null)
useEffect(() => {
if (visible) {
setLoading(true)
fetchFunnel()
.then((res) => {
setFunnel(res)
setError(undefined)
})
.catch((error) => {
setError(error)
})
.finally(() => {
setLoading(false)
})
return () => {
if (chartRef.current) {
chartRef.current.destroy()
}
}
}
}, [props.query, props.funnelName, visible, isSmallScreen])
useEffect(() => {
if (canvasRef.current && funnel && visible && !isSmallScreen) {
initialiseChart()
}
}, [funnel, visible])
useEffect(() => {
const mediaQuery = window.matchMedia('(max-width: 768px)')
setSmallScreen(mediaQuery.matches)
const handleScreenChange = (e) => {
setSmallScreen(e.matches);
}
mediaQuery.addEventListener("change", handleScreenChange);
return () => {
mediaQuery.removeEventListener("change", handleScreenChange)
}
}, [])
const isDarkMode = () => {
return document.querySelector('html').classList.contains('dark') || false
}
const getPalette = () => {
if (isDarkMode()) {
return {
dataLabelBackground: 'rgba(25, 30, 56, 0.97)',
dataLabelTextColor: 'rgb(243, 244, 246)',
visitorsBackground: 'rgb(99, 102, 241)',
dropoffBackground: '#2F3949',
dropoffStripes: 'rgb(25, 30, 56)',
stepNameLegendColor: 'rgb(228, 228, 231)',
visitorsLegendClass: 'bg-indigo-500',
dropoffLegendClass: 'bg-gray-600',
smallBarClass: 'bg-indigo-500'
}
} else {
return {
dataLabelBackground: 'rgba(25, 30, 56, 0.97)',
dataLabelTextColor: 'rgb(243, 244, 246)',
visitorsBackground: 'rgb(99, 102, 241)',
dropoffBackground: 'rgb(224, 231, 255)',
dropoffStripes: 'rgb(255, 255, 255)',
stepNameLegendColor: 'rgb(12, 24, 39)',
visitorsLegendClass: 'bg-indigo-500',
dropoffLegendClass: 'bg-indigo-100',
smallBarClass: 'bg-indigo-300'
}
}
}
const formatDataLabel = (visitors, ctx) => {
if (ctx.dataset.label === 'Visitors') {
const conversionRate = funnel.steps[ctx.dataIndex].conversion_rate
return `${conversionRate}% \n(${numberFormatter(visitors)} Visitors)`
} else {
return null
}
}
const calcOffset = (ctx) => {
const conversionRate = parseFloat(funnel.steps[ctx.dataIndex].conversion_rate)
if (conversionRate > 90) {
return -64
} else if (conversionRate > 20) {
return -28
} else {
return 8
}
}
const getFunnel = () => {
return props.site.funnels.find((funnel) => funnel.name === props.funnelName)
}
const fetchFunnel = async () => {
const funnelMeta = getFunnel()
if (typeof funnelMeta === 'undefined') {
throw new Error('Could not fetch the funnel. Perhaps it was deleted?')
} else {
return api.get(`/api/stats/${encodeURIComponent(props.site.domain)}/funnels/${funnelMeta.id}`, props.query)
}
}
const initialiseChart = () => {
if (chartRef.current) {
chartRef.current.destroy()
}
const palette = getPalette()
const createDiagonalPattern = (color1, color2) => {
// create a 10x10 px canvas for the pattern's base shape
let shape = document.createElement('canvas')
shape.width = 10
shape.height = 10
let c = shape.getContext('2d')
c.fillStyle = color1
c.strokeStyle = color2
c.fillRect(0, 0, shape.width, shape.height);
c.beginPath()
c.moveTo(2, 0)
c.lineTo(10, 8)
c.stroke()
c.beginPath()
c.moveTo(0, 8)
c.lineTo(2, 10)
c.stroke()
return c.createPattern(shape, 'repeat')
}
const labels = funnel.steps.map((step) => step.label)
const stepData = funnel.steps.map((step) => step.visitors)
const dropOffData = funnel.steps.map((step) => step.dropoff)
const ctx = canvasRef.current.getContext("2d")
const calcBarThickness = (ctx) => {
if (ctx.dataset.data.length <= 3) {
return 160
} else {
return Math.floor(650 / ctx.dataset.data.length)
}
}
// passing those verbatim to make sure canvas rendering picks them up
var fontFamily = 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'
var gradient = ctx.createLinearGradient(900, 0, 900, 900);
gradient.addColorStop(1, palette.dropoffBackground);
gradient.addColorStop(0, palette.visitorsBackground);
const data = {
labels: labels,
datasets: [
{
label: 'Visitors',
data: stepData,
backgroundColor: gradient,
hoverBackgroundColor: gradient,
borderRadius: 4,
stack: 'Stack 0',
},
{
label: 'Dropoff',
data: dropOffData,
backgroundColor: createDiagonalPattern(palette.dropoffBackground, palette.dropoffStripes),
hoverBackgroundColor: palette.dropoffBackground,
borderRadius: 4,
stack: 'Stack 0',
},
],
}
const config = {
plugins: [ChartDataLabels],
type: 'bar',
data: data,
options: {
responsive: true,
barThickness: calcBarThickness,
plugins: {
legend: {
display: false,
},
tooltip: {
enabled: false,
mode: 'index',
intersect: true,
position: 'average',
external: FunnelTooltip(palette, funnel)
},
datalabels: {
formatter: formatDataLabel,
anchor: 'end',
align: 'end',
offset: calcOffset,
backgroundColor: palette.dataLabelBackground,
color: palette.dataLabelTextColor,
borderRadius: 4,
clip: true,
font: { size: 12, weight: 'normal', lineHeight: 1.6, family: fontFamily },
textAlign: 'center',
padding: { top: 8, bottom: 8, right: 8, left: 8 },
},
},
scales: {
y: { display: false },
x: {
position: 'bottom',
display: true,
border: { display: false },
grid: { drawBorder: false, display: false },
ticks: {
padding: 8,
font: { weight: 'bold', family: fontFamily, size: 14 },
color: palette.stepNameLegendColor
},
},
},
},
}
chartRef.current = new Chart(ctx, config)
}
const header = () => {
return (
<div className="flex justify-between w-full">
<h4 className="mt-2 text-sm dark:text-gray-100">{props.funnelName}</h4>
{props.tabs}
</div>
)
}
const renderError = () => {
if (error.name === 'AbortError') return
if (error.payload && error.payload.level === 'normal') {
return (
<>
{header()}
<div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">{error.message}</div>
</>
)
} else {
return (
<>
{header()}
<div className="text-center text-gray-900 dark:text-gray-100 mt-16">
<RocketIcon />
<div className="text-lg font-bold">Oops! Something went wrong</div>
<div className="text-lg">{error.message ? error.message : 'Failed to render funnel'}</div>
<div className="text-xs mt-8">Please try refreshing your browser or selecting the funnel again.</div>
</div>
</>
)
}
}
const renderInner = () => {
if (loading) {
return <div className="mx-auto loading pt-44"><div></div></div>
} else if (error) {
return renderError()
} else if (funnel) {
const conversionRate = funnel.steps[funnel.steps.length - 1].conversion_rate
return (
<div className="mb-8">
{header()}
<p className="mt-1 text-gray-500 text-sm">{funnel.steps.length}-step funnel • {conversionRate}% conversion rate</p>
{isSmallScreen && <div className="mt-4">{renderBars(funnel)}</div>}
</div>
)
}
}
const renderBar = (step) => {
const palette = getPalette()
return (
<>
<div className="flex items-center justify-between my-1 text-sm">
<Bar
count={step.visitors}
all={funnel.steps}
bg={palette.smallBarClass}
maxWidthDeduction={"5rem"}
plot={'visitors'}
>
<span className="flex px-2 py-1.5 group dark:text-gray-100 relative z-9 break-all">
{step.label}
</span>
</Bar>
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={step.visitors.toLocaleString()}>
{numberFormatter(step.visitors)}
</span>
</div>
</>
)
}
const renderBars = (funnel) => {
return (
<>
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
<span>&nbsp;</span>
<span className="text-right">
<span className="inline-block w-20">Visitors</span>
</span>
</div>
<FlipMove>
{funnel.steps.map(renderBar)}
</FlipMove>
</>
)
}
return (
<div style={{ minHeight: '400px' }}>
<LazyLoader onVisible={() => setVisible(true)}>
{renderInner()}
</LazyLoader>
{!isSmallScreen && <canvas className="" id="funnel" ref={canvasRef}></canvas>}
</div>
)
}

@ -0,0 +1,9 @@
import React from 'react'
export default function Money({ formatted }) {
if (formatted) {
return <span tooltip={formatted.long}>{formatted.short}</span>
} else {
return "-"
}
}

@ -10,12 +10,23 @@ import {
formatFilterGroup,
filterGroupForFilter,
parseQueryFilter,
parseQueryPropsFilter,
formattedFilters
} from "./util/filters";
function removeFilter(key, history, query) {
const newOpts = {
[key]: false
function removeFilter(filterType, key, history, query) {
const newOpts = {}
if (filterType === 'props') {
if (Object.keys(query.filters.props).length == 1) {
newOpts.props = false
} else {
newOpts.props = JSON.stringify({
...query.filters.props,
[key]: undefined,
})
}
} else {
newOpts[key] = false
}
if (key === 'country') { newOpts.country_labels = false }
if (key === 'region') { newOpts.region_labels = false }
@ -37,34 +48,38 @@ function clearAllFilters(history, query) {
);
}
function filterText(key, _rawValue, query) {
const {type, clauses} = parseQueryFilter(query, key)
function filterText(filterType, key, query) {
const formattedFilter = formattedFilters[key]
if (key === "props") {
const [[propKey, _propValue]] = Object.entries(query.filters['props'])
return <>props.{propKey} {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </>
if (filterType === "props") {
const { propKey, clauses, type } = parseQueryPropsFilter(query).find((filter) => filter.propKey.value === key)
return <>Property <b>{propKey.label}</b> {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </>
} else if (formattedFilter) {
const {type, clauses} = parseQueryFilter(query, key)
return <>{formattedFilter} {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </>
}
throw new Error(`Unknown filter: ${key}`)
}
function renderDropdownFilter(site, history, [key, value], query) {
function renderDropdownFilter(site, history, { key, value, filterType }, query) {
return (
<Menu.Item key={key}>
<Menu.Item key={`${filterType}::${key}`}>
<div className="px-3 md:px-4 sm:py-2 py-3 text-sm leading-tight flex items-center justify-between" key={key + value}>
<Link
title={`Edit filter: ${formattedFilters[key]}`}
to={{ pathname: `/${encodeURIComponent(site.domain)}/filter/${filterGroupForFilter(key)}`, search: window.location.search }}
title={`Edit filter: ${formattedFilters[filterType]}`}
to={{ pathname: `/${encodeURIComponent(site.domain)}/filter/${filterGroupForFilter(filterType)}`, search: window.location.search }}
className="group flex w-full justify-between items-center"
style={{ width: 'calc(100% - 1.5rem)' }}
>
<span className="inline-block w-full truncate">{filterText(key, value, query)}</span>
<span className="inline-block w-full truncate">{filterText(filterType, key, query)}</span>
<PencilSquareIcon className="w-4 h-4 ml-1 cursor-pointer group-hover:text-indigo-700 dark:group-hover:text-indigo-500" />
</Link>
<b title={`Remove filter: ${formattedFilters[key]}`} className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500" onClick={() => removeFilter(key, history, query)}>
<b
title={`Remove filter: ${formattedFilters[filterType]}`}
className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500"
onClick={() => removeFilter(filterType, key, history, query)}
>
<XMarkIcon className="w-4 h-4" />
</b>
</div>
@ -94,9 +109,10 @@ function DropdownContent({ history, site, query, wrapped }) {
const [addingFilter, setAddingFilter] = useState(false);
if (wrapped === 0 || addingFilter) {
return Object.keys(FILTER_GROUPS)
.filter((option) => option === 'props' ? site.flags.custom_dimension_filter : true)
.map((option) => filterDropdownOption(site, option))
let filterGroups = {...FILTER_GROUPS}
if (!site.propsAvailable) delete filterGroups.props
return Object.keys(filterGroups).map((option) => filterDropdownOption(site, option))
}
return (
@ -201,13 +217,21 @@ class Filters extends React.Component {
});
};
renderListFilter(history, [key, value], query) {
renderListFilter(history, { key, value, filterType }, query) {
return (
<span key={key} title={value} className="flex bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 shadow text-sm rounded mr-2 items-center">
<Link title={`Edit filter: ${formattedFilters[key]}`} className="flex w-full h-full items-center py-2 pl-3" to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}/filter/${filterGroupForFilter(key)}`, search: window.location.search }}>
<span className="inline-block max-w-2xs md:max-w-xs truncate">{filterText(key, value, query)}</span>
<span key={`${filterType}::${key}`} title={value} className="flex bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 shadow text-sm rounded mr-2 items-center">
<Link
title={`Edit filter: ${formattedFilters[filterType]}`}
className="flex w-full h-full items-center py-2 pl-3"
to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}/filter/${filterGroupForFilter(filterType)}`, search: window.location.search }}
>
<span className="inline-block max-w-2xs md:max-w-xs truncate">{filterText(filterType, key, query)}</span>
</Link>
<span title={`Remove filter: ${formattedFilters[key]}`} className="flex h-full w-full px-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 items-center" onClick={() => removeFilter(key, history, query)}>
<span
title={`Remove filter: ${formattedFilters[filterType]}`}
className="flex h-full w-full px-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 items-center"
onClick={() => removeFilter(filterType, key, history, query)}
>
<XMarkIcon className="w-4 h-4" />
</span>
</span>
@ -234,6 +258,10 @@ class Filters extends React.Component {
)
}
trackFilterMenu() {
window.plausible && window.plausible('Filter Menu: Open', {u: `${window.location.protocol}//${window.location.hostname}/:dashboard`})
}
renderDropDown() {
const { history, query, site } = this.props;
@ -242,7 +270,7 @@ class Filters extends React.Component {
{({ open }) => (
<>
<div>
<Menu.Button className="flex items-center text-xs md:text-sm font-medium leading-tight px-3 py-2 cursor-pointer ml-auto text-gray-500 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900 rounded">
<Menu.Button onClick={this.trackFilterMenu} className="flex items-center text-xs md:text-sm font-medium leading-tight px-3 py-2 cursor-pointer ml-auto text-gray-500 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900 rounded">
{this.renderDropdownButton()}
</Menu.Button>
</div>
@ -251,11 +279,11 @@ class Filters extends React.Component {
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Menu.Items
static

@ -9,25 +9,14 @@ import Sources from './stats/sources'
import Pages from './stats/pages'
import Locations from './stats/locations';
import Devices from './stats/devices'
import Conversions from './stats/conversions'
import Behaviours from './stats/behaviours'
import ComparisonInput from './comparison-input'
import { withPinnedHeader } from './pinned-header-hoc';
import { statsBoxClass } from './index';
function Historical(props) {
const tooltipBoundary = React.useRef(null)
function renderConversions() {
if (props.site.hasGoals) {
return (
<div className="items-start justify-between block w-full mt-6 md:flex">
<Conversions site={props.site} query={props.query} />
</div>
)
}
return null
}
return (
<div className="mb-12">
<div id="stats-container-top"></div>
@ -43,15 +32,26 @@ function Historical(props) {
</div>
</div>
<VisitorGraph site={props.site} query={props.query} />
<div className="items-start justify-between block w-full md:flex">
<Sources site={props.site} query={props.query} />
<Pages site={props.site} query={props.query} />
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Sources site={props.site} query={props.query} />
</div>
<div className={ statsBoxClass }>
<Pages site={props.site} query={props.query} />
</div>
</div>
<div className="items-start justify-between block w-full md:flex">
<Locations site={props.site} query={props.query} />
<Devices site={props.site} query={props.query} />
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Locations site={props.site} query={props.query} />
</div>
<div className={ statsBoxClass }>
<Devices site={props.site} query={props.query} />
</div>
</div>
{ renderConversions() }
<Behaviours site={props.site} query={props.query} currentUserRole={props.currentUserRole} />
</div>
)
}

@ -7,6 +7,8 @@ import {parseQuery} from './query'
import * as api from './api'
import { withComparisonProvider } from './comparison-provider-hoc';
export const statsBoxClass = "stats-item relative w-full mt-6 p-4 flex flex-col bg-white dark:bg-gray-825 shadow-xl rounded"
class Dashboard extends React.Component {
constructor(props) {
super(props)

@ -1,8 +1,8 @@
import React from 'react'
import { Link, withRouter } from 'react-router-dom'
import {nowForSite} from './util/date'
import { nowForSite } from './util/date'
import * as storage from './util/storage'
import { COMPARISON_DISABLED_PERIODS, getStoredComparisonMode, isComparisonEnabled,getStoredMatchDayOfWeek } from './comparison-input'
import { COMPARISON_DISABLED_PERIODS, getStoredComparisonMode, isComparisonEnabled, getStoredMatchDayOfWeek } from './comparison-input'
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
@ -39,6 +39,7 @@ export function parseQuery(querystring, site) {
to: q.get('to') ? dayjs.utc(q.get('to')) : undefined,
match_day_of_week: matchDayOfWeek == 'true',
with_imported: q.get('with_imported') ? q.get('with_imported') === 'true' : true,
experimental_session_count: q.get('experimental_session_count'),
filters: {
'goal': q.get('goal'),
'props': JSON.parse(q.get('props')),
@ -58,6 +59,7 @@ export function parseQuery(querystring, site) {
'region': q.get('region'),
'city': q.get('city'),
'page': q.get('page'),
'hostname': q.get('hostname'),
'entry_page': q.get('entry_page'),
'exit_page': q.get('exit_page')
}
@ -65,9 +67,13 @@ export function parseQuery(querystring, site) {
}
export function appliedFilters(query) {
return Object.keys(query.filters)
.map((key) => [key, query.filters[key]])
.filter(([_key, value]) => !!value);
const propKeys = Object.entries(query.filters.props || {})
.map(([key, value]) => ({ key, value, filterType: 'props' }))
return Object.entries(query.filters)
.map(([key, value]) => ({ key, value, filterType: key }))
.filter(({ key, value }) => key !== 'props' && !!value)
.concat(propKeys)
}
function generateQueryString(data) {
@ -122,7 +128,7 @@ class QueryLink extends React.Component {
const QueryLinkWithRouter = withRouter(QueryLink)
export { QueryLinkWithRouter as QueryLink };
function QueryButton({history, query, to, disabled, className, children, onClick}) {
function QueryButton({ history, query, to, disabled, className, children, onClick }) {
return (
<button
className={className}

@ -8,22 +8,11 @@ import Sources from './stats/sources'
import Pages from './stats/pages'
import Locations from './stats/locations'
import Devices from './stats/devices'
import Conversions from './stats/conversions'
import Behaviours from './stats/behaviours'
import { withPinnedHeader } from './pinned-header-hoc';
import { statsBoxClass } from './index';
class Realtime extends React.Component {
renderConversions() {
if (this.props.site.hasGoals) {
return (
<div className="items-start justify-between block w-full mt-6 md:flex">
<Conversions site={this.props.site} query={this.props.query} title="Goal Conversions (last 30 min)" />
</div>
)
}
return null
}
render() {
const navClass = this.props.site.embedded ? 'relative' : 'sticky'
@ -40,16 +29,23 @@ class Realtime extends React.Component {
</div>
</div>
<VisitorGraph site={this.props.site} query={this.props.query} lastLoadTimestamp={this.props.lastLoadTimestamp} />
<div className="items-start justify-between block w-full md:flex">
<Sources site={this.props.site} query={this.props.query} />
<Pages site={this.props.site} query={this.props.query} />
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Sources site={this.props.site} query={this.props.query} />
</div>
<div className={ statsBoxClass }>
<Pages site={this.props.site} query={this.props.query} />
</div>
</div>
<div className="items-start justify-between block w-full md:flex">
<Locations site={this.props.site} query={this.props.query} />
<Devices site={this.props.site} query={this.props.query} />
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Locations site={this.props.site} query={this.props.query} />
</div>
<div className={ statsBoxClass }>
<Devices site={this.props.site} query={this.props.query} />
</div>
</div>
{ this.renderConversions() }
<Behaviours site={this.props.site} query={this.props.query} currentUserRole={this.props.currentUserRole} />
</div>
)
}

@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import {BrowserRouter, Switch, Route, useLocation} from "react-router-dom";
import { BrowserRouter, Switch, Route, useLocation } from "react-router-dom";
import Dash from './index'
import SourcesModal from './stats/modals/sources'
@ -9,7 +9,10 @@ import PagesModal from './stats/modals/pages'
import EntryPagesModal from './stats/modals/entry-pages'
import ExitPagesModal from './stats/modals/exit-pages'
import ModalTable from './stats/modals/table'
import PropsModal from './stats/modals/props'
import ConversionsModal from './stats/modals/conversions'
import FilterModal from './stats/modals/filter-modal'
import * as url from './util/url';
function ScrollToTop() {
const location = useLocation();
@ -23,14 +26,14 @@ function ScrollToTop() {
return null;
}
export default function Router({site, loggedIn, currentUserRole}) {
export default function Router({ site, loggedIn, currentUserRole }) {
return (
<BrowserRouter>
<Route path="/:domain">
<ScrollToTop />
<Dash site={site} loggedIn={loggedIn} currentUserRole={currentUserRole} />
<Switch>
<Route exact path={["/:domain/sources", "/:domain/utm_mediums", "/:domain/utm_sources", "/:domain/utm_campaigns", "/:domain/utm_contents", "/:domain/utm_terms" ]}>
<Route exact path={["/:domain/sources", "/:domain/utm_mediums", "/:domain/utm_sources", "/:domain/utm_campaigns", "/:domain/utm_contents", "/:domain/utm_terms"]}>
<SourcesModal site={site} />
</Route>
<Route exact path="/:domain/referrers/Google">
@ -49,13 +52,19 @@ export default function Router({site, loggedIn, currentUserRole}) {
<ExitPagesModal site={site} />
</Route>
<Route path="/:domain/countries">
<ModalTable title="Top countries" site={site} endpoint={`/api/stats/${encodeURIComponent(site.domain)}/countries`} filter={{country: 'code', country_name: 'name'}} keyLabel="Country" renderIcon={renderCountryIcon} />
<ModalTable title="Top countries" site={site} endpoint={url.apiPath(site, '/countries')} filter={{ country: 'code', country_labels: 'name' }} keyLabel="Country" renderIcon={renderCountryIcon} showPercentage={true}/>
</Route>
<Route path="/:domain/regions">
<ModalTable title="Top regions" site={site} endpoint={`/api/stats/${encodeURIComponent(site.domain)}/regions`} filter={{region: 'code', region_name: 'name'}} keyLabel="Region" renderIcon={renderRegionIcon} />
<ModalTable title="Top regions" site={site} endpoint={url.apiPath(site, '/regions')} filter={{ region: 'code', region_labels: 'name' }} keyLabel="Region" renderIcon={renderRegionIcon} />
</Route>
<Route path="/:domain/cities">
<ModalTable title="Top cities" site={site} endpoint={`/api/stats/${encodeURIComponent(site.domain)}/cities`} filter={{city: 'code', city_name: 'name'}} keyLabel="City" renderIcon={renderCityIcon} />
<ModalTable title="Top cities" site={site} endpoint={url.apiPath(site, '/cities')} filter={{ city: 'code', city_labels: 'name' }} keyLabel="City" renderIcon={renderCityIcon} />
</Route>
<Route path="/:domain/custom-prop-values/:prop_key">
<PropsModal site={site} />
</Route>
<Route path="/:domain/conversions">
<ConversionsModal site={site} />
</Route>
<Route path={["/:domain/filter/:field"]}>
<FilterModal site={site} />

@ -131,7 +131,7 @@ export default class SiteSwitcher extends React.Component {
domain === this.props.site.domain
? 'font-medium text-gray-900 dark:text-gray-100 cursor-default font-bold'
: 'hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-900 dark:focus:text-gray-100'
const showHotkey = !this.props.loggedIn
const showHotkey = this.props.loggedIn && this.state.sites.length > 1
return (
<a
href={
@ -151,7 +151,7 @@ export default class SiteSwitcher extends React.Component {
{domain}
</span>
</span>
{showHotkey ? index < 9 && <span>{index + 1}</span> : null}
{showHotkey && index < 9 ? <span>{index + 1}</span> : null}
</a>
)
}
@ -164,12 +164,14 @@ export default class SiteSwitcher extends React.Component {
<React.Fragment>
<div className="py-1">
<a
href={`/${encodeURIComponent(this.props.site.domain)}/settings`}
href={`/${encodeURIComponent(
this.props.site.domain
)}/settings/general`}
className="group flex items-center px-4 py-2 md:text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-900 dark:focus:text-gray-100"
role="menuitem"
>
<Cog8ToothIcon className="mr-2 h-4 w-4 text-gray-500 dark:text-gray-200 group-hover:text-gray-600 dark:group-hover:text-gray-400 group-focus:text-gray-500 dark:group-focus:text-gray-200" />
Site settings
Site Settings
</a>
</div>
<div className="border-t border-gray-200 dark:border-gray-500"></div>
@ -217,7 +219,7 @@ export default class SiteSwitcher extends React.Component {
className="flex px-4 py-2 md:text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-900 dark:focus:text-gray-100"
role="menuitem"
>
View all
View All
</a>
</React.Fragment>
)
@ -249,10 +251,10 @@ export default class SiteSwitcher extends React.Component {
<Transition
show={this.state.open}
enter="transition ease-out duration-100 transform"
enter="transition ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75 transform"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>

@ -12,11 +12,12 @@ function barWidth(count, all, plot) {
export default function Bar({count, all, bg, maxWidthDeduction, children, plot = "visitors"}) {
const width = barWidth(count, all, plot)
const style = maxWidthDeduction ? {maxWidth: `calc(100% - ${maxWidthDeduction})`} : {}
return (
<div
className="w-full relative"
style={{maxWidth: `calc(100% - ${maxWidthDeduction})`}}
className="w-full h-full relative"
style={style}
>
<div
className={`absolute top-0 left-0 h-full ${bg || ''}`}

@ -0,0 +1,41 @@
import React from 'react';
import * as api from '../../api'
import * as url from '../../util/url'
import { escapeFilterValue } from '../../util/filters'
import { CR_METRIC } from '../reports/metrics';
import ListReport from '../reports/list';
export default function Conversions(props) {
const { site, query } = props
function fetchConversions() {
return api.get(url.apiPath(site, '/conversions'), query, { limit: 9 })
}
function getFilterFor(listItem) {
return { goal: escapeFilterValue(listItem.name) }
}
/*global BUILD_EXTRA*/
return (
<ListReport
fetchData={fetchConversions}
getFilterFor={getFilterFor}
keyLabel="Goal"
onClick={props.onGoalFilterClick}
metrics={[
{ name: 'visitors', label: "Uniques", plot: true },
{ name: 'events', label: "Total", hiddenOnMobile: true },
CR_METRIC,
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true },
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true }
]}
detailsLink={url.sitePath(site, '/conversions')}
maybeHideDetails={true}
query={query}
color="bg-red-50"
colMinWidth={90}
/>
)
}

@ -0,0 +1,65 @@
import React from "react"
import Conversions from './conversions'
import ListReport from "../reports/list"
import { CR_METRIC } from "../reports/metrics"
import * as url from "../../util/url"
import * as api from "../../api"
export const SPECIAL_GOALS = {
'404': {title: '404 Pages', prop: 'path'},
'Outbound Link: Click': {title: 'Outbound Links', prop: 'url'},
'Cloaked Link: Click': {title: 'Cloaked Links', prop: 'url'},
'File Download': {title: 'File Downloads', prop: 'url'}
}
export function specialTitleWhenGoalFilter(query, defaultTitle) {
return SPECIAL_GOALS[query.filters.goal]?.title || defaultTitle
}
function SpecialPropBreakdown(props) {
const { site, query } = props
const prop = SPECIAL_GOALS[query.filters.goal].prop
function fetchData() {
return api.get(url.apiPath(site, `/custom-prop-values/${prop}`), query)
}
function externalLinkDest() {
if (prop === 'path') {
return (listItem) => url.externalLinkForPage(site.domain, listItem.name)
} else {
return (listItem) => listItem.name
}
}
const getFilterFor = (listItem) => { return {'props': JSON.stringify({[prop]: listItem['name']})} }
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
keyLabel={prop}
metrics={[
{name: 'visitors', label: 'Visitors', plot: true},
{name: 'events', label: 'Events', hiddenOnMobile: true},
CR_METRIC
]}
detailsLink={url.sitePath(site, `/custom-prop-values/${prop}`)}
externalLinkDest={externalLinkDest()}
maybeHideDetails={true}
query={query}
color="bg-red-50"
colMinWidth={90}
/>
)
}
export default function GoalConversions(props) {
const {site, query} = props
if (SPECIAL_GOALS[query.filters.goal]) {
return <SpecialPropBreakdown site={site} query={props.query} />
} else {
return <Conversions site={site} query={props.query} onGoalFilterClick={props.onGoalFilterClick}/>
}
}

@ -0,0 +1,344 @@
import React, { Fragment, useState, useEffect, useCallback } from 'react'
import { Menu, Transition } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import classNames from 'classnames'
import * as storage from '../../util/storage'
import GoalConversions, { specialTitleWhenGoalFilter } from './goal-conversions'
import Properties from './props'
import { FeatureSetupNotice } from '../../components/notice'
import { SPECIAL_GOALS } from './goal-conversions'
/*global BUILD_EXTRA*/
/*global require*/
function maybeRequire() {
if (BUILD_EXTRA) {
return require('../../extra/funnel')
} else {
return { default: null }
}
}
const Funnel = maybeRequire().default
const ACTIVE_CLASS = 'inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold active-prop-heading truncate text-left'
const DEFAULT_CLASS = 'hover:text-indigo-600 cursor-pointer truncate text-left'
export const CONVERSIONS = 'conversions'
export const PROPS = 'props'
export const FUNNELS = 'funnels'
export const sectionTitles = {
[CONVERSIONS]: 'Goal Conversions',
[PROPS]: 'Custom Properties',
[FUNNELS]: 'Funnels'
}
export default function Behaviours(props) {
const { site, query, currentUserRole } = props
const adminAccess = ['owner', 'admin', 'super_admin'].includes(currentUserRole)
const tabKey = `behavioursTab__${site.domain}`
const funnelKey = `behavioursTabFunnel__${site.domain}`
const [enabledModes, setEnabledModes] = useState(getEnabledModes())
const [mode, setMode] = useState(defaultMode())
const [funnelNames, _setFunnelNames] = useState(site.funnels.map(({ name }) => name))
const [selectedFunnel, setSelectedFunnel] = useState(defaultSelectedFunnel())
const [showingPropsForGoalFilter, setShowingPropsForGoalFilter] = useState(false)
const onGoalFilterClick = useCallback((e) => {
const goalName = e.target.innerHTML
const isSpecialGoal = Object.keys(SPECIAL_GOALS).includes(goalName)
const isPageviewGoal = goalName.startsWith('Visit ')
if (!isSpecialGoal && !isPageviewGoal && enabledModes.includes(PROPS) && site.hasProps) {
setShowingPropsForGoalFilter(true)
setMode(PROPS)
}
}, [])
useEffect(() => {
const justRemovedGoalFilter = !query.filters.goal
if (mode === PROPS && justRemovedGoalFilter && showingPropsForGoalFilter) {
setShowingPropsForGoalFilter(false)
setMode(CONVERSIONS)
}
}, [!!query.filters.goal])
useEffect(() => {
setMode(defaultMode())
}, [enabledModes])
function disableMode(mode) {
setEnabledModes(enabledModes.filter((m) => { return m !== mode }))
}
function setFunnel(selectedFunnel) {
return () => {
storage.setItem(tabKey, FUNNELS)
storage.setItem(funnelKey, selectedFunnel)
setMode(FUNNELS)
setSelectedFunnel(selectedFunnel)
}
}
function defaultSelectedFunnel() {
const stored = storage.getItem(funnelKey)
const storedExists = stored && site.funnels.some((f) => f.name === stored)
if (storedExists) {
return stored
} else if (site.funnels.length > 0) {
const firstAvailable = site.funnels[0].name
storage.setItem(funnelKey, firstAvailable)
return firstAvailable
}
}
function hasFunnels() {
return site.funnels.length > 0 && site.funnelsAvailable
}
function tabFunnelPicker() {
return <Menu as="div" className="relative inline-block text-left">
<div>
<Menu.Button className="inline-flex justify-between focus:outline-none">
<span className={(mode == FUNNELS) ? ACTIVE_CLASS : DEFAULT_CLASS}>Funnels</span>
<ChevronDownIcon className="-mr-1 ml-1 h-4 w-4" aria-hidden="true" />
</Menu.Button>
</div>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Menu.Items className="text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10">
<div className="py-1">
{funnelNames.map((funnelName) => {
return (
<Menu.Item key={funnelName}>
{({ active }) => (
<span
onClick={setFunnel(funnelName)}
className={classNames(
active ? 'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer' : 'text-gray-700 dark:text-gray-200',
'block px-4 py-2 text-sm',
(mode === FUNNELS && selectedFunnel === funnelName) ? 'font-bold text-gray-500' : ''
)}
>
{funnelName}
</span>
)}
</Menu.Item>
)
})}
</div>
</Menu.Items>
</Transition>
</Menu>
}
function tabSwitcher(toMode, displayName) {
const className = classNames({ [ACTIVE_CLASS]: mode == toMode, [DEFAULT_CLASS]: mode !== toMode })
const setTab = () => {
storage.setItem(tabKey, toMode)
setMode(toMode)
}
return (
<div className={className} onClick={setTab}>
{displayName}
</div>
)
}
function tabs() {
return (
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{isEnabled(CONVERSIONS) && tabSwitcher(CONVERSIONS, 'Goals')}
{isEnabled(PROPS) && tabSwitcher(PROPS, 'Properties')}
{isEnabled(FUNNELS) && Funnel && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))}
</div>
)
}
function renderConversions() {
if (site.hasGoals) {
return <GoalConversions site={site} query={query} onGoalFilterClick={onGoalFilterClick} />
}
else if (adminAccess) {
return (
<FeatureSetupNotice
site={site}
feature={CONVERSIONS}
title={'Measure how often visitors complete specific actions'}
info={'Goals allow you to track registrations, button clicks, form completions, external link clicks, file downloads, 404 error pages and more.'}
callToAction={{
action: "Set up goals",
link: `/${encodeURIComponent(site.domain)}/settings/goals`
}}
onHideAction={onHideAction(CONVERSIONS)}
/>
)
}
else { return noDataYet() }
}
function renderFunnels() {
if (Funnel === null) {
return featureUnavailable()
}
else if (Funnel && selectedFunnel && site.funnelsAvailable) {
return <Funnel site={site} query={query} funnelName={selectedFunnel} />
}
else if (Funnel && adminAccess) {
let callToAction
if (site.funnelsAvailable) {
callToAction = {action: 'Set up funnels', link: `/${encodeURIComponent(site.domain)}/settings/funnels`}
} else {
callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}
}
return (
<FeatureSetupNotice
site={site}
feature={FUNNELS}
title={'Follow the visitor journey from entry to conversion'}
info={'Funnels allow you to analyze the user flow through your website, uncover possible issues, optimize your site and increase the conversion rate.'}
callToAction={callToAction}
onHideAction={onHideAction(FUNNELS)}
/>
)
}
else { return noDataYet() }
}
function renderProps() {
if (site.hasProps && site.propsAvailable) {
return <Properties site={site} query={query} />
} else if (adminAccess) {
let callToAction
if (site.propsAvailable) {
callToAction = {action: 'Set up props', link: `/${encodeURIComponent(site.domain)}/settings/properties`}
} else {
callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}
}
return (
<FeatureSetupNotice
site={site}
feature={PROPS}
title={'Send custom data to create your own metrics'}
info={'You can attach custom properties when sending a pageview or event. This allows you to create custom metrics and analyze stats we don\'t track automatically.'}
callToAction={callToAction}
onHideAction={onHideAction(PROPS)}
/>
)
} else { return noDataYet() }
}
function noDataYet() {
return (
<div className="font-medium text-gray-500 dark:text-gray-400 py-12 text-center">
No data yet
</div>
)
}
function featureUnavailable() {
return (
<div className="font-medium text-gray-500 dark:text-gray-400 py-12 text-center">
This feature is unavailable
</div>
)
}
function onHideAction(mode) {
return () => { disableMode(mode) }
}
function renderContent() {
switch (mode) {
case CONVERSIONS:
return renderConversions()
case PROPS:
return renderProps()
case FUNNELS:
return renderFunnels()
}
}
function defaultMode() {
if (enabledModes.length === 0) { return null }
const storedMode = storage.getItem(tabKey)
if (storedMode && enabledModes.includes(storedMode)) { return storedMode }
if (enabledModes.includes(CONVERSIONS)) { return CONVERSIONS }
if (enabledModes.includes(PROPS)) { return PROPS }
return FUNNELS
}
function getEnabledModes() {
let enabledModes = []
for (const feature of Object.keys(sectionTitles)) {
const isOptedOut = site[feature + 'OptedOut']
const isAvailable = site[feature + 'Available'] !== false
// If the feature is not supported by the site owner's subscription,
// it only makes sense to display the feature tab to the owner itself
// as only they can upgrade to make the feature available.
const callToActionIsMissing = !isAvailable && currentUserRole !== 'owner'
if (!isOptedOut && !callToActionIsMissing) {
enabledModes.push(feature)
}
}
return enabledModes
}
function isEnabled(mode) {
return enabledModes.includes(mode)
}
function isRealtime() {
return query.period === 'realtime'
}
function sectionTitle() {
if (mode === CONVERSIONS) {
return specialTitleWhenGoalFilter(query, sectionTitles[mode])
} else {
return sectionTitles[mode]
}
}
if (mode) {
return (
<div className="items-start justify-between block w-full mt-6 md:flex">
<div className="w-full p-4 bg-white rounded shadow-xl dark:bg-gray-825">
<div className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">
{sectionTitle() + (isRealtime() ? ' (last 30min)' : '')}
</h3>
{tabs()}
</div>
{renderContent()}
</div>
</div>
)
} else {
return null
}
}

@ -0,0 +1,105 @@
import React, { useCallback, useState } from "react"
import ListReport from "../reports/list";
import Combobox from '../../components/combobox'
import * as api from '../../api'
import * as url from '../../util/url'
import { CR_METRIC, PERCENTAGE_METRIC } from "../reports/metrics";
import * as storage from "../../util/storage";
import { parsePrefix, escapeFilterValue } from "../../util/filters"
export default function Properties(props) {
const { site, query } = props
const propKeyStorageName = `prop_key__${site.domain}`
const propKeyStorageNameForGoal = `${query.filters.goal}__prop_key__${site.domain}`
const [propKey, setPropKey] = useState(choosePropKey())
function singleGoalFilterApplied() {
const goalFilter = query.filters.goal
if (goalFilter) {
const { type, values } = parsePrefix(goalFilter)
return type === 'is' && values.length === 1
} else {
return false
}
}
function choosePropKey() {
if (query.filters.props) {
return Object.keys(query.filters.props)[0]
} else {
return getPropKeyFromStorage()
}
}
function getPropKeyFromStorage() {
if (singleGoalFilterApplied()) {
const storedForGoal = storage.getItem(propKeyStorageNameForGoal)
if (storedForGoal) { return storedForGoal }
}
return storage.getItem(propKeyStorageName)
}
function fetchProps() {
return api.get(url.apiPath(site, `/custom-prop-values/${encodeURIComponent(propKey)}`), query)
}
const fetchPropKeyOptions = useCallback(() => {
return (input) => {
return api.get(url.apiPath(site, "/suggestions/prop_key"), query, { q: input.trim() })
}
}, [query])
function onPropKeySelect() {
return (selectedOptions) => {
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0].value
if (newPropKey) {
const storageName = singleGoalFilterApplied() ? propKeyStorageNameForGoal : propKeyStorageName
storage.setItem(storageName, newPropKey)
}
setPropKey(newPropKey)
}
}
/*global BUILD_EXTRA*/
function renderBreakdown() {
return (
<ListReport
fetchData={fetchProps}
getFilterFor={getFilterFor}
keyLabel={propKey}
metrics={[
{ name: 'visitors', label: 'Visitors', plot: true },
{ name: 'events', label: 'Events', hiddenOnMobile: true },
query.filters.goal ? CR_METRIC : PERCENTAGE_METRIC,
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true },
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true }
]}
detailsLink={url.sitePath(site, `/custom-prop-values/${propKey}`)}
maybeHideDetails={true}
query={query}
color="bg-red-50"
colMinWidth={90}
/>
)
}
const getFilterFor = (listItem) => ({
props: JSON.stringify({ ...query.filters.props, [propKey]: escapeFilterValue(listItem.name) })
})
const comboboxValues = propKey ? [{ value: propKey, label: propKey }] : []
const boxClass = 'pl-2 pr-8 py-1 bg-transparent dark:text-gray-300 rounded-md shadow-sm border border-gray-300 dark:border-gray-500'
return (
<div className="w-full mt-4">
<div>
<Combobox boxClass={boxClass} fetchOptions={fetchPropKeyOptions()} singleOption={true} values={comboboxValues} onSelect={onPropKeySelect()} placeholder={'Select a property'} />
</div>
{propKey && renderBreakdown()}
</div>
)
}

@ -1,127 +0,0 @@
import React from 'react';
import { Link } from 'react-router-dom'
import FlipMove from 'react-flip-move'
import Bar from '../bar'
import PropBreakdown from './prop-breakdown'
import numberFormatter from '../../util/number-formatter'
import * as api from '../../api'
import * as url from '../../util/url'
import { escapeFilterValue } from '../../util/filters'
import LazyLoader from '../../components/lazy-loader'
const MOBILE_UPPER_WIDTH = 767
const DEFAULT_WIDTH = 1080
export default class Conversions extends React.Component {
constructor(props) {
super(props)
this.htmlNode = React.createRef()
this.state = {
loading: true,
viewport: DEFAULT_WIDTH,
}
this.onVisible = this.onVisible.bind(this)
this.fetchConversions = this.fetchConversions.bind(this)
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
window.addEventListener('resize', this.handleResize, false);
this.handleResize();
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize, false);
document.removeEventListener('tick', this.fetchConversions)
}
handleResize() {
this.setState({ viewport: window.innerWidth });
}
onVisible() {
this.fetchConversions()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchConversions)
}
}
componentDidUpdate(prevProps) {
if (this.props.query !== prevProps.query) {
const height = this.htmlNode.current.element.offsetHeight
this.setState({loading: true, goals: null, prevHeight: height})
this.fetchConversions()
}
}
getBarMaxWidth() {
const { viewport } = this.state;
return viewport > MOBILE_UPPER_WIDTH ? "16rem" : "10rem";
}
fetchConversions() {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/conversions`, this.props.query)
.then((res) => this.setState({loading: false, goals: res, prevHeight: null}))
}
renderGoal(goal) {
const { viewport } = this.state;
const renderProps = this.props.query.filters['goal'] == goal.name && goal.prop_names
return (
<div className="my-2 text-sm" key={goal.name}>
<div className="flex items-center justify-between my-2">
<Bar
count={goal.unique_conversions}
all={this.state.goals}
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
maxWidthDeduction={this.getBarMaxWidth()}
plot="unique_conversions"
>
<Link to={url.setQuery('goal', escapeFilterValue(goal.name))} className="block px-2 py-1.5 hover:underline relative z-9 break-all lg:truncate dark:text-gray-200">{goal.name}</Link>
</Bar>
<div className="dark:text-gray-200">
<span className="inline-block w-20 font-medium text-right">{numberFormatter(goal.unique_conversions)}</span>
{viewport > MOBILE_UPPER_WIDTH && <span className="inline-block w-20 font-medium text-right">{numberFormatter(goal.total_conversions)}</span>}
<span className="inline-block w-20 font-medium text-right">{goal.conversion_rate}%</span>
</div>
</div>
{ renderProps && <PropBreakdown site={this.props.site} query={this.props.query} goal={goal} /> }
</div>
)
}
renderInner() {
const { viewport } = this.state;
if (this.state.loading) {
return <div className="mx-auto my-2 loading"><div></div></div>
} else if (this.state.goals) {
return (
<React.Fragment>
<h3 className="font-bold dark:text-gray-100">{this.props.title || "Goal Conversions"}</h3>
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
<span>Goal</span>
<div className="text-right">
<span className="inline-block w-20">Uniques</span>
{viewport > MOBILE_UPPER_WIDTH && <span className="inline-block w-20">Total</span>}
<span className="inline-block w-20">CR</span>
</div>
</div>
<FlipMove>
{ this.state.goals.map(this.renderGoal.bind(this)) }
</FlipMove>
</React.Fragment>
)
}
}
render() {
return (
<LazyLoader className="w-full p-4 bg-white rounded shadow-xl dark:bg-gray-825" style={{minHeight: '132px', height: this.state.prevHeight ?? 'auto'}} onVisible={this.onVisible} ref={this.htmlNode}>
{ this.renderInner() }
</LazyLoader>
)
}
}

@ -1,212 +0,0 @@
import React from 'react';
import { Link } from 'react-router-dom'
import * as storage from '../../util/storage'
import Bar from '../bar'
import numberFormatter from '../../util/number-formatter'
import * as api from '../../api'
const MOBILE_UPPER_WIDTH = 767
const DEFAULT_WIDTH = 1080
const BREAKDOWN_LIMIT = 100
// https://stackoverflow.com/a/43467144
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
export default class PropertyBreakdown extends React.Component {
constructor(props) {
super(props)
let propKey = props.goal.prop_names[0]
this.storageKey = 'goalPropTab__' + props.site.domain + props.goal.name
const storedKey = storage.getItem(this.storageKey)
if (props.goal.prop_names.includes(storedKey)) {
propKey = storedKey
}
if (props.query.filters['props']) {
propKey = Object.keys(props.query.filters['props'])[0]
}
this.state = {
loading: true,
propKey: propKey,
viewport: DEFAULT_WIDTH,
breakdown: [],
page: 1,
moreResultsAvailable: false
}
this.handleResize = this.handleResize.bind(this);
this.fetch = this.fetch.bind(this)
this.fetchAndReplace = this.fetchAndReplace.bind(this)
this.fetchAndConcat = this.fetchAndConcat.bind(this)
}
componentDidMount() {
window.addEventListener('resize', this.handleResize, false);
this.handleResize();
this.fetchAndReplace()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchAndReplace)
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize, false);
document.removeEventListener('tick', this.fetchAndReplace)
}
handleResize() {
this.setState({ viewport: window.innerWidth });
}
getBarMaxWidth() {
const { viewport } = this.state;
return viewport > MOBILE_UPPER_WIDTH ? "16rem" : "10rem";
}
fetch({concat}) {
if (!this.props.query.filters['goal']) return
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/property/${encodeURIComponent(this.state.propKey)}`, this.props.query, {limit: BREAKDOWN_LIMIT, page: this.state.page})
.then((res) => {
let breakdown = concat ? this.state.breakdown.concat(res) : res
this.setState(() => ({
loading: false,
breakdown: breakdown,
moreResultsAvailable: res.length >= BREAKDOWN_LIMIT
}))
})
}
fetchAndReplace() {
this.fetch({concat: false})
}
fetchAndConcat() {
this.fetch({concat: true})
}
loadMore() {
this.setState({loading: true, page: this.state.page + 1}, this.fetchAndConcat.bind(this))
}
renderUrl(value) {
if (isValidHttpUrl(value.name)) {
return (
<a target="_blank" href={value.name} rel="noreferrer" className="hidden group-hover:block">
<svg className="inline h-4 w-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
</a>
)
}
return null
}
renderPropContent(value, query) {
return (
<span className="flex px-2 py-1.5 group dark:text-gray-300 relative z-9 break-all">
<Link
to={{pathname: window.location.pathname, search: query.toString()}}
className="md:truncate hover:underline block"
>
{ value.name }
</Link>
{ this.renderUrl(value) }
</span>
)
}
renderPropValue(value) {
const query = new URLSearchParams(window.location.search)
query.set('props', JSON.stringify({[this.state.propKey]: value.name}))
const { viewport } = this.state;
return (
<div className="flex items-center justify-between my-2" key={value.name}>
<Bar
count={value.unique_conversions}
plot="unique_conversions"
all={this.state.breakdown}
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
maxWidthDeduction={this.getBarMaxWidth()}
>
{this.renderPropContent(value, query)}
</Bar>
<div className="dark:text-gray-200">
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.unique_conversions)}</span>
{
viewport > MOBILE_UPPER_WIDTH ?
(
<span
className="font-medium inline-block w-20 text-right"
>{numberFormatter(value.total_conversions)}
</span>
)
: null
}
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.conversion_rate)}%</span>
</div>
</div>
)
}
changePropKey(newKey) {
storage.setItem(this.storageKey, newKey)
this.setState({propKey: newKey, loading: true, breakdown: [], page: 1, moreResultsAvailable: false}, this.fetchAndReplace)
}
renderLoading() {
if (this.state.loading) {
return <div className="px-4 py-2"><div className="loading sm mx-auto"><div></div></div></div>
} else if (this.state.moreResultsAvailable && this.props.query.period !== 'realtime') {
return (
<div className="w-full text-center my-4">
<button onClick={this.loadMore.bind(this)} type="button" className="button">
Load more
</button>
</div>
)
}
}
renderBody() {
return this.state.breakdown.map((propValue) => this.renderPropValue(propValue))
}
renderPill(key) {
const isActive = this.state.propKey === key
if (isActive) {
return <li key={key} className="inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold mr-2 active-prop-heading">{key}</li>
} else {
return <li key={key} className="hover:text-indigo-600 cursor-pointer mr-2" onClick={this.changePropKey.bind(this, key)}>{key}</li>
}
}
render() {
return (
<div className="w-full pl-3 sm:pl-6 mt-4">
<div className="flex-col sm:flex-row flex items-center pb-1">
<span className="text-xs font-bold text-gray-600 dark:text-gray-300 self-start sm:self-auto mb-1 sm:mb-0">Breakdown by:</span>
<ul className="flex flex-wrap font-medium text-xs text-gray-500 dark:text-gray-400 leading-5 pl-1 sm:pl-2">
{ this.props.goal.prop_names.map(this.renderPill.bind(this)) }
</ul>
</div>
{ this.renderBody() }
{ this.renderLoading()}
</div>
)
}
}

@ -1,20 +1,27 @@
import React from 'react';
import * as storage from '../../util/storage'
import { isFilteringOnFixedValue } from '../../util/filters'
import ListReport from '../reports/list'
import * as api from '../../api'
import * as url from '../../util/url'
import { VISITORS_METRIC, PERCENTAGE_METRIC, maybeWithCR } from '../reports/metrics';
function Browsers({ query, site }) {
function fetchData() {
return api.get(url.apiPath(site, '/browsers'), query)
}
function getFilterFor(listItem) {
return { browser: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={{ browser: 'name' }}
getFilterFor={getFilterFor}
keyLabel="Browser"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
/>
)
@ -25,14 +32,19 @@ function BrowserVersions({ query, site }) {
return api.get(url.apiPath(site, '/browser-versions'), query)
}
const isNotSet = query.filters.browser === '(not set)'
const filter = isNotSet ? {} : { browser_version: 'name' }
function getFilterFor(listItem) {
if (query.filters.browser === '(not set)') {
return {}
}
return { browser_version: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={filter}
getFilterFor={getFilterFor}
keyLabel="Browser version"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
/>
)
@ -44,11 +56,16 @@ function OperatingSystems({ query, site }) {
return api.get(url.apiPath(site, '/operating-systems'), query)
}
function getFilterFor(listItem) {
return { os: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={{ os: 'name' }}
getFilterFor={getFilterFor}
keyLabel="Operating system"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
/>
)
@ -59,14 +76,19 @@ function OperatingSystemVersions({ query, site }) {
return api.get(url.apiPath(site, '/operating-system-versions'), query)
}
const isNotSet = query.filters.os === '(not set)'
const filter = isNotSet ? {} : { os_version: 'name' }
function getFilterFor(listItem) {
if (query.filters.os === '(not set)') {
return {}
}
return { os_version: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={filter}
getFilterFor={getFilterFor}
keyLabel="Operating System Version"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
/>
)
@ -82,11 +104,16 @@ function ScreenSizes({ query, site }) {
return iconFor(screenSize.name)
}
function getFilterFor(listItem) {
return { screen: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={{ screen: 'name' }}
getFilterFor={getFilterFor}
keyLabel="Screen size"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
renderIcon={renderIcon}
/>
@ -135,12 +162,12 @@ export default class Devices extends React.Component {
renderContent() {
switch (this.state.mode) {
case 'browser':
if (this.props.query.filters.browser) {
if (isFilteringOnFixedValue(this.props.query, 'browser')) {
return <BrowserVersions site={this.props.site} query={this.props.query} />
}
return <Browsers site={this.props.site} query={this.props.query} />
case 'os':
if (this.props.query.filters.os) {
if (isFilteringOnFixedValue(this.props.query, 'os')) {
return <OperatingSystemVersions site={this.props.site} query={this.props.query} />
}
return <OperatingSystems site={this.props.site} query={this.props.query} />
@ -177,22 +204,16 @@ export default class Devices extends React.Component {
render() {
return (
<div
className="stats-item flex flex-col mt-6 stats-item--has-header w-full"
>
<div
className="stats-item-header flex flex-col flex-grow relative p-4 bg-white rounded shadow-xl dark:bg-gray-825"
>
<div className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">Devices</h3>
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{this.renderPill('Browser', 'browser')}
{this.renderPill('OS', 'os')}
{this.renderPill('Size', 'size')}
</div>
<div>
<div className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">Devices</h3>
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{this.renderPill('Browser', 'browser')}
{this.renderPill('OS', 'os')}
{this.renderPill('Size', 'size')}
</div>
{this.renderContent()}
</div>
{this.renderContent()}
</div>
)
}

@ -1,43 +1,69 @@
import numberFormatter, {durationFormatter} from '../../util/number-formatter'
import { parsePrefix } from '../../util/filters'
export const METRIC_MAPPING = {
'Unique visitors (last 30 min)': 'visitors',
'Pageviews (last 30 min)': 'pageviews',
'Unique visitors': 'visitors',
'Visit duration': 'visit_duration',
'Total pageviews': 'pageviews',
'Views per visit': 'views_per_visit',
'Total visits': 'visits',
'Bounce rate': 'bounce_rate',
'Unique conversions': 'conversions',
export function getGraphableMetrics(query, site) {
const isRealtime = query.period === 'realtime'
const goalFilter = query.filters.goal
const pageFilter = query.filters.page
if (isRealtime && goalFilter) {
return ["visitors"]
} else if (isRealtime) {
return ["visitors", "pageviews"]
} else if (goalFilter && canGraphRevenueMetrics(goalFilter, site)) {
return ["visitors", "events", "average_revenue", "total_revenue", "conversion_rate"]
} else if (goalFilter) {
return ["visitors", "events", "conversion_rate"]
} else if (pageFilter) {
return ["visitors", "visits", "pageviews", "bounce_rate", "time_on_page"]
} else {
return ["visitors", "visits", "pageviews", "views_per_visit", "bounce_rate", "visit_duration"]
}
}
// Revenue metrics can only be graphed if:
// * The query is filtered by at least one revenue goal
// * All revenue goals in filter have the same currency
function canGraphRevenueMetrics(goalFilter, site) {
const goalsInFilter = parsePrefix(goalFilter).values
const revenueGoalsInFilter = site.revenueGoals.filter((rg) => {
return goalsInFilter.includes(rg.event_name)
})
const singleCurrency = revenueGoalsInFilter.every((rg) => {
return rg.currency === revenueGoalsInFilter[0].currency
})
return revenueGoalsInFilter.length > 0 && singleCurrency
}
export const METRIC_LABELS = {
'visitors': 'Visitors',
'pageviews': 'Pageviews',
'events': 'Total Conversions',
'views_per_visit': 'Views per Visit',
'visits': 'Visits',
'bounce_rate': 'Bounce Rate',
'visit_duration': 'Visit Duration',
'conversions': 'Converted Visitors',
'conversion_rate': 'Conversion Rate',
'average_revenue': 'Average Revenue',
'total_revenue': 'Total Revenue',
}
export const METRIC_FORMATTER = {
'visitors': numberFormatter,
'pageviews': numberFormatter,
'events': numberFormatter,
'visits': numberFormatter,
'views_per_visit': (number) => (number),
'bounce_rate': (number) => (`${number}%`),
'visit_duration': durationFormatter,
'conversions': numberFormatter,
}
export const LoadingState = {
loading: 'loading',
refreshing: 'refreshing',
loaded: 'loaded',
isLoadingOrRefreshing: function (state) { return [this.loading, this.refreshing].includes(state) },
isLoadedOrRefreshing: function (state) { return [this.loaded, this.refreshing].includes(state) }
'conversion_rate': (number) => (`${number}%`),
'total_revenue': numberFormatter,
'average_revenue': numberFormatter,
}
const buildComparisonDataset = function(comparisonPlot) {

@ -4,8 +4,9 @@ import React, { Fragment, useCallback, useEffect } from 'react';
import classNames from 'classnames'
import * as storage from '../../util/storage'
import { isKeyPressed } from '../../keybinding.js'
import { monthsBetweenDates } from '../../util/date.js'
export const INTERVAL_LABELS = {
const INTERVAL_LABELS = {
'minute': 'Minutes',
'hour': 'Hours',
'date': 'Days',
@ -13,11 +14,19 @@ export const INTERVAL_LABELS = {
'month': 'Months'
}
export const getStoredInterval = function(period, domain) {
function validIntervals(site, query) {
if (query.period === "custom" && monthsBetweenDates(query.from, query.to) > 12) {
return ["week", "month"]
} else {
return site.validIntervalsByPeriod[query.period]
}
}
function getStoredInterval(period, domain) {
return storage.getItem(`interval__${period}__${domain}`)
}
export const storeInterval = function(period, domain, interval) {
function storeInterval(period, domain, interval) {
storage.setItem(`interval__${period}__${domain}`, interval)
}
@ -32,37 +41,55 @@ function subscribeKeybinding(element) {
}, [handleKeyPress])
}
function DropdownItem({ option, currentInterval, updateInterval }) {
return (
<Menu.Item onClick={() => updateInterval(option)} key={option} disabled={option == currentInterval}>
{({ active }) => (
<span className={classNames({
'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer': active,
'text-gray-700 dark:text-gray-200': !active,
'font-bold cursor-none select-none': option == currentInterval,
}, 'block px-4 py-2 text-sm')}>
{ INTERVAL_LABELS[option] }
</span>
)}
</Menu.Item>
)
export const getCurrentInterval = function(site, query) {
const options = validIntervals(site, query)
const storedInterval = getStoredInterval(query.period, site.domain)
const defaultInterval = [...options].pop()
if (storedInterval && options.includes(storedInterval)) {
return storedInterval
} else {
return defaultInterval
}
}
export function IntervalPicker({ graphData, query, site, updateInterval }) {
export function IntervalPicker({ query, site, onIntervalUpdate }) {
if (query.period == 'realtime') return null
const menuElement = React.useRef(null)
const options = validIntervals(site, query)
const currentInterval = getCurrentInterval(site, query)
subscribeKeybinding(menuElement)
const currentInterval = graphData?.interval
const options = site.validIntervalsByPeriod[query.period]
function updateInterval(interval) {
storeInterval(query.period, site.domain, interval)
onIntervalUpdate(interval)
}
function renderDropdownItem(option) {
return (
<Menu.Item onClick={() => updateInterval(option)} key={option} disabled={option == currentInterval}>
{({ active }) => (
<span className={classNames({
'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer': active,
'text-gray-700 dark:text-gray-200': !active,
'font-bold cursor-none select-none': option == currentInterval,
}, 'block px-4 py-2 text-sm')}>
{INTERVAL_LABELS[option]}
</span>
)}
</Menu.Item>
)
}
return (
<Menu as="div" className="relative inline-block pl-2">
{({ open }) => (
<>
<Menu.Button ref={menuElement} className="text-sm inline-flex focus:outline-none text-gray-700 dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600 items-center">
{ INTERVAL_LABELS[currentInterval] }
{INTERVAL_LABELS[currentInterval]}
<ChevronDownIcon className="ml-1 h-4 w-4" aria-hidden="true" />
</Menu.Button>
@ -70,13 +97,13 @@ export function IntervalPicker({ graphData, query, site, updateInterval }) {
as={Fragment}
show={open}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95">
<Menu.Items className="py-1 text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10" static>
{ options.map((option) => DropdownItem({ option, currentInterval, updateInterval })) }
{options.map(renderDropdownItem)}
</Menu.Items>
</Transition>
</>

@ -0,0 +1,247 @@
import React from 'react';
import { withRouter } from 'react-router-dom'
import Chart from 'chart.js/auto';
import { navigateToQuery } from '../../query'
import GraphTooltip from './graph-tooltip'
import { buildDataSet, METRIC_LABELS, METRIC_FORMATTER } from './graph-util'
import dateFormatter from './date-formatter';
import FadeIn from '../../fade-in';
import classNames from 'classnames';
const calculateMaximumY = function(dataset) {
const yAxisValues = dataset
.flatMap((item) => item.data)
.map((item) => item || 0)
if (yAxisValues) {
return Math.max(...yAxisValues)
} else {
return 1
}
}
class LineGraph extends React.Component {
constructor(props) {
super(props);
this.regenerateChart = this.regenerateChart.bind(this);
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
getGraphMetric() {
let metric = this.props.graphData.metric
if (metric == 'visitors' && this.props.query.filters.goal) {
return 'conversions'
} else {
return metric
}
}
regenerateChart() {
const { graphData, query } = this.props
const metric = this.getGraphMetric()
const graphEl = document.getElementById("main-graph-canvas")
this.ctx = graphEl.getContext('2d');
const dataSet = buildDataSet(graphData.plot, graphData.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
return new Chart(this.ctx, {
type: 'line',
data: {
labels: graphData.labels,
datasets: dataSet
},
options: {
animation: false,
plugins: {
legend: { display: false },
tooltip: {
enabled: false,
mode: 'index',
intersect: false,
position: 'average',
external: GraphTooltip(graphData, metric, query)
},
},
responsive: true,
maintainAspectRatio: false,
onResize: this.updateWindowDimensions,
elements: { line: { tension: 0 }, point: { radius: 0 } },
onClick: this.maybeHopToHoveredPeriod.bind(this),
scale: {
ticks: { precision: 0, maxTicksLimit: 8 }
},
scales: {
y: {
min: 0,
suggestedMax: calculateMaximumY(dataSet),
ticks: {
callback: METRIC_FORMATTER[metric],
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
},
grid: {
zeroLineColor: 'transparent',
drawBorder: false,
}
},
yComparison: {
min: 0,
suggestedMax: calculateMaximumY(dataSet),
display: false,
grid: { display: false },
},
x: {
grid: { display: false },
ticks: {
callback: function(val, _index, _ticks) {
if (this.getLabelForValue(val) == "__blank__") return ""
const hasMultipleYears =
graphData.labels
.filter((date) => typeof date === 'string')
.map(date => date.split('-')[0])
.filter((value, index, list) => list.indexOf(value) === index)
.length > 1
if (graphData.interval === 'hour' && query.period !== 'day') {
const date = dateFormatter({
interval: "date",
longForm: false,
period: query.period,
shouldShowYear: hasMultipleYears,
})(this.getLabelForValue(val))
const hour = dateFormatter({
interval: graphData.interval,
longForm: false,
period: query.period,
shouldShowYear: hasMultipleYears,
})(this.getLabelForValue(val))
// Returns a combination of date and hour. This is because
// small intervals like hour may return multiple days
// depending on the query period.
return `${date}, ${hour}`
}
if (graphData.interval === 'minute' && query.period !== 'realtime') {
return dateFormatter({
interval: "hour", longForm: false, period: query.period,
})(this.getLabelForValue(val))
}
return dateFormatter({
interval: graphData.interval, longForm: false, period: query.period, shouldShowYear: hasMultipleYears,
})(this.getLabelForValue(val))
},
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
}
}
},
interaction: {
mode: 'index',
intersect: false,
}
}
});
}
repositionTooltip(e) {
const tooltipEl = document.getElementById('chartjs-tooltip');
if (tooltipEl && window.innerWidth >= 768) {
if (e.clientX > 0.66 * window.innerWidth) {
tooltipEl.style.right = (window.innerWidth - e.clientX) + window.pageXOffset + 'px'
tooltipEl.style.left = null;
} else {
tooltipEl.style.right = null;
tooltipEl.style.left = e.clientX + window.pageXOffset + 'px'
}
tooltipEl.style.top = e.clientY + window.pageYOffset + 'px'
tooltipEl.style.opacity = 1;
}
}
componentDidMount() {
if (this.props.graphData) {
this.chart = this.regenerateChart();
}
window.addEventListener('mousemove', this.repositionTooltip);
}
componentDidUpdate(prevProps) {
const { graphData, darkTheme } = this.props;
const tooltip = document.getElementById('chartjs-tooltip');
if (
graphData !== prevProps.graphData ||
darkTheme !== prevProps.darkTheme
) {
if (graphData) {
if (this.chart) {
this.chart.destroy();
}
this.chart = this.regenerateChart();
this.chart.update();
}
if (tooltip) {
tooltip.style.display = 'none';
}
}
if (!graphData) {
if (this.chart) {
this.chart.destroy();
}
if (tooltip) {
tooltip.style.display = 'none';
}
}
}
componentWillUnmount() {
// Ensure that the tooltip doesn't hang around when we are loading more data
const tooltip = document.getElementById('chartjs-tooltip');
if (tooltip) {
tooltip.style.opacity = 0;
tooltip.style.display = 'none';
}
window.removeEventListener('mousemove', this.repositionTooltip)
}
/**
* The current ticks' limits are set to treat iPad (regular/Mini/Pro) as a regular screen.
* @param {*} chart - The chart instance.
* @param {*} dimensions - An object containing the new dimensions *of the chart.*
*/
updateWindowDimensions(chart, dimensions) {
chart.options.scales.x.ticks.maxTicksLimit = dimensions.width < 720 ? 5 : 8
}
maybeHopToHoveredPeriod(e) {
const element = this.chart.getElementsAtEventForMode(e, 'index', { intersect: false })[0]
const date = this.props.graphData.labels[element.index] || this.props.graphData.comparison_labels[element.index]
if (this.props.graphData.interval === 'month') {
navigateToQuery(this.props.history, this.props.query, { period: 'month', date })
} else if (this.props.graphData.interval === 'date') {
navigateToQuery(this.props.history, this.props.query, { period: 'day', date })
}
}
render() {
const { graphData } = this.props
const canvasClass = classNames('mt-4 select-none', { 'cursor-pointer': !['minute', 'hour'].includes(graphData?.interval) })
return (
<FadeIn show={graphData}>
<div className="relative h-96 print:h-auto print:pb-8 w-full z-0">
<canvas id="main-graph-canvas" className={canvasClass}></canvas>
</div>
</FadeIn>
)
}
}
export default withRouter(LineGraph)

@ -0,0 +1,17 @@
import React from "react"
export default function SamplingNotice({topStatData}) {
const samplePercent = topStatData?.samplePercent
if (samplePercent && samplePercent < 100) {
return (
<div tooltip={`Stats based on a ${samplePercent}% sample of all visitors`} className="cursor-pointer w-4 h-4 mx-2">
<svg className="absolute w-4 h-4 dark:text-gray-300 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
)
} else {
return null
}
}

@ -0,0 +1,53 @@
import React, { useState } from "react"
import * as api from '../../api'
import { getCurrentInterval } from "./interval-picker"
export default function StatsExport({site, query}) {
const [exporting, setExporting] = useState(false)
function startExport() {
setExporting(true)
document.cookie = "exporting="
pollExportReady()
}
function pollExportReady() {
if (document.cookie.includes('exporting')) {
setTimeout(pollExportReady, 1000)
} else {
setExporting(false)
}
}
function renderLoading() {
return (
<svg className="animate-spin h-4 w-4 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
)
}
function renderExportLink() {
const interval = getCurrentInterval(site, query)
const queryParams = api.serializeQuery(query, [{ interval }])
const endpoint = `/${encodeURIComponent(site.domain)}/export${queryParams}`
return (
<a href={endpoint} download onClick={startExport}>
<svg className="absolute text-gray-700 feather dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
</a>
)
}
return (
<div className="w-4 h-4 mx-2">
{exporting && renderLoading()}
{!exporting && renderExportLink()}
</div>
)
}

@ -3,8 +3,9 @@ import { Tooltip } from '../../util/tooltip'
import { SecondsSinceLastLoad } from '../../util/seconds-since-last-load'
import classNames from "classnames";
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import { METRIC_MAPPING } from './graph-util'
import * as storage from '../../util/storage'
import { formatDateRange } from '../../util/date.js'
import { getGraphableMetrics } from "./graph-util.js";
function Maybe({condition, children}) {
if (condition) {
@ -14,99 +15,103 @@ function Maybe({condition, children}) {
}
}
export default class TopStats extends React.Component {
renderPercentageComparison(name, comparison, forceDarkMode = false) {
const formattedComparison = numberFormatter(Math.abs(comparison))
const defaultClassName = classNames({
"text-xs dark:text-gray-100": !forceDarkMode,
"text-xs text-gray-100": forceDarkMode
})
const noChangeClassName = classNames({
"text-xs text-gray-700 dark:text-gray-300": !forceDarkMode,
"text-xs text-gray-300": forceDarkMode
})
if (comparison > 0) {
const color = name === 'Bounce rate' ? 'text-red-400' : 'text-green-500'
return <span className={defaultClassName}><span className={color + ' font-bold'}>&uarr;</span> {formattedComparison}%</span>
} else if (comparison < 0) {
const color = name === 'Bounce rate' ? 'text-green-500' : 'text-red-400'
return <span className={defaultClassName}><span className={color + ' font-bold'}>&darr;</span> {formattedComparison}%</span>
} else if (comparison === 0) {
return <span className={noChangeClassName}>&#12336; 0%</span>
} else {
return null
}
function renderPercentageComparison(name, comparison, forceDarkBg = false) {
const formattedComparison = numberFormatter(Math.abs(comparison))
const defaultClassName = classNames({
"pl-2 text-xs dark:text-gray-100": !forceDarkBg,
"pl-2 text-xs text-gray-100": forceDarkBg
})
const noChangeClassName = classNames({
"pl-2 text-xs text-gray-700 dark:text-gray-300": !forceDarkBg,
"pl-2 text-xs text-gray-300": forceDarkBg
})
if (comparison > 0) {
const color = name === 'Bounce rate' ? 'text-red-400' : 'text-green-500'
return <span className={defaultClassName}><span className={color + ' font-bold'}>&uarr;</span> {formattedComparison}%</span>
} else if (comparison < 0) {
const color = name === 'Bounce rate' ? 'text-green-500' : 'text-red-400'
return <span className={defaultClassName}><span className={color + ' font-bold'}>&darr;</span> {formattedComparison}%</span>
} else if (comparison === 0) {
return <span className={noChangeClassName}>&#12336; 0%</span>
} else {
return null
}
}
topStatNumberShort(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
return value + '%'
} else {
return numberFormatter(value)
}
function topStatNumberShort(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
return value + '%'
} else if (['average revenue', 'total revenue'].includes(name.toLowerCase())) {
return value?.short
} else {
return numberFormatter(value)
}
}
topStatNumberLong(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
return value + '%'
} else {
return (value || 0).toLocaleString()
}
function topStatNumberLong(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
return value + '%'
} else if (['average revenue', 'total revenue'].includes(name.toLowerCase())) {
return value?.long
} else {
return (value || 0).toLocaleString()
}
}
topStatTooltip(stat, query) {
export default function TopStats(props) {
const {site, query, data, onMetricUpdate, tooltipBoundary, lastLoadTimestamp} = props
function tooltip(stat) {
let statName = stat.name.toLowerCase()
statName = stat.value === 1 ? statName.slice(0, -1) : statName
const { topStatData, lastLoadTimestamp } = this.props
const showingImported = topStatData?.imported_source && topStatData?.with_imported
return (
<div>
{query.comparison && <div className="whitespace-nowrap">
{this.topStatNumberLong(stat.name, stat.value)} vs. {this.topStatNumberLong(stat.name, stat.comparison_value)} {statName}
<span className="ml-2">{this.renderPercentageComparison(stat.name, stat.change, true)}</span>
{topStatNumberLong(stat.name, stat.value)} vs. {topStatNumberLong(stat.name, stat.comparison_value)} {statName}
<span className="ml-2">{renderPercentageComparison(stat.name, stat.change, true)}</span>
</div>}
{!query.comparison && <div className="whitespace-nowrap">
{this.topStatNumberLong(stat.name, stat.value)} {statName}
{topStatNumberLong(stat.name, stat.value)} {statName}
</div>}
{stat.name === 'Current visitors' && <p className="font-normal text-xs">Last updated <SecondsSinceLastLoad lastLoadTimestamp={lastLoadTimestamp}/>s ago</p>}
{stat.name === 'Views per visit' && showingImported && <p className="font-normal text-xs whitespace-nowrap">Based only on native data</p>}
</div>
)
}
canMetricBeGraphed(stat) {
const isTotalUniqueVisitors = this.props.query.filters.goal && stat.name === 'Unique visitors'
const isKnownMetric = Object.keys(METRIC_MAPPING).includes(stat.name)
return isKnownMetric && !isTotalUniqueVisitors
function canMetricBeGraphed(stat) {
const graphableMetrics = getGraphableMetrics(query, site)
return stat.graph_metric && graphableMetrics.includes(stat.graph_metric)
}
maybeUpdateMetric(stat) {
if (this.canMetricBeGraphed(stat)) {
this.props.updateMetric(METRIC_MAPPING[stat.name])
function maybeUpdateMetric(stat) {
if (canMetricBeGraphed(stat)) {
storage.setItem(`metric__${site.domain}`, stat.graph_metric)
onMetricUpdate(stat.graph_metric)
}
}
blinkingDot() {
function blinkingDot() {
return (
<div key="dot" className="block pulsating-circle" style={{ left: '125px', top: '52px' }}></div>
)
}
renderStatName(stat) {
const { metric } = this.props
const isSelected = metric === METRIC_MAPPING[stat.name]
function getStoredMetric() {
return storage.getItem(`metric__${site.domain}`)
}
function renderStatName(stat) {
const isSelected = stat.graph_metric === getStoredMetric()
const [statDisplayName, statExtraName] = stat.name.split(/(\(.+\))/g)
@ -123,48 +128,45 @@ export default class TopStats extends React.Component {
)
}
render() {
const { topStatData, query, site } = this.props
const stats = topStatData && topStatData.top_stats.map((stat, index) => {
const className = classNames('px-4 md:px-6 w-1/2 my-4 lg:w-auto group select-none', {
'cursor-pointer': this.canMetricBeGraphed(stat),
'lg:border-l border-gray-300': index > 0,
'border-r lg:border-r-0': index % 2 === 0
})
return (
<Tooltip key={stat.name} info={this.topStatTooltip(stat, query)} className={className} onClick={() => { this.maybeUpdateMetric(stat) }} boundary={this.props.tooltipBoundary}>
{this.renderStatName(stat)}
<div className="my-1 space-y-2">
<div>
<span className="flex items-center justify-between whitespace-nowrap">
<p className="font-bold text-xl dark:text-gray-100" id={METRIC_MAPPING[stat.name]}>{this.topStatNumberShort(stat.name, stat.value)}</p>
<Maybe condition={!query.comparison}>
{this.renderPercentageComparison(stat.name, stat.change)}
</Maybe>
</span>
<Maybe condition={query.comparison}>
<p className="text-xs dark:text-gray-100">{ formatDateRange(site, topStatData.from, topStatData.to) }</p>
</Maybe>
</div>
function renderStat(stat, index) {
const className = classNames('px-4 md:px-6 w-1/2 my-4 lg:w-auto group select-none', {
'cursor-pointer': canMetricBeGraphed(stat),
'lg:border-l border-gray-300': index > 0,
'border-r lg:border-r-0': index % 2 === 0
})
return (
<Tooltip key={stat.name} info={tooltip(stat, query)} className={className} onClick={() => { maybeUpdateMetric(stat) }} boundary={tooltipBoundary}>
{renderStatName(stat)}
<div className="my-1 space-y-2">
<div>
<span className="flex items-center justify-between whitespace-nowrap">
<p className="font-bold text-xl dark:text-gray-100" id={stat.graph_metric}>{topStatNumberShort(stat.name, stat.value)}</p>
<Maybe condition={!query.comparison}>
{ renderPercentageComparison(stat.name, stat.change) }
</Maybe>
</span>
<Maybe condition={query.comparison}>
<div>
<p className="font-bold text-xl text-gray-500 dark:text-gray-400">{ this.topStatNumberShort(stat.name, stat.comparison_value) }</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{ formatDateRange(site, topStatData.comparing_from, topStatData.comparing_to) }</p>
</div>
<p className="text-xs dark:text-gray-100">{ formatDateRange(site, data.from, data.to) }</p>
</Maybe>
</div>
<Maybe condition={query.comparison}>
<div>
<p className="font-bold text-xl text-gray-500 dark:text-gray-400">{ topStatNumberShort(stat.name, stat.comparison_value) }</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{ formatDateRange(site, data.comparing_from, data.comparing_to) }</p>
</div>
</Tooltip>
)
})
</Maybe>
</div>
</Tooltip>
)
}
if (stats && query && query.period === 'realtime') {
stats.push(this.blinkingDot())
}
const stats = data && data.top_stats.map(renderStat)
return stats || null;
if (stats && query.period === 'realtime') {
stats.push(blinkingDot())
}
return stats || null;
}

@ -1,521 +1,153 @@
import React from 'react';
import { withRouter, Link } from 'react-router-dom'
import Chart from 'chart.js/auto';
import { navigateToQuery } from '../../query'
import React, { useState, useEffect, useRef, useCallback } from 'react';
import * as api from '../../api'
import * as storage from '../../util/storage'
import LazyLoader from '../../components/lazy-loader'
import GraphTooltip from './graph-tooltip'
import { buildDataSet, METRIC_MAPPING, METRIC_LABELS, METRIC_FORMATTER, LoadingState } from './graph-util'
import dateFormatter from './date-formatter';
import { getGraphableMetrics } from './graph-util'
import TopStats from './top-stats';
import { IntervalPicker, getStoredInterval, storeInterval } from './interval-picker';
import { IntervalPicker, getCurrentInterval } from './interval-picker'
import StatsExport from './stats-export'
import WithImportedSwitch from './with-imported-switch';
import SamplingNotice from './sampling-notice';
import FadeIn from '../../fade-in';
import * as url from '../../util/url'
import classNames from 'classnames';
import { isComparisonEnabled } from '../../comparison-input'
import LineGraphWithRouter from './line-graph'
const calculateMaximumY = function(dataset) {
const yAxisValues = dataset
.flatMap((item) => item.data)
.map((item) => item || 0)
if (yAxisValues) {
return Math.max(...yAxisValues)
} else {
return 1
function fetchTopStats(site, query) {
const q = { ...query }
if (!isComparisonEnabled(q.comparison)) {
q.comparison = 'previous_period'
}
}
class LineGraph extends React.Component {
constructor(props) {
super(props);
this.boundary = React.createRef()
this.regenerateChart = this.regenerateChart.bind(this);
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
this.state = {
exported: false
};
}
return api.get(url.apiPath(site, '/top-stats'), q)
}
regenerateChart() {
const { graphData, metric, query } = this.props
const graphEl = document.getElementById("main-graph-canvas")
this.ctx = graphEl.getContext('2d');
const dataSet = buildDataSet(graphData.plot, graphData.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
function fetchMainGraph(site, query, metric, interval) {
const params = {metric, interval}
return api.get(url.apiPath(site, '/main-graph'), query, params)
}
return new Chart(this.ctx, {
type: 'line',
data: {
labels: graphData.labels,
datasets: dataSet
},
options: {
animation: false,
plugins: {
legend: { display: false },
tooltip: {
enabled: false,
mode: 'index',
intersect: false,
position: 'average',
external: GraphTooltip(graphData, metric, query)
},
},
responsive: true,
maintainAspectRatio: false,
onResize: this.updateWindowDimensions,
elements: { line: { tension: 0 }, point: { radius: 0 } },
onClick: this.onClick.bind(this),
scales: {
y: {
min: 0,
suggestedMax: calculateMaximumY(dataSet),
ticks: {
callback: METRIC_FORMATTER[metric],
maxTicksLimit: 8,
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
},
grid: {
zeroLineColor: 'transparent',
drawBorder: false,
}
},
yComparison: {
min: 0,
suggestedMax: calculateMaximumY(dataSet),
display: false,
grid: { display: false },
},
x: {
grid: { display: false },
ticks: {
maxTicksLimit: 8,
callback: function (val, _index, _ticks) {
if (this.getLabelForValue(val) == "__blank__") return ""
export default function VisitorGraph(props) {
const {site, query, lastLoadTimestamp} = props
const isRealtime = query.period === 'realtime'
const isDarkTheme = document.querySelector('html').classList.contains('dark') || false
const hasMultipleYears =
graphData.labels
.filter((date) => typeof date === 'string')
.map(date => date.split('-')[0])
.filter((value, index, list) => list.indexOf(value) === index)
.length > 1
const topStatsBoundary = useRef(null)
if (graphData.interval === 'hour' && query.period !== 'day') {
const date = dateFormatter({
interval: "date",
longForm: false,
period: query.period,
shouldShowYear: hasMultipleYears,
})(this.getLabelForValue(val))
const [topStatData, setTopStatData] = useState(null)
const [topStatsLoading, setTopStatsLoading] = useState(true)
const [graphData, setGraphData] = useState(null)
const [graphLoading, setGraphLoading] = useState(true)
const hour = dateFormatter({
interval: graphData.interval,
longForm: false,
period: query.period,
shouldShowYear: hasMultipleYears,
})(this.getLabelForValue(val))
// This state is explicitly meant for the situation where either graph interval
// or graph metric is changed. That results in behaviour where Top Stats stay
// intact, but the graph container alone will display a loading spinner for as
// long as new graph data is fetched.
const [graphRefreshing, setGraphRefreshing] = useState(false)
// Returns a combination of date and hour. This is because
// small intervals like hour may return multiple days
// depending on the query period.
return `${date}, ${hour}`
}
if (graphData.interval === 'minute' && query.period !== 'realtime') {
return dateFormatter({
interval: "hour", longForm: false, period: query.period,
})(this.getLabelForValue(val))
}
const onIntervalUpdate = useCallback((newInterval) => {
setGraphData(null)
setGraphRefreshing(true)
fetchGraphData(getStoredMetric(), newInterval)
}, [query])
return dateFormatter({
interval: graphData.interval, longForm: false, period: query.period, shouldShowYear: hasMultipleYears,
})(this.getLabelForValue(val))
},
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
}
}
},
interaction: {
mode: 'index',
intersect: false,
}
}
});
}
const onMetricUpdate = useCallback((newMetric) => {
setGraphData(null)
setGraphRefreshing(true)
fetchGraphData(newMetric, getCurrentInterval(site, query))
}, [query])
repositionTooltip(e) {
const tooltipEl = document.getElementById('chartjs-tooltip');
if (tooltipEl && window.innerWidth >= 768) {
if (e.clientX > 0.66 * window.innerWidth) {
tooltipEl.style.right = (window.innerWidth - e.clientX) + window.pageXOffset + 'px'
tooltipEl.style.left = null;
} else {
tooltipEl.style.right = null;
tooltipEl.style.left = e.clientX + window.pageXOffset + 'px'
}
tooltipEl.style.top = e.clientY + window.pageYOffset + 'px'
tooltipEl.style.opacity = 1;
}
}
useEffect(() => {
setTopStatData(null)
setTopStatsLoading(true)
setGraphData(null)
setGraphLoading(true)
fetchTopStatsAndGraphData()
componentDidMount() {
if (this.props.graphData) {
this.chart = this.regenerateChart();
if (isRealtime) {
document.addEventListener('tick', fetchTopStatsAndGraphData)
}
window.addEventListener('mousemove', this.repositionTooltip);
}
componentDidUpdate(prevProps) {
const { graphData, darkTheme } = this.props;
const tooltip = document.getElementById('chartjs-tooltip');
if (
graphData !== prevProps.graphData ||
darkTheme !== prevProps.darkTheme
) {
if (graphData) {
if (this.chart) {
this.chart.destroy();
}
this.chart = this.regenerateChart();
this.chart.update();
}
if (tooltip) {
tooltip.style.display = 'none';
}
return () => {
document.removeEventListener('tick', fetchTopStatsAndGraphData)
}
}, [query])
if (!graphData) {
if (this.chart) {
this.chart.destroy();
}
useEffect(() => {
if (topStatData) { storeTopStatsContainerHeight() }
}, [topStatData])
if (tooltip) {
tooltip.style.display = 'none';
}
}
}
componentWillUnmount() {
// Ensure that the tooltip doesn't hang around when we are loading more data
const tooltip = document.getElementById('chartjs-tooltip');
if (tooltip) {
tooltip.style.opacity = 0;
tooltip.style.display = 'none';
}
window.removeEventListener('mousemove', this.repositionTooltip)
}
/**
* The current ticks' limits are set to treat iPad (regular/Mini/Pro) as a regular screen.
* @param {*} chart - The chart instance.
* @param {*} dimensions - An object containing the new dimensions *of the chart.*
*/
updateWindowDimensions(chart, dimensions) {
chart.options.scales.x.ticks.maxTicksLimit = dimensions.width < 720 ? 5 : 8
chart.options.scales.y.ticks.maxTicksLimit = dimensions.height < 233 ? 3 : 8
}
onClick(e) {
const element = this.chart.getElementsAtEventForMode(e, 'index', { intersect: false })[0]
const date = this.props.graphData.labels[element.index] || this.props.graphData.comparison_labels[element.index]
if (this.props.graphData.interval === 'month') {
navigateToQuery(this.props.history, this.props.query, { period: 'month', date })
} else if (this.props.graphData.interval === 'date') {
navigateToQuery(this.props.history, this.props.query, { period: 'day', date })
function fetchTopStatsAndGraphData() {
fetchTopStats(site, query)
.then((res) => {
setTopStatData(res)
setTopStatsLoading(false)
})
let metric = getStoredMetric()
const availableMetrics = getGraphableMetrics(query, site)
if (!availableMetrics.includes(metric)) {
metric = availableMetrics[0]
storage.setItem(`metric__${site.domain}`, metric)
}
}
pollExportReady() {
if (document.cookie.includes('exporting')) {
setTimeout(this.pollExportReady.bind(this), 1000);
} else {
this.setState({exported: false})
}
}
const interval = getCurrentInterval(site, query)
downloadSpinner() {
this.setState({exported: true});
document.cookie = "exporting=";
setTimeout(this.pollExportReady.bind(this), 1000);
fetchGraphData(metric, interval)
}
downloadLink() {
if (this.props.query.period !== 'realtime') {
if (this.state.exported) {
return (
<div className="w-4 h-4 mx-2">
<svg className="animate-spin h-4 w-4 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</div>
)
} else {
const interval = this.props.graphData?.interval
const queryParams = api.serializeQuery(this.props.query, [{ interval }])
const endpoint = `/${encodeURIComponent(this.props.site.domain)}/export${queryParams}`
return (
<a className="w-4 h-4 mx-2" href={endpoint} download onClick={this.downloadSpinner.bind(this)}>
<svg className="absolute text-gray-700 feather dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
</a>
)
}
}
function fetchGraphData(metric, interval) {
fetchMainGraph(site, query, metric, interval)
.then((res) => {
setGraphData(res)
setGraphLoading(false)
setGraphRefreshing(false)
})
}
samplingNotice() {
const samplePercent = this.props.topStatData && this.props.topStatData.sample_percent
if (samplePercent < 100) {
return (
<div tooltip={`Stats based on a ${samplePercent}% sample of all visitors`} className="cursor-pointer w-4 h-4 mx-2">
<svg className="absolute w-4 h-4 dark:text-gray-300 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
)
}
function getStoredMetric() {
return storage.getItem(`metric__${site.domain}`)
}
importedNotice() {
const source = this.props.topStatData && this.props.topStatData.imported_source;
if (source) {
const withImported = this.props.topStatData.with_imported;
const strike = withImported ? "" : " line-through"
const target = url.setQuery('with_imported', !withImported)
const tip = withImported ? "" : "do not ";
return (
<Link to={target} className="w-4 h-4 mx-2">
<div tooltip={`Stats ${tip}include data imported from ${source}.`} className="cursor-pointer w-4 h-4">
<svg className="absolute dark:text-gray-300 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<text x="4" y="18" fontSize="24" fill="currentColor" className={"text-gray-700 dark:text-gray-300" + strike}>{ source[0].toUpperCase() }</text>
</svg>
</div>
</Link>
)
}
function storeTopStatsContainerHeight() {
storage.setItem(`topStatsHeight__${site.domain}`, document.getElementById('top-stats-container').clientHeight)
}
// This function is used for maintaining the main-graph/top-stats container height in the
// loading process. The container height depends on how many top stat metrics are returned
// from the API, but in the loading state, we don't know that yet. We can use localStorage
// to keep track of the Top Stats container height.
getTopStatsHeight() {
if (this.props.topStatData) {
function getTopStatsHeight() {
if (topStatData) {
return 'auto'
} else {
return `${storage.getItem(`topStatsHeight__${this.props.site.domain}`) || 89}px`
return `${storage.getItem(`topStatsHeight__${site.domain}`) || 89}px`
}
}
render() {
const { mainGraphRefreshing, updateMetric, updateInterval, metric, topStatData, query, site, graphData, lastLoadTimestamp } = this.props
const canvasClass = classNames('mt-4 select-none', {'cursor-pointer': !['minute', 'hour'].includes(graphData?.interval)})
return (
<div>
<div id="top-stats-container" className="flex flex-wrap" ref={this.boundary} style={{height: this.getTopStatsHeight()}}>
<TopStats site={site} query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={lastLoadTimestamp} />
return (
<div className={"relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825"}>
{(topStatsLoading || graphLoading) && renderLoader()}
<FadeIn show={!(topStatsLoading || graphLoading)}>
<div id="top-stats-container" className="flex flex-wrap" ref={topStatsBoundary} style={{ height: getTopStatsHeight() }}>
<TopStats site={site} query={query} data={topStatData} onMetricUpdate={onMetricUpdate} tooltipBoundary={topStatsBoundary.current} lastLoadTimestamp={lastLoadTimestamp} />
</div>
<div className="relative px-2">
{mainGraphRefreshing && renderLoader()}
<div className="absolute right-4 -top-10 py-2 md:py-0 flex items-center">
{ this.downloadLink() }
{ this.samplingNotice() }
{ this.importedNotice() }
<IntervalPicker site={site} query={query} graphData={graphData} metric={metric} updateInterval={updateInterval}/>
{graphRefreshing && renderLoader()}
<div className="absolute right-4 -top-8 py-1 flex items-center">
{!isRealtime && <StatsExport site={site} query={query} />}
<SamplingNotice samplePercent={topStatData}/>
<WithImportedSwitch site={site} topStatData={topStatData} />
<IntervalPicker site={site} query={query} onIntervalUpdate={onIntervalUpdate} />
</div>
<FadeIn show={graphData}>
<div className="relative h-96 w-full z-0">
<canvas id="main-graph-canvas" className={canvasClass}></canvas>
</div>
</FadeIn>
<LineGraphWithRouter graphData={graphData} darkTheme={isDarkTheme} query={query} />
</div>
</div>
)
}
}
const LineGraphWithRouter = withRouter(LineGraph)
export default class VisitorGraph extends React.Component {
constructor(props) {
super(props)
this.state = {
topStatsLoadingState: LoadingState.loading,
mainGraphLoadingState: LoadingState.loading,
metric: storage.getItem(`metric__${this.props.site.domain}`) || 'visitors'
}
this.onVisible = this.onVisible.bind(this)
this.updateMetric = this.updateMetric.bind(this)
this.fetchTopStatData = this.fetchTopStatData.bind(this)
this.fetchGraphData = this.fetchGraphData.bind(this)
this.updateInterval = this.updateInterval.bind(this)
}
isIntervalValid(interval) {
const { query, site } = this.props
const validIntervals = site.validIntervalsByPeriod[query.period] || []
return validIntervals.includes(interval)
}
getIntervalFromStorage() {
const { query, site } = this.props
const storedInterval = getStoredInterval(query.period, site.domain)
if (this.isIntervalValid(storedInterval)) {
return storedInterval
} else {
return null
}
}
updateInterval(interval) {
if (this.isIntervalValid(interval)) {
storeInterval(this.props.query.period, this.props.site.domain, interval)
this.setState({ mainGraphLoadingState: LoadingState.refreshing, graphData: null }, this.fetchGraphData)
}
}
onVisible() {
this.setState({mainGraphLoadingState: LoadingState.loading}, this.fetchGraphData)
this.fetchTopStatData()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchGraphData)
document.addEventListener('tick', this.fetchTopStatData)
}
}
componentDidUpdate(prevProps, prevState) {
const { metric } = this.state;
const { query } = this.props
if (query !== prevProps.query) {
this.setState({ mainGraphLoadingState: LoadingState.loading, topStatsLoadingState: LoadingState.loading, graphData: null, topStatData: null }, this.fetchGraphData)
this.fetchTopStatData()
}
if (metric !== prevState.metric) {
this.setState({mainGraphLoadingState: LoadingState.refreshing}, this.fetchGraphData)
}
}
resetMetric() {
const { topStatData } = this.state
const { query, site } = this.props
const savedMetric = storage.getItem(`metric__${site.domain}`)
const selectableMetrics = topStatData && topStatData.top_stats.map(({ name }) => METRIC_MAPPING[name]).filter(name => name)
const canSelectSavedMetric = selectableMetrics && selectableMetrics.includes(savedMetric)
if (query.filters.goal) {
this.setState({ metric: 'conversions' })
} else if (canSelectSavedMetric) {
this.setState({ metric: savedMetric })
} else {
this.setState({ metric: 'visitors' })
}
}
componentWillUnmount() {
document.removeEventListener('tick', this.fetchGraphData)
document.removeEventListener('tick', this.fetchTopStatData)
}
storeTopStatsContainerHeight() {
storage.setItem(`topStatsHeight__${this.props.site.domain}`, document.getElementById('top-stats-container').clientHeight)
}
updateMetric(clickedMetric) {
if (this.state.metric == clickedMetric) return
storage.setItem(`metric__${this.props.site.domain}`, clickedMetric)
this.setState({ metric: clickedMetric, graphData: null })
}
fetchGraphData() {
const url = `/api/stats/${encodeURIComponent(this.props.site.domain)}/main-graph`
let params = { metric: this.state.metric }
const interval = this.getIntervalFromStorage()
if (interval) { params.interval = interval }
api.get(url, this.props.query, params)
.then((res) => {
this.setState({ mainGraphLoadingState: LoadingState.loaded, graphData: res })
return res
})
.catch((err) => {
console.log(err)
this.setState({ mainGraphLoadingState: LoadingState.loaded, graphData: false })
})
}
fetchTopStatData() {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/top-stats`, this.props.query)
.then((res) => {
res.top_stats = this.maybeRemoveFeatureFlaggedMetrics(res.top_stats)
this.setState({ topStatsLoadingState: LoadingState.loaded, topStatData: res }, () => {
this.storeTopStatsContainerHeight()
this.resetMetric()
})
return res
})
}
maybeRemoveFeatureFlaggedMetrics(top_stats) {
if (this.props.site.flags.visits_metric) {
return top_stats
} else {
return top_stats.filter((stat) => {return !(["Total visits", "Views per visit"].includes(stat.name))})
}
}
renderInner() {
const { query, site } = this.props;
const { graphData, metric, topStatData, topStatsLoadingState, mainGraphLoadingState } = this.state;
const theme = document.querySelector('html').classList.contains('dark') || false
const mainGraphRefreshing = (mainGraphLoadingState === LoadingState.refreshing)
const topStatAndGraphLoaded = !!(topStatData && graphData)
const shouldShow =
topStatsLoadingState === LoadingState.loaded &&
LoadingState.isLoadedOrRefreshing(mainGraphLoadingState) &&
(topStatData && mainGraphRefreshing || topStatAndGraphLoaded)
return (
<FadeIn show={shouldShow}>
<LineGraphWithRouter mainGraphRefreshing={mainGraphRefreshing} graphData={graphData} topStatData={topStatData} site={site} query={query} darkTheme={theme} metric={metric} updateMetric={this.updateMetric} updateInterval={this.updateInterval} lastLoadTimestamp={this.props.lastLoadTimestamp} />
</FadeIn>
)
}
render() {
const {mainGraphLoadingState, topStatsLoadingState} = this.state
const showLoader =
[mainGraphLoadingState, topStatsLoadingState].includes(LoadingState.loading) &&
mainGraphLoadingState !== LoadingState.refreshing
return (
<LazyLoader onVisible={this.onVisible}>
<div className={"relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825"}>
{showLoader && renderLoader()}
{this.renderInner()}
</div>
</LazyLoader>
)
}
</div>
)
}
function renderLoader() {

@ -0,0 +1,40 @@
import React from "react"
import { parseNaiveDate, isBefore } from '../../util/date'
import { Link } from 'react-router-dom'
import * as url from '../../util/url'
import { BarsArrowUpIcon } from '@heroicons/react/20/solid'
export default function WithImportedSwitch({site, topStatData}) {
if (!topStatData?.imports_exist) {
return null
}
function isBeforeNativeStats(date) {
if (!date) return false
const nativeStatsBegin = parseNaiveDate(site.nativeStatsBegin)
const parsedDate = parseNaiveDate(date)
return isBefore(parsedDate, nativeStatsBegin, "day")
}
const isQueryingImportedPeriod = isBeforeNativeStats(topStatData.from)
const isComparingImportedPeriod = isBeforeNativeStats(topStatData.comparing_from)
if (isQueryingImportedPeriod || isComparingImportedPeriod) {
const withImported = topStatData.with_imported;
const toggleColor = withImported ? " dark:text-gray-300 text-gray-700" : " dark:text-gray-500 text-gray-400"
const target = url.setQuery('with_imported', !withImported)
const tip = withImported ? "" : "do not ";
return (
<Link to={target} className="w-4 h-4 mx-2">
<div tooltip={`Stats ${tip}include imported data.`} className="cursor-pointer w-4 h-4">
<BarsArrowUpIcon className={"absolute " + toggleColor} />
</div>
</Link>
)
} else {
return null
}
}

@ -6,6 +6,7 @@ import CountriesMap from './map'
import * as api from '../../api'
import {apiPath, sitePath} from '../../util/url'
import ListReport from '../reports/list'
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics';
function Countries({query, site, onClick}) {
function fetchData() {
@ -18,12 +19,17 @@ function Countries({query, site, onClick}) {
return <span className="mr-1">{country.flag}</span>
}
function getFilterFor(listItem) {
return { country: listItem['code'], country_labels: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={{country: 'code', country_labels: 'name'}}
getFilterFor={getFilterFor}
onClick={onClick}
keyLabel="Country"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={sitePath(site, '/countries')}
query={query}
renderIcon={renderIcon}
@ -41,12 +47,17 @@ function Regions({query, site, onClick}) {
return <span className="mr-1">{region.country_flag}</span>
}
function getFilterFor(listItem) {
return {region: listItem['code'], region_labels: listItem['name']}
}
return (
<ListReport
fetchData={fetchData}
filter={{region: 'code', region_labels: 'name'}}
getFilterFor={getFilterFor}
onClick={onClick}
keyLabel="Region"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={sitePath(site, '/regions')}
query={query}
renderIcon={renderIcon}
@ -64,11 +75,16 @@ function Cities({query, site}) {
return <span className="mr-1">{city.country_flag}</span>
}
function getFilterFor(listItem) {
return {city: listItem['code'], city_labels: listItem['name']}
}
return (
<ListReport
fetchData={fetchData}
filter={{city: 'code', city_labels: 'name'}}
getFilterFor={getFilterFor}
keyLabel="City"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={sitePath(site, '/cities')}
query={query}
renderIcon={renderIcon}
@ -167,25 +183,19 @@ export default class Locations extends React.Component {
render() {
return (
<div
className="stats-item flex flex-col w-full mt-6 stats-item--has-header"
>
<div
className="stats-item-header flex flex-col flex-grow bg-white dark:bg-gray-825 shadow-xl rounded p-4 relative"
>
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Locations'}
</h3>
<div className="flex font-medium text-xs text-gray-500 dark:text-gray-400 space-x-2">
{ this.renderPill('Map', 'map') }
{ this.renderPill('Countries', 'countries') }
{ this.renderPill('Regions', 'regions') }
{ this.renderPill('Cities', 'cities') }
</div>
<div>
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Locations'}
</h3>
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{ this.renderPill('Map', 'map') }
{ this.renderPill('Countries', 'countries') }
{ this.renderPill('Regions', 'regions') }
{ this.renderPill('Cities', 'cities') }
</div>
{ this.renderContent() }
</div>
{this.renderContent()}
</div>
)
}

@ -121,7 +121,7 @@ class Countries extends React.Component {
this.props.query,
{
country: country.code,
country_name: country.name
country_labels: country.name
}
)
}

@ -0,0 +1,129 @@
import React, { useEffect, useState } from "react";
import { Link } from 'react-router-dom'
import { withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import * as url from "../../util/url";
import numberFormatter from '../../util/number-formatter'
import { parseQuery } from '../../query'
import { escapeFilterValue } from '../../util/filters'
/*global BUILD_EXTRA*/
/*global require*/
function maybeRequire() {
if (BUILD_EXTRA) {
return require('../../extra/money')
} else {
return { default: null }
}
}
const Money = maybeRequire().default
function ConversionsModal(props) {
const site = props.site
const query = parseQuery(props.location.search, site)
const [loading, setLoading] = useState(true)
const [moreResultsAvailable, setMoreResultsAvailable] = useState(false)
const [page, setPage] = useState(1)
const [list, setList] = useState([])
useEffect(() => {
fetchData()
}, [])
function fetchData() {
api.get(url.apiPath(site, `/conversions`), query, { limit: 100, page })
.then((res) => {
setLoading(false)
setList(list.concat(res))
setPage(page + 1)
setMoreResultsAvailable(res.length >= 100)
})
}
function loadMore() {
setLoading(true)
fetchData()
}
function renderLoadMore() {
return (
<div className="w-full text-center my-4">
<button onClick={loadMore} type="button" className="button">
Load more
</button>
</div>
)
}
function filterSearchLink(listItem) {
const searchParams = new URLSearchParams(window.location.search)
searchParams.set('goal', escapeFilterValue(listItem.name))
return searchParams.toString()
}
function renderListItem(listItem, hasRevenue) {
return (
<tr className="text-sm dark:text-gray-200" key={listItem.name}>
<td className="p-2">
<Link
to={{ pathname: url.siteBasePath(site), search: filterSearchLink(listItem) }}
className="hover:underline block truncate">
{listItem.name}
</Link>
</td>
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.visitors)}</td>
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.events)}</td>
<td className="p-2 w-24 font-medium" align="right">{listItem.conversion_rate}%</td>
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.total_revenue} /></td>}
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue} /></td>}
</tr>
)
}
function renderLoading() {
return <div className="loading my-16 mx-auto"><div></div></div>
}
function renderBody() {
const hasRevenue = BUILD_EXTRA && list.some((goal) => goal.total_revenue)
return (
<>
<h1 className="text-xl font-bold dark:text-gray-100">Goal Conversions</h1>
<div className="my-4 border-b border-gray-300"></div>
<main className="modal__content">
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed">
<thead>
<tr>
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400 truncate" align="left">Goal</th>
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Uniques</th>
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Total</th>
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">CR</th>
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Revenue</th>}
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Average</th>}
</tr>
</thead>
<tbody>
{list.map((item) => renderListItem(item, hasRevenue))}
</tbody>
</table>
</main>
</>
)
}
return (
<Modal site={site}>
{renderBody()}
{loading && renderLoading()}
{!loading && moreResultsAvailable && renderLoadMore()}
</Modal>
)
}
export default withRouter(ConversionsModal)

@ -1,11 +1,12 @@
import React from "react";
import { Link , withRouter } from 'react-router-dom'
import { Link, withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import {parseQuery} from '../../query'
import { parseQuery } from '../../query'
import { trimURL } from '../../util/url'
class EntryPagesModal extends React.Component {
constructor(props) {
@ -24,12 +25,12 @@ class EntryPagesModal extends React.Component {
}
loadPages() {
const {query, page} = this.state;
const { query, page } = this.state;
api.get(
`/api/stats/${encodeURIComponent(this.props.site.domain)}/entry-pages`,
query,
{limit: 100, page}
{ limit: 100, page }
)
.then(
(res) => this.setState((state) => ({
@ -42,11 +43,11 @@ class EntryPagesModal extends React.Component {
loadMore() {
const { page } = this.state;
this.setState({loading: true, page: page + 1}, this.loadPages.bind(this))
this.setState({ loading: true, page: page + 1 }, this.loadPages.bind(this))
}
formatBounceRate(page) {
if (typeof(page.bounce_rate) === 'number') {
if (typeof (page.bounce_rate) === 'number') {
return `${page.bounce_rate}%`;
}
return '-';
@ -78,7 +79,7 @@ class EntryPagesModal extends React.Component {
return (
<tr className="text-sm dark:text-gray-200" key={page.name}>
<td className="p-2">
<td className="p-2 truncate">
<Link
to={{
pathname: `/${encodeURIComponent(this.props.site.domain)}`,
@ -86,12 +87,12 @@ class EntryPagesModal extends React.Component {
}}
className="hover:underline"
>
{page.name}
{trimURL(page.name, 40)}
</Link>
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_visitors)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.unique_entrances)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_entrances)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visitors)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visits)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{durationFormatter(page.visit_duration)}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.conversion_rate)}%</td>}
</tr>
@ -130,13 +131,13 @@ class EntryPagesModal extends React.Component {
</th>
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Visitors </th>}
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >{this.label()} </th>
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Entrances </th> }
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Visit Duration </th> }
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Entrances </th>}
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Visit Duration </th>}
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >CR </th>}
</tr>
</thead>
<tbody>
{ this.state.pages.map(this.renderPage.bind(this)) }
{this.state.pages.map(this.renderPage.bind(this))}
</tbody>
</table>
</main>
@ -148,8 +149,8 @@ class EntryPagesModal extends React.Component {
render() {
return (
<Modal site={this.props.site}>
{ this.renderBody() }
{ this.renderLoading() }
{this.renderBody()}
{this.renderLoading()}
</Modal>
)
}

@ -5,8 +5,8 @@ import { withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter from '../../util/number-formatter'
import {parseQuery} from '../../query'
import { parseQuery } from '../../query'
import { trimURL } from '../../util/url'
class ExitPagesModal extends React.Component {
constructor(props) {
super(props)
@ -24,18 +24,18 @@ class ExitPagesModal extends React.Component {
}
loadPages() {
const {query, page} = this.state;
const { query, page } = this.state;
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/exit-pages`, query, {limit: 100, page})
.then((res) => this.setState((state) => ({loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100})))
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/exit-pages`, query, { limit: 100, page })
.then((res) => this.setState((state) => ({ loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100 })))
}
loadMore() {
this.setState({loading: true, page: this.state.page + 1}, this.loadPages.bind(this))
this.setState({ loading: true, page: this.state.page + 1 }, this.loadPages.bind(this))
}
formatPercentage(number) {
if (typeof(number) === 'number') {
if (typeof (number) === 'number') {
return number + '%'
} else {
return '-'
@ -68,12 +68,12 @@ class ExitPagesModal extends React.Component {
return (
<tr className="text-sm dark:text-gray-200" key={page.name}>
<td className="p-2">
<Link to={{pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString()}} className="hover:underline">{page.name}</Link>
<td className="p-2 truncate">
<Link to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString() }} className="hover:underline">{trimURL(page.name, 40)}</Link>
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_visitors)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.unique_exits)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_exits)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visitors)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visits)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{this.formatPercentage(page.exit_rate)}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.conversion_rate)}%</td>}
</tr>
@ -114,7 +114,7 @@ class ExitPagesModal extends React.Component {
</tr>
</thead>
<tbody>
{ this.state.pages.map(this.renderPage.bind(this)) }
{this.state.pages.map(this.renderPage.bind(this))}
</tbody>
</table>
</main>
@ -126,8 +126,8 @@ class ExitPagesModal extends React.Component {
render() {
return (
<Modal site={this.props.site}>
{ this.renderBody() }
{ this.renderLoading() }
{this.renderBody()}
{this.renderLoading()}
</Modal>
)
}

@ -2,12 +2,16 @@ import React from "react"
import { withRouter } from 'react-router-dom'
import Modal from './modal'
import RegularFilterModal from './regular-filter-modal'
import PropFilterModal from "./prop-filter-modal"
function FilterModal(props) {
function renderBody() {
const filterGroup = props.match.params.field || 'page'
return <RegularFilterModal site={props.site} filterGroup={filterGroup}/>
if (filterGroup === 'props') {
return <PropFilterModal site={props.site} />
} else {
return <RegularFilterModal site={props.site} filterGroup={filterGroup} />
}
}
return (

@ -66,7 +66,7 @@ class GoogleKeywordsModal extends React.Component {
<RocketIcon />
<div className="text-lg">The site is not connected to Google Search Keywords</div>
<div className="text-lg">Configure the integration to view search terms</div>
<a href={`/${encodeURIComponent(this.props.site.domain)}/settings/search-console`} className="button mt-4">Connect with Google</a>
<a href={`/${encodeURIComponent(this.props.site.domain)}/settings/integrations`} className="button mt-4">Connect with Google</a>
</div>
)
} else {

@ -4,8 +4,9 @@ import { withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter, {durationFormatter} from '../../util/number-formatter'
import {parseQuery} from '../../query'
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import { parseQuery } from '../../query'
import { trimURL } from '../../util/url'
class PagesModal extends React.Component {
constructor(props) {
@ -25,14 +26,14 @@ class PagesModal extends React.Component {
loadPages() {
const detailed = this.showExtra()
const {query, page} = this.state;
const { query, page } = this.state;
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/pages`, query, {limit: 100, page, detailed})
.then((res) => this.setState((state) => ({loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100})))
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/pages`, query, { limit: 100, page, detailed })
.then((res) => this.setState((state) => ({ loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100 })))
}
loadMore() {
this.setState({loading: true, page: this.state.page + 1}, this.loadPages.bind(this))
this.setState({ loading: true, page: this.state.page + 1 }, this.loadPages.bind(this))
}
showExtra() {
@ -48,7 +49,7 @@ class PagesModal extends React.Component {
}
formatBounceRate(page) {
if (typeof(page.bounce_rate) === 'number') {
if (typeof (page.bounce_rate) === 'number') {
return page.bounce_rate + '%'
} else {
return '-'
@ -63,14 +64,14 @@ class PagesModal extends React.Component {
return (
<tr className="text-sm dark:text-gray-200" key={page.name}>
<td className="p-2">
<Link to={{pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString()}} className="hover:underline block truncate">{page.name}</Link>
<Link to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString() }} className="hover:underline block truncate">{trimURL(page.name, 50)}</Link>
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.total_visitors}</td> }
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.total_visitors}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visitors)}</td>
{this.showPageviews() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.pageviews)}</td> }
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{this.formatBounceRate(page)}</td> }
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{timeOnPage}</td> }
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.conversion_rate}%</td> }
{this.showPageviews() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.pageviews)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{this.formatBounceRate(page)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{timeOnPage}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.conversion_rate}%</td>}
</tr>
)
}
@ -114,7 +115,7 @@ class PagesModal extends React.Component {
<tr>
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="left">Page url</th>
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Total visitors</th>}
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{ this.label() }</th>
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{this.label()}</th>
{this.showPageviews() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Pageviews</th>}
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Bounce rate</th>}
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Time on Page</th>}
@ -122,7 +123,7 @@ class PagesModal extends React.Component {
</tr>
</thead>
<tbody>
{ this.state.pages.map(this.renderPage.bind(this)) }
{this.state.pages.map(this.renderPage.bind(this))}
</tbody>
</table>
</main>
@ -134,8 +135,8 @@ class PagesModal extends React.Component {
render() {
return (
<Modal site={this.props.site}>
{ this.renderBody() }
{ this.renderLoading() }
{this.renderBody()}
{this.renderLoading()}
</Modal>
)
}

@ -0,0 +1,205 @@
import React, { useEffect, useState, useMemo } from 'react'
import { withRouter } from "react-router-dom";
import { FILTER_OPERATIONS } from "../../util/filters";
import { parseQuery } from '../../query'
import { siteBasePath } from '../../util/url'
import { toFilterQuery, parseQueryPropsFilter } from '../../util/filters';
import { shouldIgnoreKeypress } from '../../keybinding';
import PropFilterRow from './prop-filter-row';
function getFormState(query) {
if (query.filters['props']) {
const values = Object.fromEntries(parseQueryPropsFilter(query, 'props').map((value, index) => [index, value]))
return {
entries: Object.keys(values).sort(),
values
}
} else {
return {
entries: [0],
values: {
0: {
propKey: null,
type: FILTER_OPERATIONS.is,
clauses: []
}
}
}
}
}
function PropFilterModal(props) {
const query = parseQuery(props.location.search, props.site)
const [formState, setFormState] = useState(getFormState(query))
const selectedPropKeys = useMemo(() => Object.values(formState.values).map((value) => value.propKey), [formState])
function onPropKeySelect(id, selectedOptions) {
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0]
setFormState(prevState => ({
...prevState,
values: {
...prevState.values,
[id]: {
...prevState.values[id],
propKey: newPropKey,
clauses: []
}
}
}))
}
function onPropValueSelect(id, selection) {
setFormState(prevState => ({
...prevState,
values: {
...prevState.values,
[id]: {
...prevState.values[id],
clauses: selection
}
}
}))
}
function onFilterTypeSelect(id, newType) {
setFormState(prevState => ({
...prevState,
values: {
...prevState.values,
[id]: {
...prevState.values[id],
type: newType
}
}
}))
}
function onPropAdd() {
setFormState(prevState => {
const id = prevState.entries[prevState.entries.length - 1] + 1
return {
entries: prevState.entries.concat([id]),
values: {
...prevState.values,
[id]: {
propKey: null,
type: FILTER_OPERATIONS.is,
clauses: []
}
}
}
})
}
function onPropDelete(id) {
setFormState(prevState => {
const entries = prevState.entries.filter((entry) => entry != id)
const values = {...prevState.values}
delete values[id]
return { entries, values }
})
}
function isDisabled() {
return formState.entries.some((id) => !formState.values[id].propKey || formState.values[id].clauses.length == 0)
}
function shouldShowClear() {
return !!query.filters['props']
}
function handleSubmit() {
const formFilters = Object.fromEntries(
Object.entries(formState.values)
.map(([_, {propKey, type, clauses}]) => [propKey.value, toFilterQuery(type, clauses)])
)
selectFiltersAndCloseModal(JSON.stringify(formFilters))
}
function selectFiltersAndCloseModal(filterString) {
const queryString = new URLSearchParams(window.location.search)
if (filterString) {
queryString.set('props', filterString)
} else {
queryString.delete('props')
}
props.history.replace({ pathname: siteBasePath(props.site), search: queryString.toString() })
}
const handleKeydown = (e) => {
if (shouldIgnoreKeypress(e)) return
if (e.target.tagName === 'BODY' && e.key === 'Enter') {
handleSubmit()
}
}
useEffect(() => {
document.addEventListener('keydown', handleKeydown)
return () => {
document.removeEventListener('keydown', handleKeydown)
}
}, [handleSubmit])
return (
<>
<h1 className="text-xl font-bold dark:text-gray-100">Filter by Property</h1>
<div className="mt-4 border-b border-gray-300"></div>
<main className="modal__content">
<form className="flex flex-col" onSubmit={handleSubmit}>
{formState.entries.map((id) => (
<PropFilterRow
key={id}
id={id}
site={props.site}
query={query}
{...formState.values[id]}
showDelete={formState.entries.length > 1}
selectedPropKeys={selectedPropKeys}
onPropKeySelect={onPropKeySelect}
onPropValueSelect={onPropValueSelect}
onFilterTypeSelect={onFilterTypeSelect}
onPropDelete={onPropDelete}
/>
))}
<div className="mt-6">
<a className="underline text-indigo-500 text-sm cursor-pointer" onClick={onPropAdd}>
+ Add another
</a>
</div>
<div className="mt-6 flex items-center justify-start">
<button
type="submit"
className="button"
disabled={isDisabled()}
>
Apply Filter
</button>
{shouldShowClear() && (
<button
type="button"
className="ml-2 button px-4 flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
onClick={() => { selectFiltersAndCloseModal(null) }}
>
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
Remove filter
</button>
)}
</div>
</form>
</main>
</>
)
}
export default withRouter(PropFilterModal)

@ -0,0 +1,86 @@
import React from 'react'
import Combobox from '../../components/combobox'
import FilterTypeSelector from "../../components/filter-type-selector";
import { FILTER_OPERATIONS } from "../../util/filters";
import * as api from '../../api'
import { apiPath } from '../../util/url'
import { TrashIcon } from '@heroicons/react/20/solid'
function PropFilterRow({
id,
query,
site,
propKey,
type,
clauses,
showDelete,
selectedPropKeys,
onPropKeySelect,
onPropValueSelect,
onFilterTypeSelect,
onPropDelete
}) {
function fetchPropKeyOptions() {
return (input) => {
return api.get(apiPath(site, "/suggestions/prop_key"), query, { q: input.trim() })
}
}
function fetchPropValueOptions() {
return (input) => {
if (type === FILTER_OPERATIONS.contains) {
return Promise.resolve([])
}
const key = propKey?.value
const updatedQuery = { ...query, filters: { ...query.filters, props: { [key]: '!(none)' } } }
return api.get(apiPath(site, "/suggestions/prop_value"), updatedQuery, { q: input.trim() })
}
}
return (
<div className="grid grid-cols-12 mt-6">
<div className="col-span-4">
<Combobox
className="mr-2"
fetchOptions={fetchPropKeyOptions()}
singleOption
autoFocus
values={propKey ? [propKey] : []}
onSelect={(value) => onPropKeySelect(id, value)}
placeholder={'Property'}
disabledOptions={selectedPropKeys}
/>
</div>
<div className="col-span-3 mx-2">
<FilterTypeSelector
isDisabled={!propKey}
forFilter={'prop_value'}
onSelect={(value) => onFilterTypeSelect(id, value)}
selectedType={type}
/>
</div>
<div className="col-span-4">
<Combobox
isDisabled={!propKey}
fetchOptions={fetchPropValueOptions()}
values={clauses}
onSelect={(value) => onPropValueSelect(id, value)}
placeholder={'Value'}
freeChoice={type == FILTER_OPERATIONS.contains}
/>
</div>
{showDelete && (
<div className="col-span-1 flex flex-col justify-center">
<a className="ml-2 text-red-600 h-5 w-5 cursor-pointer" onClick={() => onPropDelete(id)}>
<TrashIcon />
</a>
</div>
)}
</div>
)
}
export default PropFilterRow

@ -0,0 +1,132 @@
import React, { useEffect, useState } from "react";
import { Link } from 'react-router-dom'
import { withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import * as url from "../../util/url";
import numberFormatter from '../../util/number-formatter'
import { parseQuery } from '../../query'
import { specialTitleWhenGoalFilter } from "../behaviours/goal-conversions";
import { escapeFilterValue } from "../../util/filters"
/*global BUILD_EXTRA*/
/*global require*/
function maybeRequire() {
if (BUILD_EXTRA) {
return require('../../extra/money')
} else {
return { default: null }
}
}
const Money = maybeRequire().default
function PropsModal(props) {
const site = props.site
const query = parseQuery(props.location.search, site)
const propKey = props.location.pathname.split('/').pop()
const [loading, setLoading] = useState(true)
const [moreResultsAvailable, setMoreResultsAvailable] = useState(false)
const [page, setPage] = useState(1)
const [list, setList] = useState([])
useEffect(() => {
fetchData()
}, [])
function fetchData() {
api.get(url.apiPath(site, `/custom-prop-values/${propKey}`), query, { limit: 100, page })
.then((res) => {
setLoading(false)
setList(list.concat(res))
setPage(page + 1)
setMoreResultsAvailable(res.length >= 100)
})
}
function loadMore() {
setLoading(true)
fetchData()
}
function renderLoadMore() {
return (
<div className="w-full text-center my-4">
<button onClick={loadMore} type="button" className="button">
Load more
</button>
</div>
)
}
function filterSearchLink(listItem) {
const searchParams = new URLSearchParams(window.location.search)
searchParams.set('props', JSON.stringify({ [propKey]: escapeFilterValue(listItem.name) }))
return searchParams.toString()
}
function renderListItem(listItem, hasRevenue) {
return (
<tr className="text-sm dark:text-gray-200" key={listItem.name}>
<td className="p-2">
<Link
to={{ pathname: url.siteBasePath(site), search: filterSearchLink(listItem) }}
className="hover:underline block truncate">
{url.trimURL(listItem.name, 30)}
</Link>
</td>
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.visitors)}</td>
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.events)}</td>
{query.filters.goal && <td className="p-2 w-24 font-medium" align="right">{listItem.conversion_rate}%</td>}
{!query.filters.goal && <td className="p-2 w-24 font-medium" align="right">{listItem.percentage}</td>}
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.total_revenue} /></td>}
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue} /></td>}
</tr>
)
}
function renderLoading() {
return <div className="loading my-16 mx-auto"><div></div></div>
}
function renderBody() {
const hasRevenue = BUILD_EXTRA && list.some((prop) => prop.total_revenue)
return (
<>
<h1 className="text-xl font-bold dark:text-gray-100">{specialTitleWhenGoalFilter(query, 'Custom Property Breakdown')}</h1>
<div className="my-4 border-b border-gray-300"></div>
<main className="modal__content">
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed">
<thead>
<tr>
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400 truncate" align="left">{propKey}</th>
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Visitors</th>
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Events</th>
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{query.filters.goal ? 'CR' : '%'}</th>
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Revenue</th>}
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Average</th>}
</tr>
</thead>
<tbody>
{list.map((item) => renderListItem(item, hasRevenue))}
</tbody>
</table>
</main>
</>
)
}
return (
<Modal site={site}>
{renderBody()}
{loading && renderLoading()}
{!loading && moreResultsAvailable && renderLoadMore()}
</Modal>
)
}
export default withRouter(PropsModal)

@ -19,7 +19,7 @@ class ReferrerDrilldownModal extends React.Component {
const detailed = this.showExtra()
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers/${this.props.match.params.referrer}`, this.state.query, {limit: 100, detailed})
.then((res) => this.setState({loading: false, referrers: res.referrers, totalVisitors: res.total_visitors}))
.then((referrers) => this.setState({loading: false, referrers: referrers}))
}
showExtra() {
@ -74,7 +74,7 @@ class ReferrerDrilldownModal extends React.Component {
return (
<span className="flex group items-center">
<img src={`https://icons.duckduckgo.com/ip3/${referrer.url}.ico`} referrerPolicy="no-referrer" className="h-4 w-4 mr-2 inline" />
<img src={`/favicon/sources/${referrer.name}`} referrerPolicy="no-referrer" className="h-4 w-4 mr-2 inline" />
<Link className="block truncate hover:underline dark:text-gray-200" to={{search: query.toString(), pathname: '/' + this.props.site.domain}} title={referrer.name}>
{referrer.name}
</Link>

@ -3,7 +3,7 @@ import { withRouter } from 'react-router-dom'
import FilterTypeSelector from "../../components/filter-type-selector";
import Combobox from '../../components/combobox'
import { FILTER_GROUPS, parseQueryFilter, formatFilterGroup, formattedFilters, toFilterQuery, FILTER_TYPES } from '../../util/filters'
import { FILTER_GROUPS, parseQueryFilter, formatFilterGroup, formattedFilters, toFilterQuery, FILTER_OPERATIONS } from '../../util/filters'
import { parseQuery } from '../../query'
import * as api from '../../api'
import { apiPath, siteBasePath } from '../../util/url'
@ -11,21 +11,6 @@ import { shouldIgnoreKeypress } from '../../keybinding'
import { isFreeChoiceFilter } from "../../util/filters";
function getFormState(filterGroup, query) {
if (filterGroup === 'props') {
const propsObject = query.filters['props']
const entries = propsObject && Object.entries(propsObject)
if (entries && entries.length == 1) {
const [[propKey, _propVal]] = entries
const {type, clauses} = parseQueryFilter(query, 'props')
return {
'prop_key': { type: FILTER_TYPES.is, clauses: [{label: propKey, value: propKey}] },
'prop_value': { type, clauses }
}
}
}
return FILTER_GROUPS[filterGroup].reduce((result, filter) => {
const {type, clauses} = parseQueryFilter(query, filter)
@ -48,6 +33,7 @@ class RegularFilterModal extends React.Component {
const query = parseQuery(props.location.search, props.site)
const formState = getFormState(props.filterGroup, query)
this.handleKeydown = this.handleKeydown.bind(this)
this.state = { query, formState }
}
@ -75,12 +61,6 @@ class RegularFilterModal extends React.Component {
if (filterKey === 'country') { res.push({ filter: 'country_labels', value: clauses.map(clause => clause.label).join('|') }) }
if (filterKey === 'region') { res.push({ filter: 'region_labels', value: clauses.map(clause => clause.label).join('|') }) }
if (filterKey === 'city') { res.push({ filter: 'city_labels', value: clauses.map(clause => clause.label).join('|') }) }
if (filterKey === 'prop_value') { return res }
if (filterKey === 'prop_key') {
const [{value: propKey}] = clauses
res.push({ filter: 'props', value: JSON.stringify({ [propKey]: toFilterQuery(formState.prop_value.type, formState.prop_value.clauses) }) })
return res
}
res.push({ filter: filterKey, value: toFilterQuery(type, clauses) })
return res
@ -112,7 +92,7 @@ class RegularFilterModal extends React.Component {
fetchOptions(filter) {
return (input) => {
const { query, formState } = this.state
if (formState[filter].type === FILTER_TYPES.contains) {return Promise.resolve([])}
if (formState[filter].type === FILTER_OPERATIONS.contains) {return Promise.resolve([])}
const formFilters = Object.fromEntries(
Object.entries(formState)
@ -125,15 +105,7 @@ class RegularFilterModal extends React.Component {
}
queryForSuggestions(query, formFilters, filter) {
if (filter === 'prop_key') {
const propsFilter = formFilters.prop_value ? { '': formFilters.prop_value } : null
return { ...query, filters: { ...query.filters, props: propsFilter } }
} else if (filter === 'prop_value') {
const propsFilter = formFilters.prop_key ? { [formFilters.prop_key]: '!(none)' } : null
return { ...query, filters: { ...query.filters, props: propsFilter } }
} else {
return { ...query, filters: { ...query.filters, ...formFilters, [filter]: this.negate(formFilters[filter]) } }
}
return { ...query, filters: { ...query.filters, ...formFilters, [filter]: this.negate(formFilters[filter]) } }
}
negate(filterVal) {
@ -153,11 +125,7 @@ class RegularFilterModal extends React.Component {
}
isDisabled() {
if (this.props.filterGroup === 'props') {
return Object.entries(this.state.formState).some(([_key, { clauses }]) => clauses.length === 0)
} else {
return Object.entries(this.state.formState).every(([_key, { clauses }]) => clauses.length === 0)
}
return Object.entries(this.state.formState).every(([_key, { clauses }]) => clauses.length === 0)
}
selectFiltersAndCloseModal(filters) {
@ -181,9 +149,13 @@ class RegularFilterModal extends React.Component {
return (
<div className="mt-4" key={filter}>
<div className="text-sm font-medium text-gray-700 dark:text-gray-300">{formattedFilters[filter]}</div>
<div className="flex items-start mt-1">
<FilterTypeSelector forFilter={filter} onSelect={this.onFilterTypeSelect(filter)} selectedType={this.selectedFilterType(filter)}/>
<Combobox fetchOptions={this.fetchOptions(filter)} freeChoice={isFreeChoiceFilter(filter)} values={this.state.formState[filter].clauses} onSelect={this.onComboboxSelect(filter)} placeholder={`Select ${withIndefiniteArticle(formattedFilters[filter])}`} />
<div className="grid grid-cols-11 mt-1">
<div className="col-span-3 mr-2">
<FilterTypeSelector forFilter={filter} onSelect={this.onFilterTypeSelect(filter)} selectedType={this.selectedFilterType(filter)}/>
</div>
<div className="col-span-8">
<Combobox fetchOptions={this.fetchOptions(filter)} freeChoice={isFreeChoiceFilter(filter)} values={this.state.formState[filter].clauses} onSelect={this.onComboboxSelect(filter)} placeholder={`Select ${withIndefiniteArticle(formattedFilters[filter])}`}/>
</div>
</div>
</div>
)

@ -20,8 +20,24 @@ class ModalTable extends React.Component {
.then((res) => this.setState({loading: false, list: res}))
}
showConversionRate() {
return !!this.state.query.filters.goal
}
showPercentage() {
return this.props.showPercentage && !this.showConversionRate()
}
label() {
return this.state.query.period === 'realtime' ? 'Current visitors' : 'Visitors'
if (this.state.query.period === 'realtime') {
return 'Current visitors'
}
if (this.showConversionRate()) {
return 'Conversions'
}
return 'Visitors'
}
renderTableItem(tableItem) {
@ -40,11 +56,10 @@ class ModalTable extends React.Component {
{tableItem.name}
</Link>
</td>
<td className="p-2 w-32 font-medium" align="right">
{numberFormatter(tableItem.visitors)}
{tableItem.percentage >= 0 &&
<span className="inline-block text-xs w-8 pl-1 text-right">({tableItem.percentage}%)</span> }
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(tableItem.total_visitors)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(tableItem.visitors)}</td>
{this.showPercentage() && <td className="p-2 w-32 font-medium" align="right">{tableItem.percentage}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(tableItem.conversion_rate)}%</td>}
</tr>
)
}
@ -66,19 +81,11 @@ class ModalTable extends React.Component {
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed">
<thead>
<tr>
<th
className="p-2 w-48 lg:w-1/2 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400"
align="left"
>
{this.props.keyLabel}
</th>
<th
// eslint-disable-next-line max-len
className="p-2 w-32 lg:w-1/2 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400"
align="right"
>
{this.label()}
</th>
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="left">{this.props.keyLabel}</th>
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Visitors</th>}
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{this.label()}</th>
{this.showPercentage() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">%</th>}
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">CR</th>}
</tr>
</thead>
<tbody>

@ -1,29 +1,36 @@
import React from 'react';
import { Link } from 'react-router-dom'
export default function MoreLink({url, site, list, endpoint}) {
function detailsIcon() {
return (
<svg
className="feather mr-1"
style={{marginTop: '-2px'}}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
{/* eslint-disable-next-line max-len */}
<path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3" />
</svg>
)
}
export default function MoreLink({url, site, list, endpoint, className, onClick}) {
if (list.length > 0) {
return (
<div className="text-center w-full py-3 md:pb-3 md:pt-0 md:absolute md:bottom-0 md:left-0">
<div className={`w-full text-center ${className ? className : ''}`}>
<Link
to={url || `/${encodeURIComponent(site.domain)}/${endpoint}${window.location.search}`}
// eslint-disable-next-line max-len
className="leading-snug font-bold text-sm text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400 transition tracking-wide"
onClick={onClick}
>
<svg
className="feather mr-1"
style={{marginTop: '-2px'}}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
{/* eslint-disable-next-line max-len */}
<path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3" />
</svg>
{ detailsIcon() }
DETAILS
</Link>
</div>

@ -4,23 +4,27 @@ import * as storage from '../../util/storage'
import * as url from '../../util/url'
import * as api from '../../api'
import ListReport from './../reports/list'
import { VISITORS_METRIC, maybeWithCR } from './../reports/metrics';
function EntryPages({query, site}) {
function EntryPages({ query, site }) {
function fetchData() {
return api.get(url.apiPath(site, '/entry-pages'), query, {limit: 9})
return api.get(url.apiPath(site, '/entry-pages'), query, { limit: 9 })
}
function externalLinkDest(page) {
return url.externalLinkForPage(site.domain, page.name)
}
function getFilterFor(listItem) {
return { entry_page: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={{entry_page: 'name'}}
getFilterFor={getFilterFor}
keyLabel="Entry page"
valueLabel="Unique Entrances"
valueKey="unique_entrances"
metrics={maybeWithCR([{ ...VISITORS_METRIC, label: 'Unique Entrances' }], query)}
detailsLink={url.sitePath(site, '/entry-pages')}
query={query}
externalLinkDest={externalLinkDest}
@ -29,22 +33,25 @@ function EntryPages({query, site}) {
)
}
function ExitPages({query, site}) {
function ExitPages({ query, site }) {
function fetchData() {
return api.get(url.apiPath(site, '/exit-pages'), query, {limit: 9})
return api.get(url.apiPath(site, '/exit-pages'), query, { limit: 9 })
}
function externalLinkDest(page) {
return url.externalLinkForPage(site.domain, page.name)
}
function getFilterFor(listItem) {
return { exit_page: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={{exit_page: 'name'}}
getFilterFor={getFilterFor}
keyLabel="Exit page"
valueLabel="Unique Exits"
valueKey="unique_exits"
metrics={maybeWithCR([{ ...VISITORS_METRIC, label: "Unique Exits" }], query)}
detailsLink={url.sitePath(site, '/exit-pages')}
query={query}
externalLinkDest={externalLinkDest}
@ -53,20 +60,25 @@ function ExitPages({query, site}) {
)
}
function TopPages({query, site}) {
function TopPages({ query, site }) {
function fetchData() {
return api.get(url.apiPath(site, '/pages'), query, {limit: 9})
return api.get(url.apiPath(site, '/pages'), query, { limit: 9 })
}
function externalLinkDest(page) {
return url.externalLinkForPage(site.domain, page.name)
}
function getFilterFor(listItem) {
return { page: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
filter={{page: 'name'}}
getFilterFor={getFilterFor}
keyLabel="Page"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={url.sitePath(site, '/pages')}
query={query}
externalLinkDest={externalLinkDest}
@ -76,15 +88,15 @@ function TopPages({query, site}) {
}
const labelFor = {
'pages': 'Top Pages',
'entry-pages': 'Entry Pages',
'exit-pages': 'Exit Pages',
'pages': 'Top Pages',
'entry-pages': 'Entry Pages',
'exit-pages': 'Exit Pages',
}
export default class Pages extends React.Component {
constructor(props) {
super(props)
this.tabKey = `pageTab__${ props.site.domain}`
this.tabKey = `pageTab__${props.site.domain}`
const storedTab = storage.getItem(this.tabKey)
this.state = {
mode: storedTab || 'pages'
@ -94,19 +106,19 @@ export default class Pages extends React.Component {
setMode(mode) {
return () => {
storage.setItem(this.tabKey, mode)
this.setState({mode})
this.setState({ mode })
}
}
renderContent() {
switch(this.state.mode) {
case "entry-pages":
return <EntryPages site={this.props.site} query={this.props.query} />
case "exit-pages":
return <ExitPages site={this.props.site} query={this.props.query} />
case "pages":
default:
return <TopPages site={this.props.site} query={this.props.query} />
switch (this.state.mode) {
case "entry-pages":
return <EntryPages site={this.props.site} query={this.props.query} />
case "exit-pages":
return <ExitPages site={this.props.site} query={this.props.query} />
case "pages":
default:
return <TopPages site={this.props.site} query={this.props.query} />
}
}
@ -136,26 +148,20 @@ export default class Pages extends React.Component {
render() {
return (
<div
className="stats-item flex flex-col w-full mt-6 stats-item--has-header"
>
<div
className="stats-item-header flex flex-col flex-grow bg-white dark:bg-gray-825 shadow-xl rounded p-4 relative"
>
{/* Header Container */}
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Page Visits'}
</h3>
<div className="flex font-medium text-xs text-gray-500 dark:text-gray-400 space-x-2">
{ this.renderPill('Top Pages', 'pages') }
{ this.renderPill('Entry Pages', 'entry-pages') }
{ this.renderPill('Exit Pages', 'exit-pages') }
</div>
<div>
{/* Header Container */}
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Page Visits'}
</h3>
<div className="flex font-medium text-xs text-gray-500 dark:text-gray-400 space-x-2">
{this.renderPill('Top Pages', 'pages')}
{this.renderPill('Entry Pages', 'entry-pages')}
{this.renderPill('Exit Pages', 'exit-pages')}
</div>
{/* Main Contents */}
{ this.renderContent() }
</div>
{/* Main Contents */}
{this.renderContent()}
</div>
)
}

@ -2,25 +2,51 @@ import React, { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom'
import FlipMove from 'react-flip-move';
import { displayMetricValue, metricLabelFor } from './metrics';
import FadeIn from '../../fade-in'
import MoreLink from '../more-link'
import numberFormatter from '../../util/number-formatter'
import Bar from '../bar'
import LazyLoader from '../../components/lazy-loader'
import classNames from 'classnames'
import { trimURL } from '../../util/url'
const MAX_ITEMS = 9
const MIN_HEIGHT = 380
const ROW_HEIGHT = 32
const ROW_GAP_HEIGHT = 4
const DATA_CONTAINER_HEIGHT = (ROW_HEIGHT + ROW_GAP_HEIGHT) * (MAX_ITEMS - 1) + ROW_HEIGHT
const COL_MIN_WIDTH = 70
function ExternalLink({item, externalLinkDest}) {
if (externalLinkDest) {
const dest = externalLinkDest(item)
function FilterLink({ filterQuery, onClick, children }) {
const className = classNames('max-w-max w-full flex md:overflow-hidden', {
'hover:underline': !!filterQuery
})
if (filterQuery) {
return (
<Link
to={{ search: filterQuery.toString() }}
onClick={onClick}
className={className}
>
{children}
</Link>
)
} else {
return <span className={className}>{children}</span>
}
}
function ExternalLink({ item, externalLinkDest }) {
const dest = externalLinkDest && externalLinkDest(item)
if (dest) {
return (
<a
target="_blank"
rel="noreferrer"
href={dest}
className="hidden group-hover:block"
className="w-4 h-4 hidden group-hover:block"
>
<svg className="inline w-4 h-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
<svg className="inline w-full h-full ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
</a>
)
}
@ -28,117 +54,270 @@ function ExternalLink({item, externalLinkDest}) {
return null
}
// The main function component for rendering list reports and making them react to what
// is happening on the dashboard.
// A `fetchData` function must be passed through props. This function defines the format
// of the data, which is expected to be a list of objects. Think of these objects as rows
// with keys being columns. The number of columns is dynamic and should be configured
// via the `metrics` input list. For example:
// | keyLabel | METRIC_1.label | METRIC_2.label | ...
// |--------------------|---------------------------|---------------------------|-----
// | LISTITEM_1.name | LISTITEM_1[METRIC_1.name] | LISTITEM_1[METRIC_2.name] | ...
// | LISTITEM_2.name | LISTITEM_2[METRIC_1.name] | LISTITEM_2[METRIC_2.name] | ...
// Further configuration of the report is possible through optional props.
// REQUIRED PROPS:
// * `keyLabel` - What each entry in the list represents (for UI only).
// * `query` - The query object representing the current state of the dashboard.
// * `fetchData` - a function that returns an `api.get` promise that will resolve to the
// list of data.
// * `metrics` - a list of `metric` objects. Each `metric` object is required to have at
// least the `name` and the `label` keys. If the metric should have a different label
// in realtime or goal-filtered views, we'll use `realtimeLabel` and `GoalFilterLabel`.
// * `getFilterFor` - a function that takes a list item and returns the query link (with
// the filter) to navigate to when this list item is clicked. If a list item is not
// supposed to be clickable, this function should return `null` for that list item.
// OPTIONAL PROPS:
// * `onClick` - function with additional action to be taken when a list entry is clicked.
// * `detailsLink` - the pathname to the detailed view of this report. E.g.:
// `/dummy.site/pages`. If this is given as input to the ListReport, the Details button
// will always be rendered.
// * `maybeHideDetails` - set this to `true` if the details button should be hidden on
// the condition that there are less than MAX_ITEMS entries in the list. (i.e . nothing
// more to show)
// * `externalLinkDest` - a function that takes a list item and returns an external url
// to navigate to. If this prop is given, an additional icon is rendered upon hovering
// the entry.
// * `renderIcon` - a function that takes a list item and returns the
// HTML of an icon (such as a flag, favicon, or a screen size icon) for a listItem.
// * `color` - color of the comparison bars in light-mode
export default function ListReport(props) {
const [state, setState] = useState({loading: true, list: null})
const [state, setState] = useState({ loading: true, list: null })
const [visible, setVisible] = useState(false)
const valueKey = props.valueKey || 'visitors'
const showConversionRate = !!props.query.filters.goal
const metrics = props.metrics
const colMinWidth = props.colMinWidth || COL_MIN_WIDTH
const isRealtime = props.query.period === 'realtime'
const goalFilterApplied = !!props.query.filters.goal
const fetchData = useCallback(() => {
if (props.query.period !== 'realtime') {
setState({loading: true, list: null})
}
props.fetchData()
.then((res) => setState({loading: false, list: res}))
}, [props.query])
function onVisible() {
setVisible(true)
if (props.query.period == 'realtime') {
document.addEventListener('tick', fetchData)
if (!isRealtime) {
setState({ loading: true, list: null })
}
}
props.fetchData()
.then((res) => setState({ loading: false, list: res }))
}, [props.keyLabel, props.query])
const onVisible = () => { setVisible(true) }
useEffect(() => {
if (visible) { fetchData() }
}, [props.query, visible]);
if (isRealtime) {
// When a goal filter is applied or removed, we always want the component to go into a
// loading state, even in realtime mode, because the metrics list will change. We can
// only read the new metrics once the new list is loaded.
setState({ loading: true, list: null })
}
}, [goalFilterApplied]);
useEffect(() => {
if (visible) {
if (isRealtime) { document.addEventListener('tick', fetchData) }
fetchData()
}
return () => { document.removeEventListener('tick', fetchData) }
}, []);
}, [props.keyLabel, props.query, visible]);
function label() {
if (props.query.period === 'realtime') {
return 'Current visitors'
// returns a filtered `metrics` list. Since currently, the backend can return different
// metrics based on filters and existing data, this function validates that the metrics
// we want to display are actually there in the API response.
function getAvailableMetrics() {
return metrics.filter((metric) => {
return state.list.some((listItem) => listItem[metric.name] != null)
})
}
function hiddenOnMobileClass(metric) {
if (metric.hiddenOnMobile) {
return 'hidden md:block'
} else {
return ''
}
}
if (showConversionRate) {
return 'Conversions'
function renderReport() {
if (state.list && state.list.length > 0) {
return (
<div className="h-full flex flex-col">
<div style={{ height: ROW_HEIGHT }}>
{renderReportHeader()}
</div>
<div style={{ minHeight: DATA_CONTAINER_HEIGHT }}>
{renderReportBody()}
</div>
{maybeRenderDetailsLink()}
</div>
)
}
return renderNoDataYet()
}
return props.valueLabel || 'Visitors'
function renderReportHeader() {
const metricLabels = getAvailableMetrics().map((metric) => {
return (
<div
key={metric.name}
className={`text-right ${hiddenOnMobileClass(metric)}`}
style={{ minWidth: colMinWidth }}
>
{metricLabelFor(metric, props.query)}
</div>
)
})
return (
<div className="pt-3 w-full text-xs font-bold tracking-wide text-gray-500 flex items-center dark:text-gray-400">
<span className="flex-grow truncate">{props.keyLabel}</span>
{metricLabels}
</div>
)
}
function renderListItem(listItem) {
const query = new URLSearchParams(window.location.search)
function renderReportBody() {
return (
<FlipMove className="flex-grow">
{state.list.slice(0, MAX_ITEMS).map(renderRow)}
</FlipMove>
)
}
function renderRow(listItem) {
return (
<div key={listItem.name} style={{ minHeight: ROW_HEIGHT }}>
<div className="flex w-full" style={{ marginTop: ROW_GAP_HEIGHT }}>
{renderBarFor(listItem)}
{renderMetricValuesFor(listItem)}
</div>
</div>
)
}
function getFilterQuery(listItem) {
const filter = props.getFilterFor(listItem)
if (!filter) { return null }
Object.entries(props.filter).forEach((([key, valueKey]) => {
query.set(key, listItem[valueKey])
const query = new URLSearchParams(window.location.search)
Object.entries(filter).forEach((([key, value]) => {
query.set(key, value)
}))
const maxWidthDeduction = showConversionRate ? "10rem" : "5rem"
return query
}
function renderBarFor(listItem) {
const lightBackground = props.color || 'bg-green-50'
const noop = () => {}
const noop = () => { }
const metricToPlot = metrics.find(m => m.plot).name
return (
<div className="flex items-center justify-between my-1 text-sm" key={listItem.name}>
<div className="flex-grow w-full overflow-hidden">
<Bar
count={listItem[valueKey]}
count={listItem[metricToPlot]}
all={state.list}
bg={`${lightBackground} dark:bg-gray-500 dark:bg-opacity-15`}
maxWidthDeduction={maxWidthDeduction}
plot={valueKey}
plot={metricToPlot}
>
<span className="flex px-2 py-1.5 group dark:text-gray-300 relative z-9 break-all">
<Link onClick={props.onClick || noop} className="md:truncate block hover:underline" to={{search: query.toString()}}>
{props.renderIcon && props.renderIcon(listItem)}
{props.renderIcon && ' '}
{listItem.name}
</Link>
<ExternalLink item={listItem} externalLinkDest={props.externalLinkDest} />
</span>
<div className="flex justify-start px-2 py-1.5 group text-sm dark:text-gray-300 relative z-9 break-all w-full">
<FilterLink filterQuery={getFilterQuery(listItem)} onClick={props.onClick || noop}>
{maybeRenderIconFor(listItem)}
<span className="w-full md:truncate">
{trimURL(listItem.name, colMinWidth)}
</span>
</FilterLink>
<ExternalLink item={listItem} externalLinkDest={props.externalLinkDest} />
</div>
</Bar>
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={listItem[valueKey]}>
{numberFormatter(listItem[valueKey])}
{
listItem.percentage >= 0
? <span className="inline-block w-8 pl-1 text-xs text-right">({listItem.percentage}%)</span>
: null
}
</span>
{showConversionRate && <span className="font-medium dark:text-gray-200 w-20 text-right">{listItem.conversion_rate}%</span>}
</div>
)
}
function renderList() {
if (state.list && state.list.length > 0) {
function maybeRenderIconFor(listItem) {
if (props.renderIcon) {
return (
<>
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
<span>{ props.keyLabel }</span>
<span className="text-right">
<span className="inline-block w-30">{label()}</span>
{showConversionRate && <span className="inline-block w-20">CR</span>}
</span>
</div>
<FlipMove>
{ state.list.map(renderListItem) }
</FlipMove>
</>
<span className="pr-1">
{props.renderIcon(listItem)}
</span>
)
}
}
return <div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">No data yet</div>
function renderMetricValuesFor(listItem) {
return getAvailableMetrics().map((metric) => {
return (
<div
key={`${listItem.name}__${metric.name}`}
className={`text-right ${hiddenOnMobileClass(metric)}`}
style={{ width: colMinWidth, minWidth: colMinWidth }}
>
<span className="font-medium text-sm dark:text-gray-200 text-right">
{displayMetricValue(listItem[metric.name], metric)}
</span>
</div>
)
})
}
function renderLoading() {
return (
<div className="w-full flex flex-col justify-center" style={{ minHeight: `${MIN_HEIGHT}px` }}>
<div className="mx-auto loading"><div></div></div>
</div>
)
}
function renderNoDataYet() {
return (
<div className="w-full h-full flex flex-col justify-center" style={{ minHeight: `${MIN_HEIGHT}px` }}>
<div className="mx-auto font-medium text-gray-500 dark:text-gray-400">No data yet</div>
</div>
)
}
function maybeRenderDetailsLink() {
const moreResultsAvailable = state.list.length >= MAX_ITEMS
const hideDetails = props.maybeHideDetails && !moreResultsAvailable
const showDetails = props.detailsLink && !state.loading && !hideDetails
return showDetails && <MoreLink className={'mt-2'} url={props.detailsLink} list={state.list} />
}
return (
<LazyLoader onVisible={onVisible} className="flex flex-col flex-grow">
{ state.loading && <div className="mx-auto loading mt-44"><div></div></div> }
<FadeIn show={!state.loading} className="flex-grow">
{ renderList() }
</FadeIn>
{props.detailsLink && !state.loading && <MoreLink url={props.detailsLink} list={state.list} />}
<LazyLoader onVisible={onVisible} >
<div className="w-full" style={{ minHeight: `${MIN_HEIGHT}px` }}>
{state.loading && renderLoading()}
{!state.loading && <FadeIn show={!state.loading} className="h-full">
{renderReport()}
</FadeIn>}
</div>
</LazyLoader>
)
}

@ -0,0 +1,54 @@
import numberFormatter from "../../util/number-formatter"
import React from "react"
/*global BUILD_EXTRA*/
/*global require*/
function maybeRequire() {
if (BUILD_EXTRA) {
return require('../../extra/money')
} else {
return { default: null }
}
}
const Money = maybeRequire().default
export const VISITORS_METRIC = {
name: 'visitors',
label: 'Visitors',
realtimeLabel: 'Current visitors',
goalFilterLabel: 'Conversions',
plot: true
}
export const PERCENTAGE_METRIC = { name: 'percentage', label: '%' }
export const CR_METRIC = { name: 'conversion_rate', label: 'CR' }
export function maybeWithCR(metrics, query) {
if (metrics.includes(PERCENTAGE_METRIC) && query.filters.goal) {
return metrics.filter((m) => { return m !== PERCENTAGE_METRIC }).concat([CR_METRIC])
}
else if (query.filters.goal) {
return metrics.concat(CR_METRIC)
}
else {
return metrics
}
}
export function displayMetricValue(value, metric) {
if (['total_revenue', 'average_revenue'].includes(metric.name)) {
return <Money formatted={value} />
} else if (metric === PERCENTAGE_METRIC) {
return value
} else if (metric === CR_METRIC) {
return `${value}%`
} else {
return <span tooltip={value}>{numberFormatter(value)}</span>
}
}
export function metricLabelFor(metric, query) {
if (metric.realtimeLabel && query.period === 'realtime') { return metric.realtimeLabel }
if (metric.goalFilterLabel && query.filters.goal) { return metric.goalFilterLabel }
return metric.label
}

@ -2,11 +2,13 @@ import React from 'react';
import SearchTerms from './search-terms'
import SourceList from './source-list'
import ReferrerList from './referrer-list'
import { isFilteringOnFixedValue } from '../../util/filters'
export default function Sources(props) {
if (props.query.filters.source === 'Google') {
return <SearchTerms {...props} />
} else if (props.query.filters.source) {
} else if (isFilteringOnFixedValue(props.query, 'source')) {
return <ReferrerList {...props} />
} else {
return <SourceList {...props} />

@ -1,179 +1,48 @@
import React from 'react';
import { Link } from 'react-router-dom'
import FlipMove from 'react-flip-move';
import FadeIn from '../../fade-in'
import Bar from '../bar'
import MoreLink from '../more-link'
import numberFormatter from '../../util/number-formatter'
import * as api from '../../api'
import LazyLoader from '../../components/lazy-loader'
function LinkOption(props) {
if (props.disabled) {
return <span {...props}>{props.children}</span>
} else {
props = Object.assign({}, props, { className: props.className + ' hover:underline' })
return <Link {...props}>{props.children}</Link>
}
}
export default class Referrers extends React.Component {
constructor(props) {
super(props)
this.state = { loading: true }
this.onVisible = this.onVisible.bind(this)
this.fetchReferrers = this.fetchReferrers.bind(this)
}
onVisible() {
this.fetchReferrers()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchReferrers)
}
}
componentDidUpdate(prevProps) {
if (this.props.query !== prevProps.query) {
this.setState({ loading: true, referrers: null })
this.fetchReferrers()
}
}
componentWillUnmount() {
document.removeEventListener('tick', this.fetchReferrers)
}
showConversionRate() {
return !!this.props.query.filters.goal
}
import * as url from '../../util/url'
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics'
import ListReport from '../reports/list'
fetchReferrers() {
if (this.props.query.filters.source) {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers/${encodeURIComponent(this.props.query.filters.source)}`, this.props.query)
.then((res) => res.search_terms || res.referrers)
.then((referrers) => this.setState({ loading: false, referrers: referrers }))
} else if (this.props.query.filters.goal) {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/goal/referrers`, this.props.query)
.then((res) => this.setState({ loading: false, referrers: res }))
} else {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers`, this.props.query)
.then((res) => this.setState({ loading: false, referrers: res }))
}
export default function Referrers({site, query}) {
function fetchReferrers() {
return api.get(url.apiPath(site, `/referrers/${encodeURIComponent(query.filters.source)}`), query, {limit: 9})
}
renderExternalLink(referrer) {
if (this.props.query.filters.source && this.props.query.filters.source !== 'Google' && referrer.name !== 'Direct / None') {
return (
<a target="_blank" href={'//' + referrer.name} rel="noreferrer" className="hidden group-hover:block">
<svg className="inline w-4 h-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
</a>
)
}
return null
function externalLinkDest(referrer) {
if (referrer.name === 'Direct / None') { return null }
return `https://${referrer.name}`
}
renderReferrer(referrer) {
const maxWidthDeduction = this.showConversionRate() ? "10rem" : "5rem"
const query = new URLSearchParams(window.location.search)
query.set('referrer', referrer.name)
return (
<div className="flex items-center justify-between my-1 text-sm" key={referrer.name}>
<Bar
count={referrer.visitors}
all={this.state.referrers}
bg="bg-blue-50 dark:bg-gray-500 dark:bg-opacity-15"
maxWidthDeduction={maxWidthDeduction}
>
<span className="flex px-2 py-1.5 z-9 relative break-all group">
<LinkOption
className="block md:truncate dark:text-gray-300"
to={{ search: query.toString() }}
disabled={referrer.name === 'Direct / None'}
>
<img
src={`/favicon/sources/${encodeURIComponent(referrer.name)}`}
referrerPolicy="no-referrer"
className="inline w-4 h-4 mr-2 -mt-px align-middle"
/>
{referrer.name}
</LinkOption>
{this.renderExternalLink(referrer)}
</span>
</Bar>
<span className="font-medium dark:text-gray-200">{numberFormatter(referrer.visitors)}</span>
{this.showConversionRate() && <span className="font-medium dark:text-gray-200 w-20 text-right">{referrer.conversion_rate}%</span>}
</div>
)
}
label() {
if (this.props.query.period === 'realtime') {
return 'Current visitors'
}
if (this.showConversionRate()) {
return 'Conversions'
}
return 'Visitors'
function getFilterFor(referrer) {
if (referrer.name === 'Direct / None') { return null }
return { referrer: referrer.name }
}
renderList() {
if (this.state.referrers.length > 0) {
return (
<div className="flex flex-col flex-grow">
<div
className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500"
>
<span>Referrer</span>
<div className="text-right">
<span className="inline-block w-20">{this.label()}</span>
{this.showConversionRate() && <span className="inline-block w-20">CR</span>}
</div>
</div>
<FlipMove className="flex-grow">
{this.state.referrers.map(this.renderReferrer.bind(this))}
</FlipMove>
</div>
)
}
function renderIcon(listItem) {
return (
<div
className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400"
>
No data yet
</div>
<img
src={`/favicon/sources/${encodeURIComponent(listItem.name)}`}
referrerPolicy="no-referrer"
className="inline w-4 h-4 mr-2 -mt-px align-middle"
/>
)
}
renderContent() {
if (this.state.referrers) {
return (
<React.Fragment>
{this.renderList()}
<MoreLink site={this.props.site} list={this.state.referrers} endpoint={`referrers/${this.props.query.filters.source}`} />
</React.Fragment>
)
}
}
render() {
return (
<div
className="relative p-4 bg-white rounded shadow-xl stats-item flex flex-col dark:bg-gray-825 mt-6 w-full"
>
<LazyLoader onVisible={this.onVisible} className="flex flex-col flex-grow">
<h3 className="font-bold dark:text-gray-100">Top Referrers</h3>
{this.state.loading && <div className="mx-auto loading mt-44"><div></div></div>}
<FadeIn show={!this.state.loading}>
{this.renderContent()}
</FadeIn>
</LazyLoader>
</div>
)
}
return (
<div className="flex flex-col flex-grow">
<h3 className="font-bold dark:text-gray-100">Top Referrers</h3>
<ListReport
fetchData={fetchReferrers}
getFilterFor={getFilterFor}
keyLabel="Referrer"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={url.sitePath(site, `/referrers/${encodeURIComponent(query.filters.source)}`)}
query={query}
externalLinkDest={externalLinkDest}
renderIcon={renderIcon}
color="bg-blue-50"
/>
</div>
)
}

@ -85,7 +85,7 @@ export default class SearchTerms extends React.Component {
This site is not connected to Search Console so we cannot show the search phrases.
{this.state.isAdmin && this.state.error && <><br/><br/><p>Please click below to connect your Search Console account.</p></>}
</div>
{this.state.isAdmin && <a href={`/${encodeURIComponent(this.props.site.domain)}/settings/search-console`} className="button mt-4">Connect with Google</a> }
{this.state.isAdmin && <a href={`/${encodeURIComponent(this.props.site.domain)}/settings/integrations`} className="button mt-4">Connect with Google</a> }
</div>
)
} else if (this.state.searchTerms.length > 0) {
@ -119,7 +119,7 @@ export default class SearchTerms extends React.Component {
<React.Fragment>
<h3 className="font-bold dark:text-gray-100">Search Terms</h3>
{ this.renderList() }
<MoreLink site={this.props.site} list={this.state.searchTerms} endpoint="referrers/Google" />
<MoreLink site={this.props.site} list={this.state.searchTerms} endpoint="referrers/Google" className="w-full pb-4 absolute bottom-0 left-0"/>
</React.Fragment>
)
}
@ -127,9 +127,7 @@ export default class SearchTerms extends React.Component {
render() {
return (
<div
className="stats-item flex flex-col relative bg-white dark:bg-gray-825 shadow-xl rounded p-4 mt-6 w-full"
>
<div>
{ this.state.loading && <div className="loading mt-44 mx-auto"><div></div></div> }
<FadeIn show={!this.state.loading} className="flex-grow">
<LazyLoader onVisible={this.onVisible}>

@ -1,320 +1,109 @@
import React from 'react';
import { Link } from 'react-router-dom'
import FlipMove from 'react-flip-move';
import React, { Fragment, useState } from 'react';
import * as storage from '../../util/storage'
import FadeIn from '../../fade-in'
import Bar from '../bar'
import MoreLink from '../more-link'
import numberFormatter from '../../util/number-formatter'
import * as api from '../../api'
import * as url from '../../util/url'
import LazyLoader from '../../components/lazy-loader'
class AllSources extends React.Component {
constructor(props) {
super(props)
this.onVisible = this.onVisible.bind(this)
this.fetchReferrers = this.fetchReferrers.bind(this)
this.state = { loading: true }
}
onVisible() {
this.fetchReferrers()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchReferrers)
}
}
componentDidUpdate(prevProps) {
if (this.props.query !== prevProps.query) {
this.setState({ loading: true, referrers: null })
this.fetchReferrers()
}
}
componentWillUnmount() {
document.removeEventListener('tick', this.fetchReferrers)
}
showConversionRate() {
return !!this.props.query.filters.goal
}
fetchReferrers() {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/sources`, this.props.query)
.then((res) => this.setState({ loading: false, referrers: res }))
}
renderReferrer(referrer) {
const maxWidthDeduction = this.showConversionRate() ? "10rem" : "5rem"
return (
<div
className="flex items-center justify-between my-1 text-sm"
key={referrer.name}
>
<Bar
count={referrer.visitors}
all={this.state.referrers}
bg="bg-blue-50 dark:bg-gray-500 dark:bg-opacity-15"
maxWidthDeduction={maxWidthDeduction}
>
<span className="flex px-2 py-1.5 dark:text-gray-300 relative z-9 break-all">
<Link
className="md:truncate block hover:underline"
to={url.setQuery('source', referrer.name)}
>
<img
src={`/favicon/sources/${encodeURIComponent(referrer.name)}`}
className="inline w-4 h-4 mr-2 -mt-px align-middle"
/>
{referrer.name}
</Link>
</span>
</Bar>
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={referrer.visitors}>{numberFormatter(referrer.visitors)}</span>
{this.showConversionRate() && <span className="font-medium dark:text-gray-200 w-20 text-right">{referrer.conversion_rate}%</span>}
</div>
)
}
label() {
if (this.props.query.period === 'realtime') {
return 'Current visitors'
}
if (this.showConversionRate()) {
return 'Conversions'
}
return 'Visitors'
}
renderList() {
if (this.state.referrers && this.state.referrers.length > 0) {
return (
<React.Fragment>
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500">
<span>Source</span>
<div className="text-right">
<span className="inline-block w-20">{this.label()}</span>
{this.showConversionRate() && <span className="inline-block w-20">CR</span>}
</div>
</div>
<FlipMove className="flex-grow">
{this.state.referrers.map(this.renderReferrer.bind(this))}
</FlipMove>
<MoreLink site={this.props.site} list={this.state.referrers} endpoint="sources" />
</React.Fragment>
)
} else {
return <div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">No data yet</div>
}
}
renderContent() {
return (
<LazyLoader className="flex flex-col flex-grow" onVisible={this.onVisible}>
<div id="sources" className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">Top Sources</h3>
{this.props.renderTabs()}
</div>
{this.state.loading && <div className="mx-auto loading mt-44"><div></div></div>}
<FadeIn show={!this.state.loading} className="flex flex-col flex-grow">
{this.renderList()}
</FadeIn>
</LazyLoader>
)
}
render() {
return (
<div
className="relative p-4 bg-white rounded shadow-xl stats-item flex flex-col mt-6 w-full dark:bg-gray-825"
>
{this.renderContent()}
</div>
)
}
}
import * as api from '../../api'
import ListReport from '../reports/list'
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics';
import { Menu, Transition } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import { escapeFilterValue } from '../../util/filters'
import classNames from 'classnames'
const UTM_TAGS = {
utm_medium: { label: 'UTM Medium', shortLabel: 'UTM Medium', endpoint: 'utm_mediums' },
utm_source: { label: 'UTM Source', shortLabel: 'UTM Source', endpoint: 'utm_sources' },
utm_campaign: { label: 'UTM Campaign', shortLabel: 'UTM Campai', endpoint: 'utm_campaigns' },
utm_content: { label: 'UTM Content', shortLabel: 'UTM Conten', endpoint: 'utm_contents' },
utm_term: { label: 'UTM Term', shortLabel: 'UTM Term', endpoint: 'utm_terms' },
utm_medium: { label: 'UTM Medium', shortLabel: 'UTM Medium', endpoint: '/utm_mediums' },
utm_source: { label: 'UTM Source', shortLabel: 'UTM Source', endpoint: '/utm_sources' },
utm_campaign: { label: 'UTM Campaign', shortLabel: 'UTM Campai', endpoint: '/utm_campaigns' },
utm_content: { label: 'UTM Content', shortLabel: 'UTM Conten', endpoint: '/utm_contents' },
utm_term: { label: 'UTM Term', shortLabel: 'UTM Term', endpoint: '/utm_terms' },
}
class UTMSources extends React.Component {
constructor(props) {
super(props)
this.onVisible = this.onVisible.bind(this)
this.fetchReferrers = this.fetchReferrers.bind(this)
this.state = { loading: true }
}
onVisible() {
this.fetchReferrers()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchReferrers)
}
}
componentDidUpdate(prevProps) {
if (this.props.query !== prevProps.query || this.props.tab !== prevProps.tab) {
this.setState({ loading: true, referrers: null })
this.fetchReferrers()
}
}
function AllSources(props) {
const { site, query } = props
componentWillUnmount() {
document.removeEventListener('tick', this.fetchReferrers)
function fetchData() {
return api.get(url.apiPath(site, '/sources'), query, { limit: 9 })
}
showNoRef() {
return this.props.query.period === 'realtime'
function getFilterFor(listItem) {
return { source: escapeFilterValue(listItem['name']) }
}
showConversionRate() {
return !!this.props.query.filters.goal
}
fetchReferrers() {
const endpoint = UTM_TAGS[this.props.tab].endpoint
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/${endpoint}`, this.props.query)
.then((res) => this.setState({ loading: false, referrers: res }))
}
renderReferrer(referrer) {
const maxWidthDeduction = this.showConversionRate() ? "10rem" : "5rem"
function renderIcon(listItem) {
return (
<div
className="flex items-center justify-between my-1 text-sm"
key={referrer.name}
>
<Bar
count={referrer.visitors}
all={this.state.referrers}
bg="bg-blue-50 dark:bg-gray-500 dark:bg-opacity-15"
maxWidthDeduction={maxWidthDeduction}
>
<span className="flex px-2 py-1.5 dark:text-gray-300 relative z-9 break-all">
<Link
className="md:truncate block hover:underline"
to={url.setQuery(this.props.tab, referrer.name)}
>
{referrer.name}
</Link>
</span>
</Bar>
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={referrer.visitors}>{numberFormatter(referrer.visitors)}</span>
{this.showConversionRate() && <span className="font-medium dark:text-gray-200 w-20 text-right">{referrer.conversion_rate}%</span>}
</div>
<img
src={`/favicon/sources/${encodeURIComponent(listItem.name)}`}
className="inline w-4 h-4 mr-2 -mt-px align-middle"
/>
)
}
label() {
if (this.props.query.period === 'realtime') {
return 'Current visitors'
}
if (this.showConversionRate()) {
return 'Conversions'
}
return 'Visitors'
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
keyLabel="Source"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={url.sitePath(site, '/sources')}
renderIcon={renderIcon}
query={query}
color="bg-blue-50"
/>
)
}
renderList() {
if (this.state.referrers && this.state.referrers.length > 0) {
return (
<div className="flex flex-col flex-grow">
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
<span>{UTM_TAGS[this.props.tab].label}</span>
<div className="text-right">
<span className="inline-block w-20">{this.label()}</span>
{this.showConversionRate() && <span className="inline-block w-20">CR</span>}
</div>
</div>
function UTMSources(props) {
const { site, query } = props
const utmTag = UTM_TAGS[props.tab]
<FlipMove className="flex-grow">
{this.state.referrers.map(this.renderReferrer.bind(this))}
</FlipMove>
<MoreLink site={this.props.site} list={this.state.referrers} endpoint={UTM_TAGS[this.props.tab].endpoint} />
</div>
)
} else {
return <div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">No data yet</div>
}
function fetchData() {
return api.get(url.apiPath(site, utmTag.endpoint), query, { limit: 9 })
}
renderContent() {
return (
<LazyLoader onVisible={this.onVisible}>
<div className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">Top Sources</h3>
{this.props.renderTabs()}
</div>
{this.state.loading && <div className="mx-auto loading mt-44"><div></div></div>}
<FadeIn show={!this.state.loading} className="flex flex-col flex-grow">
{this.renderList()}
</FadeIn>
</LazyLoader>
)
function getFilterFor(listItem) {
return { [props.tab]: escapeFilterValue(listItem['name']) }
}
render() {
return (
<div
className="relative p-4 bg-white rounded shadow-xl stats-item flex flex-col dark:bg-gray-825 mt-6 w-full"
>
{this.renderContent()}
</div>
)
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
keyLabel={utmTag.label}
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={url.sitePath(site, utmTag.endpoint)}
query={query}
color="bg-blue-50"
/>
)
}
import { Fragment } from 'react'
import { Menu, Transition } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import classNames from 'classnames'
export default class SourceList extends React.Component {
constructor(props) {
super(props)
this.tabKey = 'sourceTab__' + props.site.domain
const storedTab = storage.getItem(this.tabKey)
this.state = {
tab: storedTab || 'all'
}
}
export default function SourceList(props) {
const { site, query } = props
const tabKey = 'sourceTab__' + props.site.domain
const storedTab = storage.getItem(tabKey)
const [currentTab, setCurrentTab] = useState(storedTab || 'all')
setTab(tab) {
function setTab(tab) {
return () => {
storage.setItem(this.tabKey, tab)
this.setState({ tab })
storage.setItem(tabKey, tab)
setCurrentTab(tab)
}
}
renderTabs() {
function renderTabs() {
const activeClass = 'inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold active-prop-heading truncate text-left'
const defaultClass = 'hover:text-indigo-600 cursor-pointer truncate text-left'
const dropdownOptions = Object.keys(UTM_TAGS)
let buttonText = UTM_TAGS[this.state.tab] ? UTM_TAGS[this.state.tab].label : 'Campaigns'
let buttonText = UTM_TAGS[currentTab] ? UTM_TAGS[currentTab].label : 'Campaigns'
return (
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
<div className={this.state.tab === 'all' ? activeClass : defaultClass} onClick={this.setTab('all')}>All</div>
<div className={currentTab === 'all' ? activeClass : defaultClass} onClick={setTab('all')}>All</div>
<Menu as="div" className="relative inline-block text-left">
<div>
<Menu.Button className="inline-flex justify-between focus:outline-none">
<span className={this.state.tab.startsWith('utm_') ? activeClass : defaultClass}>{buttonText}</span>
<span className={currentTab.startsWith('utm_') ? activeClass : defaultClass}>{buttonText}</span>
<ChevronDownIcon className="-mr-1 ml-1 h-4 w-4" aria-hidden="true" />
</Menu.Button>
</div>
@ -322,11 +111,11 @@ export default class SourceList extends React.Component {
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Menu.Items className="text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10">
<div className="py-1">
@ -335,11 +124,11 @@ export default class SourceList extends React.Component {
<Menu.Item key={option}>
{({ active }) => (
<span
onClick={this.setTab(option)}
onClick={setTab(option)}
className={classNames(
active ? 'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer' : 'text-gray-700 dark:text-gray-200',
'block px-4 py-2 text-sm',
this.state.tab === option ? 'font-bold' : ''
currentTab === option ? 'font-bold' : ''
)}
>
{UTM_TAGS[option].label}
@ -356,11 +145,25 @@ export default class SourceList extends React.Component {
)
}
render() {
if (this.state.tab === 'all') {
return <AllSources tab={this.state.tab} setTab={this.setTab.bind(this)} renderTabs={this.renderTabs.bind(this)} {...this.props} />
} else if (Object.keys(UTM_TAGS).includes(this.state.tab)) {
return <UTMSources tab={this.state.tab} setTab={this.setTab.bind(this)} renderTabs={this.renderTabs.bind(this)} {...this.props} />
function renderContent() {
if (currentTab === 'all') {
return <AllSources site={site} query={query} />
} else {
return <UTMSources tab={currentTab} site={site} query={query} />
}
}
return (
<div>
{/* Header Container */}
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
Top Sources
</h3>
{renderTabs()}
</div>
{/* Main Contents */}
{renderContent()}
</div>
)
}

@ -63,6 +63,10 @@ export function parseUTCDate(dateString) {
return dayjs.utc(dateString)
}
export function parseNaiveDate(dateString) {
return dayjs(dateString)
}
export function nowForSite(site) {
return dayjs.utc().utcOffset(site.offset / 60)
}
@ -120,3 +124,8 @@ export function isAfter(date1, date2, period) {
}
return date1.date() > date2.date()
}
export function monthsBetweenDates(date1, date2) {
var diffMonths = (date2.year() - date1.year()) * 12 + date2.month() - date1.month();
return Math.abs(diffMonths);
}

@ -1,3 +1,5 @@
const flags = JSON.parse(document.getElementById('stats-react-container').dataset.flags)
export const FILTER_GROUPS = {
'page': ['page', 'entry_page', 'exit_page'],
'source': ['source', 'referrer'],
@ -7,19 +9,23 @@ export const FILTER_GROUPS = {
'os': ['os', 'os_version'],
'utm': ['utm_medium', 'utm_source', 'utm_campaign', 'utm_term', 'utm_content'],
'goal': ['goal'],
'props': ['prop_key', 'prop_value']
'props': ['prop_key', 'prop_value'],
...(flags.hostname_filter ? { 'hostname': ['hostname'] } : {})
}
export const FILTER_TYPES = {
export const NO_CONTAINS_OPERATOR = new Set(['goal', 'screen'].concat(FILTER_GROUPS['location']))
export const FILTER_OPERATIONS = {
isNot: 'is not',
contains: 'contains',
is: 'is'
};
export const FILTER_PREFIXES = {
[FILTER_TYPES.isNot]: '!',
[FILTER_TYPES.contains]: '~',
[FILTER_TYPES.is]: ''
export const OPERATION_PREFIX = {
[FILTER_OPERATIONS.isNot]: '!',
[FILTER_OPERATIONS.contains]: '~',
[FILTER_OPERATIONS.is]: ''
};
export function supportsIsNot(filterName) {
@ -27,7 +33,7 @@ export function supportsIsNot(filterName) {
}
export function isFreeChoiceFilter(filterName) {
return FILTER_GROUPS['page'].concat(FILTER_GROUPS['utm']).includes(filterName)
return !NO_CONTAINS_OPERATOR.has(filterName)
}
// As of March 2023, Safari does not support negative lookbehind regexes. In case it throws an error, falls back to plain | matching. This means
@ -35,7 +41,7 @@ export function isFreeChoiceFilter(filterName) {
let NON_ESCAPED_PIPE_REGEX;
try {
NON_ESCAPED_PIPE_REGEX = new RegExp("(?<!\\\\)\\|", "g")
} catch(_e) {
} catch (_e) {
NON_ESCAPED_PIPE_REGEX = '|'
}
@ -46,58 +52,61 @@ export function escapeFilterValue(value) {
}
export function toFilterQuery(type, clauses) {
const prefix = FILTER_PREFIXES[type];
const prefix = OPERATION_PREFIX[type];
const result = clauses.map(clause => escapeFilterValue(clause.value.trim())).join('|')
return prefix + result;
}
function parsePrefix(rawValue) {
const type = Object.keys(FILTER_PREFIXES)
.find(type => FILTER_PREFIXES[type] === rawValue[0]) || FILTER_TYPES.is;
export function parsePrefix(rawValue) {
const type = Object.keys(OPERATION_PREFIX)
.find(type => OPERATION_PREFIX[type] === rawValue[0]) || FILTER_OPERATIONS.is;
const value = [FILTER_TYPES.isNot, FILTER_TYPES.contains].includes(type)
? rawValue.substring(1)
: rawValue;
const value = type === FILTER_OPERATIONS.is ? rawValue : rawValue.substring(1)
const values = value
.split(NON_ESCAPED_PIPE_REGEX)
.filter((clause) => !!clause)
.map((val) => val.replaceAll(ESCAPED_PIPE, '|'))
return {type, values}
return { type, values }
}
export function parseQueryPropsFilter(query) {
return Object.entries(query.filters['props']).map(([key, propVal]) => {
const { type, values } = parsePrefix(propVal)
const clauses = values.map(val => { return { value: val, label: val } })
return { propKey: { label: key, value: key }, type, clauses }
})
}
export function parseQueryFilter(query, filter) {
if (filter === 'props') {
const rawValue = query.filters['props']
const [[_propKey, propVal]] = Object.entries(rawValue)
const {type, values} = parsePrefix(propVal)
const clauses = values.map(val => { return {value: val, label: val}})
return {type, clauses}
} else {
const {type, values} = parsePrefix(query.filters[filter] || '')
const { type, values } = parsePrefix(query.filters[filter] || '')
let labels = values
let labels = values
if (filter === 'country' && values.length > 0) {
const rawLabel = (new URLSearchParams(window.location.search)).get('country_labels') || ''
labels = rawLabel.split('|').filter(label => !!label)
}
if (filter === 'country' && values.length > 0) {
const rawLabel = (new URLSearchParams(window.location.search)).get('country_labels') || ''
labels = rawLabel.split('|').filter(label => !!label)
}
if (filter === 'region' && values.length > 0) {
const rawLabel = (new URLSearchParams(window.location.search)).get('region_labels') || ''
labels = rawLabel.split('|').filter(label => !!label)
}
if (filter === 'region' && values.length > 0) {
const rawLabel = (new URLSearchParams(window.location.search)).get('region_labels') || ''
labels = rawLabel.split('|').filter(label => !!label)
}
if (filter === 'city' && values.length > 0) {
const rawLabel = (new URLSearchParams(window.location.search)).get('city_labels') || ''
labels = rawLabel.split('|').filter(label => !!label)
}
if (filter === 'city' && values.length > 0) {
const rawLabel = (new URLSearchParams(window.location.search)).get('city_labels') || ''
labels = rawLabel.split('|').filter(label => !!label)
}
const clauses = values.map((value, index) => { return { value, label: labels[index] } })
const clauses = values.map((value, index) => { return {value, label: labels[index]}})
return { type, clauses }
}
return {type, clauses}
}
export function isFilteringOnFixedValue(query, filter) {
const { type, clauses } = parseQueryFilter(query, filter)
return type == FILTER_OPERATIONS.is && clauses.length == 1
}
export function formatFilterGroup(filterGroup) {
@ -147,6 +156,7 @@ export const formattedFilters = {
'region': 'Region',
'city': 'City',
'page': 'Page',
'hostname': 'Hostname',
'entry_page': 'Entry Page',
'exit_page': 'Exit Page'
'exit_page': 'Exit Page',
}

@ -20,3 +20,59 @@ export function externalLinkForPage(domain, page) {
const domainURL = new URL(`https://${domain}`)
return `https://${domainURL.host}${page}`
}
export function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
export function trimURL(url, maxLength) {
if (url.length <= maxLength) {
return url;
}
const ellipsis = "...";
if (isValidHttpUrl(url)) {
const [protocol, restURL] = url.split('://');
const parts = restURL.split('/');
const host = parts.shift();
if (host.length > maxLength - 5) {
return `${protocol}://${host.substr(0, maxLength - 5)}${ellipsis}${restURL.slice(-maxLength + 5)}`;
}
let remainingLength = maxLength - host.length - 5;
let trimmedURL = `${protocol}://${host}`;
for (const part of parts) {
if (part.length <= remainingLength) {
trimmedURL += '/' + part;
remainingLength -= part.length + 1;
} else {
const startTrim = Math.floor((remainingLength - 3) / 2);
const endTrim = Math.ceil((remainingLength - 3) / 2);
trimmedURL += `/${part.substr(0, startTrim)}...${part.slice(-endTrim)}`;
break;
}
}
return trimmedURL;
} else {
const leftSideLength = Math.floor(maxLength / 2);
const rightSideLength = maxLength - leftSideLength;
const leftSide = url.slice(0, leftSideLength);
const rightSide = url.slice(-rightSideLength);
return leftSide + ellipsis + rightSide;
}
}

@ -0,0 +1,83 @@
// Courtesy of Benjamin von Polheim:
// https://blog.devgenius.io/build-a-performat-autocomplete-using-phoenix-liveview-and-alpine-js-8bcbbed17ba7
export default (id) => ({
isOpen: false,
id: id,
focus: null,
selectionInProgress: false,
setFocus(f) {
this.focus = f;
},
initFocus() {
if (this.focus === null) {
this.setFocus(this.leastFocusableIndex())
}
},
trackSubmitValueChange() {
this.selectionInProgress = false;
},
open() {
if (!this.isOpen) {
this.initFocus()
this.isOpen = true
}
},
suggestionsCount() {
return this.$refs.suggestions?.querySelectorAll('li').length
},
hasCreatableOption() {
return this.$refs.suggestions?.querySelector('li').classList.contains("creatable")
},
leastFocusableIndex() {
if (this.suggestionsCount() === 0) {
return 0
}
return this.hasCreatableOption() ? 0 : 1
},
maxFocusableIndex() {
return this.hasCreatableOption() ? this.suggestionsCount() - 1 : this.suggestionsCount()
},
nextFocusableIndex() {
const currentFocus = this.focus
return currentFocus + 1 > this.maxFocusableIndex() ? this.leastFocusableIndex() : currentFocus + 1
},
prevFocusableIndex() {
const currentFocus = this.focus
return currentFocus - 1 >= this.leastFocusableIndex() ? currentFocus - 1 : this.maxFocusableIndex()
},
close(e) {
// Pressing Escape should not propagate to window,
// so we'll only close the suggestions pop-up
if (this.isOpen && e.key === "Escape") {
e.stopPropagation()
}
this.isOpen = false
},
select() {
this.$refs[`dropdown-${this.id}-option-${this.focus}`]?.click()
this.close()
document.getElementById(this.id).blur()
},
scrollTo(idx) {
this.$refs[`dropdown-${this.id}-option-${idx}`]?.scrollIntoView(
{ block: 'nearest', behavior: 'smooth', inline: 'start' }
)
},
focusNext() {
const nextIndex = this.nextFocusableIndex()
this.open()
this.setFocus(nextIndex)
this.scrollTo(nextIndex)
},
focusPrev() {
const prevIndex = this.prevFocusableIndex()
this.open()
this.setFocus(prevIndex)
this.scrollTo(prevIndex)
}
})

@ -0,0 +1,20 @@
// From https://alpinejs.dev/component/dropdown
export default () => ({
open: false,
toggle() {
if (this.open) {
return this.close()
}
this.$refs.button.focus()
this.open = true
},
close(focusAfter) {
if (! this.open) return
this.open = false
focusAfter && focusAfter.focus()
},
})

@ -0,0 +1,57 @@
import "phoenix_html"
import Alpine from 'alpinejs'
import { Socket } from "phoenix"
import { LiveSocket } from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']")
let websocketUrl = document.querySelector("meta[name='websocket-url']")
if (csrfToken && websocketUrl) {
let Hooks = {}
Hooks.Metrics = {
mounted() {
this.handleEvent("send-metrics", ({ event_name, params }) => {
const afterMetrics = () => {
this.pushEvent("send-metrics-after", {event_name, params})
}
setTimeout(afterMetrics, 5000)
params.callback = afterMetrics
window.plausible(event_name, params)
})
}
}
let Uploaders = {}
Uploaders.S3 = function (entries, onViewError) {
entries.forEach(entry => {
let xhr = new XMLHttpRequest()
onViewError(() => xhr.abort())
xhr.onload = () => xhr.status === 200 ? entry.progress(100) : entry.error()
xhr.onerror = () => entry.error()
xhr.upload.addEventListener("progress", (event) => {
if (event.lengthComputable) {
let percent = Math.round((event.loaded / event.total) * 100)
if (percent < 100) { entry.progress(percent) }
}
})
let url = entry.meta.url
xhr.open("PUT", url, true)
xhr.send(entry.file)
})
}
let token = csrfToken.getAttribute("content")
let url = websocketUrl.getAttribute("content")
let liveUrl = (url === "") ? "/live" : new URL("/live", url).href;
let liveSocket = new LiveSocket(liveUrl, Socket, {
heartbeatIntervalMs: 10000,
params: { _csrf_token: token }, hooks: Hooks, uploaders: Uploaders, dom: {
// for alpinejs integration
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
Alpine.clone(from, to);
}
},
}
})
liveSocket.connect()
window.liveSocket = liveSocket
}

@ -0,0 +1,13 @@
window.addEventListener(`phx:update-value`, (e) => {
let el = document.getElementById(e.detail.id)
el.value = e.detail.value
if (e.detail.fire) {
el.dispatchEvent(new Event("input", { bubbles: true }))
}
})
window.addEventListener(`phx:js-exec`, ({ detail }) => {
document.querySelectorAll(detail.to).forEach(el => {
window.liveSocket.execJS(el, el.getAttribute(detail.attr))
})
})

16656
assets/package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -3,59 +3,44 @@
"version": "1.4.0",
"license": "AGPL-3.0-or-later",
"scripts": {
"deploy": "webpack --mode production",
"watch": "webpack --mode development --watch",
"format": "prettier --write {css,js}/**",
"check-format": "prettier --check {css,js}/**",
"lint": "eslint js/**",
"bundlemon": "bundlemon"
},
"dependencies": {
"@babel/core": "^7.14.3",
"@babel/preset-env": "^7.14.4",
"@babel/preset-react": "^7.13.13",
"@headlessui/react": "^1.7.10",
"@heroicons/react": "^2.0.11",
"@juggle/resize-observer": "^3.3.1",
"@kunukn/react-collapse": "^2.2.9",
"@popperjs/core": "^2.11.6",
"@tailwindcss/aspect-ratio": "^0.2.1",
"@tailwindcss/forms": "^0.3.2",
"@tailwindcss/aspect-ratio": "^0.4.2",
"@tailwindcss/forms": "^0.5.6",
"@tailwindcss/typography": "^0.4.1",
"abortcontroller-polyfill": "^1.7.3",
"alpinejs": "^2.8.2",
"autoprefixer": "^10.2.6",
"babel-loader": "^8.2.2",
"alpinejs": "^3.13.1",
"chart.js": "^3.3.2",
"chartjs-plugin-datalabels": "^2.2.0",
"classnames": "^2.3.1",
"copy-webpack-plugin": "^9.0.0",
"css-loader": "^5.2.6",
"css-minimizer-webpack-plugin": "^3.2.0",
"datamaps": "^0.5.9",
"dayjs": "^1.11.7",
"debounce-promise": "^3.1.2",
"iframe-resizer": "^4.3.2",
"mini-css-extract-plugin": "^1.6.0",
"phoenix": "1.5.0",
"phoenix_html": "2.12",
"postcss": "^8.3.0",
"postcss-loader": "^6.1.1",
"phoenix": "^1.7.2",
"phoenix_html": "^3.3.1",
"phoenix_live_view": "^0.18.18",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-flatpickr": "3.10.5",
"react-flip-move": "^3.0.4",
"react-intersection-observer": "^9.5.2",
"react-popper": "^2.3.0",
"react-router-dom": "^5.2.0",
"react-transition-group": "^4.4.2",
"tailwindcss": "^2.1.2",
"terser-webpack-plugin": "^5.1.2",
"url-search-params-polyfill": "^8.1.1",
"webpack": "5.38.1",
"webpack-cli": "^4.7.0"
"url-search-params-polyfill": "^8.1.1"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"bundlemon": "^1.4.0",
"eslint": "^7.2.0",
"eslint-config-prettier": "^7.0.0",
"eslint-plugin-import": "^2.26.0",
@ -65,8 +50,7 @@
"eslint-plugin-react-hooks": "^4.2.0",
"stylelint": "^14.1.0",
"stylelint-config-prettier": "^9.0.3",
"stylelint-config-standard": "^24.0.0",
"webpack-bundle-analyzer": "^4.4.2"
"stylelint-config-standard": "^24.0.0"
},
"name": "assets"
}

@ -1,6 +0,0 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save