Commit Graph

949 Commits

Author SHA1 Message Date
Adrian Gruntkowski
790984e1ad
Refactor Sites and Stats API authorization logic (#4297)
* Refactor and unify auth plugs for Stats and Sites APIs

* Expose get site Sites API endpoint to all API keys

* Test the new plug

* Add test for endpoint with modified scope

* Fix typos

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

* Rename plug for consistency (h/t @aerosol)

---------

Co-authored-by: hq1 <hq@mtod.org>
2024-07-02 15:09:23 +02:00
Karl-Aksel Puulmann
0594478add
APIv2: Replace breakdown module with QueryBuilder (#4293)
* Revert "Revert "APIv2: Replace breakdown module with QueryBuilder (#4283)" (#4292)"

This reverts commit ef5e0e0382.

* Allow querying events and pageviews from sessions table

This is not strictly accurate, especially with shorter time frames, but
is useful for a fallback mechanism. I'll figure out something around
shorter time frames in the future.

See also: https://github.com/plausible/analytics/pull/4292

* Only query events and pageviews in legacy breakdowns
2024-07-01 12:50:01 +03:00
Karl-Aksel Puulmann
ef5e0e0382
Revert "APIv2: Replace breakdown module with QueryBuilder (#4283)" (#4292)
This reverts commit 7dd12d1dd6.
2024-07-01 10:50:44 +03:00
Karl-Aksel Puulmann
7dd12d1dd6
APIv2: Replace breakdown module with QueryBuilder (#4283)
* WIP: Breakdown using QueryBuilder

* Revert "Remove problematic test"

This reverts commit b442bb5d1f.

* Get more breakdown tests passing

* Preload goals, sort when dealing with time_on_page

* Handle conversion_rate in breakdowns

* Simplify ordering by using selected_as consistently for dimensions

* Get breakdown tests passing

* Strings to atoms in keys for StatsController.transform_keys calls to work

* Handle revenue metrics removal

* Add test for nil-removal case

* Include percentage metric

* Fix and test with imported locations

* Fixup time-on-page

* Fix country/region automatic filters

* Handle multiple imports (os/browser version) in importsv2

* Filter goals

* Default to ordering by page as well

* Calculate conversion rate on sessions if needed

* Order by event dimensions - handles event:page special case

* Update tests

* Update more tests, handle goal=0 case in imports

* Handle event:goal breakdowns correctly with filters

* Revenue to money

* Improved table deciding

* Also update event:page filters on event:page breakdown

* bounce_rate to 0

Previous behavior relied on two queries being made - new query leads to 0 naturally

* Update pagination test

* dont count non-pageviews as path goal completions

* Make revenue logic breakdown-specific

Its hard to fit into the new schema and likely needs a rethink for apiv2

* Retain previous behavior for TimeSeries module

* Get GA4 test passing

Most failures are related to ordering, pageviews shouldnt be read off of sessions

* Clean up old methods

* Simplify imported.ex

* Dont crash on garbage filters

* Reflect ordering-related change in test

* Fix test data

* Update table_decider

* Re-simplify get_revenue_tracking_currency

* Revert revenue changes

* Use Query.set

* Remove a TODO

* csv importer: no pageviews

Pageviews were incorrectly fetched from sessions table before, causing issues

* csv importer tweaking

* Remove use Plausible

* to_existing_atom
2024-07-01 09:03:33 +03:00
hq1
f4e091452c
Require src attribute when seeking snippet for verification (#4290) 2024-07-01 07:38:25 +02:00
Karl-Aksel Puulmann
2eeaf7a152
APIv2: Aggregates, timeseries, conversion_rate, hostname (#4251)
* Add some aggregates tests

* Port aggregates tests to do with filtering

* Session metrics can be queried with event: filters

* Solve a typo

* Update a validation message

* Add validations for views_per_visit

* Port an aggregation/imports test

* Optimize time dimension, add tests

* Add first timeseries test, update parsing tests

* Docs for SQL.Expression

* Test timeseries more

* Allow time explicitly in order_by

* Add multiple breakdowns test

* Refactor QueryOptimizer not to care about time dimension placement in dimensions array

* Add test breaking down by event:hostname

* Add hostname filtering logic to QueryOptimizer, unblock some tests

* WIP: Breakdown by goal

* conversion rate logic for query api

* Update more tests

* Set default order_by

* dimension_label

* preloaded_goals in tests

* inline load_goals

* Use Date functions over Timex

* Comments

* is_binary

* Remove special form used in tests

* Fix defmodule

* WIP: Fix memory leak, event:page breakdown logic

* Enable more tests, fix for group_conversion_rate without explicit visitors metric

* Re-enable a partially commented test

* Re-enable a partially commented test

* Get last test passing

* No imports order_by in apiv2

* Add a TODO

* Remove redundant Util call

* Update aggregate.ex

* Remove problematic test
2024-06-28 08:59:54 +03:00
RobertJoonas
07a54ef65c
Count pending ownership sites towards account usage on the upgrade page (#4277)
* add notice about pending ownerships counting towards usage

* Refactor feature usage to take site_ids too

* Add option to query usage from pending ownerships

* count pending ownerships towards usage on the choose-plan page

* turn 'eligible_for_upgrade?' into a predicate

* fix variable names on ce

* fix unused alias on ce

* fix ce test
2024-06-27 12:09:15 +03:00
Karl-Aksel Puulmann
58a66a952c
APIv2 - initial PR (#4216)
* WIP new querying

* WIP: Move some aggregate code under new command

* WIP: Add joins, handling less metrics

* join events table to sessions if needed

* Merge imported results with built query

* Remove dead code

* WIP: /api/v2/query

* Allow grouping by time

* Use JOIN for main query

* Build query result

* update parse_time

* Make joinless order by work

* First test

* more breakdown tests

* Serialize event:goal filters in an json-encodable way/reflection

* Handle inner vs outer ORDER BY clauses properly

* Handle single conversion_rate metric

* Update more tests

* Get parsing tests passing again

* Validate filtered goal filter is configured

* Enable more validation tests

* Enable more event:name breakdown tests

* Enable more breakdown tests

* Validate site has access to custom props

* Validate conversion_rate metric which is only allowed in some situations

* Validate that empty event:props: is not valid

* handle query.dimensions properly in table_decider

* test more validations on metrics/dimensions

* Validate session metrics in combination with event dimension(s)

* Tests cleanup

* Parse include.imports

* Get imports working with new querying

* Make more imports tests work

* Make event:props:path imports-adjacent test work

* Get query imports warning-related tests running

* Remove dead pagination tests

* Solve dead import

* Solve some warnings

* Update aggregate metrics tests

* credo

* Improve test naming

* Lazy goal loading

* Use datetime methods

* Ecto -> SQL module name

* Remove Expression.dimension mode option
2024-06-25 09:27:19 +03:00
ruslandoga
5a0718aa75
update runtime to elixir-1.17.1 and erlang-27.0 (#4255)
* update runtime to elixir-1.17.1 and erlang-27.0

* update credo

* fix some warnings in tests

* temp fix (backport)

---------

Co-authored-by: hq1 <hq@mtod.org>
2024-06-24 13:22:33 +02:00
Karl-Aksel Puulmann
284b4ebbf6
does_not_contain, new filters wildcard matching (#4228)
* Make goals accept wildcards in :is queries

* Add support for contains/does_not_contains in the backend

* Support all operations for event custom properties

* Support does_not_contain on the frontend

* Changelog entry

* Render filter operations nicely for does not contain

Found 3 extra pixels for operation dropdown

* Remove multiple_filters feature flag
2024-06-21 11:32:05 +03:00
Karl-Aksel Puulmann
ed8abf426b
Revert "Revert "Re-apply multiple filters in FE (#4219)" (#4223)" (#4227)
This reverts commit 2c05676d8e.
2024-06-21 11:31:02 +03:00
Adrian Gruntkowski
766807e9fd
Add backlinks between CRM, dashboard and site members (#4252)
* Add button to dashboard in site CRM edit form

* Add links to CRM for site and each user in "People" settingsg
2024-06-20 14:03:58 +02:00
RobertJoonas
db1e755b0e
Hide 20M and 50M legacy plans from the upgrade page (#4248)
* Stop showing 20M and 50M plans unless user is already on one

* Add tests
2024-06-20 13:04:04 +03:00
Adrian Gruntkowski
fc20782287
Fix pagination is Sites CRM (#4242) 2024-06-20 09:32:38 +02:00
ruslandoga
9cbb9ba79c
Fix CE Stats API access (#4244)
* fix ce stats api access

* changelog

* tag groth tests ee only
2024-06-20 09:32:21 +02:00
RobertJoonas
b5c5ab8e61
ignore irrelevant paddle webhook (#4240) 2024-06-18 11:47:16 +03:00
hq1
1c820ba2af
Verification tweaks (#4234)
* Prioritize CSP over GTM error in case both detected

* Outline better message for persistent headless timeout

* Bump headless waiting times slightly

* Add generic type of error

For known cases, that we rather not reveal much
details about.

* Add the malformed script tag case
2024-06-18 05:58:56 +02:00
RobertJoonas
f9a4cc784d
Make billing cycles less confusing (#4233)
* Set default selected tab to last cycle when rendering usage

...And never disable this tab.

* rename Ongoing cycle to Upcoming cycle

* fix tests

* mix format
2024-06-17 13:51:30 +02:00
Adrian Gruntkowski
e65e37afc0
Implement CRM enterprise plan definition QoL improvements (#4230)
* Implement autoprefill of enterprise plan fields on user change

* Implement sanitizing input attrs in enterprise plan CRM form

* Implement number formatting for monthly pageview limit input in CRM form
2024-06-17 13:11:53 +02:00
Adrian Gruntkowski
aadf528459
Add CRM QoL improvements around usage info and linking Paddle (#4229)
* Link subscription status to Paddle profile whenever available

* Display usage info directly in user form in CRM

* Handle pageview limit fallback gracefully when rendering subscription quota

* Remove usage page link from users list view in CRM

* Add tests for usage page

* Apply `raw/1` only to the one (and only) element of the list
2024-06-17 09:21:24 +02:00
RobertJoonas
dd1d74ccb7
Always recommend a suitable plan on the choose-plan page (#4222)
* pull last_bill_date from paddle sandbox in mix task

* move cycle usage checks to Quota module

* move quota.ex to a subfolder

* split up Quota module

* set choose-plan pageview slider according to usage

* silence credo
2024-06-17 09:25:46 +03:00
hq1
86d7031336
Unify default pricing currency selection (#4221)
* Start cache meant to store customer currencies

* Expose caching fetch_or_store interface

* Improve IP picking strategy - skip empty header values

* Use customer IP in determining pricing currency

* Expose /api/paddle/currency API

* Remove cache-control header

* Tidy up
2024-06-14 14:49:22 +02:00
Karl-Aksel Puulmann
2c05676d8e
Revert "Re-apply multiple filters in FE (#4219)" (#4223)
This reverts commit 77520390f8.
2024-06-13 12:45:50 +03:00
Karl-Aksel Puulmann
77520390f8
Re-apply multiple filters in FE (#4219)
* Revert "Revert "Multiple filters on the frontend (#4174)" (#4218)"

This reverts commit 2f7dcae991.

* Make city links work again

By enforcing everything sent to the BE is stringified. We do this at serialization-time to ensure old dashboard links still work
2024-06-13 09:56:15 +03:00
hq1
2f7dcae991
Revert "Multiple filters on the frontend (#4174)" (#4218)
This reverts commit e1f0002d2e.
2024-06-11 17:42:07 +03:00
hq1
4603aa7a51
Reset grace period if usage drops within the last cycle (#4212)
So that `LockSites` job unlocks the site,
encountering no grace period and no upgrade needed.
2024-06-11 15:49:31 +02:00
hq1
9f1f826801
Allow site creation for users owning the domain_changed_from (#4215)
* Allow site creation for users owning the `domain_changed_from`

* Format
2024-06-11 15:48:46 +02:00
Karl-Aksel Puulmann
e1f0002d2e
Multiple filters on the frontend (#4174)
* Add new logic for query parsing

Note this is not yet final, but this scaffolding will soon be used

* Send filters to BE in new encoding, flag add more button

* query.property -> query.dimensions

* Reduce number of operations for filtering

This helps ensure we can be consistent/simple with apiv2

* Update search console filter mapping

* Update filters sent from frontend

* Update new filter parsing

* Remove redundant clause

* Make filtering by event:goal work

* Handle * as old backend did - prefix/suffix by **, if not using wildcards already

* Update imports logic

* Credo warning

* Spacing for add row button in filter modals

* query fix

* LegacyDashboardFilterParser

* only single hostname filter allowed

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
2024-06-11 14:22:53 +03:00
Adrian Gruntkowski
d5a1d6765e
Implement custom events suggestions (#4092)
* Start suggesting event names in goal settings form

* Fix tests

* Bump phoenix_live_view to 0.20.12

* Implement a criminal hack to track removal of modal's child live components

* Revert "Implement a criminal hack to track removal of modal's child live components"

This reverts commit f34ceb78f1.

* Remove redundant closing brace from currency combo input

* Hide batch goal add button when tab selection is in progress

* Implement unique modal ID regenerated on every modal close/open cycle

* Use unique modal ID as ID suffix to live components in goal settings form

* Reset suffix on tab selection to reset live components state on switch

* Revert "Bump phoenix_live_view to 0.20.12"

This reverts commit 1b1c801981.

* Make unique IDs more predictable

* Fix tests for `GoalSettings.Form`

* Use unique modal ID in country rule modal

* Use unique modal ID in hostname rule modal

* Use unique modal ID in page rule form modal

* Don't limit detected goals when fetching them for autoconfigure

* Escape interpolated Alpine state function argument

* Exclude goals with whitespace on either end or consisting only of whitespace

* Ensure event name suggestions update after goal deletion

* Avoid showing loading spinner when closing modal

* Don't enable spinner when new combobox selection is identical

* Revert "Don't enable spinner when new combobox selection is identical"

This reverts commit a041ba8542.
2024-06-11 08:28:25 +02:00
RobertJoonas
7b11b71dcf
Minor refactor: Remove skip_refresh_imported_opts from query modifying functions (#4204)
* Remove skip_refresh_imported_opts from query modifying functions

+ add test coverage for timeseries conversion rate.

* format

* improve comment
2024-06-10 13:03:12 +03:00
hq1
92d5092518
Verification improvements next batch (#4203)
* Upgrade req

* Fetch body even on non-200 statuses

Turns out sites, will happily go with 307 and no location
header for example. In which case saying we can't reach it
is an overstatement. After all we should let the headless
check determine the rest.

* Update callback status interpretation cases

* Update tests

* Fix flaky test

* Update expectation
2024-06-10 10:40:19 +02:00
ruslandoga
22ea56a779
increase api_keys.hourly_request_limit in CE (#4200)
* increase api_keys.hourly_request_limit in CE

* changelog

* add tests
2024-06-10 07:21:58 +02:00
hq1
823f7a8800
Plugins API: Get/Create Funnels (#4192)
* Bootstrap OpenAPI Funnel schemas

* Implement Plugins API Funnel view

* Allow casting funnel step directly from `%Goal{}`

* Check feature availability on funnel creation

just like it's done when inserting goals

* Implement Plugins API context module for Funnels

* Implement GET/PUT funnels via Plugins API

* Fix typo

* A rare event in which dialyzer found an actual bug, wow!

* Format

* Wrap creation request with a root `funnel` key

* Format

* Extract common funnel get query

* Remove redundant tag

* Refactor queries a bit
2024-06-07 13:10:01 +02:00
RobertJoonas
2a529b4eaa
Fix with imported switch + warning bubble renders (#4187)
* prioritize other skip_imported_reasons over not requested

* return with_imported_switch info from top stats

* fix the with-imported-switch component

* Refactor ImportedQueryUnsupportedWarning

* do not render warning bubble when imported data not requested

* stop displaying warning bubble before the API response is received

* fix tab switch pills jumping due to bubble height

* drop loading condition of ImportedQueryUnsupportedWarning for Funnels

* add explicit check for realtime when rendering the bubble

* remove unused JS imports

* rename snake_case to camelCase
2024-06-06 11:50:54 +03:00
Adrian Gruntkowski
fd81ef2105
Include imported page paths in pageview goal suggestions (#4193) 2024-06-06 10:40:48 +02:00
Adrian Gruntkowski
a764938928
Fix handling filtering by imported special properties (#4179)
* Handle custom prop queries separately when deciding imported table

* Add Query level tests
2024-06-04 13:06:31 +02:00
hq1
5fd4547382
More verification tweaks (#4177)
* Stop reporting multiple snippets in case manual extension is in use

* Try detecting CookieBot/GTM case
2024-06-03 13:49:04 +02:00
RobertJoonas
1d3b068233
Implement filtering for imported data (#4118)
* move imported.ex to imported subfolder

* move constructing base imported query into a separate module

* Implement imported table deciding and filtering

+ tests for pages, entry_pages, exit_pages and common filter types

* add top stats test with country filter

* add timeseries test

* Drop bounce_rate and time_on_page from imported & page-filtered Top Stats

* rename field returned by top stats

* turn pages into a fn comp

* Move dashboard API results under a results key

...and also return the skip_imported_reason to the frontend to be used
for displaying warnings.

* extend ListReport component with an optional afterFetchData prop

* turn Devices into a fn comp

* add not_requested as a skip_imported_reason

* display warning icons in the dashboard

* Implement filtering suggestions and translate filter fields for imported

* WIP

* Improve and cover filtering suggestions with tests

* Rename imported suggestions query helpers

* fix screen size breakdown with screen size filter

* support filtering by the same suggestion property

* support location filters when fetching location suggestions

* support filtering by multiple props from the same table

* Implement filtering by goals

* Make views per visit metric work for import entry and exit pages

* Get rid of circular dependencies between Stats.Imported and Stats.Imported.Base

* Clean up Query struct manipulation in Breakdown

* Rename helper function for clarity

* Automatically refresh query struct state after modifications

* Shutup credo

* display imported warning bubble in prop breakdown section

* Render warning bubble for funnels whenever imported data is in the view

* Transform any operator on respective goal filters

* Fix percentage and conversion_rate calculation in presence of custom props

* add tests for for combining page and pageview goal filters

* add skip_refresh option to query tweaking functions

* add imported CR support for timeseries

* still show url breakdown when special goal + url in filter

* rename Query.refresh

* use flat_map instead of map and concat

* fix darkmode color

* Handle invalid imported region codes in suggestions gracefully

* Add an entry to CHANGELOG.md

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
2024-06-03 12:29:08 +02:00
ruslandoga
8588776df2
Add newline to csv importer insert sql (#4172)
* add newline to csv importer insert sql

* add test

* changelog

* fix test typo

* fix test typo x2
2024-06-03 09:48:16 +02:00
hq1
bb7b0d9f94
Tidy up verification code a little (#4156) 2024-05-29 08:51:10 +02:00
hq1
9d77e970ef
Redo site verification UI (#4153)
* Redo site verification UI

* format
2024-05-28 13:43:14 +02:00
hq1
d9cf037866
Handle no snippet WordPress case (#4152) 2024-05-28 09:37:01 +02:00
hq1
78c5762761
Verification: prioritize domain mismatch over multiple snippets (#4146) 2024-05-27 10:52:22 +02:00
hq1
0381bc6121
Use codespell (#4145)
* Fix typos

* Add .codespellignore

* Add codespell GH action
2024-05-27 10:52:01 +02:00
hq1
206a6543f6
First pass: extract verification errors (#4138)
* First pass: extract verification errors

We like to make them easier to maintain.
An update fixing documentation URLs will follow.

* Update moduledoc
2024-05-24 16:23:25 +02:00
hq1
a7b69719c1
More fixes to the verification process (#4136)
* More fixes to the verification process:
 - extend the list of known attributes
 - follow redirect chain host to verify data-domain difference
 - display the actual data-domain in error message, not URL

* format

* fix test

* remove redundant pattern matching

* Update lib/plausible/verification/checks/snippet.ex

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

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
2024-05-24 12:45:31 +02:00
hq1
ee61094023
Verification improvements (#4132)
* Simplify browserless script and catch errors

* Improve fetching body:
    - follow up on max. 4 redirects
    - rely on Req default timeouts (wait much longer to account for slow
      sites)

* Improve installation check:
  - rely on Req default timeouts, wait longer
  - log service errors as warnings
  - use stealth mode to bypass captchas

* Stop cutting off body too large

* Improve diagnostics for known failures

* Another round of diagnostic improvements

* Format

* Add a test for callback status 500
2024-05-24 10:40:59 +02:00
hq1
c81cb16933
Snippet integration verification (#4106)
* Allow running browserless.io locally

* Compile tailwind classes based on extra/ too

* Add browserless runtime configuration

* Ignore verification events on ingestion

* Improve extracting HTML text in tests

* Update dependencies

- Floki will be used on production to parse site contents
- Req will be used to handle redundant stuff like retrying etc.

* Add shuttle SVG to generic components

Later on we'll use it to indicate verification errors

* Connect live socket & allow skipping awaiting the first pageview

* Connect live socket in general settings

* Implement verification checks & diagnostics

* Stub remote services with Req for testing

* Change snippet screen copy

* Update tracker script, so that:

1. headless browsers aren't ignored if `window.__plausible` is defined
2. callback optionally supplies the event response HTTP status

This will be later used to check whether the server acknowledged
the verification event.

* Implement LiveView verification UI

* Embed the verification UIs into settings and onboarding

* Implement browserless puppeteer verification script

It:
 - tries to visit the site
 - defines window.__plausible, so the tracker doesn't ignore test events
 - sends a verification event and instruments the callback
 - awaits the callback to fire and returns the result

* Improve diagnostics for CSP

Only report CSP error if the snippet is already found

* Put verification behind a feature flag/env setting

* Contact Us hint only for Enterprise Edition

* For headless code, use JS context instead of EEx interpolation

* Update diagnostics test with WordPress scenarios

* Shorten exception/throw interception

* Rename test

* Tidy up

* Bust URL always on headless check

* Update moduledoc

* Detect official Plausible WordPress Plugin

and act accordingly on diagnostics interoperation

* Stop using 'rating' in favour of 'interpretation'

* Only report CSP error if no proxy is likely

* Update CHANGELOG

* Allow event-* attributes on snippet elements

* Improve naive GTM detection, not to confuse it with GA4

* Update lib/plausible/verification.ex

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

* Update test/plausible/site/verification/checks_test.exs

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

* s/perform_wrapped/perform_safe

* Update lib/plausible/verification/checks/installation.ex

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

* Remove garbage

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
2024-05-23 15:00:50 +02:00
ruslandoga
9687fa786d
remove Plausible Analytics metions from CE (#4121)
* remove Plausible Analytics metions from CE

* update tests

* still mention Plausible Analytics on landing page
2024-05-23 09:43:01 +02:00
hq1
cd4d1d06bb
Rename Plugins API Token(s) to Plugin Token(s) (#4075)
Deployment needs to be coordinated with WordPress plugin
update. Reasoning: there's too much confusion coming
from the use of the "API" terminology, leading to wrong
keys being generated by users.
2024-05-22 07:45:09 +02:00