diff --git a/app/models/plausible.rb b/app/models/plausible.rb index e24aac15..864ec2a0 100644 --- a/app/models/plausible.rb +++ b/app/models/plausible.rb @@ -4,13 +4,17 @@ class Plausible PLAUSIBLE_API_URL = 'https://plausible.io/api/v1' + def self.date_period + "2021-01-01,#{Time.zone.today.strftime('%Y-%m-%d')}" + end + # Fetches pageview counts from Plausible for a given document id. def self.pageviews(document_id) return 'X' if ENV['PLAUSIBLE_KEY'].nil? c = PlausibleApi::Client.new(Rails.configuration.pdc_discovery.plausible_site_id, ENV['PLAUSIBLE_KEY']) page = "/discovery/catalog/#{document_id}" - response = c.aggregate({ date: "2021-01-01,#{Time.zone.today.strftime('%Y-%m-%d')}", metrics: 'visitors,pageviews', filters: "event:page==#{page}" }) + response = c.aggregate({ date: date_period, metrics: 'visitors,pageviews', filters: "event:page==#{page}" }) response["pageviews"]["value"] rescue => e Rails.logger.error "PLAUSIBLE ERROR: (Pageviews for document: #{document_id}) #{e.message}" @@ -33,13 +37,14 @@ def self.downloads(document_id) # Plausible API breakdown API: https://plausible.io/docs/stats-api#get-apiv1statsbreakdown # Notice that the Plausible API uses "==" to filter: https://plausible.io/docs/stats-api#filtering + # Time periods: https://plausible.io/docs/stats-api#time-periods site_id = Rails.configuration.pdc_discovery.plausible_site_id property = "event:props:filename" page = "/discovery/catalog/#{document_id}" filters = "event:page==#{page}" metrics = "visitors,pageviews" - period = "12mo" - url = "#{PLAUSIBLE_API_URL}/stats/breakdown?site_id=#{site_id}&property=#{property}&filters=#{filters}&metrics=#{metrics}&period=#{period}" + period = "custom" + url = "#{PLAUSIBLE_API_URL}/stats/breakdown?site_id=#{site_id}&property=#{property}&filters=#{filters}&metrics=#{metrics}&period=#{period}&date=#{date_period}" authorization = "Bearer #{ENV['PLAUSIBLE_KEY']}" response = HTTParty.get(url, headers: { 'Authorization' => authorization }) total_downloads = 0 diff --git a/spec/models/plausible_spec.rb b/spec/models/plausible_spec.rb index 1c9b081c..9a2dbae7 100644 --- a/spec/models/plausible_spec.rb +++ b/spec/models/plausible_spec.rb @@ -6,7 +6,8 @@ RSpec.describe Plausible do before do plausible = "https://plausible.io/api/v1" - url = "#{plausible}/stats/breakdown?filters=event:page==/discovery/catalog/88163&metrics=visitors,pageviews&property=event:props:filename&site_id=pdc-discovery-staging.princeton.edu&period=12mo" + date_period = "2021-01-01,#{Time.zone.today.strftime('%Y-%m-%d')}" + url = "#{plausible}/stats/breakdown?filters=event:page==/discovery/catalog/88163&metrics=visitors,pageviews&property=event:props:filename&site_id=pdc-discovery-staging.princeton.edu&period=custom&date=#{date_period}" stub_request(:get, url) .with( headers: {