Commit Graph

154 Commits

Author SHA1 Message Date
Adam Rutkowski b64a2355a0
Platform upgrade: elixir 1.19.4 and otp 27.3.4.6 (#5920)
* Platform upgrade: elixir 1.19.4 and otp 27.3.4.6

* !fixup

* credo

* credo

* Bump cache

* fix docker image tag

* hum

* hum

* Match docker images

* Define ALPINE_VERSION once

* fixup
2025-12-01 12:50:49 +00:00
Adam Rutkowski 0eea55d1c1
Slurp common test modules into exunit templates (#5909)
* Slurp common test stuff into exunit templates

* !fixup

* !fixup

* !fixup

* !fixup
2025-11-24 13:30:06 +00:00
RobertJoonas 024e6bb9ef
Prevent email reports when consolidated view ineligible (#5882)
* do not send email reports if consolidated view not ok to display

* fix CE

* more expressive condition in ok_to_send?

* Map.get -> Map.fetch
2025-11-13 10:25:44 +00:00
RobertJoonas f24aa4f305
Consolidated view email reports (#5876)
* fix weekly/monthly email reports + stats report tests

* fix title of stats email reports

* add missing test

* do not render review installation link for consolidated view traffic drop emails + test

* refactor email_match_query to predicate fn

* make site_id_query_filter a public fn

* make traffic spike notifications work + test

* improve spike/drop notification email copies

* fix ScheduleEmailReports introduction comment

* add tests for stats report email scheduling

* remove space before .

* apply credo suggestion

* fix CE tests, use module attrs for text assertions

* skip frequency comment

* single query

* rename to site_member

* single query for real
2025-11-11 13:26:52 +00:00
Uku Taht f3d326b735
Upgrade phoenix & liveview (#5766)
* Upgrade phoenix and phoenix_live_view

* Use new phoenix controller options

* Run mix format

* Upgrade lazy_html and bcrypt

* Always put root layout

* Remove deprecated use Plug.Test

* Escpaing updates for LazyHTML

* Fix double layouts in site settings

* Fix more escaping in tests

* More LazyHTML updates

* Fix remaining LazyHTML issues

* More Floki -> LazyHTML conversions

* More Floki -> LazyHTML conversions

* Fix another issue with Floki -> LazyHTML

* Fix another lazyHTML issue

* Remove parsing from tree

* Fix HTML escaping in teams_test

* More test fixes

* More test fixes

* Add layout to browser_sso_notice pipeline

* Extract elem_count helper
2025-10-07 12:29:48 +00:00
RobertJoonas 053fe71cc8
fix time-related test failure (#5759) 2025-09-26 18:07:57 +00:00
Adam Rutkowski 26285a0636
Provide safeguards for regular/consolidated sites distinction (#5742)
* exclude consolidated views when counting/listing sites

* Use Teams.owned_sites/1 now that it excludes consolidated views

* Until we figure out better - make sites.consolidated virtual for CE

* Safeguard ingestion, update tests for gate keeper/site cache

* Ensure consolidated sites are excluded from helpscout counts

* Test that consolidated views are excluded from site listings

* Update tests for owned sites to ensure consolidated views are excluded

* Update CRM tests to exclude consolidated sites

* exclude consolidated sites from quota usage

* filter out conslolidated sites from deleting events background job

* exclude consolidated (change domain background job)

* retrieve non-consolidated sites only by default

* Ensure Site struct defines a default for `consolidated`

* Make `sites.consolidated` column available in CE

* Add missing test to reminder e-mails, consolidation is irrelevant here

* Do not send setup help e-mail for consolidated sites

* Ensure no setup success email is ever sent for consolidated sites

* Skip consolidated sites in legacy time on page cut off

* Add minor test to Sites.get_for_user/2

* Extend get_for_user/get_for_user! options signature

* Move test dir up

* Write tests for Sites.get_by_domain

* Minor DRY

* fix typos

* Provide Site.regular() and ConsolidatedView.sites() for querying

* Use Site.regular() in Repo.get_by() calls

* Fix typespecs

* Update missing Site.regular() filters

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
2025-09-23 09:32:11 +00:00
Adam Rutkowski 810e48da2c
Add top goal conversions to weekly/monthly e-mail digest (#5711)
* Add top goal conversions to weekly/monthly e-mail digest

* Fix typo
2025-09-23 06:39:14 +00:00
Adrian Gruntkowski 8d6d828d1d
Reduce reliance on `Timex` and use native time API where feasible (#5712)
* Replace usages of `Timex.to_unix` with native API

* Wrap call to `Timex.is_valid_timezone?`

* Wrap calls to `Timex.today(tz)`

* Replace `Timex.today()` with `Date.utc_today()`

* Replace `Timex.now()` with `DateTime.utc_now()`

* Replace `Timex.compare` with `Date.compare`

* Wrap `Timex.diff` calls

* Replace `Timex.Timezone.convert` with `DateTime.shift_zone!`

* Wrap `Timex.parse!`

* Replace `Timex.to_date` with native API calls

* Replace `Timex.beginning|end_of...` with native API calls for Date

* Wrap `Timex.beginning|end_of...` for DateTimes and Dates for years

* Replace `Timex.format(!)` with native API calls

* Replace `Timex.to_naive_datetime` with native API calls

* Wrap time humanizing routines using Timex

* Remove unnecessary `use Timex` instances

* Replace `Timex.shift` with native API calls

* Make `QueryParser.parse_date` handle gaps and ambiguities gracefully

* Replace `Timex.now(tz)` with `DateTime.now!(tz)`

* Use a more suitable Date function for comparison (h/t @aerosol)
2025-09-10 10:21:36 +00:00
Marko Saric 797a5bf4c1
clarifying the suggested plan (#5598)
* clarifying the suggested plan

* Update over_limit.html.heex

* Update dashboard_locked.html.heex

* fix tests

---------

Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
Co-authored-by: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com>
2025-07-29 07:33:22 +00:00
Adam Rutkowski adf39ca7a8
Audit trail for SSO (#5560)
* 

* wip

* wip

* Moduledoc false

* wip

* Update extra/lib/plausible/auth/sso/saml_config.ex

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

* Include only data keys present in changes

* Improve audit logging for SSO domain verification

Make it more compact and hopefully more readable to CS

* Harden existing tests

* Use consistent naming

* Update audit entries migration: use UUIDs for primary keys

* Fix up tests

* Format

* Only test audit for EE

* Remove temporary String.Chars implementation

* Always log keys as per `derive` directive; include changes for inserts

* Write `actor_type` to audit entries

* Extract Audit.Repo functions

* Moduledocs

* Include change in audited deletions

* Make audit available only in EE build

A bit clunky? cc @zoldar

* Put test behind ee compilation flag

* Pin user e-mail in test

* Ensure encoder opts are passed for nested calls

* Carry `__allow_not_loaded__` even if no extractor defined

* Turn `actor_type` into an ecto enum type

* Remove unused function

* s/sso_forced/sso_force_mode_changed

* Unwrap single item list for protocol implementation

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

* Migration: audit entries (#5581)

* Migration: audit entries

* Put migration behind EE conditional

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
2025-07-22 10:53:24 +00:00
Adam Rutkowski 37e718db40
End-to-end sso domain verification (#5513)
* wip

* Fix up typespcs

* Extract domain status enum to module macros

* Cancel verification jobs when integration is removed

* Revisit verification interface

* Supply local DNS server for domain ownership testing

* Rename a test

* 👾

* Use identifier when submitting domain verification

* Disallow re-verification of already verified domains
2025-06-18 09:52:48 +00:00
Adam Rutkowski 70902bbc5a
SSO: phrasing; settle on domain verification, not validation (#5508)
* SSO domains: s/validation/verification

* Fix careless search&replaces
2025-06-16 18:44:57 +00:00
Adam Rutkowski b86e4eea7e
SSO: implement domain validation background service (#5505)
* SSO: implement domain validation background service

* Put tests behind `ee`

* Fix up typespecs
2025-06-16 11:56:59 +00:00
hq1 df8727f414
CRM: revert #5440; implement lock/unlock for grace period (#5475)
* Revert "CRM: team (un)lock regardless of grace period (#5440)"

This reverts commit bb63c0d0e4.

* Implement grace period (un)lock just like in kaffy

* Test grace period handling
2025-06-06 08:01:29 +00:00
Adrian Gruntkowski 4a587e2a6e
Implement remaining `SSO` functions needed for setup (#5444)
* Move data mgmt logic from `UserAuth` to `Auth.UserSessions`

* Implement remaining SSO code API needed for setup

* Change `deprovision_user` -> `deprovision_user!`

* Change `UserSessions.create` -> `UserSessions.create!`

* Change `any_verified_domain?` -> `no_verified_domains?` (h/t @aerosol)
2025-06-03 06:21:51 +00:00
hq1 bb63c0d0e4
CRM: team (un)lock regardless of grace period (#5440)
* Add `locked_by_admin` to teams schema

* Implement team locking

* Look up `teams.locked_by_admin` in relevant background services

* Add background servive tests

* Type faster than think!
2025-05-28 11:28:59 +00:00
Karl-Aksel Puulmann 6a06020ba7
ScriptV2: BunnyCDN cache purging (#5435)
* Purge bunny cdn cache when tracker script config is updated

* Only allow one purge task scheduled per site

Tested by adding logging and toggling a checkbox a few times. Only one job got executed.

* Typo
2025-05-28 10:08:33 +00:00
RobertJoonas 2dd144bf85
Starter tier: Upgrade page remodelling (#5394)
* add a new (feature flagged) upgrade page offering v5 plans

* include starter tier plans in available_plans_for + use dev prices in test

* upgrade page remodelling with starter tier

* mobile optimizations

* optimize for darkmode

* add embedded dashboards as a growth benefit

* do not hide header on LegacyChoosePlan

* consistent v5 plan feature order

* slight grandfathering notice adjustment

* display monthly price too on yearly plans

* default to v5 plans unlesss legacy? is true

* refactor: suggest volume not plan for emails

* align back link with page title

* render grandfathering notice for growth v4 too
2025-05-20 13:22:12 +00:00
Karl-Aksel Puulmann 2114c6232d
Allow marking custom events as non-interactive (#5295)
* Tracker: Allow sending non-interactive custom events

These will not affect is_bounce

* Allow marking events as `non-interactive` in events API, change bounce definition

Ref: https://3.basecamp.com/5308029/buckets/26383192/card_tables/cards/8450017341
Feedback: https://feedback.plausible.io/220

* CHANGELOG.md

* credo

* Update tracker script version

* Explicitly ignore event.interactive in schema

* Replace an old test util
2025-04-21 08:11:58 +00:00
Adrian Gruntkowski ec4c6c453a
Switch from `Site.locked` to `Team.locked` (#5304)
* Switch to `Team.locked` for checking lock state

* Rename `update_for_sites` => `update_for`
2025-04-15 06:59:34 +00:00
Adrian Gruntkowski 299e59afc2
Append `__team` parameter to URLs in notification e-mails (#5266)
* Append `__team` parameter to URLs in notification e-mails

* Improve copy in guest to team member promotion email

* Make "return_to" set in redirect in `RequireAccountPlug` actually work

* Improve accepted site transfer e-mail phrasing and link
2025-04-02 14:38:52 +00:00
RobertJoonas 167ff65a69
Add top 3 pages to traffic spike email (#5251)
* improve traffic_change_notifier_test

* add top 3 pages to traffic spike email

* improve email layout

* changelog

* fix tests after layout change
2025-03-31 09:24:28 +00:00
Karl-Aksel Puulmann 42cea1d889
time-on-page: `site.legacy_time_on_page` cronjob (#5215)
* site.legacy_time_on_page_cutoff migration

* Update migration logic

* Cronjob for setting legacy_time_on_page_cutoff

* Test site creation default legacy_time_on_page_cutoff

* Use site.legacy_time_on_page_cutoff

Leaving the query param logic for now for testing purposes

* tweak cron

* Work around defaults in tests

* Fixes

* Make cutoff date in job configurable - useful for backfilling
2025-03-31 08:54:49 +00:00
RobertJoonas 79f514910b
Add final usage check before locking sites (#5232)
* check usage last chance before locking

* move function to avoid dialyzer error

* keep some tests out of CE

* update variable name
2025-03-24 12:50:24 +00:00
hq1 841abf5e53
Add billing role (#5171)
* Update role enums with billing

* [wip] Ensure no team management can be done for roles other than admin/editor

* Track `current_role` at plug/mount level

* Some team role policy enforcement

* Guard remaining routes based on current team role

* Notify billing members via check usage worker

* Include billing members in trial/locked notifications

* Permissive team access policy when no current team assigned

Effectively the plug should no-op, so that existing user
notices/alerts can be displayed.

* Send cancellation notifications to billing role members

* Include billing members in renewal notifications

* Update moduledoc

* Exclude :guest role from team access auth plug
2025-03-11 15:43:37 +00:00
Adrian Gruntkowski bf010a1537
Implement support for multiple team owners and multiple teams per user (#5008)
* Add tests for `Teams.get_or_create/1` and `Teams.get_by_owner/1`

* Start populating `current_team` in assigns fetching value from session

* Clean up team passing in invitation services

* Make site transfer service handle multi-team scenario

* Handle multi-team and permission transfer errors on controller level

* Handle multi-teams in site creation on service and controller level

* Drop validation limiting full membership to a single team

* Make user deletion account for public team ownership

* Adjust feature availability checks for Stats API key

* Use current_team when determining limits on site transfer invitation

* Adjust trial upgrade email submission to account for multiple owners

* Remove unnecessary `Teams.load_for_site/1`

* Spike renaming `owner` and `ownership` relationships to plural versions

* Make HelpScout integration handle owner of multiple teams gracefully

* Add FIXME note

* Resolve paddle callback issue by always provisioning a new team when none passed

* Set `current_team` as `my_team` only when user is an owner

* Implement basics of Teams CRM

* Extend Teams CRM

* Further adjust User and Site CRM and refine Team CRM

* Convert Enterprise Plan CRM to refer to team directly and not via user

* Remove unused virtual fields from User schema

* Add note to HelpScout integration

* Allow listing multiple owners under Site Settings / People

* Remove unused User schema relations

* Fix current team fetch in auth plug and context

* Implement basic team switcher

* Ensure (site) editor role is properly handled in site actions auth

* Don't set `site_limit_exceeded` error marker on `permission_denied` error

* Link from HS integration to Team CRM instead of User CRM when available

* Ensure consistent ordering of preloaded owners

* Add `with_subscription` preload for optimisitation

* Add ability to search sites by team identifier

* Add ability to pick team when transferring ownership directly

* Fix failing HelpScout tests

* Scope by team when listing sites in dashboard and via API (optional)

* Add ability to search by team identifier in plans CRM lookup widget

* Add subscription plan, status and grace period to team status info

* Expose teams list in user CRM edit form and fix team details CRM view

* Fix Team Switcher styling

* Reorganise header nav menu

* Avoid additional queries when authenticating user

* Hide the pay/site transfer message on lock screen when teams FF is on

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2025-02-19 09:33:25 +00:00
Adrian Gruntkowski 339dd89a98
Rework team creation constraints (#5003)
* Move `GracePeriod` under `Teams` and clean it up a bit

* Switch to relying on new team membership constraint when creating my team

* Remove unused unique_constraint from Teams.Membership schema changeset
2025-01-29 13:05:44 +00:00
ruslandoga 6ed846395f
Autogenerate text emails (#4674)
* autogenerate text emails

* fix export email formatting

* fewer changes

* add full text_body test

* eh

* cleanup

* explain

* remove recursive collapse_whitespace

* remove comment
2025-01-02 14:32:54 +00:00
hq1 f4f4d70adb
Only check usage for EPs by _current_ subscription (#4929) 2024-12-19 10:58:20 +00:00
Adrian Gruntkowski 729a32e610
Teams writes switch (#4883)
* Comment out legacy fields and relationships

* WIP

* WIP 2

* WIP 3

* wip

* Remove teams backfill and consistency check scripts

* WIP 3

* Fix CheckUsage tests

* Update billing/subscription tests

* WIP 4

* Make site transfer fail if some invitation already exists

* Fixup: do symmetric invitation/site transfer check

* Update UI bugs: make listing sites/inviting admins work like before

* Fix Sites test

* Fix external sites controller test

* Fix live sites tests

* Fix props availability lookup

* Fix site controller tests

* Fix billing controller tests

* WIP - accept invitation tests

* Another round of test fixes + invitations logic bugs

* users_test -> teams_test

* Update registration via invitation

Here, we still rely on "polymorphic" invitation structures,
hence the "unified by id" helper.

For now, it'll remain local unless we discover it's
needed in the broader `Teams.Invitations` context.

cc @zoldar

* Yet another round of test and bugfixes along the way

* Include team in site setup success e-mail

* Fix send_site_setup_emails worker

* Fixed almost all tests except CRM ones

* Update enterprise plan admin test

* Fix CRM + remaining tests

* Address credo warnings (modulo one FIXME)

* Remove last FIXME and rephrase the invitation test case description

* Set Team fields via User CRM transparently

* Map user reference in Enterprise Plan CRM via team owner

* Fix resource actions in user CRM

* Get rid of warning when opening create form in API keys CRM

* Stop emitting warnings when editing Enterprise Plans via CRM

* Tests: Bump await_clickhouse_count interval

* Remove XXX marker

* Fix register from invitation link in email sent for ownership transfer

* Simplify fetching all pending site ownership site IDs

* Remove commented out schema fields

* Remove unused functions

* Address flakiness in ingest counter tests

* Remove unused `Teams.Sites.create`

* Don't restart trial on team with subscription when creating site

* Account for cases of legacy teams with empty trial expiry date

* Revert "Address flakiness in ingest counter tests"

This reverts commit 60dc1e4115.

* Fix flaky ingest counters tests under load

* Attempt 2

* Pre-emptively hardcode site ids in sampling cache test

to avoid supplying the same IDs alongside with counters test,
that inserts through another repo (async).
what we're observing is, clickhouse not summing mergetree columns fast
enough, even though we wait quite a bit.

* Fix ingest counter tests by accounting for delayed summation

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2024-12-16 11:11:14 +00:00
Adrian Gruntkowski 3afec60d98
Remove team adapters (#4877)
* wip

* wip

* 🍌

* WIP

* Draw the rest of the owl (well, almost)

* Remove obsolete unlimited trial logic

* Remove `allow_next_upgrade_override?` adapter

* Remove `Teams` adapter

* Remove /sites adapters

* Remove `Sites` adapter

* Remove `change_plan` adapter

* Fix up CE test

* Remove adapter for Billing.latest_enterprise_plan_with_price(s)

* Remove adapter for `Billing.has_active_subscription?`

* Remove adapter for `Billing.active_subscription_for`

* Remove remaining billing adapter

* Remove all_pending_transfers

* Remove `get_owner` adapter

* Remove `has_sites?` and `owns_sites?` adapters

* Remove `Ownership` adapter

* Remove `check_invitation_permissions` adapter

* Remove `check_team_member_limit` adapter

* Remove `ensure_transfer_valid` adapter

* Remove Invitations adapter

* Remove sole teams adapter

* Make dialyzer happy

* Consolidate `Billing.features_usage` definition

* Remove unused `Quota.Usage`

* Remove remains of `read_team_schema` FF and reduce number of CI passes

* Bang up the condition

* Include pending invitations when querying `has_sites?`

* Fix and improve conditional expression in `plan_box` component

* Update comments

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2024-12-05 09:02:09 +00:00
Adrian Gruntkowski b86c2e715f
Switch reads to Teams schemas across the rest of the app (#4860)
* Pre-emptively introduce `site.team_owner` relation

* Drop null constraint on user_id from subscriptions and enterprise_plans

* Temporarily remove populating old schemas in Teams.Test

* Point to site.owner via new schema

* Switch more reads to teams schema WIP

* Fix AuhtorizeSiteAccess test

There's no need to translate `admin`<->`editor` here,
the redundancy is inlined wherever the plug is initialized.

* Fix regions test

* Fix main graph test

* Fix authorization test

* Try to rely on team for subscription/plans where applicable

* Test fixes

* Fix plans test

* Prep for CheckUsage changes

* Skip remaining CheckUsage tests for now

* Fix user deletion to account for team relations

* Fix HelpScout tests

* 💀 Modify ingestion to read team schemas

* Made all tests green except skipped ones

* Mute warnings about transferring site with no order

By making artificial site membership struct,
when reading data off team membership schema.

* Fix site removal test case

* Re-enable locked site tests, that don't have to rely on `SiteLocker`

* Format

* Revert "Mute warnings about transferring site with no order"

This reverts commit 0e45f8c9d9.

* Re-enable old models and fix remaining tests

* Use new factories in a long running minio test

* FIXME->TODO

* Fix remaining tests in legacy mode (no FF raised)

* oof

cc @zoldar

* Add missing definitions of editor role in FE code

* Remove no longer relevant comment about roles

* Fix JS formatting

* Always prioritize site transfers over memberships in sites list

* Fix misaligned "Reject" invitation button

* Fix site pinning when user is guest in multiple sites in team

* Fix subscription settings controller tests

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2024-12-02 12:20:16 +00:00
Adrian Gruntkowski 95471c0085
Switch `AcceptInvitation` ops to read from team schemas behind FF (#4847)
* Move `bulk_transfer_ownership_direct` under `AcceptInvitation`

* [WIP] Switch ownership transfer operations to read from team schemas behind FF

* Fix usage test regression

* Semantics - current user; ownership is not necessarily involved

* Perform remaining read via adapter; remove obsolete test

* Properly list site with pending site transfer while being guest on a team

* Account for pending site transfers in Settings > People list

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2024-11-26 08:47:12 +00:00
Adrian Gruntkowski 380dc00d1a
Switch on teams schema in choose plan view behind FF (#4838)
* Switch on teams schema in choose plan view behind FF

* Proxy via Read adapter where applicable for billing context

* Proxy remaining plan-related functions

* Switch enterprise_configured?/1 tests to use the adapter

* Format

* Update SiteLocker tests

* Actually use `has_active_subscription?/1` billing adapter

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2024-11-20 08:35:18 +00:00
Adrian Gruntkowski 27ac3b6b5b
Address team syncing discrepancies (#4739)
* Clean site transfers after 48 hours

* Sync accepting site transfers and invitations within transaction

* Add dry run mode to teams backfill and make it a default

* Extend invitation clean worker tests
2024-10-28 10:11:47 +00:00
Adrian Gruntkowski 7d6f10f0cb
Ensure team is present before use in sync logic (#4709)
* Ensure team is present before use in sync logic

* Ensure teams backfill works against partially assigned sites

* Associate site with team on creation

* Associate site with team on sync

* Reuse alias

* Add tests for invitation creation sync

* Move team assertions to a helper module

* Format

* Test team creation on site creation via Sites context module

* Add tests for teams sync on subscription changes

* Tag tests

* Test grace period start syncing up with teams

* Test grace period manual lock sycning w/ teams

* Test grace period end sycing up w/ teams

* Test clearing grace period sync with teams

* Update moduledoc

* Fix missing preloads and wrong result pattern matching in sync logic

* Test sync on accepting invites and site transfers

* Test sync on membership role update and member removal

* transfer async fix WIP

* Stop privisioning team in site factory

* Remove unused relationship from Site schema

* Ensure consistent parsing of `passthrough` from Paddle webhook

* Update team passthrough notification tests & logic

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2024-10-23 11:29:15 +00:00
Adrian Gruntkowski 17b12ddaeb
Implement basics of Teams (#4658)
* Extend schemas with new fields and relationships for teams

* Implement listing sites and sites with invitations with teams

* Implement creating invitations with teams

* Implement accepting invites with teams

* Add `Teams.SiteTransfer` schema

* Implement creating ownership transfers

* Implement accepting site transfer between teams

* Make results shapes from `Teams.Memberships` role functions more consistent

* Remove :team relation from ApiKey schema

* Pass and provision team on subscription creation

* Pass and provision team on enterprise plan creation

* Implement creating site for a team

* Keep team in sync during legacy ownership transfer and invitations

* Resolve conflict in `Teams.get_or_create` without transaction

* Abstract `GracePeriod` manipulation behind `Plausible.Users`

* Put `User.start_trial` behind `Plausible.Users` API

* Sync team fields on user update, if team exists

* Sync cleaning invitations, updating and removing members

* Transfer invitations too

* Implement backfill script

* Allow separate pg repo for backfill script

* Rollback purposefully at the end

* Update backfill script with parallel processing

* Use `IS DISTINCT FROM` when comparing nullable fields

* Handle no teams to backfill case gracefully when reporting

* Parallelize guest memberships backfill

* Remove transaction wrapping and query timeouts

* Make team sync check more granular and fix formatting

* Wrap single team backfill in a transatction for consistent restarts

* Make invitation and site transfer backfills preserve invitation ID

* Update migration repo config for easier dev access

* Backfill teams for users with subscriptions without sites

* Log timestamps

* Put teams sync behind a compile-time flag

* Keep timestamps in sync and fix subscriptions backfill

* Fix formatting

* Make credo happy

* Don't `use Plausible.Migration` to avoid dialyzer complaining

None of the tooling from there is used anywhere and `@repo` can
be defined directly in the migration script.

* Drop SSL workarounds in the backfill script

---------

Co-authored-by: Adam Rutkowski <hq@mtod.org>
2024-10-21 07:35:23 +00:00
hq1 70997abfc7
Reduce Phoenix.HTML usage (#4675)
* Turn .eex templates into .heex

* Add new compile-time presets to `PlausibleWeb`

* Fix remaining templates

* Update static components

* Update live components

* Update live views

* Update rest of the owl

* Update mjml template

* Format

* Format

* Revert MJML stuff, it's coupled with EEx

* yawn at test

* Get rid of `FormHelpers` module

* Ensure YOU label shows up first on IP rules list

* Update lib/plausible_web/templates/email/welcome_email.html.heex

Co-authored-by: Artur Pata <artur.pata@gmail.com>

* Fix create site email link

* Fix server error markup (and turn thanks into heex)

* Format

---------

Co-authored-by: Artur Pata <artur.pata@gmail.com>
2024-10-15 03:55:14 +00:00
Adrian Gruntkowski 6981972617
Make invitations cleanup worker rely on UTC time (#4610) 2024-09-25 12:44:55 +00:00
hq1 3251b5bb33
Check usage for users with active/cancelled/past due subscriptions (#4607)
* Check usage for users with active/cancelled/past due subscriptions

So that over limit e-mails and grace period is handled
regardless - they're still subscribers.

* Ensure current subscription is fetched, for an ongoing plan

* Add extra test

* Revert "Ensure current subscription is fetched, for an ongoing plan"

This reverts commit 9ddc7bdccb.

* Fixup test

* Reapply "Ensure current subscription is fetched, for an ongoing plan"

This reverts commit 7ab537954b.

* Do a subscription preload and assert ID match

* Use inner lateral join to fetch subscriptions
2024-09-25 11:27:12 +00:00
Adrian Gruntkowski 373d4dd665
Implement token-based sessions (#4463)
* Turn `Plausible.Auth.UserSession` into full schema

* Implement token based sessions and use them as default

* Ignore expired user sessions during retrieval from DB

* Implement plug bumping user session last used and timeout timestamps

* Implement Oban worker removing expired user sessions with grace period

* Implement legacy session conversion on touch, when applicable

* Update `UserAuth` moduledoc

* Extend `UserAuth` tests to account for db-backed session tokens

* Update CHANGELOG

* Add tests for `UserSessionTouch` plug

* Add test for `CleanUserSessions` worker

* Add logging of legacy session retrievals

* Use single update permitting stale records  when touching user session

* Don't fetch session and user for external API endpoints (/api/event too)

* Refactor `Users.with_subscription/1` and expose helper query

* Skip fetching session in legacy `SessionTimeoutPlug`

* Rely on user session assign from `AuthContext` in `SentryContext`

* Silence legacy session warnings in `UserSessionTouchTest`

* Rely on session assign from `AuthPlug` in `SuperAdminOnlyPlug`

* Change `UserAuth` to get session, user and last subscription in one go

* Avoid refetching user session in `AuthorizeSiteAccess` plug

* Fix code formatting

* Refactor `UserAuth.get_user_token/1` (h/t @aerosol)

* Remove bogus empty opts from `scope` declarations in router

* Only touch session once an hour and keep `user.last_seen` in sync

* Bring back logging of legacy token use
2024-09-03 11:34:37 +02:00
hq1 e3af1a317d
Onboarding improvements (#4459)
* Migration: add installation meta

* Update site schema with installation meta

* Remove VERIFICATION_ENABLED env var

* Add context API to create/remove special goals

* Add context api to update installation meta

* Remove verification enabled check

* Update new progress flow definitions

* Update generic components

* Remove internal /status API

* Implement installation live view

* Update traffic change notifier link

* Update verification, no more modal

* Update routes

* Remove focus.html - will unify everything under app layout

* Fix broken link

* Update templates with focus_box mostly

* Update controller tests

* Update controllers and stop using the focus layout

* copy changes

* Update verification.ex

* Remove dead template

* Update settings_general.html.heex

* Update copy in tests

* Update installation.ex

* Remove dangling dot

* Fix link

* Update installation.ex

* Update installation.ex

* Better tooltips?

* Simpler labels

* Revert "Simpler labels"

This reverts commit 797560ef82f2067458b03b884be5aecc8fdc72bc.

* Add copy to clipboard link and fix snippet's dark mode

* Offer installation detection skip only if ws connected

* Put COPY link at the bottom with background

* Make tooltips link to docs

* Fix cherry-pick gone wrong

* Hide tooltips on mobile screens

* WIP: 404 tracking wizard

* Revert "WIP: 404 tracking wizard"

This reverts commit a9c9c79bbd.

* Update lib/plausible_web/live/components/verification.ex

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

* Update lib/plausible_web/live/installation.ex

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

* Use current_user from socket.assigns

* Update lib/plausible_web/live/installation.ex

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

* Use current_user from socket.assigns

* Use conn.private to steer verification tests

* Drop non-sticky tooltip in favour of component parametrization

Co-authored-by: Artur Pata <artur.pata@gmail.com>

* Reapply "WIP: 404 tracking wizard"

This reverts commit 3ba81671d7.

* Fix installation tests including 404 tracking

* Fixup the tooltip component

* Format

* Update installation.ex

* Put flash whenever installation option changes

* Use last known installation type on domain change

* Extract user flow definition to provide compile-time checks

* See if this helps running CE migrations successfully

* Use `styled_link` on registration/login views

* Don't crash when there's no conn.private carried over

* Format

* Push "Determining installation type" message a bit lower

* Use links and footer lists uniformly

This commit introduces a `<.focus_list/>` component
for rendering focus box footer links with colored
discs. It also equips generic link components
with the ability of sending non-GET requests
along with CSRF token, so we can apply uniform
styling and stop using legacy Phoenix link tags.

cc @zoldar @apata

* ws 👾

* Render more descriptive flashes on script config change

---------

Co-authored-by: Marko Saric <34340819+metmarkosaric@users.noreply.github.com>
Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
Co-authored-by: Artur Pata <artur.pata@gmail.com>
2024-09-02 12:49:54 +02:00
Uku Taht b868042581
Refactor: remove transform_filters function from imported base (#4409) 2024-07-31 15:36:25 +03:00
Uku Taht 49bb57f601
Fix email report sentry errors (#4381)
* Fix missing email param on email unsubscribe

* Guard against email report being deleted
2024-07-23 12:05:42 +03:00
hq1 d56bb2b4d5
Implement traffic drop notifications (#4300)
* Expose current visitors 12h aggregate

* Remove unused site association

* Distinct drop/spike notification factories

* Rename modules accordingly + implement drop handling

* Rename periodic oban service

* Implement drop email

* Rest of the owl

* Update changelog

* Update moduledoc

* Update moduledoc

* Min threshold to 1

* Threshold 1

* Remove merge artifact

* Put panel behind a feature flag

* Format
2024-07-11 14:55:18 +02:00
RobertJoonas dd1d74ccb7
Always recommend a suitable plan on the choose-plan page (#4222)
* pull last_bill_date from paddle sandbox in mix task

* move cycle usage checks to Quota module

* move quota.ex to a subfolder

* split up Quota module

* set choose-plan pageview slider according to usage

* silence credo
2024-06-17 09:25:46 +03:00
hq1 4603aa7a51
Reset grace period if usage drops within the last cycle (#4212)
So that `LockSites` job unlocks the site,
encountering no grace period and no upgrade needed.
2024-06-11 15:49:31 +02:00
Karl-Aksel Puulmann 0a883f10e7
Refactor: Use common current_visitors code (#4071)
* Use common module for counting current visitors in external stats controller

* Refactor spike notifier, remove now-dead code
2024-05-07 15:03:37 +03:00
ruslandoga 972dd5d150
redirect to s3 url when downloading exports (#4002)
* redirect to s3 url

* use new on_ee macro, reduce wait time for email to five seconds
2024-05-02 19:53:12 +01:00