Skip to content

Commit 3e98864

Browse files
authored
feat: add support for workspace context in charts (#649)
1 parent d90e148 commit 3e98864

23 files changed

+701
-360
lines changed

app/services/forest_liana/ability/permission/smart_action_checker.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def match_conditions(condition_name)
4949
begin
5050
attributes = @parameters[:data][:attributes]
5151
records = FiltersParser.new(
52-
@smart_action[condition_name][0]['filter'].to_json,
52+
@smart_action[condition_name][0]['filter'],
5353
@collection,
5454
@parameters[:timezone],
5555
@parameters

app/services/forest_liana/filters_parser.rb

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ class FiltersParser
33
AGGREGATOR_OPERATOR = %w(and or)
44

55
def initialize(filters, resource, timezone, params = nil)
6-
@filters = filters.instance_of?(ActionController::Parameters) ? filters.to_h : JSON.parse(filters)
6+
@filters = filters
77
@params = params
88
@resource = resource
99
@operator_date_parser = OperatorDateIntervalParser.new(timezone)
@@ -87,10 +87,6 @@ def parse_condition_without_smart_field(condition)
8787
value = condition['value']
8888
field_name = condition['field']
8989

90-
if value.is_a?(String) && value.start_with?('{{')
91-
value = @params[:contextVariables][value.gsub(/[{}]/, '')]
92-
end
93-
9490
if @operator_date_parser.is_date_operator?(operator)
9591
condition = @operator_date_parser.get_date_filter(operator, value)
9692
return "#{parse_field_name(field_name)} #{condition}"

app/services/forest_liana/leaderboard_stat_getter.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def perform
2727
end
2828

2929
def get_scoped_model(model, forest_user, timezone)
30-
scope_filters = ForestLiana::ScopeManager.get_scope_for_user(forest_user, model.name, as_string: true)
30+
scope_filters = ForestLiana::ScopeManager.get_scope(model.name, forest_user)
3131

3232
return model.unscoped if scope_filters.blank?
3333

app/services/forest_liana/line_stat_getter.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def get_format
2525
def perform
2626
value = get_resource()
2727

28-
filters = ForestLiana::ScopeManager.append_scope_for_user(@params[:filter], @user, @resource.name)
28+
filters = ForestLiana::ScopeManager.append_scope_for_user(@params[:filter], @user, @resource.name, @params['contextVariables'])
2929

3030
unless filters.blank?
3131
value = FiltersParser.new(filters, @resource, @params[:timezone], @params).apply_filters

app/services/forest_liana/pie_stat_getter.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def perform
77
timezone_offset = @params[:timezone].to_i
88
resource = optimize_record_loading(@resource, get_resource)
99

10-
filters = ForestLiana::ScopeManager.append_scope_for_user(@params[:filter], @user, @resource.name)
10+
filters = ForestLiana::ScopeManager.append_scope_for_user(@params[:filter], @user, @resource.name, @params['contextVariables'])
1111

1212
unless filters.blank?
1313
resource = FiltersParser.new(filters, resource, @params[:timezone], @params).apply_filters
Lines changed: 34 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
module ForestLiana
22
class ScopeManager
3-
@@scopes_cache = Hash.new
4-
# 5 minutes exipration cache
3+
# 5 minutes expiration cache
54
@@scope_cache_expiration_delta = 300
65

7-
def self.apply_scopes_on_records(records, forest_user, collection_name, timezone)
8-
scope_filters = get_scope_for_user(forest_user, collection_name, as_string: true)
6+
def self.apply_scopes_on_records(records, user, collection_name, timezone)
7+
scope_filters = get_scope(collection_name, user)
98

109
return records if scope_filters.blank?
1110

1211
FiltersParser.new(scope_filters, records, timezone).apply_filters
1312
end
1413

15-
def self.append_scope_for_user(existing_filter, user, collection_name)
16-
existing_filter = existing_filter.to_json if existing_filter.is_a?(ActionController::Parameters)
17-
scope_filter = get_scope_for_user(user, collection_name, as_string: true)
14+
def self.append_scope_for_user(existing_filter, user, collection_name, request_context_variables = nil)
15+
existing_filter = inject_context_variables(existing_filter, user, request_context_variables) if existing_filter
16+
scope_filter = get_scope(collection_name, user, request_context_variables)
1817
filters = [existing_filter, scope_filter].compact
1918

2019
case filters.length
@@ -23,80 +22,57 @@ def self.append_scope_for_user(existing_filter, user, collection_name)
2322
when 1
2423
filters[0]
2524
else
26-
"{\"aggregator\":\"and\",\"conditions\":[#{existing_filter},#{scope_filter}]}"
25+
{ 'aggregator' => 'and', 'conditions' => [existing_filter, scope_filter] }
2726
end
2827
end
2928

30-
def self.get_scope_for_user(user, collection_name, as_string: false)
31-
raise 'Missing required rendering_id' unless user['rendering_id']
32-
raise 'Missing required collection_name' unless collection_name
29+
def self.get_scope(collection_name, user, request_context_variables = nil)
30+
retrieve = fetch_scopes(user['rendering_id'])
31+
scope = retrieve['scopes'][collection_name]
3332

34-
collection_scope = get_collection_scope(user['rendering_id'], collection_name)
33+
return nil if scope.nil?
3534

36-
return nil unless collection_scope
37-
38-
filters = format_dynamic_values(user['id'], collection_scope)
39-
40-
as_string && filters ? JSON.generate(filters) : filters
35+
inject_context_variables(scope, user, request_context_variables)
4136
end
4237

43-
def self.get_collection_scope(rendering_id, collection_name)
44-
if !@@scopes_cache[rendering_id]
45-
# when scope cache is unset wait for the refresh
46-
refresh_scopes_cache(rendering_id)
47-
elsif has_cache_expired?(rendering_id)
48-
# when cache expired refresh the scopes without waiting for it
49-
Thread.new { refresh_scopes_cache(rendering_id) }
50-
end
38+
def self.inject_context_variables(filter, user, request_context_variables = nil)
39+
filter = JSON.parse(filter) if filter.is_a? String
5140

52-
@@scopes_cache[rendering_id][:scopes][collection_name].deep_dup
53-
end
41+
retrieve = fetch_scopes(user['rendering_id'])
42+
context_variables = Utils::ContextVariables.new(retrieve['team'], user, request_context_variables)
5443

55-
def self.has_cache_expired?(rendering_id)
56-
rendering_scopes = @@scopes_cache[rendering_id]
57-
return true unless rendering_scopes
58-
59-
second_since_last_fetch = Time.now - rendering_scopes[:fetched_at]
60-
second_since_last_fetch >= @@scope_cache_expiration_delta
44+
Utils::ContextVariablesInjector.inject_context_in_filter(filter, context_variables)
6145
end
6246

63-
def self.refresh_scopes_cache(rendering_id)
64-
scopes = fetch_scopes(rendering_id)
65-
@@scopes_cache[rendering_id] = {
66-
:fetched_at => Time.now,
67-
:scopes => scopes
68-
}
47+
def self.invalidate_scope_cache(rendering_id)
48+
Rails.cache.delete('forest.scopes.' + rendering_id.to_s)
6949
end
7050

7151
def self.fetch_scopes(rendering_id)
72-
query_parameters = { 'renderingId' => rendering_id }
73-
response = ForestLiana::ForestApiRequester.get('/liana/scopes', query: query_parameters)
52+
response = ForestLiana::ForestApiRequester.get("/liana/v4/permissions/renderings/#{rendering_id}")
7453

7554
if response.is_a?(Net::HTTPOK)
76-
JSON.parse(response.body)
55+
Rails.cache.fetch('forest.scopes.' + rendering_id.to_s, expires_in: @@scope_cache_expiration_delta) do
56+
data = {}
57+
parse_response = JSON.parse(response.body)
58+
59+
data['scopes'] = decode_scope(parse_response['collections'])
60+
data['team'] = parse_response['team']
61+
62+
data
63+
end
7764
else
7865
raise 'Unable to fetch scopes'
7966
end
8067
end
8168

82-
def self.format_dynamic_values(user_id, collection_scope)
83-
filter = collection_scope.dig('scope', 'filter')
84-
return nil unless filter
85-
86-
dynamic_scopes_values = collection_scope.dig('scope', 'dynamicScopesValues')
87-
88-
# Only goes one level deep as required for now
89-
filter['conditions'].map do |condition|
90-
value = condition['value']
91-
if value.is_a?(String) && value.start_with?('$currentUser')
92-
condition['value'] = dynamic_scopes_values.dig('users', user_id, value)
93-
end
69+
def self.decode_scope(raw_scopes)
70+
scopes = {}
71+
raw_scopes.each do |collection_name, value|
72+
scopes[collection_name] = value['scope'] unless value['scope'].nil?
9473
end
95-
filter
96-
end
9774

98-
def self.invalidate_scope_cache(rendering_id)
99-
@@scopes_cache.delete(rendering_id)
75+
scopes
10076
end
10177
end
10278
end
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
module ForestLiana
2+
module Utils
3+
class ContextVariables
4+
attr_reader :team, :user, :request_context_variables
5+
6+
USER_VALUE_PREFIX = 'currentUser.'.freeze
7+
8+
USER_VALUE_TAG_PREFIX = 'currentUser.tags.'.freeze
9+
10+
USER_VALUE_TEAM_PREFIX = 'currentUser.team.'.freeze
11+
12+
def initialize(team, user, request_context_variables = nil)
13+
@team = team
14+
@user = user
15+
@request_context_variables = request_context_variables
16+
end
17+
18+
def get_value(context_variable_key)
19+
return get_current_user_data(context_variable_key) if context_variable_key.start_with?(USER_VALUE_PREFIX)
20+
21+
request_context_variables[context_variable_key] if request_context_variables
22+
end
23+
24+
private
25+
26+
def get_current_user_data(context_variable_key)
27+
if context_variable_key.start_with?(USER_VALUE_TEAM_PREFIX)
28+
return team[context_variable_key[USER_VALUE_TEAM_PREFIX.length..]]
29+
end
30+
31+
if context_variable_key.start_with?(USER_VALUE_TAG_PREFIX)
32+
user['tags'].each do |tag|
33+
return tag[context_variable_key[USER_VALUE_TAG_PREFIX.length..]] if tag.key?(context_variable_key[USER_VALUE_TAG_PREFIX.length..])
34+
end
35+
end
36+
37+
user[context_variable_key[USER_VALUE_PREFIX.length..]]
38+
end
39+
end
40+
end
41+
end
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
module ForestLiana
2+
module Utils
3+
class ContextVariablesInjector
4+
5+
def self.inject_context_in_value(value, context_variables)
6+
inject_context_in_value_custom(value) do |context_variable_key|
7+
context_variables.get_value(context_variable_key).to_s
8+
end
9+
end
10+
11+
def self.inject_context_in_value_custom(value)
12+
return value unless value.is_a?(String)
13+
14+
value_with_context_variables_injected = value
15+
regex = /{{([^}]+)}}/
16+
encountered_variables = []
17+
18+
while (match = regex.match(value_with_context_variables_injected))
19+
context_variable_key = match[1]
20+
21+
unless encountered_variables.include?(context_variable_key)
22+
value_with_context_variables_injected.gsub!(
23+
/{{#{context_variable_key}}}/,
24+
yield(context_variable_key)
25+
)
26+
end
27+
28+
encountered_variables.push(context_variable_key)
29+
end
30+
31+
value_with_context_variables_injected
32+
end
33+
34+
def self.inject_context_in_filter(filter, context_variables)
35+
return nil unless filter
36+
37+
if filter.key? 'aggregator'
38+
return {
39+
'aggregator' => filter['aggregator'],
40+
'conditions' => filter['conditions'].map { |condition| inject_context_in_filter(condition, context_variables) }
41+
}
42+
end
43+
44+
{
45+
'field' => filter['field'],
46+
'operator' => filter['operator'],
47+
'value' => inject_context_in_value(filter['value'], context_variables)
48+
}
49+
50+
end
51+
end
52+
end
53+
end

app/services/forest_liana/value_stat_getter.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ def perform
66
return if @params[:aggregator].blank?
77
resource = optimize_record_loading(@resource, get_resource)
88

9-
filters = ForestLiana::ScopeManager.append_scope_for_user(@params[:filter], @user, @resource.name)
9+
filters = ForestLiana::ScopeManager.append_scope_for_user(@params[:filter], @user, @resource.name, @params['contextVariables'])
1010

1111
unless filters.blank?
1212
filter_parser = FiltersParser.new(filters, resource, @params[:timezone], @params)

spec/requests/actions_controller_spec.rb

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22

33
describe 'Requesting Actions routes', :type => :request do
44
let(:rendering_id) { 13 }
5-
let(:scope_filters) { nil }
5+
let(:scope_filters) { {'scopes' => {}, 'team' => {'id' => '1', 'name' => 'Operations'}} }
66

77
before(:each) do
88
allow(ForestLiana::IpWhitelist).to receive(:is_ip_whitelist_retrieved) { true }
99
allow(ForestLiana::IpWhitelist).to receive(:is_ip_valid) { true }
1010
Island.create(id: 1, name: 'Corsica')
1111

1212
ForestLiana::ScopeManager.invalidate_scope_cache(rendering_id)
13-
allow(ForestLiana::ScopeManager).to receive(:get_scope_for_user).and_return(scope_filters)
13+
allow(ForestLiana::ScopeManager).to receive(:fetch_scopes).and_return(scope_filters)
1414
end
1515

1616
after(:each) do
@@ -291,7 +291,21 @@
291291

292292
describe 'with scopes' do
293293
describe 'when record is in scope' do
294-
let(:scope_filters) { JSON.generate({ field: 'name', operator: 'equal', value: 'Corsica' }) }
294+
let(:scope_filters) {
295+
{
296+
'scopes' =>
297+
{
298+
'Island' => {
299+
'aggregator' => 'and',
300+
'conditions' => [{'field' => 'name', 'operator' => 'equal', 'value' => 'Corsica'}]
301+
}
302+
},
303+
'team' => {
304+
'id' => 43,
305+
'name' => 'Operations'
306+
}
307+
}
308+
}
295309

296310
it 'should respond 200 and perform the action' do
297311
post '/forest/actions/test', params: JSON.dump(params), headers: headers
@@ -301,7 +315,21 @@
301315
end
302316

303317
describe 'when record is out of scope' do
304-
let(:scope_filters) { JSON.generate({ field: 'name', operator: 'equal', value: 'Ré' }) }
318+
let(:scope_filters) {
319+
{
320+
'scopes' =>
321+
{
322+
'Island' => {
323+
'aggregator' => 'and',
324+
'conditions' => [{'field' => 'name', 'operator' => 'equal', 'value' => 'Ré'}]
325+
}
326+
},
327+
'team' => {
328+
'id' => 43,
329+
'name' => 'Operations'
330+
}
331+
}
332+
}
305333

306334
it 'should respond 400 and NOT perform the action' do
307335
post '/forest/actions/test', params: JSON.dump(params), headers: headers

0 commit comments

Comments
 (0)