Commit Graph

878 Commits

Author SHA1 Message Date
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>
2023-09-21 09:08:43 +02:00
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
2023-09-18 11:47:49 +02:00
hq1
a9bfaed70f
Get rid of the funnels flag completely (#3341) 2023-09-13 15:54:09 +02:00
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
2023-09-13 15:07:04 +02:00
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>
2023-09-13 14:55:29 +02:00
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>
2023-09-12 16:24:28 +03:00
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
2023-09-12 09:11:50 +02:00
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>
2023-09-12 10:06:24 +03:00
Cenk Kücük
45ed56b4d5
Add monitoring for ingest.plausible.io (#3334)
* Add monitoring for ingest.plausible.io

* fix deprecation warning

* fmt
2023-09-11 16:36:08 +02:00
hq1
29d0f82182
Apply unified capitalization to buttons and titles (#3321) 2023-09-05 09:43:01 -03:00
hq1
a1be27eea6
s/superadmin/super_admin (#3318)
* s/superadmin/super_admin

* Add test
2023-09-05 09:17:39 +02:00
hq1
b2df714bdb
Bugfix: ComboBox navigation with creatable on top (#3316)
* Bugfix: ComboBox navigation with creatable on top

* !fixup

* !fixup

* !fixup

* !fixup
2023-09-04 14:56:31 +02:00
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
2023-09-04 09:55:07 -03:00
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
2023-09-04 13:44:22 +02:00
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
2023-08-31 11:14:54 -03:00
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
2023-08-24 14:22:49 -03:00
Uku Taht
8c870f7c6b Increase sampling test delta to reduce flakyness 2023-08-22 14:06:20 +03:00
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>
2023-08-22 12:33:48 +02:00
Uku Taht
da3d4366f6
Add login link to 404 page (#3288)
* Add login link to 404 page

* Fix 404 test

* Fix another test
2023-08-22 08:45:38 +02:00
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
2023-08-21 13:21:20 -03:00
Vini Brasil
dad787cb4b
Rename allowance to monthly_pageview_limit (#3273)
* Remove unused site_limit_exempt list

* Rename allowance to monthly_pageview_limit
2023-08-21 10:07:27 -03:00
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
```
2023-08-21 09:01:50 -03:00
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
2023-08-16 13:38:38 -03:00
hq1
49a29d86e8
Make stats controller tests synchronous (#3264) 2023-08-14 10:49:41 -03:00
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
2023-08-10 09:23:21 +02:00
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.
2023-08-09 14:33:59 -03:00
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
2023-08-08 14:49:19 +02:00
Ё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
2023-08-07 09:32:01 +02:00
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>
2023-08-05 15:13:16 +01:00
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.
2023-08-05 14:35:31 +01:00
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
2023-08-03 16:17:44 +01:00
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
2023-08-02 13:45:49 +02:00
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.
2023-08-01 19:41:56 +01:00
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>
2023-08-01 13:52:31 +01:00
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`,
2023-07-31 09:33:37 +01:00
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
2023-07-28 19:44:56 +01:00
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
2023-07-27 16:02:16 +01:00
Vini Brasil
d49d68af8f
Create props settings page (#3191) 2023-07-27 15:46:32 +01:00
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
2023-07-27 14:27:01 +02:00
hq1
9f0e7d54f8
Fix flaky log assertion (#3199) 2023-07-27 12:51:54 +02:00
hq1
82f356f387
Add debug_replay_info context to Sentry Stats reports (#3189)
* Add debug_replay_info context to Sentry Stats reports

* Test limit
2023-07-26 10:44:04 +02:00
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
2023-07-24 15:27:44 +01:00
ruslandoga
f3a1a9d599
derive jason encoder for request (#3182)
* derive jason encoder for request

* test didn't test

---------

Co-authored-by: hq1 <hq@mtod.org>
2023-07-24 14:46:57 +02:00
hq1
928691158f
Fix test flakiness due to shared state in asynchronous run (#3184)
* Fix flaky test

* Prevent this in the future
2023-07-24 14:43:28 +02:00
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>
2023-07-24 10:18:40 +01:00
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
2023-07-21 14:58:50 +01:00
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
2023-07-21 07:35:41 +03:00
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
2023-07-19 10:23:14 +02:00
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
2023-07-17 18:00:52 +03:00
hq1
e6996ccfda
Fix weekly/monthly report e-mails (MJML) (#3150)
* Render weekly/monthly reports with MJML

* Update changelog

* Fix APP-2NA (#3119)
2023-07-17 16:59:01 +02:00
hq1
4b9b3abafd
Respond with early 400 on malformed export request (#3151)
* Respond with early 400 on malformed export request

* credo
2023-07-17 14:50:56 +02:00
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
2023-07-15 12:04:29 +01:00
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>
2023-07-12 14:04:56 +02:00
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
2023-07-12 10:25:34 +01:00
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>
2023-07-11 10:52:09 +02:00
hq1
cf5cc8de94
Filter out GA imported data with no visitors recorded (#3123) 2023-07-11 10:47:24 +02:00
hq1
9debcdee24
Fix APP-2NA (#3119) 2023-07-11 10:47:14 +02:00
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
2023-07-11 10:47:03 +02:00
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
2023-07-04 12:07:24 +02:00
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.
2023-07-04 12:07:16 +02:00
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 🤡
2023-06-28 13:20:19 +02:00
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>
2023-06-27 10:04:35 +02:00
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.
2023-06-23 09:02:22 +01:00
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).
2023-06-22 19:36:43 +01:00
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
2023-06-22 09:00:07 +02:00
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.
2023-06-20 09:41:00 +01:00
Cenk Kücük
94591a5a20
Update loadbalancer url (#3056) 2023-06-19 13:31:11 +02:00
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.
2023-06-19 11:05:00 +01:00
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.
2023-06-19 11:02:31 +01:00
Vini Brasil
f0bdf872b5
Add eventually/1 call to flaky test (#3054) 2023-06-19 10:32:34 +01:00
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
2023-06-14 14:39:06 +01:00
Uku Taht
98055d2f1c
Fix queries with wildcard goals (#3015)
* Fix queries with wildcard goals

* Changelog
2023-06-14 14:14:27 +01:00
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>
2023-06-13 14:01:39 +02:00
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
2023-06-13 12:26:33 +02:00
hq1
dc0853bac7
Revert "UI groundwork: Conversions to Behaviors (#3005)" (#3024)
This reverts commit ba19f9530e.
2023-06-13 12:05:13 +02:00
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
2023-06-13 08:16:38 +02:00
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
2023-06-12 18:29:17 +01:00
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.
2023-06-07 09:24:43 +01:00
Uku Taht
fc918081b5
Fix event name validation (#2975)
* Fix event name validation

* Add @moduledoc

* Move tests to Ingestion.RequestTest

* Remove comment
2023-06-01 14:37:46 +03:00
ruslandoga
25f95ae84e
add landing page (#2989)
* add landing page

* cont.

* add redirect to /sites test

* add changelog entry

* adapt for mobile
2023-06-01 14:34:48 +03:00
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>
2023-05-25 10:37:10 +03:00
ruslandoga
ce7401dd83
add MAILER_NAME (#2937)
* add MAILER_NAME

* add mailer test

---------

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
2023-05-25 10:34:39 +03:00
ruslandoga
7b22aff11c
add MAILGUN_BASE_URI (#2935)
* add MAILGUN_BASE_URI support

* add changelog entry
2023-05-25 10:32:50 +03:00
RobertJoonas
dafb60164a
Allow setting sample_threshold in dashboard API queries (#2958)
* refactor Query.from/2

* allow specifying sample_threshold number in query
2023-05-24 14:25:05 +03:00
Uku Taht
1a94456586
Wrap user deletion in DB transaction (#2964) 2023-05-24 14:23:23 +03:00
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>
2023-05-23 12:08:09 +02:00
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
2023-05-23 11:37:58 +03:00
Uku Taht
2259651b21
Ignore missing subscription on update (#2930) 2023-05-23 11:35:18 +03:00
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>
2023-05-19 13:26:13 +02:00
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>
2023-05-18 12:05:24 +02:00
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.
2023-05-17 15:13:28 +02:00
RobertJoonas
00d05b2edd
Fix a bug with query bindings (#2932) 2023-05-17 14:26:39 +02:00
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
2023-05-16 11:59:56 +02:00
Uku Taht
eec842c46b
Remove visits_metric feature flag (#2898)
* Remove `visits_metric` feature flag

* Fix credo warning
2023-05-16 11:58:40 +02:00
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
2023-05-16 10:52:17 +02:00
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>
2023-05-09 11:51:35 +03:00
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
2023-05-04 14:09:43 +02:00
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
2023-05-03 09:46:28 +01:00
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>
2023-05-02 16:33:28 +03:00
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
2023-04-27 14:09:33 +03:00
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.
2023-04-26 12:22:33 +01:00
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>
2023-04-26 10:06:40 +01:00
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
2023-04-24 12:17:57 +02:00
hq1
b8e96b948f
Stop using Double in cache store tests (#2854) 2023-04-17 09:24:45 +01:00
Vini Brasil
3d656ae95b
Match day of the week feature for comparisons (#2822)
* Add support for `match_day_of_week?` back-end option

* Add match day of week input to comparison input

* Default match day of the week to true
2023-04-13 14:01:54 +01:00
hq1
825a754976
Make ingest threshold configurable (#2845)
* Make ingest threshold configurable

* Credo
2023-04-13 13:52:54 +02:00
Vini Brasil
9f036d3915
Show detailed comparison dates in top stats (#2804)
* Pass comparison_query as argument to top stats functions

* Add comparison values and dates to top stats API

* Display comparison dates and values in top stats

* Rename function to renderPercentageComparison

* Create component to do conditional rendering

* DRY date range formatting function

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
2023-04-11 09:59:10 -03:00
hq1
c04e9286dd
Associate goals with sites, not domains (#2828)
* Revert "Rephrase error message"

This reverts commit f624443a96.

* Revert "Temporarily disable goal creation"

This reverts commit a091635b9d.

* Update ecto schema

* Make sure goal operations are per site

* Update tests

* Split postgres migrations
2023-04-10 10:51:36 +02:00
hq1
3cb089eab4
Migrate and freeze goals creation (#2833)
* Full migration (to be submitted separately)

* Do not remove `Goal.domain` just yet

* Do not make Goal.site not nullable just yet

* Temporarily disable goal creation

* Rephrase error message

* Add down migration
2023-04-10 10:29:10 +02:00
hq1
154ce3a44c
Split clickhouse repos - making the main one read only (#2826)
* Split clickhouse pools into readonly/import deletions

* Remove CRM site transfers

* Initialize ImportDeletionRepo

* Put ImportDeletionRepo to use
2023-04-06 12:45:36 +02:00
RobertJoonas
7204e470a8
Filter modal refactor (#2806)
* Refactor: FilterModal -> RegularFilterModal

* Rename filter.js to regular-filter-modal.js

* Refactor: extract FilterTypeSelector component

* fix undefined order in test

* classNames function style improvement
2023-04-05 16:20:35 +01:00
Uku Taht
71e4d228c0
Escape pipes in goal names (#2814)
* Escape pipes in goal names

* Apply suggestions from code review

Use ~S sigil for better readability

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

---------

Co-authored-by: Vini Brasil <vini@hey.com>
2023-04-05 12:59:25 +03:00
hq1
406ea6f0cd
Render an error on site creation with domain=domain_changed_from (#2821) 2023-04-05 11:57:20 +02:00
hq1
1d01328287
Allow domain change (#2803)
* Migration (PR: https://github.com/plausible/analytics/pull/2802)

* Implement Site.Domain interface allowing change and expiry

* Fixup seeds so they work with V2_MIGRATION_DONE=1

* Update Sites.Cache so it's capable of multi-keyed lookups

* Implement worker handling domain change expiration

* Implement domain change UI

* Implement transition period for public APIs

* Exclude v2 tests in primary test run

* Update lib/plausible_web/controllers/site_controller.ex

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

* Update lib/plausible_web/controllers/site_controller.ex

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

* Update moduledoc

* Update changelog

* Remove remnant from previous implementation attempt

* !fixup

* !fixup

* Implement domain change via Sites API

cc @ukutaht

* Update CHANGELOG

* Credo

* !fixup commit missing tests

* Allow continuous domain change within the same site

---------

Co-authored-by: Vini Brasil <vini@hey.com>
2023-04-04 10:55:12 +02:00
hq1
70a85c3f4c
Revert "Temporarily disable site creation (#2813)" (#2817)
This reverts commit b626329ec5.
2023-04-04 08:23:31 +02:00
Uku Taht
b626329ec5
Temporarily disable site creation (#2813)
* Temporarily disable site creation

* Fix linter

* Disabled message wording
2023-04-04 08:14:42 +02:00
Uku Taht
46048e50f7
Support multiple filters - frontend (#2773)
* Wrap Plausible.Stats.Filters with unit tests

* Parse `member` filter type

* Support for `member` filter in `aggregate_time_on_page`

* Support `not_member` filter type

* Support `matches_member` and `not_matches_member` filters

* Extract util module for React filters

* Implement Combobox from scratch with no libs

* Support multple filter clauses in combobox

* Don't use browser / os in version label

* Show highlighted option in combobox

* WIP

* Fix location filters outside filter modal

* Align open/close behaviour with react-select

* Styling updates for combobox

* Add support for wildcards in Combobox

* Implement keybindings for combobox

* Allow free choice inputs in combobox

* Rename 'Save filter' -> Apply filter

* Remove TODO comment

* Clean up some rebase mistakes

* Rename `allowWildcard` -> `freeChoice`

* Dark mode fixes

* Remove hint from filter modal

* Escape pipe character in filter modal

* Do not allow selecting duplicate options in combobox

* Escape brackets in `page_regex/1`

* Fix disabled style in dark mode

* Add regex fallback for safari

* Show no matches found when visibleOptions is empty

* Disable enter key when no visible options

* Do not submit empty form fields

* Remove unnecessary setOpen(true)
2023-03-27 16:51:31 +03:00
hq1
d2f2c69387
Conditionally support switching between v1 and v2 clickhouse schemas (#2780)
* Remove ClickhouseSetup module

This has been an implicit point of contact to many
tests. From now on the goal is for each test to maintain
its own, isolated setup so that no accidental clashes
and implicit assumptions are relied upon.

* Implement v2 schema check

An environment variable V2_MIGRATION_DONE acts like
a feature flag, switching plausible from using old events/sessions
schemas to v2 schemas introduced by NumericIDs migration.

* Run both test suites sequentially

While the code for v1 and v2 schemas must be kept still,
we will from now on run tests against both code paths.
Secondary test run will set V2_MIGRATION_DONE=1 variable,
thus making all `Plausible.v2?()` checks return `true'.

* Remove unused function

This is a remnant from the short period when
we would check for existing events before allowing
creating a new site.

* Update test setups/factories with v2 migration check

* Make GateKeeper return site id along with :allow

* Make Billing module check for v2 schema

* Make ingestion aware of v2 schema

* Disable site transfers for when v2 is live

In a separate changeset we will implement simplified
site transfer for when v2 migration is complete.
The new transfer will only rename the site domain in postgres
and keep track of the original site prior to the transfer
so we keep an ingestion grace period until the customers
redeploy their scripting.

* Make Stats base queries aware of v2 schema switch

* Update breakdown with v2 conditionals

* Update pageview local start with v2 check

* Update current visitoris with v2 check

* Update stats controller with v2 checks

* Update external controller with v2 checks

* Update remaining tests with proper fixtures

* Rewrite redundant assignment

* Remove unused alias

* Mute credo, this is not the right time

* Add test_helper prompt

* Fetch priv dir so it works with a release

* Fetch distinct partitions only

* Don't limit inspect output for partitions

* Ensure SQL is printed to IO

* Remove redundant domain fixture
2023-03-27 13:52:42 +02:00
Uku Taht
a75d0b35b0
Fix Timex.total_offset blowing up during clock changes (#2788)
* Fix Timex.total_offset blowing up during clock changes

* Format large numbers with underscore in tests

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

---------

Co-authored-by: Adam <hq@mtod.org>
2023-03-24 10:41:01 -03:00
Vini Brasil
87a63fe28a
Custom comparison mode (#2753)
This commit implements the custom comparison mode using a date range.
2023-03-22 09:31:44 -03:00
Uku Taht
a154a4214b
Support multiple filters - backend (#2749)
* Wrap Plausible.Stats.Filters with unit tests

* Parse `member` filter type

* Support escaped | in member filter

* Support for `member` filter in `aggregate_time_on_page`

* Add support for `member` filter type on goals

* Disable Credo warning

* Support `not_member` filter type

* Disable credo for `query_sessions`

* Support `matches_member` and `not_matches_member` filters

* Disable Credo for `Filters.filter_value/2`

* Support `matches_member` and `not_matches_member` for goal filter

* Support for contains_member and friends

* Updates for new chto driver

* make top_stats_test.exs:203 pass (#2779)

---------

Co-authored-by: ruslandoga <rusl@n-do.ga>
2023-03-22 11:01:25 +02:00
Adam
6d79ca5093
Switch to new clickhouse adapter (ch/chto) (#2733)
* another clickhouse adapter

* don't restore stats_removal.ex

* fix events main-graph error (#2746)

* update ch, chto

* update chto again (#2759)

* Stop treating page filter as an entry_page filter (#2752)

* remove dead code

* stop treating page filter as entry page filter in breakdown queries

* stop treating page filter as entry page filter in aggregate queries

* stop treating page filter as entry page filter in timeseries queries

* mix format

* update changelog

* break code down to smaller functions to keep credo happy

* remove unused functions

* make CSV export return only conversions with goal filter (#2760)

* make CSV export return only conversions with goal filter

* update changelog

* update elixir version in mix.exs (#2742)

* revert admin.ex changes (#2776)

---------

Co-authored-by: ruslandoga <67764432+ruslandoga@users.noreply.github.com>
Co-authored-by: ruslandoga <rusl@n-do.ga>
Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
2023-03-21 09:55:59 +01:00
Adam
736e6e385c
Capture no_cache sentry messages together (#2772) 2023-03-20 14:03:05 +01:00
RobertJoonas
4175a7abae
make CSV export return only conversions with goal filter (#2760)
* make CSV export return only conversions with goal filter

* update changelog
2023-03-20 10:40:37 +02:00
RobertJoonas
d0895efbdd
Stop treating page filter as an entry_page filter (#2752)
* remove dead code

* stop treating page filter as entry page filter in breakdown queries

* stop treating page filter as entry page filter in aggregate queries

* stop treating page filter as entry page filter in timeseries queries

* mix format

* update changelog

* break code down to smaller functions to keep credo happy

* remove unused functions
2023-03-15 18:12:59 +02:00
RobertJoonas
a490016f6e
fix test to make build green (#2747) 2023-03-14 09:25:18 +02:00
Adam
3417b2dd0e
Disallow site creation with insufficient input (#2741) 2023-03-10 16:32:10 -03:00
RobertJoonas
ad3edbfb9a
Bug fix - show views_per_visit when stats include imported data (#2738)
* show views_per_visit with imported data

* use optional chaining instead
2023-03-10 10:28:01 +02:00
RobertJoonas
4eca1aef70
fix a bug in percent change calculation (#2731) 2023-03-08 08:45:04 -03:00
Adam
4b21b4e6d0
Remove Firewall plug; redundant at infra level (#2730)
* Remove Firewall plug; redundant at infra level

* Update changelog
2023-03-08 09:07:15 +01:00
Vini Brasil
8b0f0cabc2
Implement "Year over Year" comparison mode (#2704)
This pull request adds support for multiple comparison modes, changes the comparison checkbox to a combobox, and implements the year over year comparison mode. The feature is still behind a feature flag.

Co-authored-by: Uku Taht <uku.taht@gmail.com>
2023-03-07 12:52:26 -03:00
RobertJoonas
874d664521
Add the new Views per Visit metric to dashboard Top Stats and CSV export (#2728)
* globally rename 'pages_per_visit' to 'views_per_visit'

* change the order of top stats

* rename 'Visits' to 'Total visits' in the UI

* add views_per_visit to UI

* put the new metric under a feature flag

* add new metric to CSV export under feature flag

* mix format

* use only one feature flag
2023-03-07 13:58:36 +02:00
RobertJoonas
0d6c72d50f
Add new Pages / Visit metric to Stats API Aggregate and Timeseries (#2714)
* refactor metric validation

* link to the correct docs section

* add the new metric to aggregate API

* explicitly remove __internal_visits

The overall metric selection is well defined by
`Plausible.Stats.Timeseries.empty_row/2`. The only metric that needs
to be removed from the timeseries response is __internal_visits.

This commit also moves the `remove_internal_visits_metric` function to a
new Util module to be used by both breakdown and timeseries.

* add the new metric to timeseries API

* mix format

* add moduledoc to keep credo happy

* convert pages_per_visit to string straight away

* do rounding in db query

* query # of visits with sum(sign) instead

* stop converting pages_per_visit to string
2023-03-06 12:07:53 +02:00
Uku Taht
43bf7dd09f
Use user-agent instead of screen_width to get device type (#2711)
* Use user-agent instead of screen_width to get device type

Co-authored-by: eriknakata <erik.nakata5@gmail.com>

* Fix credo

* Log on unhandled UAInspector device type

* Make 'browser' the default tab in devices report

* Remove device tooltip

* Remove screen_width from ingestion completely

* Remove browserstack harness, run playwright directly

* Select meta key based on OS platform

* Run CI tests in parallel

* Improve device match readability

* Add changelog

---------

Co-authored-by: eriknakata <erik.nakata5@gmail.com>
2023-03-02 11:04:01 +01:00
Uku Taht
f26ca7da9f
Update native stats start date when transferring (#2719) 2023-03-02 11:01:57 +01:00
Adam
8f86036e57
Keep track of native stats start timestamp when retrieving data (#2715)
* Stats boundary/PoC?

* Delete stats removal

* Drop events check on site creation

* Update seeds script

* Use native_stats_start_at

* Don't rely on native stats pointer in imported stats queries

* Reset site

* Export reset/1

* Remove unnecessary inserted_at settings

* Update seeds

* Remove unnecessary inserted_at setting
2023-03-01 13:11:31 +01:00
Adam Rutkowski
867dad6da7
Implement ingest counters (#2693)
* Clickhouse migration: add ingest_counters table

* Configure ingest counters per MIX_ENV

* Emit telemetry for ingest events with rich metadata

* Allow building Request.t() with fake now() - for testing purposes

* Use clickhousex branch where session_id is assigned to each connection

* Add helper function for getting site id via cache

* Add Ecto schema for `ingest_counters` table

* Implement metrics buffer

* Implement buffering handler for `Plausible.Ingestion.Event` telemetry

* Implement periodic metrics aggregation

* Update counters docs

* Add toStartOfMinute() to ordering key

* Reset the sync connection state in `after` clause

* Flush counters on app termination

* Use separate Repo with async settings enabled at config level

* Switch to clickhouse_settings repo root config key

* Add AsyncInsertRepo module
2023-02-23 14:34:24 +01:00
Adam Rutkowski
7dec454a23
Don't rely on Mix.env check in runtime (#2703) 2023-02-23 10:35:46 +01:00
RobertJoonas
bc557b78fd
Add visits metric under a feature flag (#2687)
* Add visits metric and make it graphable

* include visits metric in csv export (visitors.csv)

* put visits under a feature flag (CSV export)

* feature flag for displaying visits on the dashboard

* fix formatting

* add visits metric to top stats (fix)

* fix imported_test to expect visits metric included

* fix formatting
2023-02-22 18:10:18 +02:00
Adam Rutkowski
ecb552479f
Upgrade erlang/elixir/alpine stack (#2695)
* Dockerfile: pin elixir-1.14.3, erlang-25.2.3, alpine-3.17.0

* asdf: pin erlang 25.2.3, elixir 1.14.3-otp-25

* Remove nonsense

* Remove erlang dupe

* Remove erlang, it's in the base image already

* Remove empty file

* Truncate seconds in NaiveDateTime instances

* Bump cache key

* Mitigate Error:error:0308010C:digital envelope routines::unsupported

See: https://www.newline.co/@kchan/how-to-fix-the-error-errorerror0308010cdigital-envelope-routinesunsupported--0f8d3f17

* Upgrade to latest alpine image and pin to an exact digest

* Revert "Upgrade to latest alpine image and pin to an exact digest"

This reverts commit cdf6624efa.

* Pin alpine image to an exact digest

---------

Co-authored-by: Cenk Kücük <c@cenk.me>
2023-02-22 09:49:43 +01:00
Adam Rutkowski
ef894b0546
Fail the CI if tests emit log errors/warnings (#2694)
* Make CI fail if tests emit warning/error logs

* Swallow log output in GA test case
2023-02-21 10:38:22 +01:00
Uku Taht
531dfb114b
Refactor: Use HeadlessUI for search-select component (#2676)
* Use HeadlessUI for search select box

* Remove downshift from package.json

* More consistent API for Combobox component

* Combine toFilterType and valueWithoutPrefix into a single function

* Rename MyCombobox -> PlausibleCombobox

* Update webpack-cli

* Disable cache for build

* Revert "Disable cache for build"

This reverts commit aa130541f8.

* Disable cache for build

* Update webpack dependencies

* Remove glob from webpack config

* Webpack is required by package.json

* Require autoprefixer in postcss config

* Revert build changes

* Fix styling for dark mode
2023-02-20 11:10:11 +02:00
Uku Taht
412e8df41b
Validate property key in breakdown API endpoint (#2686)
* Validate property key in breakdown API endpoint

* Add missing properties

* Do not allow empty custom prop
2023-02-16 14:34:11 +02:00
Vini Brasil
535874be6f
Reject unknown imported cities from queries (#2675)
* Reject unknown imported cities from queries

This commit fixes a bug where the city report returned `N/A` entries.
The functions that build imported data queries were using SQL
`COALESCE`, assuming city data is `NULL` when unknown, when actually its
unknown value is `0`.

This commit addresses the problem using SQL `NULLIF` combined with the
previous `COALESCE` call. With this change both `0` and `NULL` are
treated as unknown.

Since 1cb07efe6d cities can be `NULL`, but
previously we saved `0` as unknown.

Closes #1960

* Add entry to CHANGELOG

* Ignore cyclomatic complexity Credo check
2023-02-15 07:35:35 -03:00
Vini Brasil
1cb07efe6d
Save city name when importing from GA (#2608)
This commit adds city data to imported records from Google Analytics. The
current implementation sets city to 0 because GA does not use the GeoNames
database.

Google Analytics Reporting API uses [Geographical IDs](https://developers.google.com/analytics/devguides/collection/protocol/v1/geoid)
to identify cities and countries. Plausible uses
[GeoNames](https://geonames.org/) and I couldn't find databases corelating the
two.

Fortunately, GA also returns the city name and this commit uses the city name
and the country ISO code to find the Geoname ID. To avoid making expensive ETS
searches, I created another ETS table in the Location library that uses
{country, city} as a key.

Related PR: https://github.com/plausible/location/pull/3
2023-02-14 09:32:18 -03:00
Uku Taht
8fcf4d3304
Fix 'field key does not exist' error (#2674) 2023-02-14 08:57:38 -03:00
ruslandoga
e9ba60c8b4
improve transfer ownership error message (#2651)
* improve transfer ownership error message

* add changelog

* simplify

* revert changeset invitation error message

* more descriptive error message

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2023-02-13 15:25:17 +01:00
Adam Rutkowski
8f85b110aa
Split Clickhouse pools into Read-Only and Read/Write (dedicated to writes) (#2661)
* Configure ingest repo access/pool size

If I'm not mistaken 3 is a sane default, the only
inserts we're doing are:

  - session buffer dump
  - events buffer dump
  - GA import dump

And all are serializable within their scopes?

* Add IngestRepo

* Start IngestRepo

* Use IngestRepo for inserts

* Annotate ClickhouseRepo as read_only

So no insert* functions are expanded

* Update moduledoc

* rename alias

* Fix default env var value so it can be casted

* Use IngestRepo for migrations

* Set default ingest pool size from 3 to 5

in case conns are restarting or else...

* Ensure all Repo prometheus metrics are collected
2023-02-12 17:50:57 +01:00
Uku Taht
3b73836136
Fix unknown bind meta (#2654)
* Fix 'unknown bind meta' error

* Changelog

* Use one case instead of nested ifs

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2023-02-09 14:56:21 +01:00
Uku Taht
1cc5ac0b11
Fix bug with multiple ARRAY JOIN query (#2653)
* Fix bug with multiple ARRAY JOIN query

* Add changelog entry

* Remove 'bug' label from test description

* Simplify pattern match

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

* Rename has_join_with_table -> joins_table?

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

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2023-02-09 14:14:09 +01:00
ruslandoga
7b2f4c99ee
Support alternative mailing services (Mailgun, Mandrill, Sendgrid) (#2649)
* more bamboo adapters

* add changelog

* add tests
2023-02-07 12:56:47 +01:00
Adam Rutkowski
8a2df294f5
Replace empty OS/screen size/Browser with (not set) in UI/API/exports (#2646)
* Make Device section components aware of (not set)

So that no extra sub-filters are possible when the unset
top item is selected.

* Support '(not set)' in breakdown/filters

* Update expectations for export tests

* Add extra tests for returning/filtering by '(not set)'

* Add changelog entry

* Remove ListReport conditional render

* Prevent redundant sub-filters

* Fix filter text rendering

---------

Co-authored-by: Uku Taht <uku.taht@gmail.com>
2023-02-07 12:47:54 +01:00
Marko Saric
4ea519fd11
Some changes to the "site taken" copy (#2647)
* Some changes to the "site taken" copy

* Update site.ex

* Fix tests

---------

Co-authored-by: Vinicius Brasil <vini@hey.com>
2023-02-06 15:33:45 -03:00
Adam Rutkowski
482249ffba
Better error message on site creation error (#2644)
* Ensure clear error message on site creation error

* Update colons in API error messages
2023-02-06 12:20:48 +01:00
Adam Rutkowski
f678cfab25
Prevent error reports from being sent with short feedback (#2635) 2023-02-01 05:36:14 -03:00
Adam Rutkowski
8f9f032968
Delay stats deletions (#2632)
* Implement Site removal transaction

* Implement Stats removal Oban worker

* Configure site removal queue

* Call Site.Removal.run() instead of Purge.delete_site!

* Test site/stats removal

* Remove FIXME - filed a ticket

* Over-communicate lenghty deletion process to the users
2023-01-31 16:11:04 -03:00
Adam Rutkowski
ad12e1ef31
Show user feedback form on server errors (#2617)
* Move Endpoint errors setup to common config

* Implement naive Sentry link resolver

* Implement error report e-mail

* Delete static sentry script

* Implement user feedback form on server errors

* Re-arrange pipe

* Use Sentry.Config.dsn() where applicable

* Fix typo

* Use Map.replace/3
2023-01-25 15:15:41 +01:00
Marko Saric
c1d174d0fa
Some changes to the "locked site" copy (#2615)
Some changes to be more consistent with the emails we send. Also "valid" subscription rather than "active" subscription fits better for the different cases where this screen is shown
2023-01-23 09:02:21 -03:00
RobertJoonas
bd0de97521
Fix returning more pageviews with a visit property filter (#2612)
* fix subquery for sessions in base_event_query/2

As the 'sessions' table is using the CollapsingMergeTree engine, we have
to select session_id's distinctively. Otherwise we will get multiple rows
(with sign -1 and 1) as long as the background merge hasn't happened.

* update changelog

* use GROUP BY instead of SELECT DISTINCT

* remove comma
2023-01-23 12:14:27 +02:00
Adam Rutkowski
1a4b65c36c
Communicate site creation edge cases to the users (#2605)
* Fingerprint DBConnection.ConnectionError in Sentry

* Check events before creating a site

* Enable sites limit screen

* Remove debugging remnant

* Fix buggy assertions

This wasn't doing what expected:

  iex(1)> Repo.exists?(Plausible.Site, domain: "foo")
  [debug] QUERY OK source="sites" db=0.6ms idle=1906.2ms
  SELECT TRUE FROM "sites" AS s0 LIMIT 1 []

* Encapsulate check to satisfy credo

* Use less technically involved error message

* Bring back e-mail to the limit error message
2023-01-19 15:03:18 +01:00
ruslandoga
166748dcf2
Replace Geolix with Locus (#2362)
This PR replaces geolix with locus to simplify self-hosted setup. locus can auto-update maxmind dbs which are recommended for self-hosters if they want city-level geolocation. locus is also a bit faster.

This PR also uses a test mmdb file from https://github.com/maxmind/MaxMind-DB for e2e geolocation tests without stubs.
2023-01-17 12:05:09 -03:00
Uku Taht
2a4061de8c
Make checkly alert after 5 minutes of downtime (#2599) 2023-01-17 11:58:01 +02:00
Cenk Kücük
d9011e4189
unmute checkly (#2588) 2023-01-12 16:24:25 +01:00
Uku Taht
256e8263c0 Add Hetzner load balancer to health checks 2023-01-09 18:02:38 +02:00
Uku Taht
f10c67e0e7 Add custom.plausible.io to checkly monitoring 2023-01-09 17:59:44 +02:00
RobertJoonas
13a05b4e1e
Change metric labels for realtime with goal filter (#2560)
* change metric labels for realtime with goal filter

* changelog

* fix formatting
2023-01-09 09:31:55 +02:00
Uku Taht
1772ddff17
Add Checkly (#2520)
* Add Checkly Terraform config

* add deployment workflow

* use pagerduty instead of email for notifications

* use terraform cloud backend

* update variable declaration

* rename checkly check group

* update syntax

* test trigger

* Revert "test trigger"

This reverts commit 333e82beac.

* run a single job at a time

Co-authored-by: Cenk Kücük <c@cenk.me>
2023-01-05 20:25:54 +01:00
Vini Brasil
4503895d0a
Fix breakdown API pagination when using event metrics (#2562)
* Fix breakdown API pagination when using event metrics

This commit fixes a bug where the subsequent breakdown API pages had
the same items as the first page. The fix sorts the underlying
ClickHouse query by timestamp, keeping the same order between requests,
as we use OFFSET/LIMIT pagination.

* Fix repeated results assertion

* Add different ORDER BY to each breakdown property
2023-01-04 22:14:40 -03:00
Uku Taht
1785653b1e
Ignore unknown countries (#2556)
* Ignore XX and T1 countries

* Add fallback if country_code=nil

* Lookup city overrides directly in CityOverrides module

* Changelog

* Add empty moduledoc

* Remove redundant comment
2023-01-03 10:35:23 -03:00
Vini Brasil
b6d30019ef
Cascade delete sent_renewal_notifications table when user is deleted (#2549)
* Cascade delete sent_renewal_notifications table when user is deleted

This commit fixes a bug when deleting a user would trigger a constraint
error.

* Update CHANGELOG.md
2023-01-02 11:46:18 -03:00
Adam Rutkowski
5de43b758d
Run tests in async mode where applicable (#2542)
* Set pg pool size for MIX_ENV=test

* Include slow tests in CI run

* Exclude slow tests by default

* Mark tests slow/async where applicable

* Restructure captcha mocks

* Revert async where env is relied upon

* Add --max-failures=1 to CI run

* Set warnings as errors

* Disable async where various mocks are used

* Revert "Disable async where various mocks are used"

This reverts commit 2446b72a29.

* Disable async for test using vcr
2022-12-26 10:20:29 -03:00
Vini Brasil
5152e8d416
Reject events with long URIs and data URIs (#2536)
* Reject events with data URIs

* Reject events with URIs longer than 2,000 characters

* Update CHANGELOG.md
2022-12-21 15:53:04 +02:00
Vini Brasil
0e87b489f6
Return empty list when breaking down by event:page without events (#2530)
* Return empty list when breaking down by event:page without events

This commit fixes a bug with pagination where breaking down by event:page
would always return results despite pagination.

Closes #2255

* Update CHANGELOG.md
2022-12-19 13:49:03 +01:00
Uku Taht
a37b3433d7
Always show direct traffic in sources reports (#2531)
* Remove show_noref behaviour

Removes query param show_noref which was used from React to control
whether to show Direct / None traffic or not. The show_noref behaviour
was untested previously.

Closes #2523

* Add changelog entry

* Fix tests

* Removed files I did not mean to check in :)
2022-12-19 13:40:21 +01:00
Vini Brasil
478e0c6990
Handle GA authentication errors (#2505) 2022-12-07 23:32:14 -03:00
Vini Brasil
9b32dace3e
Add Content-Security-Policy to favicon Plug (#2489) 2022-12-02 06:33:24 -03:00
Adam Rutkowski
467317f24e
Fix: application startup, event timestamps (#2479)
### Changes

This PR:
- pushes PromEx to the bottom of supervision stack to avoid Endpoint
instrumentation failure
- ensures the site cache is ready by exposing it through the health
check endpoint
- fixes event timestamps being calculated at compile time, with
regression unit and integration tests

### Tests
- [x] Automated tests have been added
- [ ] This PR does not require tests

### Changelog
- [ ] Entry has been added to changelog
- [x] This PR does not make a user-facing change

### Documentation
- [ ] [Docs](https://github.com/plausible/docs) have been updated
- [x] This change does not need a documentation update

### Dark mode
- [ ] The UI has been tested both in dark and light mode
- [x] This PR does not change the UI
2022-11-29 10:46:49 +01:00
Adam Rutkowski
356575ef78
Gatekeep ingestion pipeline (#2472)
* Update Sites.Cache

So it's now capable of refreshing most recent sites.
Refreshing a single site is no longer wanted.

* Introduce Warmer.RecentlyUpdated

This is Sites Cache warmer that runs only for
most recently updated sites every 30s.

* Validate Request creation early

* Rename RateLimiter to GateKeeper and introduce detailed policies

* Update events API tests - a provisioned site is now required

* Update events ingestion tests

* Make limits visible in CRM Sites index

* Hard-deprecate DOMAIN_BLACKLIST

* Remove unnecessary clause

* Fix typo

* Explicitly delegate Warmer.All

* GateKeeper.allwoance => GateKeeper.check

* Instrument Sites.Cache measurments

* Update send_pageview task to output response headers

* Instrument ingestion pipeline

* Credo

* Make event telemetry test a sync case

* Simplify Request.uri/hostname handling

* Use embedded schema, apply action and rely on get_field
2022-11-28 15:50:55 +01:00
Vini Brasil
ffbfb14714
Pass interval param to CSV export (#2469)
This commit adds the interval param to the CSV export client-side
request.
2022-11-25 10:53:22 +02:00
ruslandoga
77cca04417
fix ownership transfer when is_selfhost=true (#2455)
* fix ownership transfer when is_selfhost=true

* add changelog entry
2022-11-24 16:18:29 +02:00
Vini Brasil
994e7d09de
Parse event URL and domain in Plausible.Ingestion.Request (#2351)
* Parse event URL in Plausible.Ingestion.Request

* Parse event domain in Plausible.Ingestion.Request

* Rework ingestion pipeline processing (#2462)

* Rework ingestion pipeline processing

So that Request can have multiple domains and
based on that each event is processed uniformly.
The build_and_buffer/1 function now returns an
accumulator with all the dropped/buffered events
for further inspection.

* Reduce function complexity

* Don't chain struct fields to check for an empty host

* Separate referrer and utm tags

* Fix up `with` clause, credo was right cc @vinibrsl

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2022-11-23 14:05:44 +01:00
Vignesh Joglekar
497a52c10a
Add support for intervals (#1574)
Co-authored-by: Vini Brasil <vini@hey.com>
Co-authored-by: Vignesh Joglekar <hey@vigneshjoglekar.com>
2022-11-22 09:50:58 -03:00
Adam Rutkowski
ed9e03ae14
Outline basic rate-limiting interface (#2452)
* Outline basic rate-limiting interface

* Fixup typespecs

* Address empty cache race condition on refresh (#2457)

Ref https://github.com/plausible/analytics/pull/2444/files#r1023751222

* Fix up test case: make sure the cache is refreshed
2022-11-21 15:54:47 +01:00
Vini Brasil
3bedf9281c
Seed database with pageviews (#2449)
* Seed database with pageviews

This commit adds basic support for database seeding useful for testing,
especially dashboard changes, like intervals.

It creates two years of pageviews with random timestamps. There is lot
of room for improvement, such as adding sources, entry pages,
geolocation, devices, custom events, but this already helps us with
testing.

* Update CONTRIBUTING.md file
2022-11-17 21:46:42 -03:00
Adam Rutkowski
3fe6a95696
Update sites cache implementation (#2444)
* Allow refreshing a single site cache + clear cache on prefill

* Reorganize Site.Cache tests with describe blocks

* Tidy up Cache tests

* Make sure the cache is cleared on (p)re-fill

* Allow process name customization in Cache.Warmer

* s/Cache.prefill/Cache.refresh

* Unify Cache refresh instrumentation

* Apply credo suggestion: change `with` to `case`

* Update typespecs to pass dialyzer
2022-11-16 15:04:53 +01:00
Adam Rutkowski
457a558471
Kick off sites by domain cache implementation (#2434)
* Implement sites by domain caching interface + warmer

* Add test

* Implement hit rate interface

* Add moduledocs

* Fix up typespec

* s/warmer/warmer_fn

* Extract measure_duration/2

* Fix up typespec

* Log errors and return nil on cache internal errors

* Fix up non-existing cache test

* Retrieve specific db columns when pre-filling the cache

* Reduce the subset of fields retrieved from the DB

See 63f3c6233d (r89871536)
2022-11-16 10:06:23 +01:00
Vini Brasil
9c98a3f2e8
Add API support for intervals (#2417) 2022-11-14 18:41:51 -03:00
RobertJoonas
47bf003c29
Merge pull request #2431 from plausible/fix-email-links
Fix email links
2022-11-10 16:45:43 +02:00
Robert
27e8d8db3c remove redundant test 2022-11-10 15:55:33 +02:00
ruslandoga
0b7870dc4d
improve first launch experience for self-hosters (#2357)
* first launch

* dynamic children, wait for repo

* remove wait_for_repo and app env manipulations

* don't mention free trial in self-hosted pages

* add changelog

* assigns[:is_selfhost] -> @is_selfhost

* better changelog wording

* rm admin_user, admin_email, admin_pwd from app env

* rm DISABLE_AUTH

* redirect / to /login when not authenticated

* remove TODO

* Update lib/plausible_web/controllers/page_controller.ex

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

* format

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
2022-11-10 12:42:22 +01:00
Robert
d6125ffeb1 add tests for base_email template 2022-11-09 19:56:46 +02:00
Uku Taht
8bdbabbdad
Enable Dialyzer and Credo in CI (#2315) 2022-11-04 23:42:03 -03:00
Robert
fbe3a4e6f1 add a test and fix rendering the dashboard link 2022-11-03 11:31:32 +02:00
Vinicius Brasil
90c78e8995
Move GA fixtures to fixtures/ folder (#2398)
This commit fixes up 29347126db871429d9e5c37c63c4f79.
2022-10-29 09:44:10 +02:00
RobertJoonas
7ccbc5d432
fix typos (#2393) 2022-10-27 08:57:34 +02:00
Adam Rutkowski
a44b8ff7f5
Improve test coverage (#2392)
Co-authored-by: ruslandoga <doga.ruslan@gmail.com>
2022-10-27 08:39:34 +02:00
Adam Rutkowski
6ba5e53574
Trim goals when creating and retrieving from the DB (#2382)
People are likely to enter (copy/paste) goals from external sources
which can lead to whitespace characters appended by accident.
That renders the goal unusable and hard to distinct visually.

Normally to fix up existing goals we would use a data migration,
but this should be good enough to check if the problem
with never appearing goals resurfaces.
2022-10-26 09:35:30 +02:00
Marko Saric
252cecbf25
Correct the spelling of JavaScript (#2380)
* Update README.md

* Update snippet.html.eex

* Update settings_general.html.eex

* Update site_controller_test.exs
2022-10-26 08:34:33 +02:00
Vinicius Brasil
73444ddfb6
Fix and test Google Analytics token refresh (#2381)
This commit fixes a bug where Google Analytics import tokens were not
being refreshed properly because the function was not returning the
expected tuple. Thanks to @aerosol we can nicely test this now.
2022-10-26 07:43:49 +02:00
Adam Rutkowski
8e75f2fc07
Separate GA/SC scopes (#2372)
* Use separate scopes for GA/SC integrations

* Update tests with google scope expectations
2022-10-25 08:17:17 -03:00
Adam Rutkowski
d29597ed37
Fix random typos (#2375) 2022-10-25 08:17:09 -03:00
Vinicius Brasil
c9945e09cf
Suggest enterprise plan when usage is greater than 10M pageviews (#2345) 2022-10-25 13:16:44 +02:00
Vinicius Brasil
a86d9697ba
Clear stats_start_date after clearing GA stats (#2370)
This commit fixes a bug where users clearing one import and trying to
re-import would get invalid import date ranges. This was caused because
the stats_start_date field was not updated to nil after clearing
imported stats, as this field defines the end date of the import.
2022-10-25 12:17:59 +02:00
Adam Rutkowski
3ddfda94a1
Fix up Purge tests (#2364) 2022-10-24 07:15:18 -03:00
Vinicius Brasil
e48851a9ed
Skip rows with empty dates from GA imports (#2359) 2022-10-24 07:13:52 -03:00
Adam Rutkowski
0fa6b688af
Google APIs integration improvements (#2358)
* Make TestUtils module available in all tests

* Add macros patching the application env in tests

Unfortunately a lot of existing functionality relies on
certain application env setup. This isn't ideal because
the app config is a shared state that prevents us from
running the tests in parallel.

Those macros encapsulate setting up new env for test purposes
and make sure the changes are reverted when the test finishes.

* Allow passing request opts to HTTPClient.post/4

We need this to swap custom request building in
Google Analytics import.

* Unify errors when listing sites

* React: propagate backend error messages if available

* React: catch API errors in Search Terms component

* Propagate google API errors on referrer drilldown

* Handle verified properties errors in SC settings

* Add missing tests for SC settings controller

* Unify errors for fetching search analytics queries (list stats)

* Unify errors refreshing Google Auth Token

* Test fetch_stats/3 errors and replace Double with Mox

* Fixup makrup

* s/class/className

* Simplify Search Terms display in case of errors

* Fix warnings
2022-10-24 09:34:02 +02:00
Vinicius Brasil
93bb62ef27
Remove inserts per second Google Analytics test assertion (#2334)
This commit removes a flaky test assertion from the GA suite. The
initial purpose of this test was to ensure we are not inserting to
Clickhouse more than 1 time per second during an import.

Although it is nice to have an assertion like this, the test is flaky
and fails sometimes. To get the total inserts during a time range, it
queries Clickhouse internal tables for insert commands, and this number
is not deterministic.

In a real-world scenario with Clickhouse, the app runs in multiple nodes
not aware of their neighbors' CH calls. In that case, Grafana provides
us visibility over CH, and these tests do not suffice.
2022-10-20 10:26:40 -03:00
Adam Rutkowski
e3ca3b32db
Include tests for Captcha success/failure scenarios (#2344)
* Include tests for Captcha success/failure scenarios

* DRY
2022-10-17 08:16:59 -03:00
Vinicius Brasil
c26e029d22
Increase flaky test timeout (#2330) 2022-10-13 14:56:25 +02:00
Adam Rutkowski
28cec9d939
Automatically decode JSON payloads from HTTP (#2329) 2022-10-13 09:39:15 -03:00
Vinicius Brasil
fb05e447f9
Increase Google Analytics timeout and lower page size (#2326)
The Google Analytics report request may take some time, especially with big
imports with thousands of pages. To mitigate the issue this commit increases
the timeout to 60s and lowers the page size to 7,500 records per request.
2022-10-13 14:10:00 +02:00
Adam Rutkowski
ae4ae5d0a0
Handle duplicate invitations gracefully (#2323) 2022-10-11 11:40:20 -03:00
Adam Rutkowski
ec90a264b4
Improve user input validation (#2291)
* Make pagination params parsing ignore bad input

* Remove unused binding

* Don't crash on filter parse error

* Sanitize input date on internal stats API

* Revert Query module changes (ref 55645734)

* Implement simplistic input date validation in stats controller

* Mute bad request logging
2022-10-11 14:42:14 +02:00
RobertJoonas
c0da024b23
Remove static tracker files (#2116)
* remove tracker files from git index

* generate tracker files on npm test

* generate tracker files for elixir tests/dev/CI

* update tracker/package-lock.json

* exclude npm run deploy from mix test + some docs
2022-10-11 12:19:28 +02:00
Vinicius Brasil
0733efa89e
Delete stats improvements (#2318)
* Move clear stats functions to Plausible.Purge

* Delete both native and imported stats when deleting a site

This commit moves the delete site function to the Plausible.Purge
module, and fixes a bug where deleted sites could leave dangling
imported stats.

* Clear sites.stats_start_date after clearing stats

This commit fixes a bug where resetting stats left an invalid state of
the stats_start_date field, used for GA imports, for example.
2022-10-10 08:55:58 -03:00
Adam Rutkowski
523b114682
Allow super-admin Stats API access for locked sites (#2308) 2022-10-05 12:04:37 +02:00
Vinicius Brasil
beabef7269
Redirect user after upgrading only when subscription is created (#2285)
* Create API to check for an active subscription

* Redirect after upgrading only when subscription is created

* Change upgrade page copy

* Add timeout notice to upgrade success page
2022-10-04 15:54:54 +03:00
Adam Rutkowski
bf2b6880c5
Block Stats API for locked sites (#2302)
* Extract Sites.locked? predicate

* Lock Stats API when dashboard is locked

* Tidy tests

* Don't pollute application env from tests

* Add changelog entry

* Revert "Add changelog entry"

This reverts commit 76346074f9.
2022-10-04 15:34:45 +03:00
Uku Taht
0bc762bfdc
Fix svg favicons (#2295)
* Overrides content-type for SVG favicons

* Organize favicon rendering

Make sure the placeholder icon is always requested from
/favicon/sources/placeholder

* Run prettier on site-switcher.js

* Yak Shave: upgrade Heroicons to 2.0

* Use HeroIcons instead of custom svg

* Update lib/plausible_web/plugs/favicon.ex

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

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2022-10-04 13:20:51 +03:00
Uku Taht
12a513f3cd
Remove Mimic dependency (#2280) 2022-10-03 11:41:51 -03:00
Uku Taht
4096d88171
[Sentry APP-189] Fallback to current date in all time parsing (#2277)
* Fallback to current date in all time parsing

* Add changelog
2022-09-28 09:45:37 -03:00
Uku Taht
65f0ce3061
[Sentry APP-5B] Ensure form errors can be rendered on /settings (#2278)
* Ensure form errors can be rendered on /settings

* Changelog
2022-09-28 08:56:07 -03:00
Uku Taht
d104abb53d
Add fallback for favicon (#2279)
* Add fallback for favicon

* Add Favicon tests

* Changelog

* Move placeholder icon to priv folder
2022-09-28 08:55:46 -03:00
Vinicius Brasil
7489290d11
International Domain Names (IDN) Support (#2034)
* Accept letters from non-Latin alphabets in domain names

* Replace static URLs with Router functions in settings_visibility

* Beautify dashboard URL in visibility tab

* Add IDN support to CHANGELOG
2022-09-28 10:42:15 +03:00
Vinicius Brasil
c07361fbce
Increase GA import request receive_timeout to 30s (#2274)
This commit increases the receive_timeout from 15s to 30s for Google
Analytics import requests. Timeouts have been reported, and I could
replay some requests that took 15-20 seconds to complete when fetching
10,000 records in a single request.
2022-09-28 10:37:44 +03:00
RobertJoonas
155e274150
Stats API: allow escaping | literal character with \| when filtering (#2266)
* add separate module for filter parsing

* add tests for filter parser

* allow escaping pipe character in filter value

* add documentation and doctests

* do not remove escape chars from wildcard values

* changelog update

* change the parse_filters/1 function argument
2022-09-26 16:20:08 +03:00
Vinicius Brasil
db03cc0ac6
Fix timezone list when time changes (#2268)
This commit fixes an exception when calling `Timex.Timezone.get/2` after
there has been a timezone change. Similar issues have already been reported
in Timex (bitwaker/timex#691, bitwalker/timex#555, bitwalker/timex#625).

This skips timezones from the list when they fail to fetch, and use
`Timex.Timezone.get/2` to get the current offset using `DateTime.utc_now/0`
instead of the `NaiveDateTime` default.
2022-09-26 12:30:20 +03:00
Vinicius Brasil
1adda42a75
Refresh Google Analytics token before import (#2254)
* Capture refresh and expires from GA callback

* Pass GA refresh token to import worker

* Refresh GA token before import
2022-09-26 12:29:56 +03:00
Uku Taht
e849e03058
Fix favicons (#2257) 2022-09-23 07:22:43 -03:00
RobertJoonas
80e01fedd5
do not show invoices for free subscription (#2249)
* do not show invoices for free subscription

* use refute instead of negative assert

* changed to refute in the other test too
2022-09-22 17:25:24 -03:00
Vinicius Brasil
2b753cdcfd
Improve GA Imports error reporting (#2244)
* Return error tuple instead of exception when GA request fails

* Report Google Analytics failed request body to Sentry

* Improve Google Analytics function @doc

* fixup! Report Google Analytics failed request body to Sentry

* fixup! Improve Google Analytics function @doc
2022-09-20 15:41:23 +02:00
Uku Taht
e16e357dd2
Fix shared link with bad auth (#2225)
* Render 404 when shared link cannot be found

* Add documentation for StatsController and shared link rendering

* Refactor shared_link/2 for more clarity

* Add changelog entry

* Use mermaid graph for sequence diagram

* Use more accurate return value in sequence diagram

* Refactor Ecto query to be more idiomatic

* Remove order dependence in test

* Restore backwards compatibility for older shared links

* Add changelog entry
2022-09-20 15:37:18 +03:00
Uku Taht
669091f2ef
Ignore unknown country in imported data (#2247) 2022-09-20 15:02:14 +03:00
Vinicius Brasil
40182f6d6e
Manually lock outgrown enterprise accounts (#2197)
* Rename enterprise_over_limit e-mail template

* Change suggested_plan/2 function to suggest enterprise plans

* Start grace period for enterprise accounts

* Create separate module for GracePeriod schema

* Enable manual locking of enterprise accounts

* Update outgrown account alert for enterprise accounts

* Document account locking feature

* fixup! Enable manual locking of enterprise accounts
2022-09-20 11:46:28 +03:00
Adam Rutkowski
75264f8f1c
Treat non-200 HTTP responses as errors (#2243)
* Tag non-200 HTTP responses as errors

Co-authored-by: RobertJoonas <robertjoonas16@gmail.com>

* Send get_invoices/1 errors to Sentry

Co-authored-by: RobertJoonas <robertjoonas16@gmail.com>

* Keep Google API module matching non-200 responses

Co-authored-by: RobertJoonas <robertjoonas16@gmail.com>

* Make sure HTTPClient.Error.t() doesn't appear in the UI

* Unify get_invoices/1 signature

Co-authored-by: RobertJoonas <robertjoonas16@gmail.com>

Co-authored-by: RobertJoonas <robertjoonas16@gmail.com>
2022-09-20 09:31:12 +02:00
Uku Taht
5d4918b66b
Allow admins to grant admin rights (#2216)
* Make sure admin can grant the admin role

* Use `site` and `current_user_role` from conn.assigns to avoid extra lookups

* Add some missing documentation

* Restrict owners in the `update_role` action

* Move @moduledoc to appropriate location

* Use Ecto.Enum to get role atoms

* Remove unused functionality

* Ensure that owners cannot lock themselves out

* Add question mark to `can_grant_role`

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

* Use strict short-circuit operator for booleans

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

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2022-09-16 11:03:09 +03:00
Uku Taht
b239f73a6d
Ignore unknown country code (#2223)
* Ignore unknown country code

* Add changelog entry
2022-09-16 11:02:39 +03:00
RobertJoonas
0194d57b38
add upper bound to limit parameter (#2226)
* add upper bound to limit parameter

* add more strict validation for limit parameter + 2 tests

* update changelog
2022-09-16 10:21:44 +03:00
Vinicius Brasil
178e34b9e7
Fix timezone input (#2222)
* Update Timex version from 3.7.7 to 3.7.8

* Generate timezone list from Tzdata

This commit fixes a bug where timezone changes weren't updating the
timezone list displayed when editing or creating a site.

Timezones were being pulled from a static list. This commit changes it
to generate the list from Tzdata, that uses a timezone database with
updated information on time changes. Additionally it adds more timezones
with aliases and links to the list.

Closes #1340

* Use timezone name from browser to recommend timezone

This commit matches the timezone name instead of offset to recommend a
timezone when creating a new site. The JavaScript Intl.DateTimeFormat
API is widely supported according to the link. In any case, if the
timezone fails to match by name, it fallbacks to the offset strategy.

https://caniuse.com/mdn-javascript_builtins_intl_datetimeformat_resolvedoptions_computed_timezone

Closes #904
2022-09-14 09:58:42 -03:00
Adam Rutkowski
cc4d4bb8e0
Fixup error reporting (ref #2181) (#2204)
* Fixup error reporting (ref #2181)

Fixes two problems:

 - `extra` sent to Sentry is always expected to be a map
 - no `String.Chars` protocol is implemented for `Finch.Error` struct

* Use explicit paths in http client tests

* Make HTTP Client tests sync
2022-09-12 13:46:23 +03:00
Vinicius Brasil
d31db86b49
List all Google Analytics views during import (#2184)
* List all Google Analytics views during import

This commit fixes a bug where different Google Analytics views with the
same name and URI were not shown. This was caused because GA views were
stored as a map, that naturally doesn't support duplicate keys.

This change updates the GA views list to display view IDs, making it
clearer to know what is being imported. The dropdown is now grouped by
website URL.

* Put Google Analytics API URLs in app env

* Add controller test to GA view list
2022-09-08 21:02:17 +03:00
Adam Rutkowski
e2aa519c31
Test HTTPClient (#2185)
* Sort dependencies

* Add :bypass dependency

* Test HTTPClient

* Rename test module
2022-09-07 14:17:57 +02:00
Adam Rutkowski
9c23e886aa
Merge pull request #2174 from plausible/fix-flaky-test-assuming-order
Do not assume any order in browser data import test
2022-09-05 13:27:20 +02:00
Adam Rutkowski
79b4550bed Do not assume any order in browser data import test 2022-09-05 11:51:50 +02:00
Adam Rutkowski
2275cd8e22 Respond with 400 when no auth supplied to shared link request 2022-09-05 11:15:09 +02:00
Vinicius Brasil
bc68235d04
Add fallback for GA reports without rows (#2121) 2022-08-19 13:14:49 +03:00
Vinicius Brasil
a10d44a0d7
Refactor event struct creation function (#2098)
* Replace Ingestion.Request headers with user_agent

* Replace generic Ingestion.Request params with specific fields

* Refactor event building function into small functions

* Move Plausible.Ingestion to Plausible.Ingestion.Event

* Add option to override event fields while building

* Rename Ingestion.Request meta to props

* Replace UTM-specific fields with generic query_params

* Remove Map.from_struct/1 call from ingestion pipeline

* Remove stash options from ingestion
2022-08-16 14:43:10 +03:00
Vinicius Brasil
4d20c7ce70
Catch Google Search Console grant error (#2101)
* Remove invalid Jason.decode argument

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>

* Add custom message to Google invalid grant error

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>

* Test invalid_grant while refreshing Google token

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
2022-08-16 10:55:46 +03:00
Uku Taht
a5757bc61e Allow ownership transfers 2022-08-11 13:16:46 +03:00
Vinicius Brasil
6b8ed12567
Fix Google Search Console API call (#2090)
This commit fixes a bug where fetching Google Search Console keywords
raised a FunctionClauseError. This was introduced in #2046. This commit
also adds test coverage.
2022-08-11 11:03:06 +03:00
ruslandoga
ce461b5192 Auth updates 2022-08-10 10:37:37 +03:00
RobertJoonas
a058cf6240
added a test and changed hashmode condition (#2082) 2022-08-09 14:31:37 +03:00
Vinicius Brasil
4b9032d822
Google Analytics Import Refactor (#2046)
* Create separate module for GA HTTP requests

* Fetch GA data entirely instead of monthly

* Add buffering to GA imports

* Change positional args to maps when serializing from GA

* Create Google Analytics VCR tests
2022-08-03 12:25:50 +03:00
Igor Kapkov
61fe38e0d4
Fix script path for k6 load test (#2068) 2022-07-29 09:00:50 -03:00
Vinicius Brasil
b415ebe776
Fix geolocation subdivision pattern matching (#2063)
* Fix geolocation subdivision pattern matching

This commit fixes a bug where regions were not being saved. This was
caused because Geolix response was returning an additional
`:geolocation` map key. It also adds a test case for this.

Closes #2033

* Add geolocation database to .gitignore
2022-07-28 15:59:39 +03:00
Vinicius Brasil
b5ea6ae3dc
Keep user filter when listing cities, countries, and regions stats (#2030)
This commit fixes a bug where location filters were filtering stats but
not the locations list. This was caused by a `Map.put/3` call that
overrides the user filter. This commit rollbacks 5b57143273
changes and removes the `Map.put/3` call.

Closes #1982
2022-07-25 12:19:38 +03:00
Sasha Fonseca
db3a852f26
Fix missing 'pageviews' column from 'pages.csv' (#1988)
* Fix missing 'pageviews' column from 'pages.csv'

* Add CHANGELOG entry for Issue #1878 fix
2022-07-12 23:46:47 +03:00
Uku Taht
292a419473
Add feature flag to block event ingest (#1991)
Event ingest can be blocked using the flag `block_event_ingest`
2022-07-06 12:25:40 +03:00
Uku Taht
3e5695408a
Use new Session.CacheStore in favour of Session.Store (#1934)
* Remove Session.Store in favour of Session.CacheStore

* Add CHANGELOG entry

* Use appropriate enum function
2022-06-06 10:44:33 +03:00
Kurt McAlpine
b92889aaf0
Add API to retrieve site by domain (#1942) 2022-06-03 10:37:14 +03:00
Uku Taht
102ff1885e Trim trailing whitespace from pathname 2022-06-02 11:34:10 +03:00
RobertJoonas
11654ddc07
Script extension additions (#1915)
* added data-include attribute to plausible.exclusions.js

* reorder extensions in filename when serving the plausible script

* fix formatting

* tweaks after review

* changelog update
2022-05-27 10:11:40 +03:00
Uku Taht
948de2b4c9 Mark more tests as async 2022-05-06 10:30:38 +03:00
Uku Taht
cd8df23e5e Do not rely on insertion order in tests 2022-05-06 10:20:35 +03:00
Uku Taht
6f3399bb7c Fix annual notification loop 2022-05-03 17:00:19 +03:00
Uku Taht
e4816e8f64 Update Elixir version 2022-05-02 11:56:00 +03:00
Uku Taht
02abbda06d Ignore nil custom prop as well 2022-04-29 11:50:31 +03:00
Uku Taht
c92c548ca8 Do not error on empty string custom prop value 2022-04-29 11:13:36 +03:00
Uku Taht
f18a211dcc
Ingest throughput improvement test setup (#1867)
* Add OTEL and test Cachex for sessions

* Move load test

* Start apps in the appropriate order
2022-04-28 12:24:29 +03:00
Uku Taht
ce55dc4ae9
Retries Google Analytics API request if it returns empty rows (#1858)
* Retries Google Analytics API request if it returns empty rows

* Remove HTTPoison.Retry completely
2022-04-26 13:57:32 +03:00
Uku Taht
5e415c2420 Add entry_props back in 2022-04-22 10:58:02 +03:00
Uku Taht
8fb4f3f886 Revert entry props 2022-04-21 19:22:38 +03:00
RobertJoonas
40275b64d4
Pageview custom dimensions (#1816)
* added custom dimension filtering tests for pages

* first filter UI in place

* pages, entry pages and exit pages can be filtered by pageview props

* added tests for expected filtering behaviour

* fix dimension filter for sources + tests

* added is_not filtering functionality

* fixed formatting

* fixed admin_test

* added (none) as filter value + is_not filter type in UI

* added prefilling applied filter values and some UI tweaks

* added fetch options

* Make prop suggestions work with `props` filter

* Fix test

* Track login state internally

* Add CHANGELOG entry

Co-authored-by: Uku Taht <uku.taht@gmail.com>
2022-04-21 11:47:15 +03:00
Uku Taht
66aceda9e9 Fix main graph selection with imported data 2022-04-19 10:50:50 +03:00
Uku Taht
404a5d15a3 Fix tests 2022-04-18 14:51:33 +03:00
Uku Taht
05c210ad85 Enforce site limit 2022-04-18 14:47:30 +03:00
Uku Taht
3d231fc094 Redirect to correct change plan page for enterprise customers 2022-04-18 14:18:49 +03:00
Andrea Mazzarella
1128ff4bfa
Update the internal /sites api to paginate results (#1824)
* Update the internal /sites api to paginate results and adapts site-switcher to it

* Update the Changelog

* Format internal controller

* Remove the `+ Add Site` link from the site-switcher in the dashboard

* Change camel to snake case and replace imports with fully qualified calls

* Remove trailing comma from site-switcher
2022-04-18 12:32:01 +03:00
Uku Taht
d2dc06ec96 Fix trial notifications 2022-04-18 11:05:08 +03:00
Vignesh Joglekar
3b97ecdc62
Adds Main Graph Metric Selection (#1364)
* First pass bringing in previous graph improvements, and comparsion context

* Swaps issue template to new issue form syntax

* Indentation update

* Indentation update?

* More indentation

* Intendation is hard

* Finalized indentation?

* Github indentation

* Missing fields

* Formatting changes

* Checkbox changes

* Uses new timeseries API, various UI improvements, descopes conversions, ToP from graphing

* Fixes Mobile UI Issues

* Improves point detection and display on hover

* Fixes & adds tests for updated main-graph API route

* Changelog

* Changes to better metric option declaration & minor UI/default fixes

* Fixes top stat tooltips showing unformatted numbers for special (non-rounded) top stats

* Formatting

* Fixes regression with dashed portion not stopping at present_index

* Removes comparison + lint

* Improves top stat active style

* Removes comparison tests

* Splits out tooltip and top stats

Still needs:
- Tests
- Potentially more cleanup

* Adds/moves tests for top stats

* Formatting

* Updates metric LS key, removes console log

* Various fixes + cleanup

* Makes tooltip position & style more consistent

* Fixes test (returns import status on both main graph & top stats)

* Fixes interaction with month dateFormatter

* Fixes edge case tooltip behavior

It was simpler than I thought :/

* Make the entire top stat clickable

* Minor UI improvements

* Fixes another tooltip visibility edge case + cleans up boolean algebra

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
2022-04-13 10:38:47 +03:00
Kian-Meng Ang
70cb3eed54
Fix typos (#1829) 2022-04-11 20:42:40 +03:00
Uku Taht
06b165eb6d Run GA import in monthly batches 2022-04-08 08:43:07 +03:00
Uku Taht
7c755d7c6d Forget has_stats 2022-04-06 11:52:19 +03:00
Uku Taht
a359271af2 Fix more tests 2022-04-06 11:34:54 +03:00
Uku Taht
25baa6bae9 Fix tests 2022-04-06 11:30:18 +03:00
Uku Taht
333de87ceb Add stats_start_date field 2022-04-06 10:10:53 +03:00
Uku Taht
9308092184 Fix test 2022-04-04 11:53:16 +03:00
Uku Taht
d40faf6ec7 More datepicker improvements 2022-03-31 16:47:19 +03:00
Uku Taht
7f58e6be4e Add Year to Date option in datepicker 2022-03-31 13:52:48 +03:00
Uku Taht
8467979051 Add All Time option to datepicker 2022-03-31 11:00:20 +03:00
Uku Taht
ed871e7a0b Parse scientific notation in GA import 2022-03-30 14:04:56 +03:00
Uku Taht
8719865a41 Redirect user when they've already upgraded 2022-03-30 10:10:44 +03:00
Uku Taht
ce649966ed Fix display 2022-03-29 13:38:35 +03:00
Uku Taht
ebdd856df7 Fix tests 2022-03-29 13:06:44 +03:00
Andrea Mazzarella
3c93a2d91b
1421 contains filter (#1799)
* small refactors and adds 'contains' to modal

* supports contains filter in the backend

* moves entry and exit page under the page filter

* prettier

* updates the CHANGELOG

* undo package-lock changes

* fixes formatting for elixir

* renames unused parameter to _

* Update changelog

* Use uppercase for constants and update type/prefix lookup
2022-03-29 08:39:16 +03:00
RobertJoonas
e5cf800d4a
Improve stats api (#1759)
* can now query events metric when breaking down on a visit prop

* updated changelog

* fixed formatting

* fixed a bug - querying for bounce rate does not return visits anymore

* removed the changelog update
2022-03-24 16:16:51 +02:00
RobertJoonas
492f47ba1e
Crm transfer data (#1749)
* pull from master

* added query generation by struct fields

* ready, improved tests

* fixed a naming mistake
2022-03-24 16:11:04 +02:00
Uku Taht
51cd24bcaf Allow user to cancel ongoing import 2022-03-23 11:58:36 +02:00
Uku Taht
203f87520b
Ga import improvements (#1784)
* Do not link Google account for import

* Record start date

* Fix tests
2022-03-22 16:09:45 +02:00
Uku Taht
59acff02f8 Fix tests 2022-03-21 12:55:20 +02:00