Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closes #236 add url matching exact or contains #267

Merged
merged 1 commit into from
Mar 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions frontend/src/ActionEdit.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ class ActionStep extends Component {
this.sendStep = this.sendStep.bind(this);
this.AutocaptureFields = this.AutocaptureFields.bind(this);
this.TypeSwitcher = this.TypeSwitcher.bind(this);
this.URLMatching = this.URLMatching.bind(this);
this.stop = this.stop.bind(this);

this.box = document.createElement('div');
Expand Down Expand Up @@ -154,7 +155,7 @@ class ActionStep extends Component {
}
this.setState({selection: this.state.selection}, () => this.sendStep(this.props.step))
}}
/> {props.label}</label>
/> {props.label} {props.extra_options}</label>
{props.item == 'selector' ?
<textarea className='form-control' onChange={onChange} value={this.props.step[props.item]} /> :
<input className='form-control' onChange={onChange} value={this.props.step[props.item]} />}
Expand Down Expand Up @@ -217,22 +218,38 @@ class ActionStep extends Component {
/>
</div>
}
URLMatching(step) {
return <div className='btn-group' style={{margin: '0 0 0 8px'}}>
<button
onClick={() => this.sendStep({...step, url_matching: 'contains'})}
type="button"
className={'btn btn-sm ' + ((!step.url_matching || step.url_matching == 'contains') ? 'btn-secondary' : 'btn-light')}>
contains
</button>
<button
onClick={() => this.sendStep({...step, url_matching: 'exact'})}
type="button"
className={'btn btn-sm ' + (step.url_matching == 'exact' ? 'btn-secondary' : 'btn-light')}>
exactly matches
</button>
</div>
}
render() {
let { step, isEditor } = this.props;
return <div style={{borderBottom: '1px solid rgba(0, 0, 0, 0.1)', padding: '8px 0'}}>
{(!isEditor || step.event == '$autocapture') && <button style={{marginTop: -3}} type="button" className="close pull-right" aria-label="Close" onClick={this.props.onDelete}>
<span aria-hidden="true">&times;</span>
</button>}
{!isEditor && <this.TypeSwitcher />}
<div>
<div style={{marginTop: 8}}>
{this.props.isEditor && <button type="button" className='btn btn-sm btn-secondary' style={{margin: '0 0 8px'}} onClick={() => this.start()}>
Inspect element
</button>}
{step.event == '$autocapture' && <this.AutocaptureFields />}
{(step.event == '$autocapture' || step.event == '$pageview') && <this.Option
item='url'
label='Only match if URL contains'
/>}
extra_options={<this.URLMatching {...step} />}
label='URL' />}
</div>
</div>
}
Expand Down Expand Up @@ -272,7 +289,7 @@ export class ActionEdit extends Component {
if(detail.detail == 'action-exists') this.setState({saved: false, error: 'action-exists', error_id: detail.id})
}
let steps = this.state.action.steps.map((step) => {
if(step.event == '$pageview') step.selection = ['url'];
if(step.event == '$pageview') step.selection = ['url', 'url_matching'];
if(step.event != '$pageview' && step.event != '$autocapture') step.selection = [];
if(!step.selection) return step;
let data = {};
Expand Down
12 changes: 6 additions & 6 deletions frontend/src/ActionEvents.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { Component } from 'react';
import api from './Api';
import moment from 'moment';
import { Link } from 'react-router-dom';
import { toParams, fromParams, colors } from './utils';
import { toParams, fromParams, colors, Loading } from './utils';
import PropTypes from 'prop-types';
import { EventDetails } from './Events';
import PropertyFilters from './PropertyFilter';
Expand All @@ -14,7 +14,8 @@ export class ActionEventsTable extends Component {

this.state = {
propertyFilters: fromParams(),
newEvents: []
newEvents: [],
loading: true
}
this.fetchEvents = this.fetchEvents.bind(this);
this.FilterLink = this.FilterLink.bind(this);
Expand All @@ -29,7 +30,7 @@ export class ActionEventsTable extends Component {
})
clearTimeout(this.poller)
api.get('api/event/actions/?' + params).then((events) => {
this.setState({events: events.results});
this.setState({events: events.results, loading: false});
this.poller = setTimeout(this.pollEvents, this.pollTimeout);
})
}
Expand Down Expand Up @@ -61,7 +62,7 @@ export class ActionEventsTable extends Component {
}
render() {
let params = ['$current_url']
let { propertyFilters, events } = this.state;
let { loading, propertyFilters, events } = this.state;
return (
<div class='events'>
<PropertyFilters propertyFilters={propertyFilters} onChange={(propertyFilters) => this.setState({propertyFilters}, this.fetchEvents)} />
Expand All @@ -73,9 +74,8 @@ export class ActionEventsTable extends Component {
<th scope="col">User</th>
<th scope="col">Date</th>
<th scope="col">Browser</th>
<th scope="col">City</th>
<th scope="col">Country</th>
</tr>
{loading && <Loading />}
{events && events.length == 0 && <tr><td colSpan="7">We didn't find any events matching any actions. You can either <Link to='/actions'>set up some actions</Link> or <Link to='/setup'>integrate PostHog in your app</Link>.</td></tr>}
{events && events.map((action, index) => [
index > 0
Expand Down
2 changes: 1 addition & 1 deletion posthog/api/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
class ActionStepSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ActionStep
fields = ['id', 'event', 'tag_name', 'text', 'href', 'selector', 'url', 'name']
fields = ['id', 'event', 'tag_name', 'text', 'href', 'selector', 'url', 'name', 'url_matching']


class ActionSerializer(serializers.HyperlinkedModelSerializer):
Expand Down
6 changes: 3 additions & 3 deletions posthog/api/event.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from posthog.models import Event, Team, Person, Element, Action, ActionStep, PersonDistinctId, ElementGroup
from posthog.models import Event, Team, Person, Element, Action, PersonDistinctId, ElementGroup
from rest_framework import request, response, serializers, viewsets # type: ignore
from rest_framework.decorators import action # type: ignore
from django.http import HttpResponse, JsonResponse
from django.db.models import Q, Count, QuerySet, query, Prefetch, F, Func, TextField, functions
from django.db.models import Q, Count, QuerySet, query, F, Func, functions
from django.forms.models import model_to_dict
from typing import Any, Union, Tuple, Dict, List
import re
Expand Down Expand Up @@ -93,7 +93,7 @@ def actions(self, request: request.Request) -> response.Response:
actions = Action.objects.filter(
deleted=False,
team=request.user.team_set.get()
).prefetch_related(Prefetch('steps', queryset=ActionStep.objects.all()))
)
matches = []
for action in actions:
events = Event.objects.filter_by_action(action)
Expand Down
18 changes: 18 additions & 0 deletions posthog/migrations/0028_actionstep_url_matching.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.0.3 on 2020-03-04 01:20

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('posthog', '0027_move_elements_to_group'),
]

operations = [
migrations.AddField(
model_name='actionstep',
name='url_matching',
field=models.CharField(choices=[('exact', 'exact'), ('contains', 'contains')], default='contains', max_length=400),
),
]
11 changes: 10 additions & 1 deletion posthog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,9 @@ def filter_by_element(self, action_step):
def filter_by_url(self, action_step):
if not action_step.url:
return {}
return {'properties__$current_url': action_step.url}
if action_step.url_matching == ActionStep.EXACT:
return {'properties__$current_url': action_step.url}
return {'properties__$current_url__icontains': action_step.url}

def filter_by_event(self, action_step):
if not action_step.event:
Expand Down Expand Up @@ -323,12 +325,19 @@ def __str__(self):
return self.name

class ActionStep(models.Model):
EXACT = 'exact'
CONTAINS = 'contains'
URL_MATCHING = [
(EXACT, EXACT),
(CONTAINS, CONTAINS),
]
action: models.ForeignKey = models.ForeignKey(Action, related_name='steps', on_delete=models.CASCADE)
tag_name: models.CharField = models.CharField(max_length=400, null=True, blank=True)
text: models.CharField = models.CharField(max_length=400, null=True, blank=True)
href: models.CharField = models.CharField(max_length=400, null=True, blank=True)
selector: models.CharField = models.CharField(max_length=400, null=True, blank=True)
url: models.CharField = models.CharField(max_length=400, null=True, blank=True)
url_matching: models.CharField = models.CharField(max_length=400, choices=URL_MATCHING, default=CONTAINS)
name: models.CharField = models.CharField(max_length=400, null=True, blank=True)
event: models.CharField = models.CharField(max_length=400, null=True, blank=True)

Expand Down
13 changes: 9 additions & 4 deletions posthog/test/test_event_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,22 +103,27 @@ def test_attributes(self):
self.assertEqual(len(events), 1)
self.assertEqual(events[0], event1)

def test_filter_events_by_url(self):
def test_filter_events_by_url_exact(self):
Person.objects.create(distinct_ids=['whatever'], team=self.team)
event1 = Event.objects.create(team=self.team, distinct_id='whatever')

event2 = Event.objects.create(team=self.team, distinct_id='whatever', properties={'$current_url': 'https://posthog.com/feedback/123'}, elements=[
Element(tag_name='div', text='some_other_text', nth_child=0, nth_of_type=0, order=1)
])

action1 = Action.objects.create(team=self.team)
ActionStep.objects.create(action=action1, url='https://posthog.com/feedback/123')
ActionStep.objects.create(action=action1, url='https://posthog.com/feedback/123', url_matching=ActionStep.EXACT)
ActionStep.objects.create(action=action1, href='/a-url-2')

action2 = Action.objects.create(team=self.team)
ActionStep.objects.create(action=action2, url='123', url_matching=ActionStep.CONTAINS)

events = Event.objects.filter_by_action(action1)
self.assertEqual(events[0], event2)
self.assertEqual(len(events), 1)

events = Event.objects.filter_by_action(action2)
self.assertEqual(events[0], event2)
self.assertEqual(len(events), 1)

def test_person_with_different_distinct_id(self):
action_watch_movie = Action.objects.create(team=self.team, name='watched movie')
ActionStep.objects.create(action=action_watch_movie, tag_name='a', href='/movie')
Expand Down