repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
rajat2502/WikiEduDashboard
spec/features/term_recap_emails_spec.rb
# frozen_string_literal: true require 'rails_helper' describe 'term recap emails page', type: :feature do let(:admin) { create(:admin, email: '<EMAIL>') } let(:course) { create(:course, article_count: 2) } let(:active_course) do create(:course, slug: 'active', article_count: 10, user_count: 1, character_sum: 10_000) end before do course.campaigns << Campaign.first active_course.campaigns << Campaign.first JoinCourse.new(course: course, user: admin, role: CoursesUsers::Roles::INSTRUCTOR_ROLE) JoinCourse.new(course: active_course, user: admin, role: CoursesUsers::Roles::INSTRUCTOR_ROLE) login_as admin end it 'lets admins send term recap emails' do visit '/mass_email/term_recap' expect(TermRecapMailer).to receive(:email).and_call_original expect(TermRecapMailer).to receive(:basic_email).and_call_original select(Campaign.first.title, from: 'campaign') click_button 'Send recap emails' expect(page).to have_content('Emails are going out') end end
rajat2502/WikiEduDashboard
lib/importers/article_importer.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/replica" #= Imports articles from Wikipedia into the dashboard database class ArticleImporter def initialize(wiki) @wiki = wiki @articles = [] end def import_articles(ids) article_ids = ids.map { |id| { 'mw_page_id' => id } } articles_data = [] article_ids.each_slice(40) do |some_article_ids| some_article_data = Replica.new(@wiki).get_existing_articles_by_id some_article_ids next if some_article_data.nil? articles_data += some_article_data end return if articles_data.empty? import_articles_from_replica_data(articles_data) end def import_articles_by_title(titles) titles.each_slice(40) do |some_article_titles| query = { prop: 'info', titles: some_article_titles } response = WikiApi.new(@wiki).query(query) results = response&.data next if results.blank? results = results['pages'] next if results.blank? import_articles_from_title_query(results) end end private def import_articles_from_replica_data(articles_data) articles = [] articles_data.each do |article_data| articles << Article.new(mw_page_id: article_data['page_id'], title: article_data['page_title'], namespace: article_data['page_namespace'], wiki_id: @wiki.id) end Article.import articles, on_duplicate_key_ignore: true end def import_articles_from_title_query(results) articles = [] results.each_value do |page_data| next if page_data['missing'] articles << Article.new(mw_page_id: page_data['pageid'].to_i, title: page_data['title'].tr(' ', '_'), wiki_id: @wiki.id, namespace: page_data['ns'].to_i) end Article.import articles, on_duplicate_key_ignore: true end end
rajat2502/WikiEduDashboard
app/views/courses/_blocks.json.jbuilder
<filename>app/views/courses/_blocks.json.jbuilder # frozen_string_literal: true user ||= current_user json.blocks blocks.each do |block| json.partial! 'courses/block', block: block, course: course, user: user end
rajat2502/WikiEduDashboard
spec/lib/tickets/ticket_notification_emails_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/tickets/ticket_notification_emails" describe TicketNotificationEmails do let(:owner) { create(:admin, email: '<EMAIL>') } let(:course) { create(:course) } let(:ticket) do TicketDispenser::Dispenser.call(content: 'Help!', project_id: course.id, owner_id: owner.id, sender_id: nil, details: {}) end let(:ticket_two) do TicketDispenser::Dispenser.call(content: 'Help again!', project_id: nil, owner_id: nil, sender_id: nil, details: {}) end context 'when there is 1 open ticket' do before do ticket.update(status: TicketDispenser::Ticket::Statuses::OPEN) end it 'emails the owner of the ticket' do expect { described_class.notify }.to change { ActionMailer::Base.deliveries.count }.by(1) last_email = ActionMailer::Base.deliveries.last expect(last_email.subject).to include('there is 1 open ticket') end end context 'when there is an unassigned ticket' do before do ticket.update(status: TicketDispenser::Ticket::Statuses::OPEN) ticket_two.update(status: TicketDispenser::Ticket::Statuses::OPEN) end it 'includes the unassigned ticket in the count' do expect { described_class.notify }.to change { ActionMailer::Base.deliveries.count }.by(1) last_email = ActionMailer::Base.deliveries.last expect(last_email.subject).to include('there are 2 open tickets') end end context 'when there are no open tickets' do before do ticket.update(status: TicketDispenser::Ticket::Statuses::RESOLVED) end it 'emails the ticket owner(s)' do expect { described_class.notify }.to change { ActionMailer::Base.deliveries.count }.by(0) end end end
rajat2502/WikiEduDashboard
spec/lib/duplicate_article_deleter_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/duplicate_article_deleter" describe DuplicateArticleDeleter do describe '.resolve_duplicates' do let(:en_wiki) { Wiki.get_or_create(language: 'en', project: 'wikipedia') } let(:deleted_article) do create(:article, title: 'Columbian_exchange', namespace: 0, mw_page_id: 5589352, created_at: '2017-08-23', wiki: en_wiki, deleted: true) end let(:extant_article) do create(:article, title: 'Columbian_exchange', namespace: 0, mw_page_id: 622746, created_at: '2017-12-08', wiki: en_wiki, deleted: false) end let(:duplicate_deleted_article) do create(:article, title: 'Columbian_exchange', namespace: 0, mw_page_id: 622746, created_at: '2017-12-08', wiki: en_wiki, deleted: true) end it 'marks one deleted when there are two ids for one page' do first = create(:article, id: 2262715, title: 'Kostanay', namespace: 0, created_at: 1.day.from_now) second = create(:article, id: 46349871, title: 'Kostanay', namespace: 0, created_at: 1.day.ago) described_class.new.resolve_duplicates([first]) undeleted = Article.where( title: 'Kostanay', namespace: 0, deleted: false ) expect(undeleted.count).to eq(1) expect(undeleted.first.id).to eq(second.id) end it 'does not mark any deleted when articles different in title case' do first = create(:article, id: 123, title: 'Communicative_language_teaching', namespace: 0) second = create(:article, id: 456, title: 'Communicative_Language_Teaching', namespace: 0) described_class.new.resolve_duplicates([first, second]) expect(first.reload.deleted).to eq(false) expect(second.reload.deleted).to eq(false) end it 'marks does not end up leaving both articles deleted' do described_class.new.resolve_duplicates([deleted_article, extant_article]) expect(deleted_article.reload.deleted).to eq(true) expect(extant_article.reload.deleted).to eq(false) end it 'does not error if all articles are already deleted' do described_class.new.resolve_duplicates([deleted_article, duplicate_deleted_article]) expect(deleted_article.reload.deleted).to eq(true) expect(duplicate_deleted_article.reload.deleted).to eq(true) end end end
rajat2502/WikiEduDashboard
spec/features/assigned_exercise_spec.rb
# frozen_string_literal: true require 'rails_helper' describe 'students with assigned exercise modules', type: :feature, js: true do let(:student) { create(:user) } let(:course) { create(:course, weekdays: '1111111') } let(:week) { create(:week, course: course) } let(:evaluate_exercise_id) { 34 } let(:presentation_exercise_id) { 40 } let(:assigned_ids) { [evaluate_exercise_id] } before do ActionController::Base.allow_forgery_protection = true TrainingModule.load_all create(:block, week: week, training_module_ids: assigned_ids) course.campaigns << Campaign.first course.users << student create(:training_modules_users, user: student, training_module_id: evaluate_exercise_id, completed_at: Time.zone.now) login_as student end after do ActionController::Base.allow_forgery_protection = false end it 'can go mark a module complete, then mark it incomplete' do visit "/courses/#{course.slug}" expect(page).to have_content 'Upcoming Exercises' click_button 'Mark Complete' expect(page).not_to have_content 'Upcoming Exercises' click_link 'Resources' click_button 'Mark Incomplete' click_link 'Home' expect(page).to have_content 'Evaluate Wikipedia' end context 'when there are multiple incomplete exercises' do let(:assigned_ids) { [evaluate_exercise_id, presentation_exercise_id] } it 'see the next incomplete exercise after complete one' do visit "/courses/#{course.slug}" within '.my-exercises' do expect(page).to have_content 'Upcoming Exercises' expect(page).to have_content 'Evaluate Wikipedia' expect(page).not_to have_content 'In-class presentation' click_button 'Mark Complete' expect(page).to have_content 'Upcoming Exercises' expect(page).not_to have_content 'Evaluate Wikipedia' expect(page).to have_content 'In-class presentation' end end end end
rajat2502/WikiEduDashboard
spec/models/basic_course_spec.rb
# frozen_string_literal: true require 'rails_helper' describe BasicCourse do let(:flags) { nil } let(:subject) { create(:basic_course, flags: flags) } describe '#assignment_edits_enabled?' do it 'should return true by default' do expect(subject.assignment_edits_enabled?).to eq(true) end context 'with edit_settings flag' do let(:flags) do { 'edit_settings' => { 'assignment_edits_enabled' => false } } end it 'should return the value of the set flag' do expect(subject.assignment_edits_enabled?).to eq(false) end end end end
rajat2502/WikiEduDashboard
lib/analytics/campaign_csv_builder.rb
# frozen_string_literal: true require 'csv' require_dependency "#{Rails.root}/lib/analytics/course_csv_builder" require_dependency "#{Rails.root}/lib/analytics/course_articles_csv_builder" require_dependency "#{Rails.root}/lib/analytics/course_revisions_csv_builder" class CampaignCsvBuilder def initialize(campaign) @campaign = campaign || AllCourses end def courses_to_csv csv_data = [CourseCsvBuilder::CSV_HEADERS] @campaign.courses.each do |course| csv_data << CourseCsvBuilder.new(course).row end CSV.generate { |csv| csv_data.uniq.each { |line| csv << line } } end def articles_to_csv csv_data = [CourseArticlesCsvBuilder::CSV_HEADERS + ['course_slug']] @campaign.courses.each do |course| CourseArticlesCsvBuilder.new(course).article_rows.each do |row| row_with_slug = row + [course.slug] csv_data << row_with_slug end end CSV.generate { |csv| csv_data.each { |line| csv << line } } end def revisions_to_csv csv_data = [CourseRevisionsCsvBuilder::CSV_HEADERS + ['course_slug']] @campaign.courses.each do |course| CourseRevisionsCsvBuilder.new(course).revisions_rows.each do |row| row_with_slug = row + [course.slug] csv_data << row_with_slug end end CSV.generate { |csv| csv_data.each { |line| csv << line } } end class AllCourses def self.courses Course.all end end end
rajat2502/WikiEduDashboard
spec/lib/data_cycle/daily_update_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/data_cycle/daily_update" describe DailyUpdate do before do course = create(:course, start: '2015-03-20', end: 1.month.from_now, flags: { salesforce_id: 'a0f1a9063a1Wyad' }) course.campaigns << Campaign.first old_course = create(:course, slug: 'old', start: '2015-03-20', end: '2015-04-20', flags: { salesforce_id: 'b0f1a9063a1Wyad' }) old_course.campaigns << Campaign.first end describe 'on initialization' do it 'calls lots of update routines' do expect(UserImporter).to receive(:update_users) expect(AssignedArticleImporter).to receive(:import_articles_for_assignments) expect(ArticlesCoursesCleaner).to receive(:rebuild_articles_courses) expect(RatingImporter).to receive(:update_all_ratings) expect(ArticleStatusManager).to receive(:update_article_status) expect(UploadImporter).to receive(:find_deleted_files) expect_any_instance_of(OverdueTrainingAlertManager).to receive(:create_alerts) expect(PushCourseToSalesforce).to receive(:new) expect(UpdateCourseFromSalesforce).to receive(:new) expect(Raven).to receive(:capture_message).and_call_original update = described_class.new sentry_logs = update.instance_variable_get(:@sentry_logs) expect(sentry_logs.grep(/Pushing course data to Salesforce/).any?).to eq(true) end it 'reports logs to sentry even when it errors out' do allow(Raven).to receive(:capture_message) allow(UploadImporter).to receive(:find_deleted_files).and_raise(StandardError) expect { described_class.new }.to raise_error(StandardError) expect(Raven).to have_received(:capture_message) end end context 'when a pid file is present' do it 'deletes the pid file for a non-running process' do allow_any_instance_of(described_class).to receive(:create_pid_file) allow_any_instance_of(described_class).to receive(:run_update) File.open('tmp/batch_update_daily.pid', 'w') { |f| f.puts '123456789' } described_class.new expect(File.exist?('tmp/batch_update_daily.pid')).to eq(false) end end end
rajat2502/WikiEduDashboard
app/models/training_module.rb
# frozen_string_literal: true # == Schema Information # # Table name: training_modules # # id :bigint not null, primary key # name :string(255) # estimated_ttc :string(255) # wiki_page :string(255) # slug :string(255) # slide_slugs :text(65535) # description :text(65535) # translations :text(16777215) # created_at :datetime not null # updated_at :datetime not null # kind :integer default(0) # require_dependency "#{Rails.root}/lib/training/training_base" #= Class representing an individual training module class TrainingModule < ApplicationRecord attr_accessor :status serialize :slide_slugs, Array serialize :translations, Hash validates_uniqueness_of :slug, case_sensitive: false module Kinds TRAINING = 0 EXERCISE = 1 DISCUSSION = 2 end def self.path_to_yaml "#{base_path}/modules/*.yml" end def self.wiki_base_page ENV['training_modules_wiki_page'] end def self.trim_id_from_filename false end def self.load TrainingBase.load(content_class: self) end def self.base_path TrainingBase.base_path end def self.load_all TrainingBase.load_all end # This reloads all the library and module content, but only updates the slides # for the module with the given slug. def self.reload_module(slug:) # First reload the libraries and modules so we have the new list of slugs # and can load slides for brand-new modules. TrainingLibrary.load TrainingModule.load # Reload the requested module's slides training_module = TrainingModule.find_by(slug: slug) raise ModuleNotFound, "No module #{slug} found!" unless training_module TrainingSlide.load(slug_list: training_module.slide_slugs) end def self.inflate(content, slug, wiki_page = nil) training_module = TrainingModule.find_or_initialize_by(id: content['id']) training_module.slug = slug training_module.name = content['name'] || content[:name] training_module.description = content['description'] || content[:description] training_module.estimated_ttc = content['estimated_ttc'] training_module.translations = content['translations'] training_module.wiki_page = wiki_page training_module.slide_slugs = content['slides'].pluck('slug') training_module.kind = training_module_kind(content['kind']) validate_and_save(training_module, slug) training_module rescue StandardError, TypeError => e # rubocop:disable Lint/ShadowedException puts "There's a problem with file '#{slug}'" if Rails.env.development? raise e end def self.validate_and_save(training_module, slug) valid = training_module.valid? if training_module.errors[:slug].any? raise TrainingBase::DuplicateSlugError, "Duplicate TrainingModule slug detected: #{slug}" end training_module.save if valid end def self.training_module_kind(value) case value when 'exercise' TrainingModule::Kinds::EXERCISE when 'discussion' TrainingModule::Kinds::DISCUSSION else TrainingModule::Kinds::TRAINING end end #################### # Instance methods # #################### def training? kind == TrainingModule::Kinds::TRAINING end def exercise? kind == TrainingModule::Kinds::EXERCISE end def discussion? kind == TrainingModule::Kinds::DISCUSSION end def slides return @sorted_slides if @sorted_slides.present? selected_slides = TrainingSlide.where(slug: slide_slugs) @sorted_slides = selected_slides.sort do |a, b| slide_slugs.index(a.slug) <=> slide_slugs.index(b.slug) end end def translated_name translated(:name) || name end def translated_description translated(:description) || description end def translated(key) translations.dig(I18n.locale.to_s, key) end class ModuleNotFound < StandardError; end end
rajat2502/WikiEduDashboard
app/controllers/articles_controller.rb
# frozen_string_literal: true class ArticlesController < ApplicationController respond_to :json before_action :set_course, except: :article_data # returns revision score data for vega graphs def article_data @article = Article.find(params[:article_id]) end # returns details about how an article changed during a course def details @article = Article.find(params[:article_id]) revisions = @course.tracked_revisions.where(article_id: @article.id).order(:date) @first_revision = revisions.first @last_revision = revisions.last editor_ids = revisions.pluck(:user_id).uniq @editors = User.where(id: editor_ids) end # updates the tracked status of an article def update_tracked_status article_course = @course.articles_courses.find_by(article_id: params[:article_id]) article_course.update(tracked: params[:tracked]) render json: {}, status: :ok end private def set_course @course = Course.find(params[:course_id]) end end
rajat2502/WikiEduDashboard
lib/alerts/unsubmitted_course_alert_manager.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true class UnsubmittedCourseAlertManager def create_alerts unsubmitted_recently_started_courses.each do |course| next if Alert.exists?(course_id: course.id, type: 'UnsubmittedCourseAlert') alert = Alert.create(type: 'UnsubmittedCourseAlert', course: course, user: course.instructors.first) alert.send_email end end private TIME_WINDOW = 3.days def unsubmitted_recently_started_courses ClassroomProgramCourse.unsubmitted .where('courses.created_at <= ?', TIME_WINDOW.ago) .where(start: TIME_WINDOW.ago...TIME_WINDOW.from_now) end end
rajat2502/WikiEduDashboard
lib/importers/category_importer.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true require_dependency "#{Rails.root}/lib/replica" require_dependency "#{Rails.root}/lib/importers/revision_score_importer" require_dependency "#{Rails.root}/lib/importers/article_importer" require_dependency "#{Rails.root}/lib/importers/average_views_importer" require_dependency "#{Rails.root}/lib/wiki_api" #= Imports articles for a category, along with view data and revision scores class CategoryImporter ################ # Entry points # ################ def initialize(wiki, opts={}) @wiki = wiki @depth = opts[:depth] || 0 @min_views = opts[:min_views] || 0 @max_wp10 = opts[:max_wp10] || 100 end def page_titles_for_category(category, depth=0, namespace=nil) page_properties_for_category(category, 'title', depth, namespace) end private def page_properties_for_category(category, property, depth=0, namespace=nil) cat_query = category_query(category, namespace) page_data = get_category_member_properties(cat_query, property) if depth.positive? depth -= 1 subcats = subcategories_of(category) subcats.each do |subcat| page_data += page_properties_for_category(subcat, property, depth, namespace) end end page_data end def get_category_member_properties(query, property) property_values = [] continue = true until continue.nil? cat_response = WikiApi.new(@wiki).query query page_data = cat_response.data['categorymembers'] page_data.each { |page| property_values << page[property] } continue = cat_response['continue'] query['cmcontinue'] = continue['cmcontinue'] if continue end property_values end def subcategories_of(category) subcat_query = category_query(category, 14) # 14 is the Category namespace subcats = get_category_member_properties(subcat_query, 'title') subcats end def category_query(category, namespace=0) { list: 'categorymembers', cmtitle: category, cmlimit: 500, cmnamespace: namespace, # mainspace articles by default continue: '' } end end
rajat2502/WikiEduDashboard
spec/mailers/previews/course_approval_mailer_preview.rb
# frozen_string_literal: true class CourseApprovalMailerPreview < ActionMailer::Preview def returning_instructor_approval CourseApprovalMailer.email(example_returning_course, example_user) end def new_instructor_approval CourseApprovalMailer.email(example_course, example_user) end private def example_course Course.new( school: 'Example University', title: 'Example Course', term: 'Fall 2019', slug: 'Example_University/Example_Course_(Fall_2019)', passcode: 'abcdefg' ) end def example_returning_course course = example_course course.define_singleton_method(:tag?) do |tag| tag == 'returning_instructor' end course end def example_user User.new(email: '<EMAIL>', username: 'Ragesoss', real_name: '<NAME>') end end
rajat2502/WikiEduDashboard
db/migrate/20191015181443_add_flags_to_training_modules_users.rb
class AddFlagsToTrainingModulesUsers < ActiveRecord::Migration[6.0] def change add_column :training_modules_users, :flags, :text end end
rajat2502/WikiEduDashboard
lib/errors/rescue_development_errors.rb
<gh_stars>1-10 # frozen_string_literal: true # Extra error handling for the development environment module Errors module RescueDevelopmentErrors def self.included(base) rescue_from_rev_manifest(base) rescue_from_no_campaigns(base) end REV_MANIFEST_EXPLANATION = '<p>This error occurs when the asset build process has not generated '\ 'the required rev-manifest.json files, which specify the filenames '\ 'of the compiled stylesheet and javascript files.</p>'\ '<p>Run `gulp` or `gulp build` and make sure there are no build errors.</p>' def self.rescue_from_rev_manifest(base) base.rescue_from ActionView::Template::Error do |e| raise e unless /rev-manifest.json/.match?(e.message) explanation = '<p><code>' + String.new(e.message) + '</p></code>' explanation << REV_MANIFEST_EXPLANATION render plain: explanation, status: :internal_server_error raise StandardError, explanation if Rails.env.test? end end def self.rescue_from_no_campaigns(base) base.rescue_from CoursesPresenter::NoCampaignError do Campaign.create(title: 'Default Campaign', slug: ENV['default_campaign']) redirect_to '/' end end end end
rajat2502/WikiEduDashboard
lib/training/training_base.rb
<filename>lib/training/training_base.rb # frozen_string_literal: true require_dependency "#{Rails.root}/lib/training/yaml_training_loader" require_dependency "#{Rails.root}/lib/training/wiki_training_loader" class TrainingBase # cattr_accessor would be cause children's implementations to conflict w/each other class << self attr_accessor :path_to_yaml end ################# # Class methods # ################# # called for each child class in initializers/training_content.rb def self.load(slug_list: nil, content_class: self) loader = training_loader_class.new(content_class: content_class, slug_list: slug_list) loader.load_content end # Called during manual :training_reload action. # This should regenerate all training content from yml files and/or wiki. def self.load_all TrainingLibrary.load TrainingModule.load if Features.wiki_trainings? TrainingModule.all.each { |tm| TrainingSlide.load(slug_list: tm.slide_slugs) } else TrainingSlide.load end end def self.base_path if ENV['training_path'] "#{Rails.root}/#{ENV['training_path']}" else "#{Rails.root}/training_content/wiki_ed" end end def self.training_loader_class Features.wiki_trainings? ? WikiTrainingLoader : YamlTrainingLoader end class DuplicateSlugError < StandardError end end
rajat2502/WikiEduDashboard
spec/controllers/revision_feedback_controller_spec.rb
# frozen_string_literal: true require 'rails_helper' describe RevisionFeedbackController, type: :request do describe '#index' do let!(:course) { create(:course, id: 1) } let(:assignment) { create(:assignment, id: 1, course_id: course.id) } let(:params) { { 'title': 'Quantum_Chemistry', 'assignment_id': assignment.id } } context 'When the article exists' do before do VCR.use_cassette 'ores_features' do get '/revision_feedback', params: params end end it 'renders without error' do expect(response.status).to eq(200) end it 'calls RevisionFeedbackService with features' do VCR.use_cassette 'ores_features' do # Checks if a valid feedback is received from RevisionFeedbackService expect_any_instance_of(RevisionFeedbackService).to receive(:feedback) .and_call_original get '/revision_feedback', params: params expect(response.body).to include('Cite your sources!') end end it 'assigns valid feedback' do feedback = assigns(:feedback) expect(feedback.length).to be >= 1 end end end end
rajat2502/WikiEduDashboard
spec/lib/ores_api_spec.rb
<filename>spec/lib/ores_api_spec.rb # frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/ores_api" describe OresApi do context 'when the wiki is not a wikipedia or wikidata' do before { stub_wiki_validation } let!(:wiki) { create(:wiki, project: 'wikivoyage', language: 'en') } let(:subject) { described_class.new(wiki) } it 'raises an error' do expect { subject }.to raise_error OresApi::InvalidProjectError end end describe '#get_revision_data' do let(:rev_ids) { [641962088, 12345] } let(:wiki) { create(:wiki, project: 'wikidata', language: 'en') } let(:subject) { described_class.new(Wiki.find(1)).get_revision_data(rev_ids) } let(:subject2) { described_class.new(wiki).get_revision_data(rev_ids) } let(:first_id) { 641962088 } let(:last_id) { first_id + OresApi::REVS_PER_REQUEST - 1 } let(:many_rev_ids) { (first_id..last_id).to_a } it 'fetches json from ores.wikimedia.org for wikipedia' do VCR.use_cassette 'ores_api' do expect(subject).to be_a(Hash) expect(subject.dig('enwiki', 'scores', '12345', 'articlequality', 'features')).to be_a(Hash) expect(subject.dig('enwiki', 'scores', '641962088')).to be_a(Hash) end end it 'fetches json from ores.wikimedia.org for wikidata' do VCR.use_cassette 'ores_api' do expect(subject2).to be_a(Hash) expect(subject2.dig('wikidatawiki', 'scores', '12345', 'itemquality', 'features')) .to be_a(Hash) expect(subject2.dig('wikidatawiki', 'scores', '641962088')).to be_a(Hash) end end it 'handles many revisions per request for wikipedia' do VCR.use_cassette 'ores_api' do result = described_class.new(Wiki.find(1)).get_revision_data(many_rev_ids) expect(result.dig('enwiki', 'scores').count).to eq(OresApi::REVS_PER_REQUEST) end end it 'handles many revisions per request for wikidata' do VCR.use_cassette 'ores_api' do result = described_class.new(wiki).get_revision_data(many_rev_ids) expect(result.dig('wikidatawiki', 'scores').count).to eq(OresApi::REVS_PER_REQUEST) end end end end
rajat2502/WikiEduDashboard
spec/features/feedback_form_spec.rb
<reponame>rajat2502/WikiEduDashboard<filename>spec/features/feedback_form_spec.rb # frozen_string_literal: true require 'rails_helper' describe 'feedback form' do before { TrainingModule.load_all } let(:slide_with_feedback_link) do '/training/instructors/new-instructor-orientation/new-instructor-orientation-complete' end let(:feedback_link_text) { 'Submit Feedback' } context 'from a training module', type: :feature, js: true do let(:body) { 'It was great' } let(:user) { create(:user) } it 'submits successfully for a logged in user' do login_as user visit slide_with_feedback_link click_link feedback_link_text within_window(page.windows.last) do fill_in 'feedback_form_response_body', with: body click_button 'Submit' expect(page).to have_content 'Thank you.' end form = FeedbackFormResponse.last expect(form.body).to eq(body) expect(form.user_id).to eq(user.id) expect(form.subject).to match(slide_with_feedback_link) end it 'submits successfully for a logged out user' do visit slide_with_feedback_link click_link feedback_link_text within_window(page.windows.last) do fill_in 'feedback_form_response_body', with: body click_button 'Submit' expect(page).to have_content 'Thank you.' end form = FeedbackFormResponse.last expect(form.body).to eq(body) expect(form.user_id).to eq(nil) expect(form.subject).to match(slide_with_feedback_link) end end context 'with a query param' do let(:body) { 'It was great' } let(:user) { create(:user) } let(:referer) { 'wikipedia.org' } it 'submits successfully' do login_as user visit "/feedback?referer=#{referer}" fill_in 'feedback_form_response_body', with: body click_button 'Submit' expect(page).to have_content 'Thank you.' form = FeedbackFormResponse.last expect(form.body).to eq(body) expect(form.user_id).to eq(user.id) expect(form.subject).to match(referer) end end meths = ['#index', '#show'] meths.each do |meth| context meth do let(:user) { create(:user) } let!(:resp) do FeedbackFormResponse.create(body: 'bananas', subject: 'wikipedia.org', user_id: user.id) end let(:text) { 'Feedback' } before do login_as user if meth == '#index' visit feedback_form_responses_path else visit feedback_form_response_path(resp.id) end end context 'non-admin' do context 'current user' do it 'denies access' do expect(page).to have_content "You don't have access to that page" end end context 'logged out' do it 'denies access' do visit feedback_form_responses_path expect(page).to have_content "You don't have access to that page" end end end context 'admin' do let(:user) { create(:admin) } it 'permits' do expect(page).to have_content text expect(page).to have_content resp.topic end end end end end
rajat2502/WikiEduDashboard
spec/features/settings_spec.rb
# frozen_string_literal: true require 'rails_helper' describe 'settings', type: :feature, js: true do let(:super_admin) { create(:super_admin) } let(:user) { create(:user) } let(:special_user) { create(:user, username: 'specialuser') } before do login_as(super_admin, scope: :user) SpecialUsers.set_user('communications_manager', special_user.username) visit '/settings' end context 'for special users' do it 'adds a special user' do click_button 'Add Special User' fill_in('new_special_user', with: user.username) select 'communications_manager' click_button 'Submit' find('[value=confirm]').click expect(page).to have_content('was upgraded') expect(SpecialUsers.is?(user, 'communications_manager')).to eq(true) end it 'removes a special user' do click_button 'Revoke Special User' click_button I18n.t( 'settings.special_users.remove.revoke_button_confirm', username: special_user.username ) expect(page).to have_content('was removed') expect(SpecialUsers.is?(special_user, 'communications_manager')).to eq(false) end it 'shows an error for invalid user' do click_button 'Add Special User' fill_in('new_special_user', with: 'loliamnouser') select 'communications_manager' click_button 'Submit' find('[value=confirm]').click expect(page).to have_content('not an existing user.') end end end
rajat2502/WikiEduDashboard
lib/analytics/course_students_csv_builder.rb
# frozen_string_literal: true require 'csv' class CourseStudentsCsvBuilder def initialize(course) @course = course end def generate_csv csv_data = [CSV_HEADERS] courses_users.each do |courses_user| csv_data << row(courses_user) end CSV.generate { |csv| csv_data.each { |line| csv << line } } end private def courses_users @course.courses_users.where(role: CoursesUsers::Roles::STUDENT_ROLE).includes(:user) end CSV_HEADERS = %w[ username enrollment_timestamp registered_at revisions_during_project mainspace_bytes_added userpace_bytes_added draft_space_bytes_added references_added registered_during_project ].freeze def row(courses_user) row = [courses_user.user.username] row << courses_user.created_at row << courses_user.user.registered_at row << courses_user.revision_count row << courses_user.character_sum_ms row << courses_user.character_sum_us row << courses_user.character_sum_draft row << courses_user.references_count row << newbie?(courses_user.user) end def newbie?(user) (@course.start..@course.end).cover? user.registered_at end end
rajat2502/WikiEduDashboard
app/workers/daily_update/import_ratings_worker.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/importers/rating_importer" class ImportRatingsWorker include Sidekiq::Worker sidekiq_options unique: :until_executed def perform RatingImporter.update_all_ratings end end
rajat2502/WikiEduDashboard
spec/controllers/blocks_controller_spec.rb
<filename>spec/controllers/blocks_controller_spec.rb<gh_stars>100-1000 # frozen_string_literal: true require 'rails_helper' describe BlocksController, type: :request do describe '#destroy' do let!(:block) { create(:block) } let(:admin) { create(:admin, id: 2) } before do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) end it 'destroys the block' do expect(Block.count).to eq(1) delete "/blocks/#{block.id}", params: { id: block.id, format: :json } expect(Block.count).to eq(0) end end end
rajat2502/WikiEduDashboard
docs/analytics_scripts/ticket_open_time.rb
<gh_stars>1-10 CSV.open("/home/sage/ticket_status.csv", 'wb') do |csv| csv << ['opened', 'updated', 'time_difference', 'status', 'message_count', 'owner'] TicketDispenser::Ticket.all.includes(:owner).each do |ticket| csv << [ticket.created_at, ticket.updated_at, ticket.updated_at - ticket.created_at, ticket.status, ticket.messages.count, ticket.owner&.username] end end
rajat2502/WikiEduDashboard
spec/controllers/weeks_controller_spec.rb
# frozen_string_literal: true require 'rails_helper' describe WeeksController, type: :request do describe '#destroy' do let!(:week) { create(:week) } let(:admin) { create(:admin, id: 2) } before do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) end it 'destroys the week' do expect(Week.count).to eq(1) delete "/weeks/#{week.id}", params: { id: week.id, format: :json } expect(Week.count).to eq(0) end end end
rajat2502/WikiEduDashboard
app/models/wiki_content/revision.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true # == Schema Information # # Table name: revisions # # id :integer not null, primary key # characters :integer default(0) # created_at :datetime # updated_at :datetime # user_id :integer # article_id :integer # views :bigint(8) default(0) # date :datetime # new_article :boolean default(FALSE) # deleted :boolean default(FALSE) # system :boolean default(FALSE) # wp10 :float(24) # wp10_previous :float(24) # ithenticate_id :integer # wiki_id :integer # mw_rev_id :integer # mw_page_id :integer # features :text(65535) # #= Revision model class Revision < ApplicationRecord belongs_to :user belongs_to :article belongs_to :wiki scope :live, -> { where(deleted: false) } scope :user, -> { where(system: false) } # Helps with importing data alias_attribute :rev_id, :mw_rev_id validates :mw_page_id, presence: true validates :mw_rev_id, presence: true validates :wiki_id, presence: true serialize :features, Hash serialize :features_previous, Hash include ArticleHelper #################### # Instance methods # #################### # Returns the web diff url for the revision, e.g., # https://en.wikipedia.org/w/index.php?title=Eva_Hesse&diff=prev&oldid=655980945 def url return if article.nil? title = article.escaped_full_title "#{wiki.base_url}/w/index.php?title=#{title}&diff=prev&oldid=#{mw_rev_id}" end # Returns all of the revision author's courses where the revision occured # within the course start/end dates. def infer_courses_from_user return [] if user.blank? user.courses.where('start <= ?', date).where('end >= ?', date) end # Returns a link to the plagiarism report for a revision, if there is one. def plagiarism_report_link return unless ithenticate_id "/recent-activity/plagiarism/report?ithenticate_id=#{ithenticate_id}" end WIKITEXT_REF_TAGS = 'feature.wikitext.revision.ref_tags' WIKIDATA_REFERENCES = 'feature.len(<datasource.wikidatawiki.revision.references>)' WIKI_SHORTENED_REF_TAGS = 'feature.enwiki.revision.shortened_footnote_templates' def references_count(ores_features) return nil if ores_features.empty? (ores_features[WIKITEXT_REF_TAGS] || ores_features[WIKIDATA_REFERENCES] || 0) + (ores_features[WIKI_SHORTENED_REF_TAGS] || 0) end def references_added return (references_count(features) || 0) if new_article return 0 unless references_count(features) && references_count(features_previous) references_count(features) - references_count(features_previous) end end
rajat2502/WikiEduDashboard
app/workers/daily_update/salesforce_sync_worker.rb
# frozen_string_literal: true class SalesforceSyncWorker include Sidekiq::Worker sidekiq_options unique: :until_executed def perform Course.current.each do |course| next unless course.flags[:salesforce_id] next unless course.approved? PushCourseToSalesforce.new(course) end ClassroomProgramCourse .archived .where(withdrawn: false) .reject(&:closed?) .select(&:approved?).each do |course| UpdateCourseFromSalesforce.new(course) end end end
rajat2502/WikiEduDashboard
spec/models/assignment_spec.rb
# frozen_string_literal: true # == Schema Information # # Table name: assignments # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # user_id :integer # course_id :integer # article_id :integer # article_title :string(255) # role :integer # wiki_id :integer # sandbox_url :text(65535) # require 'rails_helper' describe Assignment do before { stub_wiki_validation } describe 'assignment creation' do context 'when no similar assignments exist' do it 'creates Assignment objects' do course = create(:course) assignment = create(:assignment, course_id: course.id) assignment2 = create(:redlink, course_id: course.id) expect(assignment.id).to be_kind_of(Integer) expect(assignment2.article_id).to be_nil end it 'generates a sandbox_url by default' do course = create(:course) user = create(:user) article = create(:article) article_title = article.title assignment = create(:assignment, course: course, user: user, article: article, article_title: article.title, wiki_id: 1) base_url = "https://#{assignment.wiki.language}.#{assignment.wiki.project}.org/wiki" expected = "#{base_url}/User:#{user.username}/#{article_title}" expect(assignment.sandbox_url).to eq(expected) end it 'generates a sandbox_url if no language is defined' do wiki = create(:wiki, language: nil, project: 'wikidata') course = create(:course) user = create(:user) article = create(:article) article_title = article.title assignment = create(:assignment, course: course, user: user, article: article, article_title: article.title, wiki: wiki) base_url = 'https://www.wikidata.org/wiki' expected = "#{base_url}/User:#{user.username}/#{article_title}" expect(assignment.sandbox_url).to eq(expected) end it 'uses an already existing sandbox URL for assignments with the same article' do course = create(:course) user = create(:user) article = create(:article) article_title = article.title # Another classmate is assigned that article first classmate = create(:user, username: 'ClassmateUsername') create(:assignment, course: course, user: classmate, article: article, article_title: article_title, wiki_id: 1) assignment = create(:assignment, course: course, user: user, article: article, article_title: article_title, wiki_id: 1) base_url = "https://#{assignment.wiki.language}.#{assignment.wiki.project}.org/wiki" expected = "#{base_url}/User:#{classmate.username}/#{article_title}" expect(assignment.sandbox_url).to eq(expected) end it 'generates a sandbox_url for new articles' do course = create(:course) user = create(:user) article_title = 'New_Article' assignment = create(:assignment, course: course, user: user, article_title: article_title, wiki_id: 1) base_url = "https://#{assignment.wiki.language}.#{assignment.wiki.project}.org/wiki" expected = "#{base_url}/User:#{user.username}/#{article_title}" expect(assignment.sandbox_url).to eq(expected) end end context 'when the same article on a different wiki is assignment' do let(:es_wiki) { create(:wiki, language: 'es', project: 'wikipedia') } before do create(:assignment, user_id: 1, course_id: 1, wiki_id: 1, article_title: 'Selfie', role: 0) end it 'creates the new assignment' do described_class.create(user_id: 1, course_id: 1, wiki_id: es_wiki.id, article_title: 'Selfie', role: 0) expect(described_class.count).to eq(2) end end context 'when the same article is assignment twice' do before do create(:assignment, user_id: 1, course_id: 1, wiki_id: 1, article_title: 'Selfie', role: 0) end let(:subject) do described_class.create!(user_id: 1, course_id: 1, wiki_id: 1, article_title: 'Selfie', role: 0) end it 'does not create a duplicate' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid) end end end end
rajat2502/WikiEduDashboard
lib/wiki_response.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/app/workers/blocked_edits_worker" #= Reports message to Sentry about the success or failure of wiki edits class WikiResponse ############### # Entry point # ############### def self.capture(response_data, opts) message = new(response_data, opts) message.parse_api_response message.send_to_sentry end ################# # Main routines # ################# def initialize(response_data, opts={}) @response_data = response_data @edit_data = response_data['edit'] @current_user = opts[:current_user] || {} @post_data = opts[:post_data] @type = opts[:type] end def parse_api_response # {"edit"=> # {"result"=>"Success", # "pageid"=>11543696, # "title"=>"User:Ragesock", # "contentmodel"=>"wikitext", # "oldrevid"=>671572777, # "newrevid"=>674946741, # "newtimestamp"=>"2015-08-07T05:27:43Z"}} # # A failed edit will have a response like this: # {"servedby"=>"mw1135", # "error"=> # {"code"=>"protectedpage", # "info"=>"The \"templateeditor\" right is required to edit this page", # "*"=>"See https://en.wikipedia.org/w/api.php for API usage"}} # # An edit stopped by the abuse filter will respond like this: # {"edit"=> # {"result"=>"Failure", # "code"=>"abusefilter-warning-email", # "info"=>"Hit AbuseFilter: Adding emails in articles", # "warning"=>"[LOTS OF HTML WARNING TEXT]"}} if @response_data['error'] parse_api_error_response elsif @edit_data parse_api_edit_response elsif @response_data['query'] parse_api_query_response elsif @response_data['options'] parse_api_options_response elsif @response_data['createaccount'] parse_api_createaccount_response else parse_api_unknown_response end end # These represent well-known messages that we do not need to capture. # Bypassing Sentry capture avoids a performance hit. MESSAGES_TO_IGNORE = [ 'Successful edit', 'tokens query', 'Successful options update' ].freeze def send_to_sentry return if MESSAGES_TO_IGNORE.include?(@title) Raven.capture_message @title, level: @level, tags: { username: @current_user[:username], action_type: @type }, extra: { response_data: @response_data, post_data: @post_data, current_user: @current_user } end ################### # Parsing methods # ################### private def parse_api_edit_response if @edit_data['result'] == 'Success' @title = "Successful #{@type}" @level = 'info' else parse_failed_edit end end def parse_failed_edit @title = "Failed #{@type}" @title += ': CAPTCHA' if @edit_data['captcha'] @title += ': spamblacklist' if @edit_data['spamblacklist'] code = @response_data['edit']['code'] @title += ": #{code}" if @edit_data['code'] @level = 'warning' end def parse_api_error_response code = @response_data['error']['code'] # If the OAuth credentials are invalid, we need to flag this. # It gets handled by application controller. case code when 'mwoauth-invalid-authorization' @current_user.update(wiki_token: 'invalid') when 'blocked', 'autoblocked' BlockedEditsWorker.schedule_notifications(user: @current_user, response_data: @response_data) end @title = "Failed #{@type}: #{code}" @level = 'warning' end def parse_api_query_response @title = "#{@type} query" @level = 'info' end def parse_api_options_response if @response_data['warnings'] @title = "Unexpected warning for #{@type} update" @level = 'error' else @title = "Successful #{@type} update" @level = 'info' end end def parse_api_createaccount_response @level = 'info' result = @response_data['createaccount']['status'] @title = "Create account result: #{result}" end def parse_api_unknown_response @title = "Unknown response for #{@type}" @level = 'error' end end
rajat2502/WikiEduDashboard
spec/lib/analytics/course_articles_csv_builder_spec.rb
<filename>spec/lib/analytics/course_articles_csv_builder_spec.rb # frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/analytics/course_articles_csv_builder" describe CourseArticlesCsvBuilder do let(:course) { create(:course) } let(:user) { create(:user, registered_at: course.start + 1.minute) } let!(:courses_user) { create(:courses_user, course: course, user: user) } let(:article) { create(:article) } let(:article2) { create(:article, title: 'Second_Article') } let(:revision_count) { 5 } let(:subject) { described_class.new(course).generate_csv } before do # multiple revisions for first article revision_count.times do |i| create(:revision, mw_rev_id: i, user: user, date: course.start + 1.minute, article: article) end # one revision for second article create(:revision, mw_rev_id: 123, user: user, date: course.start + 1.minute, article: article2) # revisions with nil and characters, to make sure this does not cause problems create(:revision, mw_rev_id: 124, user: user, date: course.start + 1.minute, article: article2, characters: nil) create(:revision, mw_rev_id: 125, user: user, date: course.start + 1.minute, article: article2, characters: -500) end it 'creates a CSV with a header and a row of data for each article' do expect(subject.split("\n").count).to eq(3) end it 'creates an edited CSV article with a rating column' do article_headers = subject.split('\n').first expect(article_headers.include?('rating')).to be true end it 'excludes untracked articles' do create(:articles_course, course: course, article: article, tracked: false) create(:articles_course, course: course, article: article2, tracked: true) expect(subject.split("\n").count).to eq(2) expect(subject).not_to include(article.title) expect(subject).to include(article2.title) end context 'for an ArticleScopedProgram' do let(:course) { create(:article_scoped_program) } before do create(:assignment, user: user, course: course, article: article) end it 'only includes in-scope articles' do expect(subject.split("\n").count).to eq(2) expect(subject).to include(article.title) expect(subject).not_to include(article2.title) end end end
rajat2502/WikiEduDashboard
lib/data_cycle/daily_update.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/app/workers/daily_update/update_users_worker" require_dependency "#{Rails.root}/app/workers/daily_update/update_commons_uploads_worker" require_dependency "#{Rails.root}/app/workers/daily_update/find_assignments_worker" require_dependency "#{Rails.root}/app/workers/daily_update/clean_articles_courses_worker" require_dependency "#{Rails.root}/app/workers/daily_update/import_ratings_worker" require_dependency "#{Rails.root}/app/workers/daily_update/update_article_status_worker" require_dependency "#{Rails.root}/app/workers/daily_update/refresh_categories_worker" require_dependency "#{Rails.root}/app/workers/daily_update/overdue_training_alert_worker" require_dependency "#{Rails.root}/app/workers/daily_update/salesforce_sync_worker" require_dependency "#{Rails.root}/lib/data_cycle/batch_update_logging" # Executes all the steps of 'update_constantly' data import task class DailyUpdate include BatchUpdateLogging QUEUE = 'daily_update' def initialize setup_logger return if updates_paused? return if update_running?(:daily) run_update_with_pid_files(:daily) end private def run_update log_start_of_update 'Daily update tasks are beginning.' update_users update_commons_uploads update_article_data update_category_data generate_overdue_training_alerts if Features.wiki_ed? push_course_data_to_salesforce if Features.wiki_ed? log_end_of_update 'Daily update finished.' # rubocop:disable Lint/RescueException rescue Exception => e log_end_of_update 'Daily update failed.' raise e end # rubocop:enable Lint/RescueException ############### # Data import # ############### def update_users log_message 'Updating registration dates for new Users' UpdateUsersWorker.set(queue: QUEUE).perform_async end def update_commons_uploads log_message 'Identifying deleted Commons uploads' UpdateCommonsUploadsWorker.set(queue: QUEUE).perform_async end def update_article_data log_message 'Finding articles that match assignment titles' FindAssignmentsWorker.set(queue: QUEUE).perform_async log_message 'Rebuilding ArticlesCourses for all current students' CleanArticlesCoursesWorker.set(queue: QUEUE).perform_async log_message 'Updating ratings for all articles' ImportRatingsWorker.set(queue: QUEUE).perform_async log_message 'Updating article namespace and deleted status' UpdateArticleStatusWorker.set(queue: QUEUE).perform_async end def update_category_data log_message 'Updating tracked categories' RefreshCategoriesWorker.set(queue: QUEUE).perform_async end ########## # Alerts # ########## def generate_overdue_training_alerts log_message 'Generating alerts for overdue trainings' OverdueTrainingAlertWorker.set(queue: QUEUE).perform_async end ############### # Data export # ############### def push_course_data_to_salesforce log_message 'Pushing course data to Salesforce' SalesforceSyncWorker.set(queue: QUEUE).perform_async end end
rajat2502/WikiEduDashboard
app/mailers/ticket_notification_mailer.rb
# frozen_string_literal: true class TicketNotificationMailer < ApplicationMailer add_template_helper(TicketsHelper) def self.notify_of_message(opts) return unless Features.email? notify(opts).deliver_now end def self.notify_of_open_tickets(opts) return unless Features.email? open_tickets_notify(opts).deliver_now end def notify(course:, message:, recipient:, sender:, bcc_to_salesforce:) @course = course @message = message @ticket = message.ticket @recipient = recipient @sender = sender @sender_name = @sender.real_name || @sender.username @bcc_to_salesforce = bcc_to_salesforce @course_link = "https://#{ENV['dashboard_url']}/courses/#{@course.slug}" if @course @ticket_dashboard_link = "https://#{ENV['dashboard_url']}/tickets/dashboard" mail(to: @recipient.email, bcc: bcc, cc: carbon_copy, from: @sender.email, subject: email_subject, reply_to: @sender.email) end def open_tickets_notify(tickets:, owner:) @tickets = tickets @owner = owner @open_count = tickets.count subject = if @open_count == 1 'Dashboard Tickets: there is 1 open ticket' else "Dashboard Tickets: there are #{@open_count} open tickets" end mail(to: owner.email, subject: subject) end private def bcc @bcc_to_salesforce ? ENV['SALESFORCE_BCC_EMAIL'] : nil end def carbon_copy cc = @message.details[:cc] cc&.map { |entry| entry[:email] } end def email_subject subject_prefix = @course ? "#{@course.title}: " : '' subject_prefix + 'Response to your help request' end end
rajat2502/WikiEduDashboard
spec/services/update_course_stats_spec.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true require 'rails_helper' describe UpdateCourseStats do let(:course) { create(:course, flags: flags) } let(:subject) { described_class.new(course) } context 'when debugging is not enabled' do let(:flags) { nil } it 'posts no Sentry logs' do expect(Raven).not_to receive(:capture_message) subject end end context 'when the course has :needs_update set "true"' do let(:course) { create(:course, needs_update: true) } it 'updates it to "false"' do subject expect(course.reload.needs_update).to eq(false) end end context 'when :debug_updates flag is set' do let(:flags) { { debug_updates: true } } it 'posts debug info to Sentry' do expect(Raven).to receive(:capture_message).at_least(6).times.and_call_original subject end end context 'when there are revisions' do let(:course) { create(:course, start: '2018-11-23', end: '2018-11-30') } let(:user) { create(:user, username: 'Ragesoss') } before do course.campaigns << Campaign.first JoinCourse.new(course: course, user: user, role: 0) VCR.use_cassette 'course_update' do subject end end it 'imports average views of edited articles' do expect(course.articles.count).to eq(2) expect(course.articles.last.average_views).to be > 0 end it 'imports the revisions and their ORES data' do expect(course.revisions.count).to eq(2) course.revisions.each do |revision| expect(revision.features).to have_key('feature.wikitext.revision.ref_tags') expect(revision.features_previous).to have_key('feature.wikitext.revision.ref_tags') end end end end
rajat2502/WikiEduDashboard
app/controllers/personal_data_controller.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true # Allows users to download the personal data bout them stored on the Dashboard class PersonalDataController < ApplicationController before_action :require_signed_in respond_to :json def show @user = current_user end end
rajat2502/WikiEduDashboard
spec/factories/courses_wikis.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true FactoryBot.define do factory :courses_wikis do end end
rajat2502/WikiEduDashboard
app/models/wiki_content/article.rb
<gh_stars>1-10 # frozen_string_literal: true # == Schema Information # # Table name: articles # # id :integer not null, primary key # title :string(255) # updated_at :datetime # created_at :datetime # views_updated_at :date # namespace :integer # rating :string(255) # rating_updated_at :datetime # deleted :boolean default(FALSE) # language :string(10) # average_views :float(24) # average_views_updated_at :date # wiki_id :integer # mw_page_id :integer # require_dependency "#{Rails.root}/lib/importers/article_importer" #= Article model class Article < ApplicationRecord has_many :revisions has_many :editors, through: :revisions, source: :user has_many :articles_courses, class_name: 'ArticlesCourses' has_many :courses, -> { distinct }, through: :articles_courses has_many :assignments belongs_to :wiki alias_attribute :page_id, :mw_page_id scope :live, -> { where(deleted: false) } scope :current, -> { joins(:courses).merge(Course.current).distinct } scope :ready_for_update, -> { joins(:courses).merge(Course.ready_for_update).distinct } scope :namespace, ->(ns) { where(namespace: ns) } scope :assigned, -> { joins(:assignments).distinct } validates :title, presence: true validates :wiki_id, presence: true validates :mw_page_id, presence: true before_validation :set_defaults_and_normalize #################### # CONSTANTS # #################### module Namespaces MAINSPACE = 0 TALK = 1 USER = 2 USER_TALK = 3 PROJECT = 4 PROJECT_TALK = 5 FILE = 6 TEMPLATE = 10 TEMPLATE_TALK = 11 PAGE = 104 WIKIJUNIOR = 110 TRANSLATION = 114 DRAFT = 118 DRAFT_TALK = 119 PROPERTY = 120 QUERY = 122 LEXEME = 146 end NS_PREFIX = { Namespaces::MAINSPACE => '', Namespaces::TALK => 'Talk:', Namespaces::USER => 'User:', Namespaces::USER_TALK => 'User_talk:', Namespaces::TEMPLATE => 'Template:', Namespaces::TEMPLATE_TALK => 'Template_talk:', Namespaces::DRAFT => 'Draft:', Namespaces::DRAFT_TALK => 'Draft_talk:', Namespaces::PROPERTY => 'Property:', Namespaces::QUERY => 'Query:', Namespaces::LEXEME => 'Lexeme:', Namespaces::FILE => 'File:', Namespaces::PAGE => 'Page:', Namespaces::WIKIJUNIOR => 'Wikijunior:', Namespaces::TRANSLATION => 'Translation:', # The following namespace index are spread over # several wikis and needs to be additionally # namespaced via project 4 => { 'wikipedia' => 'Wikipedia:', 'wiktionary' => 'Wiktionary:', 'wikisource' => 'Wikisource:', 'wikiversity' => 'Wikiversity:', 'wikidata' => 'Wikidata:', 'wikiquote' => 'Wikiquote:', 'wikivoyage' => 'Wikivoyage:', 'wikinews' => 'Wikinews:', 'wikibooks' => 'Wikibooks:', 'commons' => 'Commons:', 'incubator' => 'Incubator:' }, 5 => { 'wikipedia' => 'Wikipedia_talk:', 'wiktionary' => 'Wiktionary_talk:', 'wikisource' => 'Wikisource_talk:', 'wikiversity' => 'Wikiversity_talk:', 'wikidata' => 'Wikidata_talk:', 'wikiquote' => 'Wikiquote_talk:', 'wikivoyage' => 'Wikivoyage_talk:', 'wikinews' => 'Wikinews_talk:', 'wikibooks' => 'Wikibooks_talk:', 'commons' => 'Commons_talk:', 'incubator' => 'Incubator_talk:' }, 100 => { 'wiktionary' => 'Appendix:', 'wikisource' => 'Portal:', 'wikiversity' => 'School:' }, 102 => { 'wikisource' => 'Author:', 'wikibooks' => 'Cookbook:', 'wikiversity' => 'Portal:' }, 106 => { 'wiktionary' => 'Rhymes:', 'wikisource' => 'Index:', 'wikiversity' => 'Collection:' } }.freeze #################### # Instance methods # #################### def url "#{wiki.base_url}/wiki/#{namespace_prefix}#{title}" end def full_title title = self.title.tr('_', ' ') "#{namespace_prefix}#{title}" end def escaped_full_title "#{namespace_prefix}#{title}" end def namespace_prefix prefix = NS_PREFIX[namespace] return prefix if prefix.is_a?(String) prefix[wiki.project == 'wikimedia' ? wiki.language : wiki.project] end private def set_defaults_and_normalize # Always save titles with underscores instead of spaces, since that's the way # they are in the MediaWiki database. self.title = title.tr(' ', '_') unless title.nil? end end
rajat2502/WikiEduDashboard
db/migrate/20181117054036_create_training_module.rb
class CreateTrainingModule < ActiveRecord::Migration[5.2] def change create_table :training_modules do |t| t.string :name t.string :estimated_ttc t.string :wiki_page t.string :slug, index: { unique: true } t.text :slide_slugs, limit: 16_000 t.text :description, limit: 16_000 t.text :translations, limit: 2_000_000 t.timestamps null: false end end end
rajat2502/WikiEduDashboard
app/models/user_data/training_modules_users.rb
<gh_stars>1-10 # frozen_string_literal: true # == Schema Information # # Table name: training_modules_users # # id :integer not null, primary key # user_id :integer # training_module_id :integer # last_slide_completed :string(255) # completed_at :datetime # created_at :datetime # updated_at :datetime # flags :text(65535) # require_dependency "#{Rails.root}/lib/training_progress_manager" class TrainingModulesUsers < ApplicationRecord belongs_to :user has_one :training_module serialize :flags, Hash def training_module @training_module ||= TrainingModule.find(training_module_id) end def furthest_slide?(slide_slug) return true if last_slide_completed.nil? training_progress_manager.slide_further_than_previous?(slide_slug, last_slide_completed) end def mark_completion(value=true) flags[:marked_complete] = value end def marked_complete? flags[:marked_complete] || false end private def training_progress_manager @manager ||= TrainingProgressManager.new(user, training_module, training_module_user: self) end end
rajat2502/WikiEduDashboard
app/controllers/explore_controller.rb
<gh_stars>1-10 # frozen_string_literal: true #= Controller for campaign/course functionality class ExploreController < ApplicationController respond_to :html def index # 'cohort' is the old name for campaign. We accept 'cohort' as an alternative # Redirect to new campaign overview page if a parameter is given, for backwards compatibility campaign_param = params[:campaign] || params[:cohort] redirect_to campaign_path(campaign_param) if campaign_param @presenter = CoursesPresenter.new(current_user: current_user, campaign_param: ENV['default_campaign']) @campaign = @presenter.campaign set_search if params[:search].present? end def set_search search_presenter = CoursesPresenter.new( current_user: current_user, courses_list: Course.where(private: false) ) @query = params[:search] @results = search_presenter.search_courses(@query) end end
rajat2502/WikiEduDashboard
spec/lib/data_cycle/update_logger_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/data_cycle/update_logger" describe UpdateLogger do describe '.update_settings_record' do it 'adds the time of the metrics last update as a value to the settings table' do described_class.update_settings_record('start_time' => Time.zone.now, 'end_time' => Time.zone.now) record = Setting.find_or_create_by(key: 'metrics_update') expect(record.value['constant_update'].values.last['end_time']) .to be_within(2.seconds).of(Time.zone.now) end it 'adds a maximum of 10 records' do 15.times do described_class.update_settings_record('start_time' => Time.zone.now, 'end_time' => Time.zone.now) end record = Setting.find_or_create_by(key: 'metrics_update') number_of_updates = record.value['constant_update'].size expect(number_of_updates).to be(10) end it 'adds the average delay time to the settings table' do described_class.update_settings_record('start_time' => 14.hours.ago, 'end_time' => 12.hours.ago) described_class.update_settings_record('start_time' => 12.hours.ago, 'end_time' => 9.hours.ago) described_class.update_settings_record('start_time' => 9.hours.ago, 'end_time' => 8.hours.ago) described_class.update_settings_record('start_time' => 8.hours.ago, 'end_time' => 6.hours.ago) record = Setting.find_or_create_by(key: 'metrics_update') delay = record.value['average_delay'] expect(delay).to eq(7200) end it 'does not set average delay if there was only one update' do described_class.update_settings_record('start_time' => 10.hours.ago, 'end_time' => 8.hours.ago) record = Setting.find_or_create_by(key: 'metrics_update') delay = record.value['average_delay'] expect(delay).to be(nil) end end end
rajat2502/WikiEduDashboard
lib/analytics/course_revisions_csv_builder.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true require 'csv' class CourseRevisionsCsvBuilder def initialize(course) @course = course set_revisions end def generate_csv csv_data = [CSV_HEADERS] revisions_rows.each do |row| csv_data << row end CSV.generate { |csv| csv_data.each { |line| csv << line } } end def revisions_rows @new_revisions.values.map do |revision_data| build_row(revision_data) end end def set_revisions @new_revisions = {} @course.all_revisions.includes(:wiki, :article, :user).map do |edit| revision_edits = @new_revisions[edit.article_id] || new_revision(edit) update_title_username(revision_edits, edit) revision_edits[:mw_rev_id] = edit.mw_rev_id revision_edits[:mw_page_id] = edit.mw_page_id revision_edits[:wiki] = edit.wiki.domain update_characters_references_views(revision_edits, edit) revision_edits[:new_article] = true if edit.new_article revision_edits[:deleted] = true if edit.deleted revision_edits[:wp10] = edit.wp10 revision_edits[:wp10_previous] = edit.wp10_previous @new_revisions[edit.article_id] = revision_edits end end def new_revision(edit) article = edit.article { title: article.title, new_article: false, views: 0, characters: {}, references: {}, deleted: edit.deleted, wp10: {}, wp10_previous: {} } end def update_title_username(revision_edits, edit) revision_edits[:title] = edit.article.title revision_edits[:username] = edit.user.username end def update_characters_references_views(revision_edits, edit) revision_edits[:characters] = edit.characters revision_edits[:references] = edit.references_added revision_edits[:views] = edit.views end CSV_HEADERS = %w[ Article_title User revision_id page_id wiki characters_added references_added new pageviews deleted wp10 wp10_previous ].freeze def build_row(revision_data) row = [revision_data[:title]] row << revision_data[:username] row << revision_data[:mw_rev_id] row << revision_data[:mw_page_id] row << revision_data[:wiki] add_characters_references(revision_data, row) row << revision_data[:new_article] row << revision_data[:views] row << revision_data[:deleted] row << revision_data[:wp10] row << revision_data[:wp10_previous] end def add_characters_references(revision_data, row) row << revision_data[:characters] row << revision_data[:references] end end
rajat2502/WikiEduDashboard
app/models/feedback_form_response.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true # == Schema Information # # Table name: feedback_form_responses # # id :integer not null, primary key # subject :string(255) # body :text(65535) # user_id :integer # created_at :datetime # class FeedbackFormResponse < ApplicationRecord def topic if %r{/training/}.match? subject path = URI.parse(subject).path parts = path.split('/') return parts[3] end subject end end
rajat2502/WikiEduDashboard
app/services/update_course_from_salesforce.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/word_count" #= Pulls course-related data from Salesforce class UpdateCourseFromSalesforce def initialize(course) return unless Features.wiki_ed? @course = course @salesforce_id = @course.flags[:salesforce_id] return unless @salesforce_id @client = Restforce.new(SalesforceCredentials.get) update rescue StandardError => e Raven.capture_exception e end private def salesforce_record @salesforce_record ||= @client.find('Course__c', @salesforce_id) end def update @course.flags[:closed_date] = salesforce_record['Course_Closed_Date__c'] @course.save end end
rajat2502/WikiEduDashboard
spec/controllers/about_this_site_controller_spec.rb
# frozen_string_literal: true require 'rails_helper' describe AboutThisSiteController, type: :request do describe '#private_information' do it 'renders privacy-related info' do get '/private_information' expect(response.status).to eq(200) expect(response.body).to include('Private Information') end end end
rajat2502/WikiEduDashboard
app/workers/daily_update/refresh_categories_worker.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true class RefreshCategoriesWorker include Sidekiq::Worker sidekiq_options unique: :until_executed def perform Category.refresh_categories_for(Course.current) end end
rajat2502/WikiEduDashboard
app/controllers/ask_controller.rb
# frozen_string_literal: true require 'uri' # Controller for ask.wikiedu.org search form class AskController < ApplicationController ASK_ROOT = 'https://ask.wikiedu.org/questions/scope:all/sort:relevance-desc/' def search if params[:q].blank? # Default to the 'student' tag redirect_to "#{ASK_ROOT}tags:student/page:1/", allow_other_host: true else log_to_sentry query = CGI.escape(params[:q]) redirect_to "#{ASK_ROOT}page:1/query:#{query}/", allow_other_host: true end end private def log_to_sentry # Logging to see how this feature gets used Raven.capture_message 'ask.wikiedu.org query', level: 'info', tags: { 'source' => params[:source], 'query' => params[:q] }, extra: { query: params[:q], username: current_user&.username } end end
rajat2502/WikiEduDashboard
db/migrate/20190606035515_add_previous_features_to_revision.rb
class AddPreviousFeaturesToRevision < ActiveRecord::Migration[5.2] def change add_column :revisions, :features_previous, :text end end
rajat2502/WikiEduDashboard
app/workers/daily_update/update_article_status_worker.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/article_status_manager" class UpdateArticleStatusWorker include Sidekiq::Worker sidekiq_options unique: :until_executed def perform ArticleStatusManager.update_article_status end end
rajat2502/WikiEduDashboard
spec/features/category_scopes_spec.rb
# frozen_string_literal: true require 'rails_helper' describe 'Tracked categories and template', js: true do let(:course) { create(:course, type: 'ArticleScopedProgram') } let(:user) { create(:user) } before do JoinCourse.new(course: course, user: user, role: CoursesUsers::Roles::INSTRUCTOR_ROLE) login_as user stub_oauth_edit end it 'lets a facilitator add and remove a category' do visit "/courses/#{course.slug}/articles" expect(page).to have_content 'Tracked Categories' click_button 'Add category' find('#category_name').set('Photography') click_button 'Add this category' click_button 'OK' expect(page).to have_content 'Category:Photography' # Re-add the same category click_button 'Add category' find('#category_name').set('Photography') click_button 'Add this category' click_button 'OK' click_button 'Remove' expect(page).not_to have_content 'Photography' end it 'lets a facilitator add a template' do visit "/courses/#{course.slug}/articles" click_button 'Add template' find('#category_name').set('Stub') click_button 'Add this template' click_button 'OK' expect(page).to have_content 'Template:Stub' end end
rajat2502/WikiEduDashboard
spec/models/rapidfire/question_spec.rb
<filename>spec/models/rapidfire/question_spec.rb # frozen_string_literal: true require 'rails_helper' describe Rapidfire::Question do describe 'Answer Options Validation' do it "raises an error if answer_options aren't specified and no course data is set" do invalid_question = build(:q_radio, answer_options: '') invalid_question.valid? expect(invalid_question.errors[:answer_options].size).to eq(1) valid_question = build(:q_radio, course_data_type: 'Students') valid_question.valid? expect(valid_question.errors[:answer_options].size).to eq(0) end it 'should not raise an error if the question type has changed to'\ " one that doesn't require answer options" do valid_question = build(:q_radio, course_data_type: 'Students') valid_question.type = 'Rapidfire::Questions::RangeInput' valid_question.answer_options = '' valid_question.valid? expect(valid_question.errors[:answer_options].size).to eq(0) end end describe 'Matrix Question Creation' do it 'creates create a question' do create(:matrix_question) expect(described_class.last.question_text).to eq('Question?') end it 'raises an error if the question type is not an available type for matrix questions' do invalid_question = build(:matrix_question, type: 'Rapidfire::Questions::Long') invalid_question.valid? expect(invalid_question.errors[:type].size).to eq(1) end end describe 'Reordering Questions' do before do @question_group = create(:question_group) @question1 = create(:q_short, question_group: @question_group) @question2 = create(:q_short, question_group: @question_group) @question3 = create(:q_short, question_group: @question_group) end it 'is placed at the bottom of the list on create' do expect(@question3.position).to eq(3) end it 'has position 1 if move to top of list' do @question3.insert_at(1) expect(@question3.position).to eq(1) end end end
rajat2502/WikiEduDashboard
db/migrate/20191004175010_add_kind_to_training_modules.rb
<gh_stars>100-1000 class AddKindToTrainingModules < ActiveRecord::Migration[6.0] def change add_column :training_modules, :kind, :integer, default: 0, limit: 1 end end
rajat2502/WikiEduDashboard
lib/data_cycle/training_update.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/data_cycle/batch_update_logging" # Executes all the steps of 'update_views' data import task class TrainingUpdate attr_reader :result include BatchUpdateLogging def initialize(module_slug:) @module_slug = module_slug setup_logger if update_running?(:training) @result = 'Another training update process is already in progress. Try again later.' return end run_update_with_pid_files(:training) end private def run_update log_start_of_update "Training update task is beginning. Module: #{@module_slug}" update_training_content @result = 'Success!' log_end_of_update 'Training update finished.' # rubocop:disable Lint/RescueException rescue Exception => e log_end_of_update 'Training update failed.' raise e end # rubocop:enable Lint/RescueException def update_training_content if @module_slug == 'all' TrainingModule.load_all else TrainingModule.reload_module slug: @module_slug end end end
rajat2502/WikiEduDashboard
lib/wiki_userpage_output.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/wiki_output_templates" #= Class for generating wikitext for updating a userpage class WikiUserpageOutput include WikiOutputTemplates def initialize(course) @course = course @templates = @course.home_wiki.edit_templates end def enrollment_template "{{#{template_name(@templates, 'editor')}"\ "#{course_page_param}"\ "#{course_slug_param}"\ "#{course_type_param}"\ ' }}' end def enrollment_summary case @course.type when 'FellowsCohort' "User is participating in #{@course.slug}." else "User has enrolled in [[#{@course.wiki_title}]]." end end def enrollment_talk_template "{{#{template_name(@templates, 'user_talk')}"\ "#{course_page_param}"\ "#{course_slug_param}"\ "#{course_type_param}"\ ' }}' end def sandbox_template(dashboard_url) "{{#{dashboard_url} sandbox#{course_type_param}}}" end private def course_page_param return unless @course.wiki_title " | course = [[#{@course.wiki_title}]]" end def course_slug_param " | slug = #{@course.slug}" end def course_type_param return unless @course.wiki_template_param " | type = #{@course.wiki_template_param}" end end
rajat2502/WikiEduDashboard
lib/importers/assigned_article_importer.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/importers/article_importer" class AssignedArticleImporter def initialize(wiki) @wiki = wiki end ############### # Entry point # ############### def self.import_articles_for_assignments assignments_missing_articles = Assignment.where(article_id: nil) assignments_missing_articles.group_by(&:wiki).each do |wiki, assignments| new(wiki).import_articles(assignments) end end ######################### # Wiki-specific routine # ######################### def import_articles(assignments) missing_titles = assignments.map(&:article_title).uniq ArticleImporter.new(@wiki).import_articles_by_title(missing_titles) newly_imported_article_titles = Article.where(namespace: Article::Namespaces::MAINSPACE, title: missing_titles, wiki_id: @wiki.id).pluck(:title) assignments_to_update = Assignment.where(article_title: newly_imported_article_titles, wiki_id: @wiki.id) assignments_to_update.each do |assignment| update_assignment(assignment) end end def update_assignment(assignment) article = Article.find_by(title: assignment.article_title, namespace: Article::Namespaces::MAINSPACE, wiki_id: @wiki.id, deleted: false) return unless article&.title == assignment.article_title # guard against case variants assignment.article_id = article.id assignment.save end end
rajat2502/WikiEduDashboard
app/workers/daily_update/overdue_training_alert_worker.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/alerts/overdue_training_alert_manager" class OverdueTrainingAlertWorker include Sidekiq::Worker sidekiq_options unique: :until_executed def perform OverdueTrainingAlertManager.new(Course.strictly_current).create_alerts end end
rajat2502/WikiEduDashboard
app/services/create_requested_account.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/wiki_edits" require_dependency "#{Rails.root}/lib/importers/user_importer" # Processes a RequestedAccount by creating a new mediawiki account, and # creating the User record upon success. class CreateRequestedAccount attr_reader :result, :user, :creator def initialize(requested_account, creator) @creator = creator @requested_account = requested_account @course = requested_account.course @wiki = @course.home_wiki.edits_enabled? ? @course.home_wiki : en_wiki @username = requested_account.username @email = requested_account.email.strip # This instance variable is used to determine whether or not to retry # the account creation with a backup account and/or en.wiki @use_backup_creator = false course_link = "#{ENV['dashboard_url']}/courses/#{@course.slug}" @creation_reason = I18n.t('wiki_api.create_account_reason', event: course_link, locale: @wiki.language) process_request(@creator, @creation_reason) end private def en_wiki @en_wiki ||= Wiki.find_by(language: 'en', project: 'wikipedia') end def process_request(creator, creation_reason) @wiki_edits = WikiEdits.new(@wiki) @response = @wiki_edits.create_account(creator: creator, username: @username, email: @email, reason: creation_reason) handle_mediawiki_response end # We only handle one-step PASS and FAIL statuses. For more complicated results, # such as an intermediate CAPTCHA step, we just fail immediately; users are expected # to have account creator rights on the target wiki, so that CAPTCHA is not required. def handle_mediawiki_response response = @response['createaccount'] || {} status, message, messagecode = response.values_at('status', 'message', 'messagecode') status == 'PASS' ? create_account : handle_failed_account_creation(message, messagecode) end def create_account @result = { success: "Created account for #{@username} on #{@wiki.base_url}. A password will be emailed to #{@email}." } returned_username = @response.dig('createaccount', 'username') raise AccountCreationError, 'no username returned' if returned_username.blank? @user = UserImporter.new_from_username(returned_username, @wiki) raise AccountCreationError, "could not create user #{returned_username}" if @user.blank? @requested_account.destroy end MESSAGE_CODES_TO_RETRY = %w[ acct_creation_throttle_hit captcha-createaccount-fail ].freeze def handle_failed_account_creation(message, messagecode) if messagecode == 'userexists' destroy_request_if_user_exists(message, messagecode) elsif MESSAGE_CODES_TO_RETRY.include?(messagecode) && !@use_backup_creator retry_request_with_backup_account_on_en_wiki else log_unexpected_response end end def destroy_request_if_user_exists(message, messagecode) @result = { failure: "Could not create account for #{@username} / #{@email}. #{@wiki.base_url} message: #{messagecode} — #{message}" } code = @response.dig('createaccount', 'messagecode') @requested_account.destroy if code == 'userexists' end def retry_request_with_backup_account_on_en_wiki @use_backup_creator = true @wiki = en_wiki backup_account = SpecialUsers.backup_account_creator creation_reason = "#{@creation_reason} Account created by #{@creator.username}." process_request(backup_account, creation_reason) end def log_unexpected_response @result = { failure: "Could not create account for #{@username} / #{@email}. #{@wiki.base_url} response: #{@response}" } raise AccountCreationError, 'unexpected account creation response' rescue AccountCreationError => e Raven.capture_exception(e, extra: { response: @response }) end class AccountCreationError < StandardError; end end
rajat2502/WikiEduDashboard
spec/controllers/survey_assignments_controller_spec.rb
<gh_stars>100-1000 # frozen_string_literal: true require 'rails_helper' describe SurveyAssignmentsController, type: :request do let(:admin) { create(:admin) } let(:survey) { create(:survey) } describe '#create' do let(:follow_up) { 7 } let(:send_days) { 7 } let(:send_email) { true } let(:campaign) { create(:campaign) } let(:instructor) { 1 } let(:post_params) do { survey_assignment: { survey_id: survey.id, campaign_ids: campaign.id, courses_user_role: instructor, send_date_days: send_days, send_before: false, send_date_relative_to: 'end', follow_up_days_after_first_notification: follow_up, published: true, notes: 'foo', send_email: send_email, custom_email_subject: 'bar', custom_email_body: 'baz', custom_email_signature: '', custom_banner_message: 'ohai' } } end before do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) end it 'allows create and sets appropriate params' do post '/surveys/assignments', params: post_params expect(SurveyAssignment.last.follow_up_days_after_first_notification).to eq(follow_up) expect(SurveyAssignment.last.send_email).to eq(send_email) expect(SurveyAssignment.last.custom_email).to be_a(Hash) end end describe '#send_notifications' do let(:send_email) { nil } let(:user) { create(:user, email: '<EMAIL>') } let(:courses_user) { create(:courses_user, user_id: user.id) } let(:survey_assignment) do create(:survey_assignment, send_email: send_email, survey_id: survey.id) end let!(:survey_notification) do create(:survey_notification, survey_assignment_id: survey_assignment.id, dismissed: false, completed: false, courses_users_id: courses_user.id) end before do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) end context 'send_email is not set' do it 'does not attempt to send' do expect(SurveyMailer).not_to receive(:send_notification) post '/survey_notification/send' end end context 'send_email is set' do let(:send_email) { true } it 'attempts to send email' do expect(SurveyMailer).to receive(:send_notification) post '/survey_notification/send' end end end describe '#send_test_email' do let(:survey_assignment) do create(:survey_assignment, survey_id: survey.id) end let(:params) { { id: survey_assignment.id } } before do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) end it 'invokes SurveyTestEmailManager and redirects' do expect_any_instance_of(SurveyTestEmailManager).to receive(:send_email) post "/survey_assignments/#{survey_assignment.id}/send_test_email", params: params expect(response.status).to eq(302) end end end
rajat2502/WikiEduDashboard
spec/lib/importers/category_importer_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/importers/category_importer" describe CategoryImporter do let(:wiki) { Wiki.default_wiki } let(:subject) { described_class.new(wiki).page_titles_for_category(category, depth) } describe '.page_titles_for_category' do context 'for depth 0' do let(:category) { 'Category:AfD debates' } let(:depth) { 0 } it 'returns page page titles for a given category' do VCR.use_cassette 'category_importer/page_titles' do expect(subject).to include('Category:AfD debates (Places and transportation)') end end end context 'for depth 1' do let(:category) { 'Category:Crocodile Dundee' } let(:article_in_cat) { 'Michael "Crocodile" Dundee' } let(:article_in_subcat) { 'Crocodile Dundee in Los Angeles' } let(:depth) { 1 } it 'works recursively for subcategories' do VCR.use_cassette 'category_importer/page_titles' do expect(subject).to include(article_in_cat) expect(subject).to include(article_in_subcat) end end end end end
rajat2502/WikiEduDashboard
app/views/explore/index.json.jbuilder
<filename>app/views/explore/index.json.jbuilder # frozen_string_literal: true json.courses @presenter.active_courses
rajat2502/WikiEduDashboard
spec/features/training_translation_spec.rb
<gh_stars>1-10 # frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/data_cycle/training_update" describe 'Training Translations', type: :feature, js: true do let(:basque_user) { create(:user, id: 2, username: 'ibarra', locale: 'eu') } before do TrainingModule.destroy_all TrainingSlide.destroy_all TrainingLibrary.destroy_all allow(Features).to receive(:wiki_trainings?).and_return(true) VCR.use_cassette 'training/slide_translations' do TrainingUpdate.new(module_slug: 'all') end login_as(basque_user, scope: :user) end it 'shows the translated text of a quiz' do visit '/training/editing-wikipedia/wikipedia-essentials/five-pillars-quiz-1' expect(page).to have_content 'Wikipedia artikulu batek' end it 'shows the translated names in the table of contents' do visit '/training/editing-wikipedia/wikipedia-essentials/five-pillars-quiz-1' expect(page).to have_css('.slide__menu__nav__dropdown ol', text: 'Bost euskarriei buruzko proba', visible: false) end # Make sure default trainings get reloaded end
rajat2502/WikiEduDashboard
spec/mailers/previews/term_recap_mailer_preview.rb
<reponame>rajat2502/WikiEduDashboard<gh_stars>100-1000 # frozen_string_literal: true class TermRecapMailerPreview < ActionMailer::Preview def email_to_instructors TermRecapMailer.email(example_course, Campaign.default_campaign) end def basic_email_to_instructors TermRecapMailer.basic_email(example_course, Campaign.default_campaign) end private def example_course Course.where('revision_count > 20').first end end
rajat2502/WikiEduDashboard
spec/models/assignment_suggestion_spec.rb
<filename>spec/models/assignment_suggestion_spec.rb # frozen_string_literal: true # == Schema Information # # Table name: assignment_suggestions # # id :bigint(8) not null, primary key # text :text(65535) # assignment_id :bigint(8) # created_at :datetime not null # updated_at :datetime not null # user_id :integer # require 'rails_helper' RSpec.describe AssignmentSuggestion, type: :model do let(:assignment) { create(:assignment) } let!(:assignment_suggestion) { create(:assignment_suggestion, assignment: assignment) } it 'is destroyed when its Assignment is destroyed' do expect(assignment_suggestion).to be assignment.destroy expect(described_class.exists?(assignment_suggestion.id)).to eq(false) end end
rajat2502/WikiEduDashboard
lib/course_cache_manager.rb
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/revision_stat" require_dependency "#{Rails.root}/lib/course_training_progress_manager" #= Service for updating the counts that are cached on Course objects class CourseCacheManager def initialize(course) @course = course end def update_cache update_character_sum update_references_count update_view_sum update_user_count update_trained_count update_revision_count update_recent_revision_count update_article_count update_new_article_count update_upload_count update_uploads_in_use_count update_upload_usages_count @course.save end def update_user_count @course.user_count = @course.students.size end private ################## # Cache updaters # ################## def update_character_sum # Do not consider revisions with negative byte changes @course.character_sum = @course.courses_users .where(role: CoursesUsers::Roles::STUDENT_ROLE) .sum(:character_sum_ms) end def update_references_count @course.references_count = @course.courses_users .where(role: CoursesUsers::Roles::STUDENT_ROLE) .sum(:references_count) end def update_view_sum @course.view_sum = @course.articles_courses.tracked.live.sum(:view_count) end def update_trained_count # The cutoff date represents the switch from on-wiki training, indicated by # the 'trained' attribute of a User, to the in-dashboard training module # system introduced for the beginning of 2016. For courses after the cutoff # date, 'trained_count' is represents the count of students who don't have # assigned training modules that are overdue. trained_count = if past_training_cutoff? @course.students_up_to_date_with_training.count else @course.students.trained.size end @course.trained_count = trained_count end def update_revision_count @course.revision_count = @course.tracked_revisions.live.size end def update_recent_revision_count @course.recent_revision_count = RevisionStat.get_records(course: @course) end def update_article_count @course.article_count = @course.tracked_articles.namespace(0).live.size end def update_new_article_count @course.new_article_count = @course.new_articles.count end def update_upload_count @course.upload_count = @course.uploads.count end def update_uploads_in_use_count @course.uploads_in_use_count = @course.uploads_in_use.count end def update_upload_usages_count @course.upload_usages_count = @course.uploads_in_use.sum(:usage_count) end ############ # Helplers # ############ def past_training_cutoff? @course.start > CourseTrainingProgressManager::TRAINING_BOOLEAN_CUTOFF_DATE end end
rajat2502/WikiEduDashboard
spec/features/course_deletion_spec.rb
# frozen_string_literal: true require 'rails_helper' describe 'course deletion', type: :feature, js: true do let(:course) { create(:course) } let(:admin) { create(:admin) } it 'destroys the course and redirects to the home page' do login_as admin stub_oauth_edit visit "/courses/#{course.slug}" expect(Course.count).to eq(1) accept_prompt(with: course.title) do click_button 'Delete course' end expect(page).to have_content 'Create Course' expect(Course.count).to eq(0) end end
rajat2502/WikiEduDashboard
app/controllers/unsubmitted_courses_controller.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true class UnsubmittedCoursesController < ApplicationController respond_to :html def index @unsubmitted_courses = Course.unsubmitted.order(created_at: :desc).includes(:tags, :instructors) end end
rajat2502/WikiEduDashboard
spec/controllers/application_controller_spec.rb
<reponame>rajat2502/WikiEduDashboard # frozen_string_literal: true require 'rails_helper' describe ApplicationController do let(:user) { create(:user) } let(:admin) { create(:admin) } let(:super_admin) { create(:super_admin) } let(:course) { create(:course) } controller do def index head 200 end end describe '#new_session_path' do it 'returns the sign in path' do result = controller.send(:new_session_path, nil) expect(result).to eq('/sign_in') end end describe 'invalid authenticity tokens' do it 'returns an html 401' do exception = ActionController::InvalidAuthenticityToken.new('Unauthorized') allow(controller).to receive(:current_user).and_return(user) allow(controller).to receive(:check_for_unsupported_browser).and_raise(exception) get :index expect(response.status).to eq(401) end it 'returns a json 401' do exception = ActionController::InvalidAuthenticityToken.new('Unauthorized') allow(controller).to receive(:current_user).and_return(user) allow(controller).to receive(:check_for_unsupported_browser).and_raise(exception) allow(controller).to receive(:json?).and_return(true) get :index, as: :json expect(response.status).to eq(401) end end describe '#require_permissions' do controller do def index require_permissions head 200 end end context 'when user lacks permissions' do it 'returns an html 401' do allow(controller).to receive(:current_user).and_return(user) get :index, params: { id: course.slug } expect(response.status).to eq(401) end it 'returns a json 401' do allow(controller).to receive(:current_user).and_return(user) allow(controller).to receive(:json?).and_return(true) get :index, params: { id: course.slug }, as: :json expect(response.status).to eq(401) end end end describe '#require_participating_user' do controller do def index require_participating_user head 200 end end context 'when user is not enrolled' do it 'returns an html 401' do allow(controller).to receive(:current_user).and_return(user) get :index, params: { id: course.slug } expect(response.status).to eq(401) end it 'returns a json 401' do allow(controller).to receive(:current_user).and_return(user) allow(controller).to receive(:json?).and_return(true) get :index, params: { id: course.slug }, as: :json expect(response.status).to eq(401) end end end describe '#require_admin_permissions' do controller do def index require_admin_permissions head 200 end end context 'when user is not an admin' do it 'returns an html 401' do allow(controller).to receive(:current_user).and_return(user) get :index expect(response.status).to eq(401) end it 'returns a json 401' do allow(controller).to receive(:current_user).and_return(user) allow(controller).to receive(:json?).and_return(true) get :index, as: :json expect(response.status).to eq(401) end end context 'when user is an admin' do it 'does not return a 401' do allow(controller).to receive(:current_user).and_return(admin) get :index expect(response.status).to eq(200) end end context 'when user is a super_admin' do it 'does not return a 401' do allow(controller).to receive(:current_user).and_return(super_admin) get :index expect(response.status).to eq(200) end end end describe '#require_super_admin_permissions' do controller do def index require_super_admin_permissions head 200 end end context 'when user is < admin' do it 'returns an html 401' do allow(controller).to receive(:current_user).and_return(user) get :index expect(response.status).to eq(401) end it 'returns a json 401' do allow(controller).to receive(:current_user).and_return(user) allow(controller).to receive(:json?).and_return(true) get :index, as: :json expect(response.status).to eq(401) end it 'returns custom error message' do allow(controller).to receive(:current_user).and_return(user) allow(controller).to receive(:json?).and_return(true) get :index, as: :json message = JSON.parse(response.body)['message'] expect(message).to eq('Only super administrators may do that.') end end context 'when user is an admin' do it 'returns an html 401' do allow(controller).to receive(:current_user).and_return(admin) get :index expect(response.status).to eq(401) end it 'returns a json 401' do allow(controller).to receive(:current_user).and_return(admin) allow(controller).to receive(:json?).and_return(true) get :index, as: :json expect(response.status).to eq(401) end end context 'when user is a super_admin' do it 'does not return a 401' do allow(controller).to receive(:current_user).and_return(super_admin) get :index expect(response.status).to eq(200) end end end describe '#require_signed_in' do controller do def index require_signed_in head 200 end end context 'when user is not signed in' do it 'returns an html 401' do get :index expect(response.status).to eq(401) end it 'returns a json 401' do allow(controller).to receive(:json?).and_return(true) get :index, as: :json expect(response.status).to eq(401) end end context 'when user is signed in' do it 'returns a 200' do allow(controller).to receive(:current_user).and_return(user) get :index expect(response.status).to eq(200) end end end describe '#set_locale' do let(:user) { create(:user, locale: 'zh-hans') } def index render nothing: true end it 'sets the locale from user preference' do allow(controller).to receive(:current_user).and_return(user) get :index expect(I18n.locale).to eq(:'zh-hans') end it 'sets the locale from a param' do get :index, params: { locale: 'zh-hant' } expect(I18n.locale).to eq(:'zh-hant') end it 'falls back to a default if locale is not available' do get :index, params: { locale: 'not-a-real-locale' } expect(I18n.locale).to eq(:en) end end end
rajat2502/WikiEduDashboard
app/models/course_data/articles_courses.rb
<filename>app/models/course_data/articles_courses.rb<gh_stars>1-10 # frozen_string_literal: true # == Schema Information # # Table name: articles_courses # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # article_id :integer # course_id :integer # view_count :bigint(8) default(0) # character_sum :integer default(0) # new_article :boolean default(FALSE) # #= ArticlesCourses is a join model between Article and Course. #= It represents a mainspace Wikipedia article that has been worked on by a #= student in a course. class ArticlesCourses < ApplicationRecord belongs_to :article belongs_to :course scope :live, -> { joins(:article).where(articles: { deleted: false }).distinct } scope :new_article, -> { where(new_article: true) } scope :current, -> { joins(:course).merge(Course.current).distinct } scope :ready_for_update, -> { joins(:course).merge(Course.ready_for_update).distinct } scope :tracked, -> { where(tracked: true).distinct } scope :not_tracked, -> { where(tracked: false).distinct } #################### # Instance methods # #################### def view_count update_cache unless self[:view_count] self[:view_count] end def character_sum update_cache unless self[:character_sum] self[:character_sum] end def references_count update_cache unless self[:references_count] self[:references_count] end def new_article self[:new_article] end def live_manual_revisions course.revisions.live.where(article_id: article_id) end def all_revisions course.all_revisions.where(article_id: article_id) end def update_cache revisions = live_manual_revisions self.character_sum = revisions.where('characters >= 0').sum(:characters) self.references_count = revisions.sum(&:references_added) self.view_count = views_since_earliest_revision(revisions) # We use the 'all_revisions' scope so that the dashboard system edits that # create sandboxes are not excluded, since those are often wind up being the # first edit of a mainspace article's revision history self.new_article = all_revisions.exists?(new_article: true) save end def views_since_earliest_revision(revisions) return if revisions.empty? return if article.average_views.nil? days = (Time.now.utc.to_date - revisions.order('date ASC').first.date.to_date).to_i days * article.average_views end ################# # Class methods # ################# def self.update_all_caches(articles_courses) articles_courses.find_each(&:update_cache) end def self.update_from_course(course) mainspace_revisions = get_mainspace_revisions(course.revisions) course_article_ids = course.articles.where(wiki: course.wikis).pluck(:id) revision_article_ids = mainspace_revisions.pluck(:article_id).uniq # Remove all the ArticlesCourses that do not correspond to course revisions. # That may happen if the course dates changed, so some revisions are no # longer part of the course. # Also remove records for articles that aren't on a tracked wiki. tracked_article_ids = revision_article_ids & course_article_ids course.articles_courses.where.not(article_id: tracked_article_ids).destroy_all # Add new ArticlesCourses ActiveRecord::Base.transaction do revision_article_ids.each do |article_id| next if course_article_ids.include?(article_id) article = Article.find(article_id) next unless course.wikis.include?(article.wiki) course.articles << article end end end def self.get_mainspace_revisions(revisions) revisions.joins(:article).where(articles: { namespace: '0' }) end end
rajat2502/WikiEduDashboard
db/migrate/20190624123659_add_references_count_to_courses_users.rb
<reponame>rajat2502/WikiEduDashboard<gh_stars>100-1000 class AddReferencesCountToCoursesUsers < ActiveRecord::Migration[5.2] def change add_column :courses_users, :references_count, :integer, default: 0 end end
rajat2502/WikiEduDashboard
app/views/alerts_list/index.json.jbuilder
# frozen_string_literal: true json.alerts @alerts do |alert| json.id alert.id json.course_id alert.course_id json.user_id alert.user_id json.article_id alert.article_id json.revision_id alert.revision_id json.message alert.message json.target_user_id alert.target_user_id json.subject_id alert.subject_id json.details alert.details json.type alert.type json.created_at alert.created_at json.user alert.user&.username json.course alert.course&.title json.course_slug alert.course&.slug json.article alert.article&.title json.article_url alert.article&.url json.resolved alert.resolved json.resolvable alert.resolvable? end
rajat2502/WikiEduDashboard
spec/services/update_course_from_salesforce_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/app/services/update_course_from_salesforce" describe UpdateCourseFromSalesforce do let(:course) { create(:course, flags: flags) } let(:salesforce_id) { 'a2qQ0101015h4HF' } let(:mock_salesforce_record) { { 'Course_Closed_Date__c' => '2018-06-07' } } let(:subject) { described_class.new(course) } context 'when a course has a Salesforce record' do let(:flags) { { salesforce_id: salesforce_id } } it 'updates the record with the closed date' do expect_any_instance_of(Restforce::Data::Client).to receive(:find) .and_return(mock_salesforce_record) subject expect(course.reload.flags[:closed_date]).to eq('2018-06-07') end it 'handles Salesforce API downtime gracefully' do expect_any_instance_of(Restforce::Data::Client).to receive(:find) .and_raise(Faraday::ParsingError.new('Salesforce is down')) subject end end context 'when a course does not have a Salesforce record' do let(:flags) { {} } it 'returns without error' do subject expect(course.reload.flags[:closed_date]).to be_nil end end end
rajat2502/WikiEduDashboard
spec/lib/importers/revision_importer_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/importers/revision_importer" require "#{Rails.root}/lib/articles_courses_cleaner" describe RevisionImporter do describe '.users_with_no_revisions' do let(:user) { create(:user) } let(:course_1) { create(:course, start: '2015-01-01', end: '2015-12-31') } let(:course_2) { create(:course, start: '2016-01-01', end: '2016-12-31', slug: 'foo/course2') } let!(:cu) do create(:courses_user, course_id: course_1.id, user_id: user.id, role: CoursesUsers::Roles::STUDENT_ROLE) end let!(:cu2) do create(:courses_user, course_id: course_2.id, user_id: user.id, role: CoursesUsers::Roles::STUDENT_ROLE) end let(:article) { create(:article) } let!(:revision) do create(:revision, user_id: user.id, article_id: article.id, date: course_1.start + 1.month) end before { CoursesUsers.all.collect(&:update_cache) } it 'returns users who have no revisions for the given course' do result = described_class.new(Wiki.default_wiki, course_2).send(:users_with_no_revisions) expect(result).to include(user) end it 'does not return users who have revisions for the course' do result = described_class.new(Wiki.default_wiki, course_1).send(:users_with_no_revisions) expect(result).not_to include(user) end end describe '#import_revisions_for_course' do let(:course) { create(:course, start: '2018-01-01', end: '2018-12-31') } let(:user) { create(:user, username: 'Ragesoss') } let(:article) { create(:article, title: 'Stray_Cats', mw_page_id: 164007, wiki: home_wiki) } let(:home_wiki) { Wiki.get_or_create(language: 'en', project: 'wikipedia') } let(:subject) do described_class.new(home_wiki, course).import_revisions_for_course(all_time: false) end let(:revision_count) { 0 } before do create(:courses_user, course: course, user: user, revision_count: revision_count) end context 'when there are no edits' do it 'imports all edits' do expect(Revision.count).to eq(0) VCR.use_cassette 'revision_importer/all' do subject end expect(Revision.count).to be > 77 end end context 'when there already some edits' do let(:revision_count) { 1 } before do Revision.create(user: user, date: 'Fri, 27 Jul 2018 05:09:32 UTC +00:00', wiki: home_wiki, article: article, mw_page_id: 164007, mw_rev_id: 852177599) end it 'only imports newer edits' do expect(Revision.count).to eq(1) VCR.use_cassette 'revision_importer/newer' do subject end expect(Revision.count).to be > 54 end end context 'when there are edits to articles with four-byte unicode characters in the title' do # Workaround for # https://github.com/WikiEducationFoundation/WikiEduDashboard/issues/1744 let(:home_wiki) { Wiki.new(language: 'zh', project: 'wikipedia', id: 999) } let(:course) { create(:course, start: '2019-04-30', end: '2019-05-02') } let(:user) { create(:user, username: 'Elmond') } it 'handles revisions with four-byte unicode characters' do VCR.use_cassette 'four-byte-unicode' do expect(Article.exists?(title: CGI.escape('黃𨥈瑩'))).to be(false) subject expect(Article.exists?(title: CGI.escape('黃𨥈瑩'))).to be(true) end end end end end
rajat2502/WikiEduDashboard
app/helpers/tickets_helper.rb
<reponame>rajat2502/WikiEduDashboard<filename>app/helpers/tickets_helper.rb # frozen_string_literal: true #= Helpers for tickets module TicketsHelper def sender_for_message(message) message.sender&.real_name || message.sender&.username || message.details[:sender_email] end def successful_replies_in_reverse(ticket, recipient) successful_messages = ticket.messages.reject do |message| message.details[:delivered].nil? && message.details[:delivery_failed] end reversed_messages = successful_messages.reverse reversed_messages.select do |message| recipient.admin? || message.reply? end end end
rajat2502/WikiEduDashboard
spec/helpers/course_helper_spec.rb
<gh_stars>100-1000 # frozen_string_literal: true require 'rails_helper' describe CourseHelper, type: :helper do describe '#date_highlight_class' do it 'returns "table-row--warning" for courses ending soon' do course = build(:course, start: 1.month.ago, end: 5.days.from_now) expect(date_highlight_class(course)).to eq('table-row--warning') end it 'returns "table-row--info" for courses that started recently' do course = build(:course, start: 5.days.ago, end: 1.month.from_now) expect(date_highlight_class(course)).to eq('table-row--info') end it 'returns empty string for other courses' do course = build(:course, start: 1.month.ago, end: 1.month.from_now) expect(date_highlight_class(course)).to eq('') end end end
rajat2502/WikiEduDashboard
spec/lib/wiki_userpage_output_spec.rb
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/lib/wiki_userpage_output" describe WikiUserpageOutput do let(:enrollment_template) { described_class.new(course).enrollment_template } let(:enrollment_summary) { described_class.new(course).enrollment_summary } let(:enrollment_talk_template) { described_class.new(course).enrollment_talk_template } let(:sandbox_template) { described_class.new(course).sandbox_template('dashboard.wikiedu.org') } context 'for a ClassroomProgramCourse' do let(:course) { create(:course, submitted: true) } it '#enrollment_template returns output without the type param' do expect(enrollment_template).not_to include('| type =') end it '#enrollment_summary includes wikilink' do expect(enrollment_summary).to match(/User has enrolled in \[\[.*\]\]/) end end context 'for a FellowsCohort' do let(:course) { create(:fellows_cohort) } it 'returns output with the type param in each template' do expect(enrollment_template).to include('| type = scholars-and-scientists') expect(enrollment_talk_template).to include('| type = scholars-and-scientists') expect(sandbox_template).to include('| type = scholars-and-scientists') end it '#enrollment_summary does not include wikilink' do expect(enrollment_summary).not_to match(/\[\[.*\]\]/) end end end
rajat2502/WikiEduDashboard
app/mailers/unsubmitted_course_alert_mailer.rb
# frozen_string_literal: true class UnsubmittedCourseAlertMailer < ApplicationMailer def self.send_email(alert) return if !alert.user || alert.user.email.blank? email(alert).deliver_now end def email(alert) @instructor = alert.user @name = @instructor.real_name || @instructor.username @course_url = "https://#{ENV['dashboard_url']}/courses/#{alert.course.slug}" @classroom_program_manager = SpecialUsers.classroom_program_manager subject = 'Reminder: Submit your Wiki Education course page' mail(to: @instructor.email, reply_to: @classroom_program_manager.email, subject: subject) end end
mark-from-usds/cron
metadata.rb
name 'cron' maintainer '<NAME>, Inc.' maintainer_email '<EMAIL>' license 'Apache-2.0' description 'Installs cron' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '6.1.1' recipe 'cron', 'Installs the cron package and starts the crond service.' %w(ubuntu debian fedora redhat centos scientific oracle amazon smartos omnios solaris2 freebsd zlinux opensuse suse opensuseleap).each do |os| supports os end source_url 'https://github.com/chef-cookbooks/cron' issues_url 'https://github.com/chef-cookbooks/cron/issues' chef_version '>= 12.7' if respond_to?(:chef_version)
mark-from-usds/cron
resources/d.rb
# # Cookbook:: cron # Resource:: d # # Copyright:: 2008-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'shellwords' property :cron_name, String, name_property: true property :cookbook, String, default: 'cron' property :predefined_value, String, equal_to: %w( @reboot @yearly @annually @monthly @weekly @daily @midnight @hourly ) property :minute, [Integer, String], default: '*', callbacks: { 'should be a valid minute spec' => lambda do |spec| ::Cron::Helpers.validate_numeric(spec, 0, 59) end, } property :hour, [Integer, String], default: '*', callbacks: { 'should be a valid hour spec' => ->(spec) { ::Cron::Helpers.validate_numeric(spec, 0, 23) }, } property :day, [Integer, String], default: '*', callbacks: { 'should be a valid day spec' => ->(spec) { ::Cron::Helpers.validate_numeric(spec, 1, 31) }, } property :month, [Integer, String], default: '*', callbacks: { 'should be a valid month spec' => ->(spec) { ::Cron::Helpers.validate_month(spec) }, } property :weekday, [Integer, String], default: '*', callbacks: { 'should be a valid weekday spec' => ->(spec) { ::Cron::Helpers.validate_dow(spec) }, } property :command, String, required: true property :user, String, default: 'root' property :mailto, [String, NilClass] property :path, [String, NilClass] property :home, [String, NilClass] property :shell, [String, NilClass] property :comment, [String, NilClass] property :environment, Hash, default: {} property :mode, [String, Integer], default: '0600' def after_created raise 'The cron_d resource requires Linux as it needs support for the cron.d directory functionality.' unless node['os'] == 'linux' end action :create do create_template(:create) end action :create_if_missing do create_template(:create_if_missing) end action :delete do # cleanup the legacy named job if it exists file 'legacy named cron.d file' do path "/etc/cron.d/#{new_resource.cron_name}" action :delete end file "/etc/cron.d/#{sanitized_name}" do action :delete end end action_class do def sanitized_name new_resource.cron_name.tr('.', '-') end def create_template(create_action) # cleanup the legacy named job if it exists file "#{new_resource.cron_name} legacy named cron.d file" do path "/etc/cron.d/#{new_resource.cron_name}" action :delete only_if { new_resource.cron_name != sanitized_name } end template "/etc/cron.d/#{sanitized_name}" do cookbook new_resource.cookbook source 'cron.d.erb' mode new_resource.mode variables( name: sanitized_name, predefined_value: new_resource.predefined_value, minute: new_resource.minute, hour: new_resource.hour, day: new_resource.day, month: new_resource.month, weekday: new_resource.weekday, command: new_resource.command, user: new_resource.user, mailto: new_resource.mailto, path: new_resource.path, home: new_resource.home, shell: new_resource.shell, comment: new_resource.comment, environment: new_resource.environment ) action create_action end end end
mark-from-usds/cron
spec/unit/recipes/default_spec.rb
require 'spec_helper' platforms = [ { platform: 'debian', version: '9.3', package: 'cron', }, { platform: 'ubuntu', version: '16.04', package: 'cron', }, { platform: 'centos', version: '6.9', package: 'cronie', }, { platform: 'fedora', version: '27', package: 'cronie', }, { platform: 'centos', version: '7.4.1708', package: 'cronie', }, { platform: 'amazon', version: '2017.09', package: 'cronie', }, { platform: 'amazon', version: '2', package: 'cronie', }, { platform: 'suse', version: '11.4', package: 'cron', }, { platform: 'suse', version: '12.3', package: 'cronie', }, ] platforms.each do |p| describe "cron::default on #{p[:platform]} #{p[:version]}" do cached(:chef_run) { ChefSpec::SoloRunner.new(platform: p[:platform], version: p[:version]).converge('cron::default') } it 'installs the necessary cron package' do expect(chef_run).to install_package(p[:package]) end end end
marcreynolds/spree_affiliate
app/models/spree/user_decorator.rb
Spree::User.class_eval do has_many :affiliates, :class_name => 'Spree::Affiliate', :foreign_key => "partner_id" has_many :referred_users, :class_name => 'Spree::User', :through => :affiliates has_one :affiliate_partner, :class_name => "Spree::Affiliate", :foreign_key => "user_id" def referred_by affiliate_partner.partner end def ref_id self.id.to_s.reverse end def self.find_by_ref_id(ref_id) Spree::User.find_by_id(ref_id.to_s.reverse) end end
marcreynolds/spree_affiliate
app/controllers/spree/base_controller_decorator.rb
<filename>app/controllers/spree/base_controller_decorator.rb # This should be done in core/controller_helper for controllers not inheriting from basecontroller like devise registration Spree::BaseController.class_eval do before_filter :remember_affiliate private def remember_affiliate cookies.permanent[:ref_id] = params[:ref_id] if params[:ref_id] end end
marcreynolds/spree_affiliate
app/models/spree/affiliate_event.rb
class Spree::AffiliateEvent < ActiveRecord::Base attr_accessible :reward, :name, :user belongs_to :affiliate, :class_name => 'Spree::Affiliate' belongs_to :reward, :polymorphic => true belongs_to :user, :class_name => 'Spree::User' belongs_to :order, :class_name => 'Spree::Order' end
marcreynolds/spree_affiliate
spec/support/reset_affiliate_preferences.rb
<reponame>marcreynolds/spree_affiliate def reset_affiliate_preferences Spree::Preferences::Store.instance.persistence = false config = Rails.application.config.spree.affiliate_preferences config.reset yield(config) if block_given? end
marcreynolds/spree_affiliate
app/models/spree/affiliate_reward.rb
<filename>app/models/spree/affiliate_reward.rb module Spree class AffiliateReward < ActiveRecord::Base belongs_to :user, :class_name => 'Spree::User', :foreign_key => :user_id belongs_to :original_order, :class_name => 'Spree::Order', :foreign_key => :order_id attr_accessible :user, :order, :amount, :date_paid_out, :date_deleted, :comment, :paid # scope :ordered, order("order.created_at DESC") def paid? date_paid_out.present? end def paid=(object) # debugger if(object.to_i == 1 and self.date_paid_out.nil?) self.date_paid_out = Time.now elsif object.to_i == 0 and self.date_paid_out.present? self.date_paid_out = nil end end end end
marcreynolds/spree_affiliate
lib/affiliate_credits.rb
<gh_stars>0 module AffiliateCredits private def create_affiliate_credits(sender, recipient, event, order) # debugger #check if sender should receive credit on affiliate register sender_credit_amount = [SpreeAffiliate::Config["sender_credit_on_#{event}_amount".to_sym].to_f, (SpreeAffiliate::Config["sender_credit_on_#{event}_amount_percent".to_sym].to_f / 100.0) * order.total].max Spree::AffiliateReward.create(:user => sender, :order => order, :amount => sender_credit_amount) # if sender_credit_amount.to_f > 0 # credit = Spree::StoreCredit.create(:amount => sender_credit_amount, # :remaining_amount => sender_credit_amount, # :reason => "Affiliate: #{event}", :user_id => sender.id) # # log_event recipient.affiliate_partner || sender, sender, credit, event, order # end # # unless recipient.nil? # #check if affiliate should recevied credit on sign up # recipient_credit_amount = [SpreeAffiliate::Config["recipient_credit_on_#{event}_amount".to_sym].to_f, # (SpreeAffiliate::Config["recipient_credit_on_#{event}_amount_percent".to_sym].to_f / 100.0) * order.total # ] # if recipient_credit_amount.to_f > 0 # credit = Spree::StoreCredit.create(:amount => recipient_credit_amount, # :remaining_amount => recipient_credit_amount, # :reason => "Affiliate: #{event}", :user => recipient) # # log_event recipient.affiliate_partner, recipient, credit, event, order # end # end end # def log_event(affiliate, user, credit, event, order) # affiliate.events.create(:reward => credit, :name => event, :user => user, :order => order) # end end
marcreynolds/spree_affiliate
spec/requests/checkout_spec.rb
require 'spec_helper' feature 'affiliate store credit feature' do let(:sender) { Factory(:admin_user) } let!(:address) { FactoryGirl.create(:address, :state => Spree::State.first) } background do PAYMENT_STATES = Spree::Payment.state_machine.states.keys unless defined? PAYMENT_STATES SHIPMENT_STATES = Spree::Shipment.state_machine.states.keys unless defined? SHIPMENT_STATES ORDER_STATES = Spree::Order.state_machine.states.keys unless defined? ORDER_STATES FactoryGirl.create(:shipping_method, :zone => Spree::Zone.find_by_name('North America')) FactoryGirl.create(:payment_method, :environment => 'test') @product = FactoryGirl.create(:product, :name => "RoR Mug", :price => 49.99) end def add_product_to_cart_and_fill_address visit spree.product_path(@product) click_button "Add To Cart" click_link "Checkout" str_addr = "bill_address" select "United States", :from => "order_#{str_addr}_attributes_country_id" ['firstname', 'lastname', 'address1', 'city', 'zipcode', 'phone'].each do |field| fill_in "order_#{str_addr}_attributes_#{field}", :with => "#{address.send(field)}" end select "#{address.state.name}", :from => "order_#{str_addr}_attributes_state_id" check "order_use_billing" click_button "Save and Continue" click_button "Save and Continue" end scenario "recipient credit on register", :js => true do reset_affiliate_preferences do |config| config.recipient_credit_on_register_amount = 30 end visit "/?ref_id=#{sender.ref_id}" visit "/signup" fill_in "Email", :with => "<EMAIL>" fill_in "Password", :with => "<PASSWORD>" fill_in "Password Confirmation", :with => "<PASSWORD>" click_button "Create" add_product_to_cart_and_fill_address page.should have_content("You have $30.00 of store credits") fill_in "order_store_credit_amount", :with => "30" click_button "Save and Continue" page.should have_content("Your order has been processed successfully") end scenario "sender credit on purchase", :js => true do reset_affiliate_preferences do |config| config.sender_credit_on_purchase_amount = 30 end visit "/ref_id=#{sender.ref_id}" add_product_to_cart_and_fill_address click_button "Save and Continue" Spree::AffiliateReward.where(:user => user).count.should == 1 end end
marcreynolds/spree_affiliate
config/routes.rb
Spree::Core::Engine.routes.prepend do namespace :admin do resource :affiliate_settings end resources :affiliates, :only => [:show, :index] end
marcreynolds/spree_affiliate
config/initializers/load_configuration.rb
# module SpreeAffiliate # Config = SpreeAffiliate::Configuration.new # end
marcreynolds/spree_affiliate
app/models/spree/affiliate.rb
<reponame>marcreynolds/spree_affiliate class Spree::Affiliate < ActiveRecord::Base belongs_to :partner, :class_name => "Spree::User", :foreign_key => :partner_id belongs_to :user, :class_name => 'Spree::User' has_many :events, :class_name => "Spree::AffiliateEvent" attr_accessible :user_id def name I18n.t(:affiliate_program) end def ref_id partner ? partner.ref_id : '' end end
marcreynolds/spree_affiliate
app/models/spree/order_decorator.rb
<filename>app/models/spree/order_decorator.rb<gh_stars>0 Spree::Order.class_eval do # has_one :affiliate_reward, :class_name => "Spree::AffiliateReward" end
marcreynolds/spree_affiliate
lib/spree_affiliate.rb
<gh_stars>0 require 'spree_core' # require 'spree_auth' require 'spree_affiliate/engine'
marcreynolds/spree_affiliate
db/migrate/20121023065159_create_spree_affiliate_reward.rb
class CreateSpreeAffiliateReward < ActiveRecord::Migration def up create_table :spree_affiliate_rewards do |t| t.integer :user_id t.integer :order_id t.float :amount t.date :date_paid_out t.date :date_deleted t.string :comment end end def down drop_table :spree_affiliate_rewards end end
marcreynolds/spree_affiliate
spree_affiliate.gemspec
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_affiliate' s.version = '1.0.1' s.authors = ['Rails Dog'] s.email = '<EMAIL>' s.homepage = 'http://github.com/spree/spree_affiliate' s.summary = 'Affiliate support for Spree' s.description = 'Affiliate support for Spree' s.required_ruby_version = '>= 1.8.7' s.rubygems_version = '1.3.6' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_dependency('spree_core', '>= 1.2.0') # s.add_dependency('spree_auth', '>= 1.2.0') # s.add_dependency('spree_store_credits', '>= 1.0.0') s.add_development_dependency 'capybara', '1.0.1' s.add_development_dependency 'factory_girl' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.7' s.add_development_dependency 'sass-rails' s.add_development_dependency 'sqlite3' s.add_development_dependency 'launchy' s.add_development_dependency 'debugger' end
marcreynolds/spree_affiliate
app/controllers/spree/checkout_controller_decorator.rb
Spree::CheckoutController.class_eval do include AffiliateCredits private def after_complete # debugger session[:order_id] = nil # still should create reward if the user was a guest sender = (current_user && current_user.affiliate_partner) || (cookies[:ref_id] && Spree::User.find_by_id(cookies[:ref_id])) # if current_user && current_user.affiliate_partner # && current_user.orders.where(:state => 'complete').count == 1 # sender = current_user.affiliate_partner.partner #create credit (if required) create_affiliate_credits(sender, current_user, "purchase", @order) unless sender.nil? # end end end
kozo2/bio-keggapi
lib/keggapi.rb
<filename>lib/keggapi.rb require 'net/http' module Keggapi def self.info(database) url = URI.parse("http://rest.kegg.jp/info/") res = Net::HTTP.start(url.host, url.port) do |http| sub = root + database http.get(sub) end p res.body end end
JulianNicholls/Complete-Finance-Tracker
app/controllers/user/registrations_controller.rb
# Controller for user registration to allow for first and last names class User::RegistrationsController < Devise::RegistrationsController before_filter :configure_permitted_parameters protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up).push(:first_name, :last_name) devise_parameter_sanitizer.for(:account_update).push(:first_name, :last_name) end end
JulianNicholls/Complete-Finance-Tracker
test/models/user_stock_test.rb
require 'test_helper' # Tests for User tracked Stocks class UserStockTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
JulianNicholls/Complete-Finance-Tracker
app/controllers/user_stocks_controller.rb
# Controller fur user tracked stocks class UserStocksController < ApplicationController # GET /user_stocks # GET /user_stocks.json def index @user_stocks = UserStock.all end # GET /user_stocks/new def new @user_stock = UserStock.new end # POST /user_stocks # POST /user_stocks.json def create @user_stock = create_record respond_to do |format| if @user_stock.save ticker = @user_stock.stock.ticker format.html do redirect_to my_portfolio_path, notice: "The stock #{ticker} was successfully added." end format.json { render :show, status: :created, location: @user_stock } else format.html { render :new } format.json do render json: @user_stock.errors, status: :unprocessable_entity end end end end # DELETE /user_stocks/1 # DELETE /user_stocks/1.json def destroy @user_stock = UserStock.find(params[:id]) @user_stock.destroy respond_to do |format| format.html do redirect_to my_portfolio_path, notice: 'The stock was successfully removed.' end format.json { head :no_content } end end private # Never trust parameters from the internet, only allow the white list through. def user_stock_params params.require(:user_stock).permit(:user_id, :stock_id) end def create_record if params[:stock_id].present? UserStock.new stock_id: params[:stock_id], user: current_user else create_from_stock_record end end def create_from_stock_record stock = Stock.find_by_ticker stock_ticker return record_from_stock(stock) if stock stock = Stock.new_from_lookup stock_ticker return record_from_stock(stock) if stock.save flash[:error] = 'The stock is not currently available.' nil end def record_from_stock(stock) UserStock.new stock: stock, user: current_user end def stock_ticker params[:stock_ticker] end end
JulianNicholls/Complete-Finance-Tracker
test/controllers/welcome_controller_test.rb
<filename>test/controllers/welcome_controller_test.rb<gh_stars>1-10 require 'test_helper' # Tests for home page controller class WelcomeControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end
JulianNicholls/Complete-Finance-Tracker
app/controllers/friendships_controller.rb
<reponame>JulianNicholls/Complete-Finance-Tracker<filename>app/controllers/friendships_controller.rb class FriendshipsController < ApplicationController def destroy friend = current_user.friendships.where(friend_id: params[:id]).first friend.destroy respond_to do |format| format.html { redirect_to my_friends_path, notice: 'The friend was removed successfully' } end end end