0
0
mirror of https://github.com/PostHog/posthog.git synced 2024-11-24 18:07:17 +01:00
Commit Graph

39 Commits

Author SHA1 Message Date
Eric Duong
34d45e3436
[cohort] insight cohorts (#7569)
* initial working'

* fix tests

* correct tests

* typing

* update snapshot

* add funnel test

* remove unnused

* rest of tests

* function name

* typing

* raise if debugging otherwise send to sentry

* no limit option for cohorts

* remove duplicate

* propogate types correctly

* add param

* cleanup

* update snapshots

* add comment

* change var name

* reverse arg

* use func

* fix tests and types

* add simplify

* move simplification

* adjust checks

* explicit type

* don't init
2022-01-06 10:38:29 -05:00
Karl-Aksel Puulmann
c32f214d63
Track organization groups usage (#7597) 2021-12-09 15:51:24 +02:00
Karl-Aksel Puulmann
7de761dff0
Update BE tracking to use groups (#7355)
* Update some posthoganalytics.capture calls

* Update report_user_logged_in tracking

* Update report_team_member_invited

* Update report_bulk_invited

* Update report_org_usage

* Update AnalyticsDestroyModelMixin

* Update action creation/updating tracking

* Update annotations tracking

* Update cohort tracking

* Update dashboards tracking

* Update feature flags tracking

* Update imports, sessions tracking

* More typeignores

* Default properties blank

* update metadata default

* Stringify

* Fix some tests

* Kill debug code

* Update FF tests

* Update test_organization

* Update test_organization_invites

* Update test_user

* Fix org usage report

* update test_send_license_usage

* Update organization tests

* Respect dry-run on errors as well, log

* Update organization properties on report

* Assert organization props

* Remove dead imports

* Fix test
2021-11-30 10:58:37 +02:00
Eric Duong
7979f52e8a
[groups persons] API for returning groups based on trend results (#7144)
* working for unique_groups math

* fix types

* add null check

* update snapshots

* update payload

* update snapshots

* use constructor

* adjust queries

* introduce base class

* consolidate querying

* shared serializer and typed

* sort imports

* snapshots

* typing

* change name

* Add group model

```sql
BEGIN;
--
-- Create model Group
--
CREATE TABLE "posthog_group" ("id" serial NOT NULL PRIMARY KEY, "group_key" varchar(400) NOT NULL, "group_type_index" integer NOT NULL, "group_properties" jsonb NOT NULL, "created_at" timestamp with time zone NOT NULL, "properties_last_updated_at" jsonb NOT NULL, "properties_last_operation" jsonb NOT NULL, "version" bigint NOT NULL, "team_id" integer NOT NULL);
--
-- Create constraint unique team_id/group_key/group_type_index combo on model group
--
ALTER TABLE "posthog_group" ADD CONSTRAINT "unique team_id/group_key/group_type_index combo" UNIQUE ("team_id", "group_key", "group_type_index");
ALTER TABLE "posthog_group" ADD CONSTRAINT "posthog_group_team_id_b3aed896_fk_posthog_team_id" FOREIGN KEY ("team_id") REFERENCES "posthog_team" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "posthog_group_team_id_b3aed896" ON "posthog_group" ("team_id");
COMMIT;
```

* Remove a dead import

* Improve typing for groups

* Make groups updating more generic, avoid mutation

This simplifies using the same logic for groups

Note there's a behavioral change: We don't produce a new kafka message
if nothing has been updated anymore.

* Rename a function

* WIP: Handle group property updates

... by storing them in postgres

Uses identical pattern to person property updates, except we handle
first-seen case within updates as well.

* Get rid of boolean option

* WIP continued

* fetchGroup() and upsertGroup()

* Test more edge cases

* Add tests for upsertGroup() in properties-updater

* Rename to PropertyUpdateOperation

* Followup

* Solve typing issues

* changed implementation to use pg

* unusd

* update type

* update snapshots

* rename and remove inlining

* restore bad merge code

* adjust types

* add flag

* remove var

* misnamed

* change to uuid

* make sure to use string when passing result

* remove from columnoptimizer logic and have group join logic implemented by event query classes per insight

* remove unnecessary logic

* typing

* remove dead imports

* remove verbosity

* update snapshots

* typos

* remove signals

* remove plugin excess

Co-authored-by: Karl-Aksel Puulmann <oxymaccy@gmail.com>
2021-11-18 11:58:48 -05:00
Karl-Aksel Puulmann
42192e07c7
BE (Groups/Trends): Make breakdowns work with groups (#6899)
* Extract GroupsJoinQuery

* Add test for breakdown filtering

* Unify breakdown mixins

* Allow passing breakdown_type == 'group' with breakdown_group_type_index

* Allow breakdown by group props in trends

* Add tests for trends breakdown_props function on group breakdowns

* Solve common issues

* Output snapshot diff into console

* Clean up materialized columns after tests

* Add zero protection

* Solve test failure
2021-11-05 13:47:41 +02:00
Karl-Aksel Puulmann
fa79f8ea67
BE (Groups/Trends): Allow aggregating by groups (#6894)
* Type math in Entity

* Allow passing group_type_index from FE to BE

* Get a initial query running

* Add group value filter if aggregating by groups

* Add snapshot testing for trends queries

* isort

* Update tests

* Add test for column_optimizer

* Update ee/clickhouse/queries/trends/util.py

Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>

Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
2021-11-05 13:08:32 +02:00
Tim Glaser
0f7de25f33
Fix cohort creation from trends (#6636)
* Fix cohort creation from trends

* REVERT debug issue

* fix nit

* Revert "REVERT debug issue"

This reverts commit ea50db28ce.

* REVERT try debugging issue

* REVERT Try final

* Don't insert into clickhouse twice

* remove unused var

* debug

* fix and revert

* test mixin

* fix black

* fix

* Update ee/tasks/test/test_calculate_cohort.py

Co-authored-by: Michael Matloka <dev@twixes.com>

Co-authored-by: Michael Matloka <dev@twixes.com>
2021-11-04 11:46:08 +01:00
Michael Matloka
b0aa8f0c91
Migrate cohort-related logics to be project-based (#6683)
* Migrate cohort-related logics to be project-based

* Fix `cohortsDetail`

* Remove `teamId` param from `determineEndpoint` methods
2021-10-28 13:29:53 +02:00
Sam Winslow
62cc72684e
Capture exception if organization user is not found (#6528) 2021-10-20 01:18:51 +01:00
Sam Winslow
95746b9bce
Send event for license usage by organization (#6333) 2021-10-14 12:42:14 -04:00
Michael Matloka
e97c20ad33
Purge PLUGIN_SERVER_ACTION_MATCHING flag (#6358)
* Remove `PLUGIN_SERVER_ACTION_MATCHING` flag

* Fix action bug

* Try to fix mocking
2021-10-11 21:33:48 +02:00
Tim Glaser
e31d166d74
Don't count internal metrics for billing purposes (#6228) 2021-10-05 15:05:51 +03:00
Tim Glaser
3402ba4ee7
Fix status reports (#6194)
* Fix status reports

* remove active in period

* types

* mypy
2021-10-01 18:56:29 +02:00
Alex Gyujin Kim
6d6202317a
Add custom_name to entity model (#6090)
* add custom_name to entity model

* fix test and add custom name to funnel

* fix more tests

* remaining broken tests
2021-09-24 08:31:16 -07:00
Tim Glaser
eba29d85f6
Send license usage (#6060)
* Send license usage

* type errors

* Update posthog/celery.py

Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>

* Use correct URL

Co-authored-by: Paolo D'Amico <paolodamico@users.noreply.github.com>
2021-09-22 14:17:38 +02:00
Michael Matloka
1d4187923b
Refactor AvailableFeature from strings to an enum everywhere (#5856)
* Refactor `AvailableFeature` from strings to an enum everywhere

* Fix circular dependency and type
2021-09-09 12:19:55 +02:00
Karl-Aksel Puulmann
b6b2508233
Make marking materialized columns as MATERIALIZED stateless (#5831)
This simplifies the operational model a lot
2021-09-07 11:53:57 +00:00
Karl-Aksel Puulmann
8d8705d1bb
Materialize person columns automatically (#5760)
* Hotfix: Use materialized columns on cloud

This was broken since default_kind was different on Distributed tables
on cloud

* Improve __init__.py

* Make reverting DEFAULT column async, only ON CLUSTER for events table
2021-08-28 12:14:30 +03:00
Eric Duong
63c57dc5b4
comment out test (#5364) 2021-07-28 23:24:32 +00:00
Eric Duong
562e3bacfc
Funnel persons per step and dropoff (#4883)
* wip: pagination for persons on clickhouse funnels

* wip: added offset support for getting a list of persons; added support for conversion window;

* fixed mypy exception

* helper function to insert data for local testing

* moved generate code into separate class for more functionality later

* corrected person_distinct_id to use the person id from postgres

* minor corrections to generate local class along with addition of data cleanup via destroy() method

* reduce the number of persons who make it to each step

* moved funnel queries to a new folder for better organization; separated funnel_persons and funnel_trends_persons into individual classes;

* funnel persons and tests

* initial implementation

* invoke the funnel or funnel trends class respectively

* add a test

* add breakdown handling and first test

* add test stubs

* remove repeats

* mypy corrections and PR feedback

* run funnel test suite on new query implementation

* remove imports

* corrected tests

* minor test updates

* correct func name

* fix types

* func name change

* move builder functions to funnel base

* add test classe for new funnel

* Handle multiple same events in the funnel (#4863)

* dedup + tests

* deep equality. Tests to come

* write test for entity equality

* finish testing funnels

* clean up comments

* add ability to specify per step or dropoff persons

* remove defaults

* remove funnel_window parameter unless it's needed

* add param to filters

* test api

* remove print

* fix tests

* change distribution

* add none condition for funnel step

* add order by

* remove funnel window days

Co-authored-by: Buddy Williams <buddy@posthog.com>
Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
2021-06-29 12:22:42 -04:00
Buddy Williams
7d045c86f3
Refactoring funnel trends (#4419)
* checkpoint: refactoring funnel trends so that they work correctly

* wip: refactoring funnel trends query to return the results we actually need

* wip: added in new query for testing

* wip: moved sql into a separate file, converted list to dictionary, and added several tests to check data quality

* wip: with a better understaning of funnel trends I've refactored the query so that I can write a data transformer in python

* moved code into funnel_trends for both logic and tests to isolate the concern

* reordered methods for readability

* wip: refactoring funnel trends to support filters

* wip: added updated SQL which will replace the existing FUNNEL_TREND_SQL

* correct column name so that it's clearer

* added substitution variables to new query

* fixed missing substitution variable

* wip: integrating new query with correct params, added mixins for funnel_window, and working toward working test

* several query corrections

* summarize funnel trends

* moved method down

* removed unused code

* added data quality checks

* corrected cohort size for tests

* test window size and incomplete status

* corrected a few names

* removed unnecessary comment

* commented out old funnel trends tests

* removed print statement

* removed old funnel trend code

* made funnel trends response match existing data structure layout

* removed unused imports

* removed more unused imports

* fixed mypy errors

* Added ClickhouseFunnelBase to extract common methods for both ClickhouseFunnelTrends and ClickhouseFunnel; this also fixes issues with tests;

* removed unused type comment

* corrected test to account for new funnel_window_days mixin

* fixed clickhouse funnel tests

* fixes for automated tests

* changed team_id to use client substitution to avoid sql injection attempts in the future but since it's not user supplied it's not currently an issue

* corrections prompted by PR review

* corrected test to dict test with funnel_window_days
2021-06-03 17:06:08 -04:00
Karl-Aksel Puulmann
008ee1f04c
Include more clickhouse query metrics (#4256)
* Use `statshog` over python-statsd

More support for tags!

* Include custom tags for every query + add annotation to query

After this we can:
- Figure out from query logs where queries are coming from (speeding up debugging)
- Break down query speeds by user queries vs others (e.g. celery) --
better represents overall speed
- Can figure out how fast queries are on average for various teams

* Use tags in more queries over interpolation

This way we can set up more interesting graphs \o/

* Solve mypy error

* Fix a flaky test (due to ordering)
2021-05-10 10:47:54 +03:00
Michael Matloka
819a2413b9
Handle webhooks better (#3605)
* Don't fire webhooks for soft-deleted actions

* Handle regex errors in webhook firing gracefully
2021-03-09 16:37:42 +01:00
Michael Matloka
b9f00b2710
Fix webhooks specifity (#3463)
* Fix webhooks specifity

* Make REST hook firing monitoring better reflect reality
2021-02-24 23:14:02 +01:00
Eric Duong
9514e290a2
Static cohort on person modal (#2952)
* Upload static cohort using CSV, closes #2868

* fix tests

* Fix tests

* Fix e2e test

* Avoid double inserts

* Speed up query

* Move to params

* fix tests

* initial cleanup

* initial scaffold for cohort static logic

* intiial frontend changes

* initial working

* fix error on iterable

* stickiness people func refactor

* Use JSON instead of protobuf

* stickiness working

* clickhouse route

* unused import

* move button

* make interface easier to user

* clickhouse support

* restore cache decorator

* endpoint adjustment

* adjust how clickhouse handles inserting for static cohorts

* split out processing into pg

* use worker for clickhouse querying too

* add pg test

* ee test

* add input for cohort naming

* add stickiness test

* condition for when to show save cohort

* fix types

* minor fix

* remove repeats

* remove hardcoded id

* add date handling to trends cohort func

* remove print

* add link on success creation

* cohort working

* fix backend test

* fix cohort typescript

* remove unnecessary kafka topic

* remove brackets

* shift default

* raise exceptions when debug or test is true

* remove test flag

* move trends insight related components to different folder

* change get_earliest_timestamp

* remove extraneous condition

* fix test call

* put behind ff

* fix test x2

* fix tests

* restore exceptions hog

* fix tests

* restore exceptions hog

* fix test x20

Co-authored-by: Tim Glaser <tim@glsr.nl>
2021-02-24 09:59:13 -05:00
PostHog bot
146469770b
Update plugin server to 0.9.24 (#3445)
* Update plugin server to 0.9.24

* Add more hook metrics in Python

Co-authored-by: posthog-bot <posthog-bot@users.noreply.github.com>
Co-authored-by: Michael Matloka <dev@twixes.com>
2021-02-23 18:07:06 +01:00
Michael Matloka
36bc39b09b
Add telemetry for the hooks task (#3442) 2021-02-23 16:56:21 +01:00
Michael Matloka
828770f48b
REST/webhook optimizations (#3267)
* Ignore erroneous webhook firing prefiltering

* Optimize EE web/RESThook firing
2021-02-09 18:31:50 +01:00
Karl-Aksel Puulmann
259a2290b4
Serialize/deserialize elements_chain on webhooks_ee (#3262)
Solves https://sentry.io/organizations/posthog/issues/2207757069/?project=1899813&query=is%3Aunassigned+is%3Aunresolved
2021-02-09 13:54:02 +01:00
Michael Matloka
973769340a
Revert "Revamp and optimize hooks on EE (#3119)" (#3249)
This reverts commit 5485fb058d.
2021-02-09 10:16:38 +01:00
Michael Matloka
5485fb058d
Revamp and optimize hooks on EE (#3119)
* Revamp and optimize hooks on EE

* Improve retry strategy

* Improve some minor things

* Cache available_features in memory

* Address feedback
2021-02-09 09:52:19 +01:00
Michael Matloka
5d5ede19e4
Fix REST hook firing (#2894)
* Fix REST hooks being only fired if project has webhook

* Fix firing more

* Actually still filter but also for Zapier

* Don't .only() Team in EE process_event to optimize REST hook firing

* Fix REST hook duplication in EE

* Update test_process_event.py

* Debug

* Revert "Debug"

This reverts commit 6d4c9f754d.

* Fix organization-less teams partly

* Fix more organization-less teams

* Fix moar organization-less teams

* Explicitly bootstrap org without user in tests

* Fix org bootstrap

* Fix typing

* Fix bootstrap usage

* Update test_process_event.py

* Fix num queries

* Add test_action_on_perform_hook_fired_once

* Fix Action.objects.create call

* Don't test hook firing as it's offloaded to worker
2021-01-12 13:09:27 +01:00
Michael Matloka
43b09727d6
Fix REST hook deletion (#2893)
* Fix REST hook deletion

* Fix hook deletion better

* Add API DELETE test
2021-01-08 15:15:48 +01:00
Tim Glaser
adcf493202
Fix ee webhook (#2664)
* Fix ee webhook

* Get rid of warnings

* Add webhooks
2020-12-04 16:43:22 +01:00
Michael Matloka
96e4ee8512
Nest endpoints of project-based models under /api/project/ – LITE (#2485)
* Nest endpoints under /project/ with StructuredViewSetMixin

* Rewrite URLs

* isort

* Update utils.py

* Fix errors

* Fix almoast all the errors

Last left to do: shared dashboards and permission classes.

* isort

* Adjust for master

* Add compatbility with shared dashboards

* Debug ClickHouse

* Remove some # type: ignores

* Simplify CursorPagination

* Move test base from posthog.api.test to posthog.test

* Improve API structure

* Bring back legacy endpoints

* Fix legacy compatibility

* Fix bugs and typing

* isort

* Fix hooks test

* Try fixing errors

* Fix oversight

* isort

* Fix problems

* isort

* Be more tolerant

* Fix naming and remove redundant code

* Fix imports

* Update deleteWithUndo

* Roll back

* Roll back more

* Update .gitignore

* Rollll back

* Rollllllll

* back

* Betterify

* Address feedback
2020-11-24 23:26:28 +01:00
Eric Duong
fae9fe5238
Fix doubled up slack hook (#2340)
* fix doubled up and change name

* Fix test

Co-authored-by: Tim Glaser <tim@glsr.nl>
2020-11-12 08:31:32 -05:00
Eric Duong
7a5bcab99e
Restore slack hook (#2186)
* add back hook

* add back hook

* filter event matcher

* create artificial event to query for actions

* fix test

* possible solution

* remove printer

* reformat

* remove test_event temp

* comment out tests

* comment out

* uncomment

* patch another

* reduce var

* fix timestamp
2020-11-05 14:40:30 +01:00
Marius Andra
75192cf725
Try to debug redis leak (#2102)
* add a bunch of ignore_result=True statements

* ignore more tasks

* ignore all other results

* ignore more results, add .delay setting with notice
2020-10-29 17:24:41 +01:00
Michael Matloka
c040601f49
Personal API keys and Zapier integration (#1281)
* Add missing migration

* Add generate_random_token() model util

* Move PublicTokenAuthentication to utils

* Make use of generate_random_token

* Add User.personal_access_token field

* Add PersonalAccessTokenAuthentication

* Fix PublicTokenAuthentication

* Fix migration and auth import

* Add personal_access_token to user API

* Update Setup.js

* Support trailing slash in API

* Improve PAT auth quality

* Add django-rest-hooks requirement

* Update settings.py for rest_hooks

* Fix django-rest-hooks requirement

* Bring back API routes with no double trailing slash

* Rename posthog.api.team to team_user

* Add API TODO

* Ad PAT auth with X-PAT HTTP header

* Replace User.personal_access_token with PersonalAPIKey model

* Fix PersonalAPIKey max_lengths

* Describe posthog.models.utils.generate_random_token better

* Add personal_api_key to API

* Add authenticate_header to PersonalAPIKeyAuthentication

* Add hook API endpoint

* Use django.utils.timezone in place of datetime.datetime

* Add Personal API Keys to Setup

* Sort personal_api_keys in ORM

* Add Action.on_perform()

* Remove requirements.txt comment

* Add a

* Add REST hook tasks

* Optimize PersonalAPIKeyAuthentication query

* Add a trailing slash version of /e endpoint

* Add team field to PersonalAPIKey model

* Add personal API key support to capture endpoint, get_cached_from_token

* Reject personal API keys from inactive users

* Add extra_properties_json field to /capture

* Improve PAK auth header regex

* Use custom hook model

* Deliver hooks

* Handle action.on_perform

* Consolidate userLogic in userLogic.tsx

* Update PersonalAPIKeys.js

* Make PersonalAPIKey foreign keys read-only

* Update requirements/dev.txt

* Make PersonalAPIKeys TSX

* Fix conflict

* Fix migration

* Fix minor mishaps

* Update and fix tests

* Use CharField of random 32 bits as hook.id

* Fix conflicting migrations

* Fix ValidationError in HookSerializer.validate_event

* Use query param in /api/event/actions ID filtering

* Rename endpoint `hook` to `hooks`

* Satisfy mypy

* Add tests

* Use DRF serialization in action_defined and annotation_created triggers

* Update migration leafs

* Make mypy ignore rest_hooks

* Update Django signal receiver names

* Update TS dependencies

* Revert "Update TS dependencies"

This reverts commit 7fc26fefcd.

* Add field user to Hook model

* Update migration leafs

* Fix circular import

* Fix some code

* Install git before running pip install in Dockerfiles

* Improve personal API keys UI

* Satisfy mypy

* Reword key label placeholder

* Add personal API key support to /api/user/*

Unfortunately these endpoints are still limited by CSRF protections at the moment, so not accessible outside PostHog itself.

* Improve PersonalAPIKeyAuthentication and add CsrfOrKeyViewMiddleware

* Run collectstatic before test

* Don't install dev dependencies in CI

* Update dependency installation order in CI

* Fix bug and describe PersonalAPIKeyAuthentication

* Fix CI issues

* Fix typing issues

* Fix more typing issues

* Use /api/personal_api_keys to list keys

* Move REST hooks (and therefore Zapier) to ee/

* Refactor personal API logic with kea-loaders

* Add "More about API authentication in PostHog docs."

* Update PersonalAPIKeys.tsx

* Use TestMixin

* Fix "Authentication" that should've been "Authorization"

* Add option to skip self.client.force_login in API tests

* Include team_id and user_id in personal API key serialization

* Update test_hooks.py

* Add personal API key tests

* Remove leftover

* Make ee.settings override posthog.settings

* Don't directly import from models

* Remove unused imports

* Fix mypy issues

* Fix HOOK_DELIVERER

* Use decorator for /api/user PAK auth

* Don't fire REST hook if user doesn't have "zapier" feature

* Import Optional

* Reword to "premium Zapier"

* Make mypy happy

* Fix test_delete_personal_api_key

* Fix misclick

* Fix and test /capture with personal API key

* Make mypy happy

* Remove extra_properties_json

* Resolve migrations

* Remove apt-utils

* Optimize and test PAK user.is_active filtering

* Replace DEBUG true with 1

* Remove unused instance_id

* Improve typing

* Fix deletion toast

* Refactor CopyToClipboard and use it in PAKs

* Use toast.success

* Update migrations

* Fix migration

* Fix migrations

* Complete merge

Co-authored-by: Tim Glaser <tim@glsr.nl>
2020-08-26 10:34:57 +02:00