repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
daniel-sim/common
lib/pr/common/version.rb
<filename>lib/pr/common/version.rb module PR module Common VERSION = '0.3.8' end end
daniel-sim/common
app/jobs/shop_update_job.rb
<gh_stars>0 class ShopUpdateJob < PR::Common::ApplicationJob def perform(params) with_analytics do shop = Shop.find_by(shopify_domain: params[:shop_domain]) # ensure we have a user PR::Common::UserService .new .find_or_create_user_by_shopify(email: params[:webhook][:email], shop: shop) shopify_service = PR::Common::ShopifyService.new(shop: shop) shopify_service.update_shop(shopify_plan: params[:webhook][:plan_name], uninstalled: false) shopify_service.update_user(email: params[:webhook][:email]) end end end
daniel-sim/common
db/migrate/20181008151650_add_provider_to_users.rb
class AddProviderToUsers < ActiveRecord::Migration[5.0] def change # prevent this migration failing for apps that already have a # provider on users return if column_exists? :users, :provider add_column :users, :provider, :integer end end
daniel-sim/common
db/migrate/20180920132700_add_uninstalled_to_shops.rb
class AddUninstalledToShops < ActiveRecord::Migration[5.0] def change # prevent this migration failing for apps that already have an # uninstalled on shops return if column_exists? :shops, :uninstalled add_column :shops, :uninstalled, :boolean, null: false, default: false end end
daniel-sim/common
spec/dummy/db/schema.rb
<filename>spec/dummy/db/schema.rb # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2019_05_20_170125) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "admins", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["email"], name: "index_admins_on_email", unique: true t.index ["reset_password_token"], name: "index_admins_on_reset_password_token", unique: true end create_table "promo_codes", id: :serial, force: :cascade do |t| t.string "code", null: false t.string "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "expires_at" t.decimal "value", precision: 5, scale: 2, default: "100.0", null: false t.integer "created_by_id" t.index ["code"], name: "index_promo_codes_on_code" t.index ["created_by_id"], name: "index_promo_codes_on_created_by_id" end create_table "shops", force: :cascade do |t| t.string "shopify_plan" t.string "shopify_domain" t.string "shopify_token", null: false t.boolean "uninstalled", default: false, null: false t.string "app_plan" t.integer "promo_code_id" t.index ["app_plan"], name: "index_shops_on_app_plan" t.index ["promo_code_id"], name: "index_shops_on_promo_code_id" t.index ["shopify_domain"], name: "index_shops_on_shopify_domain" end create_table "time_periods", force: :cascade do |t| t.datetime "start_time", default: -> { "now()" }, null: false t.datetime "end_time" t.integer "kind", default: 0, null: false t.datetime "shop_retained_analytic_sent_at" t.bigint "shop_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "converted_to_paid_at" t.decimal "monthly_usd", default: "0.0", null: false t.datetime "period_last_paid_at" t.integer "periods_paid", default: 0, null: false t.index ["converted_to_paid_at"], name: "index_time_periods_on_converted_to_paid_at" t.index ["end_time"], name: "index_time_periods_on_end_time" t.index ["kind"], name: "index_time_periods_on_kind" t.index ["period_last_paid_at"], name: "index_time_periods_on_period_last_paid_at" t.index ["shop_id"], name: "index_time_periods_on_shop_id" t.index ["shop_retained_analytic_sent_at"], name: "index_time_periods_on_shop_retained_analytic_sent_at" t.index ["start_time"], name: "index_time_periods_on_start_time" end create_table "users", id: :serial, force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.string "name" t.boolean "confirmed" t.string "access_token" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "active_charge", default: false t.integer "shop_id" t.string "referrer" t.integer "provider" t.datetime "charged_at" t.string "username", null: false t.string "website", null: false t.index ["email"], name: "index_users_on_email", unique: true t.index ["provider"], name: "index_users_on_provider" t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true t.index ["username"], name: "index_users_on_username" end end
daniel-sim/common
app/controllers/admin/promo_codes_controller.rb
<reponame>daniel-sim/common module Admin class PromoCodesController < BaseController def new @promo_code = PR::Common::Models::PromoCode.new end def create @promo_code = PR::Common::Models::PromoCode.new(promo_code_params) @promo_code.created_by = current_admin if @promo_code.save redirect_to new_admin_promo_code_path, notice: "Promo code <code>#{@promo_code.code}</code> saved!" return end flash[:alert] = "Could not save Promo Code." render :new end private def promo_code_params params.require(:promo_code).permit(:code, :value, :description, :expires_at) end end end
daniel-sim/common
lib/pr/common/configuration.rb
module PR module Common class Configuration attr_accessor :signup_params, :send_welcome_email, :send_confirmation_email, :referrer_redirect, :pricing, :default_app_plan attr_writer :pricing_method # Symbol of method to call on ShopifyService or lambda. def pricing_method @pricing_method || :determine_price_by_plan_name end end end end
daniel-sim/common
db/migrate/20190514142223_common_add_created_by_to_promo_codes.rb
class CommonAddCreatedByToPromoCodes < ActiveRecord::Migration[5.0] def change add_reference :promo_codes, :created_by end end
daniel-sim/common
spec/models/shop_spec.rb
require "rails_helper" RSpec.describe Shop, type: :model do it { is_expected.to belong_to(:promo_code).optional } describe ".with_active_charge" do it "includes only shops with a user whose active charge is true" do active_charge_shop = create(:shop, user: build(:user, active_charge: true)) inactive_charge_shop = create(:shop) shops = Shop.with_active_charge expect(shops).to include(active_charge_shop) expect(shops).not_to include(inactive_charge_shop) end end describe ".with_active_plan" do it "includes only shops whose plan is not cancelled, frozen, locked, or fraudulent" do active_plan_shop = create(:shop) cancelled_plan_shop = create(:shop, shopify_plan: "cancelled") locked_plan_shop = create(:shop, shopify_plan: "locked") frozen_plan_shop = create(:shop, shopify_plan: "frozen") fraudulent_plan_shop = create(:shop, shopify_plan: "frozen") shops = Shop.with_active_plan expect(shops).to include active_plan_shop expect(shops).not_to include cancelled_plan_shop expect(shops).not_to include locked_plan_shop expect(shops).not_to include fraudulent_plan_shop expect(shops).not_to include frozen_plan_shop end end describe ".installed" do it "includes only shops which are not uninstalled" do installed_shop = create(:shop, uninstalled: false) uninstalled_shop = create(:shop, uninstalled: true) shops = Shop.installed expect(shops).to include installed_shop expect(shops).not_to include uninstalled_shop end end describe "#installed?" do subject { shop.installed? } context "when not uninstalled" do let(:shop) { build(:shop) } it { is_expected.to eq true } end context "when uninstalled" do let(:shop) { build(:shop, :uninstalled) } it { is_expected.to eq false } end end describe "#app_plan" do context "when it is not set to anything" do it "returns nil" do expect(build(:shop).app_plan).to be_nil end end context "when it is not set to anything but a default is set" do before { allow(PR::Common.config).to receive(:default_app_plan).and_return("something") } it "returns the default" do expect(build(:shop).app_plan).to eq "something" end end context "when it is set" do it "returns the set app_plan" do expect(build(:shop, app_plan: "foo").app_plan).to eq "foo" end end end describe "#status" do it "is :inactive when shop is frozen" do expect(build(:shop, shopify_plan: Shop::PLAN_FROZEN).status).to eq :inactive end it "is :inactive when shop is closed" do expect(build(:shop, shopify_plan: Shop::PLAN_CANCELLED).status).to eq :inactive end it "is :inactive when shop is fraudulent" do expect(build(:shop, shopify_plan: Shop::PLAN_FRAUDULENT).status).to eq :inactive end it "is :locked when shop is locked" do expect(build(:shop, shopify_plan: Shop::PLAN_LOCKED).status).to eq :locked end it "is :uninstalled if app is uninstalled" do expect(build(:shop, uninstalled: true).status).to eq :uninstalled end it "is :active for any other shop" do expect(build(:shop).status).to eq :active end end describe "#time_periods" do let(:current_time) { DateTime.new(2018, 1, 1) } around { |example| Timecop.freeze(current_time, &(example.method(:run))) } context "when shop is newly installed" do let(:shop) { create(:shop) } it "creates a new time period of type `installed`" do expect(shop.time_periods.count).to eq 1 expect(shop.time_periods.last).to be_installed expect(shop.time_periods.last.start_time).to eq current_time expect(shop.time_periods.last.end_time).to be_nil end end context "when shop is `uninstalled`" do let(:shop) { create(:shop, :uninstalled) } it "creates a new time period of type `uninstalled`" do expect(shop.time_periods.count).to eq 1 expect(shop.time_periods.last).to be_uninstalled expect(shop.time_periods.last.start_time).to eq current_time expect(shop.time_periods.last.end_time).to be_nil end end context "when shop has a `cancelled` plan" do let(:shop) { create(:shop, :cancelled) } it "creates a new time period of type `closed`" do expect(shop.time_periods.count).to eq 1 expect(shop.time_periods.last).to be_closed expect(shop.time_periods.last.start_time).to eq current_time expect(shop.time_periods.last.end_time).to be_nil end end shared_examples "inherits attributes from previous time period" do it "copies converted_to_paid_at, monthly_usd, and period_last_paid_at from the previous time period" do converted_to_paid_at = Time.zone.local(2018, 1, 1) period_last_paid_at = Time.zone.local(2018, 1, 1) monthly_usd = 20.0 shop.current_time_period.update!(monthly_usd: monthly_usd, period_last_paid_at: period_last_paid_at, converted_to_paid_at: converted_to_paid_at) operation expect(shop.time_periods.last.monthly_usd).to eq monthly_usd expect(shop.time_periods.last.period_last_paid_at).to eq period_last_paid_at expect(shop.time_periods.last.converted_to_paid_at).to eq converted_to_paid_at end end context "when transitioning from installed to uninstalled" do let!(:shop) { create(:shop) } let(:operation) { shop.update!(uninstalled: true) } it "ends the current period" do operation expect(shop.time_periods.first.end_time).to eq current_time end it "creates a new time period" do expect { operation } .to change { shop.time_periods.count } .from(1) .to(2) end it "starts now" do operation expect(shop.time_periods.last.start_time).to eq current_time end it "has no end time" do operation expect(shop.time_periods.last.end_time).to eq nil end it "is of kind 'uninstalled'" do operation expect(shop.time_periods.last).to be_uninstalled end include_examples "inherits attributes from previous time period" end context "when transitioning from uninstalled to reinstalled" do let!(:shop) { create(:shop, :uninstalled) } let(:operation) { shop.update!(uninstalled: false) } it "ends the current period" do operation expect(shop.time_periods.first.end_time).to eq current_time end it "creates a new time period" do expect { operation } .to change { shop.time_periods.count } .from(1) .to(2) end it "starts now" do operation expect(shop.time_periods.last.start_time).to eq current_time end it "has no end time" do operation expect(shop.time_periods.last.end_time).to eq nil end it "is of kind 'reinstalled'" do operation expect(shop.time_periods.last).to be_reinstalled end it "does not copy over converted_to_paid_at, monthly_usd, and period_last_paid_at from the previous time period" do converted_to_paid_at = Time.zone.local(2018, 1, 1) period_last_paid_at = Time.zone.local(2018, 1, 1) monthly_usd = 20.0 shop.current_time_period.update!(monthly_usd: monthly_usd, period_last_paid_at: period_last_paid_at, converted_to_paid_at: converted_to_paid_at) operation expect(shop.time_periods.last.monthly_usd).to eq 0 expect(shop.time_periods.last.period_last_paid_at).to eq nil expect(shop.time_periods.last.converted_to_paid_at).to eq nil end end context "when transitioning from installed to closed" do let!(:shop) { create(:shop) } let(:operation) { shop.update!(shopify_plan: "cancelled") } it "ends the current period" do operation expect(shop.time_periods.first.end_time).to eq current_time end it "creates a new time period" do expect { operation } .to change { shop.time_periods.count } .from(1) .to(2) end it "starts now" do operation expect(shop.time_periods.last.start_time).to eq current_time end it "has no end time" do operation expect(shop.time_periods.last.end_time).to eq nil end it "is of kind 'closed'" do operation expect(shop.time_periods.last).to be_closed end include_examples "inherits attributes from previous time period" end context "when transitioning from closed to reopened" do let!(:shop) { create(:shop, :cancelled) } let(:operation) { shop.update!(shopify_plan: "affiliate") } it "ends the current period" do operation expect(shop.time_periods.first.end_time).to eq current_time end it "creates a new time period" do expect { operation } .to change { shop.time_periods.count } .from(1) .to(2) end it "starts now" do operation expect(shop.time_periods.last.start_time).to eq current_time end it "has no end time" do operation expect(shop.time_periods.last.end_time).to eq nil end it "is of kind 'reopened'" do operation expect(shop.time_periods.last).to be_reopened end include_examples "inherits attributes from previous time period" end end describe "#current_time_period" do let(:shop) { create(:shop) } before do # installed -> uninstalled -> reinstalled -> closed -> reopened shop.update!(uninstalled: true) shop.update!(uninstalled: "false") shop.update!(shopify_plan: "cancelled") shop.update!(shopify_plan: "basic") end it "returns the most recent time period" do expect(shop.current_time_period).to be_reopened end end describe "#total_days_installed" do it "returns the total days whilst installed, reopened, and reinstalled" do # new shop with installed time period Timecop.freeze Time.zone.local(2018, 1, 1) shop = create(:shop) # 1 day effective, create uninstalled time period Timecop.freeze Time.zone.local(2018, 1, 1, 0, 0, 1) shop.update!(uninstalled: true) # 1 day effective, create reinstalled time period Timecop.freeze Time.zone.local(2018, 1, 1, 0, 0, 2) shop.update!(uninstalled: "false") # 1 day effective, create cancelled time period Timecop.freeze Time.zone.local(2018, 1, 1, 0, 0, 3) shop.update!(shopify_plan: "cancelled") # 1 day effective, create reopened time period Timecop.freeze Time.zone.local(2018, 1, 1, 0, 0, 4) shop.update!(shopify_plan: "basic") # 1 day effective Timecop.freeze Time.zone.local(2018, 1, 1, 0, 0, 5) expect(shop.total_days_installed).to eq 3 Timecop.return end end # installed -> uninstalled -> reinstalled # total periods paid: 7, 3 of which are at $100 and 4 of which are at $10 def create_paid_time_periods(shop) shop.current_time_period.update!(periods_paid: 3, monthly_usd: 100.0) shop.update!(uninstalled: true) shop.update!(uninstalled: "false") shop.current_time_period.update!(periods_paid: 4, monthly_usd: 10.0) end describe "#total_periods_paid" do subject(:shop) { create(:shop) } before do create_paid_time_periods(shop) shop.reload end it "returns the periods paid across all time periods" do expect(shop.total_periods_paid).to eq 7 end end describe "#total_usd_paid" do subject(:shop) { create(:shop) } before do create_paid_time_periods(shop) shop.reload end it "returns the amount paid across all time periods" do expect(shop.total_usd_paid).to eq BigDecimal("340.0") end end end
daniel-sim/common
spec/lib/pr/common/sustained_analytics_service_spec.rb
<reponame>daniel-sim/common require "rails_helper" describe PR::Common::SustainedAnalyticsService do subject(:service) { described_class.new(shop, current_time: current_time) } let!(:shop) { create(:shop, :with_user, shopify_plan: "basic", charged_at: current_time) } let(:current_time_period) { shop.current_time_period } let(:current_time) { Time.zone.local(2018, 1, 14, 0, 0, 1) } before do current_time_period.update!(monthly_usd: 10) # this should be set from activating the charge end around { |example| Timecop.freeze(current_time, &example.method(:run)) } describe "#perform" do describe "payment charged" do context "when shop was converted to paid 30 days ago" do let(:current_time) { Time.zone.local(2018, 1, 31) } before do current_time_period.update!(converted_to_paid_at: Time.zone.local(2018, 1, 1)) shop.time_periods.reload end it "updates period_last_paid_at to now" do expect { service.perform } .to change { current_time_period.reload.period_last_paid_at } .from(nil) .to(current_time) end it "increments periods_paid" do expect { service.perform } .to change { current_time_period.reload.periods_paid } .from(0) .to(1) end it "sends an identify analytic" do expect(Analytics).to receive(:identify) .with( user_id: shop.user.id, traits: { email: shop.user.email, currentPeriodsPaid: 1, totalPeriodsPaid: 1, monthlyUsd: 10.0, currentUsdPaid: 10.0, totalUsdPaid: 10.0 } ) service.perform end it "sends a Payment Charged track analytic" do expect(Analytics).to receive(:track) .with( user_id: shop.user.id, event: "Payment Charged", properties: { email: shop.user.email, current_periods_paid: 1, total_periods_paid: 1, monthly_usd: 10.0, current_usd_paid: 10.0, total_usd_paid: 10.0 } ) service.perform end end end context "when shop's current time period is installed" do context "when time period started under 7 days ago and shop_retained_analytic_sent_at is nil" do before { current_time_period.update!(start_time: current_time) } it "does not send an identify analytic" do expect(Analytics).not_to receive(:identify) service.perform end it "does not send a track analytic" do expect(Analytics).not_to receive(:track) service.perform end it "does not change the time period's shop_retained_analytic_sent_at" do expect { service.perform } .not_to change(current_time_period, :shop_retained_analytic_sent_at) .from(nil) end end context "when time period was started over 7 days ago and shop_retained_analytic_sent_at is nil" do before do current_time_period.update!(start_time: Time.zone.local(2018, 1, 7)) shop.update!(charged_at: Time.zone.local(2018, 1, 7), app_plan: :generic) end it "sends identify analytics" do expect(Analytics).to receive(:identify) .with( user_id: shop.user.id, traits: { email: shop.user.email, trial: false, monthlyUsd: 10.0, appPlan: "generic" } ) expect(Analytics).to receive(:identify) .with( user_id: shop.user.id, traits: { email: shop.user.email, monthlyUsd: 10.0, currentPeriodsPaid: 1, currentUsdPaid: 10.0, totalPeriodsPaid: 1, totalUsdPaid: 10.0 } ) expect(Analytics).to receive(:identify) .with( user_id: shop.user.id, traits: { email: shop.user.email, currentDaysInstalled: 8, totalDaysInstalled: 8 } ) service.perform end it "sends track analytics" do expect(Analytics).to receive(:track) .with( user_id: shop.user.id, event: "Converted to Paid", properties: { email: shop.user.email, monthly_usd: 10.0, app_plan: "generic" } ) expect(Analytics).to receive(:track) .with( user_id: shop.user.id, event: "Payment Charged", properties: { email: shop.user.email, monthly_usd: 10.0, current_periods_paid: 1, current_usd_paid: 10.0, total_periods_paid: 1, total_usd_paid: 10.0 } ) expect(Analytics).to receive(:track) .with( user_id: shop.user.id, event: "Shop Retained", properties: { email: shop.user.email, current_days_installed: 8, total_days_installed: 8 } ) service.perform end it "updates the time period's shop_retained_analytic_sent_at to the current time" do expect { service.perform } .to change { current_time_period.reload.shop_retained_analytic_sent_at } .from(nil) .to(current_time) end end context "when time period was started over 7 days ago and shop_retained_analytic_sent_at was under 7 days ago" do before do current_time_period.update!(start_time: Time.zone.local(2018, 1, 1), shop_retained_analytic_sent_at: current_time) end it "does not send an identify analytic" do expect(Analytics).not_to receive(:identify) service.perform end it "does not send a track analytic" do expect(Analytics).not_to receive(:track) service.perform end it "does not change the time period's shop_retained_analytic_sent_at" do expect { service.perform } .not_to change { current_time_period.reload.shop_retained_analytic_sent_at } end end context "when time period was started over 7 days ago and shop_retained_analytic_sent_at is over 7 days ago" do before do current_time_period.update!(start_time: Time.zone.local(2018, 1, 1), shop_retained_analytic_sent_at: Time.zone.local(2018, 1, 7)) end it "sends an identify analytic" do expect(Analytics).to receive(:identify) .with( user_id: shop.user.id, traits: { email: shop.user.email, currentDaysInstalled: 14, totalDaysInstalled: 14 } ) service.perform end it "sends a track analytic" do expect(Analytics).to receive(:track) .with( user_id: shop.user.id, event: "Shop Retained", properties: { email: shop.user.email, current_days_installed: 14, total_days_installed: 14 } ) service.perform end it "updates the time period's shop_retained_analytic_sent_at to the current time" do expect { service.perform } .to change { current_time_period.reload.shop_retained_analytic_sent_at } .to(current_time) end end end end end
daniel-sim/common
spec/lib/pr/common/session_promo_code_service_spec.rb
<filename>spec/lib/pr/common/session_promo_code_service_spec.rb require "rails_helper" describe SessionPromoCodeService do subject(:service) { described_class.new(session) } let(:code) { "THE-CODE" } let(:promo_code) { PR::Common::Models::PromoCode.create(code: code) } let(:shop) { create(:shop) } let(:session) { {} } describe "#maybe_apply_to_shop" do context "when no code is in session" do it "does not apply" do expect { service.maybe_apply_to_shop(shop) } .not_to change(shop, :promo_code) end end context "when the promo code in session does not exist" do before { session[:promo_code] = "non-existant code" } it "does not apply" do expect { service.maybe_apply_to_shop(shop) } .not_to change(shop, :promo_code) end end context "when the promo code in session does exist" do before { session[:promo_code] = code } context "when the promo code is expired" do around do |example| Timecop.freeze do promo_code.update!(expires_at: Time.current) example.run end end it "does not apply the code" do expect { service.maybe_apply_to_shop(shop) } .not_to change(shop, :promo_code) .from(nil) end end context "when the shop has no promo code" do it "applies the code" do expect { service.maybe_apply_to_shop(shop) } .to change(shop, :promo_code) .from(nil) .to(promo_code) end end context "when the shop already has a promo code" do let(:existing_promo_code) { PR::Common::Models::PromoCode.create(code: "EXISTING-PROMO-CODE") } before { shop.update!(promo_code: existing_promo_code) } it "overwrites the old code" do expect { service.maybe_apply_to_shop(shop) } .to change(shop, :promo_code) .from(existing_promo_code) .to(promo_code) end end end end describe "#store" do it "stores the code in session" do expect { service.store(promo_code) } .to change { session[:promo_code] } .from(nil) .to(code) end end describe "#clear" do it "deletes the promo code from the session" do session[:promo_code] = code expect { service.clear } .to change { session[:promo_code] } .from(code) .to(nil) end end end
daniel-sim/common
lib/pr/common/models/promo_code.rb
<reponame>daniel-sim/common module PR module Common module Models class PromoCode < ApplicationRecord self.table_name = "promo_codes" def self.model_name ActiveModel::Name.new(self, nil, "PromoCode") end has_many :shops, class_name: "::Shop" belongs_to :created_by, class_name: "PR::Common::Models::Admin", inverse_of: :promo_codes validates :code, uniqueness: true, presence: true validates :value, numericality: { greater_than_or_equal_to: 0 } before_validation :upcase_code def redeemable? return true unless expires_at expires_at > Time.current end private def upcase_code code&.upcase! end end end end end
daniel-sim/common
spec/factories/shops.rb
FactoryBot.define do factory :shop do sequence(:shopify_domain) { |n| "shop#{n}" } shopify_token { "<PASSWORD>" } shopify_plan { "affiliate" } uninstalled { false } trait :uninstalled do uninstalled { true } end trait :cancelled do shopify_plan { "cancelled" } end trait :frozen do shopify_plan { "frozen" } end trait :with_user do user end end end
daniel-sim/common
db/migrate/20190118074633_common_add_converted_to_paid_add_to_time_period.rb
<reponame>daniel-sim/common class CommonAddConvertedToPaidAddToTimePeriod < ActiveRecord::Migration[5.0] def change add_column :time_periods, :converted_to_paid_at, :datetime add_index :time_periods, :converted_to_paid_at end end
daniel-sim/common
lib/tasks/pr/common_tasks.rake
<reponame>daniel-sim/common namespace 'common' do namespace 'webhooks' do desc "Recreate all webhooks based on config. Optionally pass a comma-separated list of domains." task :recreate, [:shops_file] => [:environment] do |_, args| FileUtils.mkdir_p(Rails.root.join('tmp')) Rails.logger = Logger.new Rails.root.join('tmp', 'common-webhooks-recreate.log') shops = if args[:shops_file].present? Shop.where( shopify_domain: File .read(args[:shops_file]) .split('\s') .map(&:strip)) else Shop.installed end puts PR::Common::WebhookService.recreate_webhooks!(shops) end end namespace "shops" do desc "Reconcile shops" task reconcile: :environment do PR::Common::ShopUpdateReconcileJob.enqueue end end namespace "import" do # This is a one-off task to import payment history, populating the last payment # and sending relevant analytics. It's not well tested, and is intended to be removed # when it has been run across all apps. # # Notes: # There may be duplicate shops (we will use only the one with the most recent end date) # Every row must have an `end_date` # If the end date is more than 100 days ago, we will ignore it # Each shop will be reconciled before any changes are made # Analytic will only be sent for shops whose time period is in TIME_PERIOD::KINDS_IN_USE, and # where the end period is <= current time desc "Payment history" task :payment_history, [:csv_file] => :environment do |_, args| shops = Hash.new { |h, k| h[k] = [] } CSV.foreach(Rails.root.join(args[:csv_file]), col_sep: ";", headers: :first_row) do |row| next if row["Billing Period End"].blank? shop_domain = row["Shop Domain"] period_end = Time.zone.parse(row["Billing Period End"]) shops[shop_domain] << period_end end shops.each do |domain, period_end_dates| now = Time.current most_recent_date = period_end_dates.max if most_recent_date < (now - 100.days) puts "[#{domain}]: Most recent date is too old!\n\n" next end shop = Shop.find_by(shopify_domain: domain) unless shop puts "[#{domain}]: Could not find shop!\n\n" next end puts "[#{domain}]: Reconciling" reconciled = begin PR::Common::ShopifyService.new(shop: shop).reconcile_with_shopify rescue puts "[#{domain}]: Reconciliation raised error!\n\n" next end unless reconciled puts "[#{domain}] Reconciliation failed!\n\n" next end current_time_period = shop.current_time_period if current_time_period.reload.closed? || current_time_period.uninstalled? puts "[#{domain}] Time period is #{current_time_period.kind}, so skipping.\n\n" next end current_time_period.update(period_last_paid_at: most_recent_date, periods_paid: current_time_period.periods_paid.next) puts "[#{domain}]: Setting last payment date: #{most_recent_date}, incrementing periods paid" if most_recent_date > now puts "[#{domain}]: Paid in the future; not sending analytics\n\n" else puts "[#{domain}]: Sending analytics\n\n" shop.reload current_periods_paid = current_time_period.periods_paid total_periods_paid = shop.total_periods_paid monthly_usd = current_time_period.monthly_usd.to_f current_usd_paid = current_time_period.usd_paid.to_f total_usd_paid = shop.total_usd_paid.to_f Analytics.identify( user_id: shop.user.id, traits: { email: shop.user.email, currentPeriodsPaid: current_periods_paid, totalPeriodsPaid: total_periods_paid, monthlyUsd: monthly_usd, currentUsdPaid: current_usd_paid, totalUsdPaid: total_usd_paid } ) Analytics.track( user_id: shop.user.id, event: "Payment Charged", properties: { email: shop.user.email, current_periods_paid: current_periods_paid, total_periods_paid: total_periods_paid, monthly_usd: monthly_usd, current_usd_paid: current_usd_paid, total_usd_paid: total_usd_paid } ) Analytics.flush end end end end end
daniel-sim/common
config/initializers/sidekiq.rb
require 'sidekiq' require 'sidekiq/web' Sidekiq::Web.use(Rack::Auth::Basic) do |user, password| [user, password] == [ENV['sidekiq_admin_login'], ENV['sidekiq_admin_password']] end
daniel-sim/common
app/controllers/sessions_controller.rb
<reponame>daniel-sim/common class SessionsController < ApiBaseController skip_before_action :authenticate_user_from_token! def create auth_key = Devise.authentication_keys.first @user = User.find_for_database_authentication(auth_key => signin_params[auth_key]) if @user && @user.valid_password?(signin_params[:password]) sign_in :user, @user render json: @user, serializer: SessionSerializer, meta: {} else warden.custom_failure! render json: nil, serializer: SessionSerializer, meta: { errors: { auth_key => ["Invalid #{auth_key} and/or password"] }}, status: :unprocessable_entity end end protected private def signin_params params.require(:signin).permit(:username, :email, :password) end end
daniel-sim/common
lib/pr/common/webhook_service.rb
<gh_stars>0 module PR module Common class WebhookService # Recreates all webhooks and returns a list of any that failed def self.recreate_webhooks!(shops = Shop.installed) shops.find_each.map do |shop| new(shop).recreate_webhooks! || shop.shopify_domain end.reject { |item| item == true } end def initialize(shop) @shop = shop end def recreate_webhooks! wrap_errors do with_shop do Rails.logger.info "Recreating webhooks for #{@shop.shopify_domain}" # If anything fails due to shop not being installed, # I would expect it to happen here. existing_webhooks = fetch_existing # ensure that any new webhooks are installed first. # that way, if something goes wrong, at least we haven't removed # anything. maybe_install_from_config(existing_webhooks) maybe_destroy(existing_webhooks) true end end end private def fetch_existing ShopifyAPI::Webhook.all end def maybe_install_from_config(api_webhooks) configured_webhooks .reject { |configured_webhook| api_webhook_exists?(configured_webhook, api_webhooks) } .each(&(ShopifyAPI::Webhook.method(:create))) end def maybe_destroy(api_webhooks) Array.wrap(api_webhooks) .reject(&method(:configured_webhook_exists?)) .each { |api_webhook| ShopifyAPI::Webhook.delete(api_webhook.id) } end def api_webhook_exists?(configured_webhook, api_webhooks) api_webhooks.detect do |api_webhook| configured_webhook[:topic] == api_webhook.topic && configured_webhook[:address] == api_webhook.address && configured_webhook[:format] == api_webhook.format end end def configured_webhook_exists?(api_webhook) configured_webhooks.include?( topic: api_webhook.topic, address: api_webhook.address, format: api_webhook.format ) end def with_shop ShopifyAPI::Session.temp(@shop.shopify_domain, @shop.shopify_token) do return yield end end def configured_webhooks ShopifyApp.configuration.webhooks end # We don't want things to explode if something goes wrong, but we do want to # notify. def wrap_errors yield rescue ActiveResource::UnauthorizedAccess => e # This probably means the shop is no longer installed. Rails.logger.error "Failed to modify webhooks for #{@shop.shopify_domain}. "\ "Unauthorized: Consider checking if it's still installed, and uninstalling if not. Error: "\ "#{e.message}" return false rescue ActiveResource::ConnectionError => e Rails.logger.error "Failed to modify webhooks for #{@shop.shopify_domain}. "\ "Some kind of connection error occurred. Error: "\ "#{e.message}" return false rescue Timeout::Error => e Rails.logger.error "Failed to modify webhooks for #{@shop.shopify_domain}. "\ "Connection timed out. Error: #{e.message}" return false rescue OpenSSL::SSL::SSLError => e Rails.logger.error "Failed to modify webhooks for #{@shop.shopify_domain}. "\ "SSLError. Error: #{e.message}" return false rescue Exception => e Rails.logger.error "Failed to modify webhooks for #{@shop.shopify_domain}. "\ "This shouldn't have happened. Error: #{e.message}" return false end end end end
daniel-sim/common
spec/lib/pr/common/user_service_spec.rb
<reponame>daniel-sim/common<gh_stars>0 require "rails_helper" describe PR::Common::UserService do describe "#find_or_create_user_by_shopify" do subject(:service) { PR::Common::UserService.new } let(:shop) { create(:shop) } context "when user exists" do let(:user) { create(:user, username: "shopify-#{shop.shopify_domain}", shop: shop) } let(:returned_user) do service.find_or_create_user_by_shopify(email: user.email, shop: shop) end it "returns that user" do expect(returned_user.id).to eq user.id end end context "when user does not exist" do let(:created_user) do service.find_or_create_user_by_shopify(email: "<EMAIL>", shop: shop) end it "creates and returns a new user" do created_user expect(Shop.count).to eq 1 expect(created_user.username).to eq "shopify-#{shop.shopify_domain}" expect(created_user.password).not_to <PASSWORD> expect(created_user.provider).to eq "shopify" expect(created_user.website).to eq shop.shopify_domain expect(created_user.shop_id).to eq shop.id expect(created_user.email).to eq "<EMAIL>" end it "tracks installation via ShopifyService" do shopify_service = PR::Common::ShopifyService.new(shop: shop) allow(PR::Common::ShopifyService) .to receive(:new) .with(shop: shop) .and_return(shopify_service) expect(shopify_service) .to receive(:track_installed) created_user end end end end
daniel-sim/common
lib/pr/common/engine.rb
<filename>lib/pr/common/engine.rb require 'rack-affiliates' require 'sidekiq' module PR module Common class Engine < ::Rails::Engine config.generators do |g| g.test_framework :rspec g.fixture_replacement :factory_bot, dir: 'spec/factories' end initializer :append_migrations do |app| unless app.root.to_s.match root.to_s config.paths["db/migrate"].expanded.each do |expanded_path| app.config.paths["db/migrate"] << expanded_path ActiveRecord::Migrator.migrations_paths << expanded_path end end end initializer :enable_affiliates do |app| app.middleware.use Rack::Affiliates app.middleware.use PR::Common::AffiliateRedirect end initializer :configure_active_job do |app| if app.config.active_job.queue_adapter != :sidekiq raise 'Ensure you have config.active_job.queue_adapter = :sidekiq in your application.rb' end end end end end
daniel-sim/common
spec/lib/pr/common/webhook_service_spec.rb
require "rails_helper" describe PR::Common::WebhookService do let(:shop) { create(:shop) } let(:uninstalled_shop) { create(:shop, :uninstalled) } let(:existing_api_webhooks) do [ OpenStruct.new( id: 1, address: "https://localhost:3000/webhooks/shop_update", topic: "shop/update", created_at: "2018-10-09T08:08:15-04:00", updated_at: "2018-10-09T08:08:15-04:00", format: "json", fields: [], metafield_namespaces: [] ), OpenStruct.new( id: 2, address: "https://localhost:3000/webhooks/app_uninstalled", topic: "app/uninstalled", created_at: "2018-10-09T08:08:15-04:00", updated_at: "2018-10-09T08:08:15-04:00", format: "json", fields: [], metafield_namespaces: [] ) ] end let(:configured_webhooks) do [ { topic: "app/installed", address: "https://localhost:3000/webhooks/app_installed", format: "json" }, { topic: "app/uninstalled", address: "https://localhost:3000/webhooks/app_uninstalled", format: "json" } ] end describe ".recreate_webhooks!" do it "creates a new instance for installed shops only" do service_shop = described_class.new(shop) expect(described_class) .to receive(:new) .with(shop) .and_return service_shop expect(described_class) .not_to receive(:new) .with(uninstalled_shop) described_class.recreate_webhooks! end end subject(:service) { described_class.new(shop) } describe "#recreate_webhooks!" do before do allow(ShopifyApp.configuration).to receive(:webhooks) { configured_webhooks } allow(ShopifyAPI::Webhook).to receive(:all) { existing_api_webhooks } allow(ShopifyAPI::Webhook).to receive(:delete).with(existing_api_webhooks.first) allow(ShopifyAPI::Webhook).to receive(:create).with(configured_webhooks.first) end it "requests all existing webhooks" do expect(ShopifyAPI::Webhook).to receive(:all) service.recreate_webhooks! end it "creates new webhooks that do not already exist" do expect(ShopifyAPI::Webhook).to receive(:create).with(configured_webhooks.first) service.recreate_webhooks! end it "does not create webhooks that already exist" do expect(ShopifyAPI::Webhook).not_to receive(:create).with(configured_webhooks.second) service.recreate_webhooks! end it "deletes existing webhooks that are not configured" do expect(ShopifyAPI::Webhook).to receive(:delete).with(existing_api_webhooks.first.id) service.recreate_webhooks! end it "does not delete existing webhooks that are also configured" do expect(ShopifyAPI::Webhook).not_to receive(:delete).with(existing_api_webhooks.second.id) service.recreate_webhooks! end error_classes = [ ActiveResource::UnauthorizedAccess, ActiveResource::ConnectionError, Timeout::Error, OpenSSL::SSL::SSLError, Exception ] error_classes.each do |error_class| context "when a #{error_class} occurs" do let(:error) { error_class.new("fail") } before do allow(ShopifyAPI::Webhook).to receive(:all) { raise error } end it "catches the error" do expect { service.recreate_webhooks! }.not_to raise_error end it "logs an error" do expect(Rails.logger).to receive(:error) service.recreate_webhooks! end it "returns false" do expect(service.recreate_webhooks!).to eq false end end end end end
daniel-sim/common
pr-common.gemspec
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require 'pr/common/version' Gem::Specification.new do |s| s.name = "pr-common" s.version = PR::Common::VERSION s.licenses = ['MIT'] s.authors = ["Pemberton Rank Ltd"] s.email = ["<EMAIL>"] s.homepage = "https://www.pembertonrank.com" s.summary = "Common components for the React/Rails Shopify app" s.files = Dir["{app,config,db,lib}/**/*", "Rakefile", "README.rdoc"] s.test_files = Dir["spec/**/*"] s.add_dependency 'rails', '>= 5.0' s.add_dependency 'shopify_app', '~> 7.2.0' s.add_dependency 'active_model_serializers' s.add_dependency 'nokogiri', '>= 1.8.2' s.add_dependency 'activeresource' s.add_dependency 'rack-affiliates' s.add_dependency 'config' s.add_development_dependency 'rspec-rails' s.add_development_dependency 'rspec_junit_formatter' end
daniel-sim/common
lib/pr/common/sign_in_service.rb
<reponame>daniel-sim/common module PR module Common # Generic sign in service. To be filled out further later module SignInService def self.track(shop) Rails.logger.info "Shop signed in. shop_id=#{shop.id}" user = shop.user properties = { email: user.email, promo_code: shop.promo_code&.code } Analytics.identify(user_id: user.id, traits: properties) Analytics.track(user_id: user.id, event: "Shop Signed In", properties: properties) end end end end
daniel-sim/common
db/migrate/20180922164900_drop_application_charges.rb
<filename>db/migrate/20180922164900_drop_application_charges.rb class DropApplicationCharges < ActiveRecord::Migration[5.0] def change # prevent this migration failing for apps that don't have have an # application_charges table return unless table_exists? :application_charges drop_table :application_charges end end
daniel-sim/common
db/migrate/20181009124306_add_charged_at_to_users.rb
<filename>db/migrate/20181009124306_add_charged_at_to_users.rb class AddChargedAtToUsers < ActiveRecord::Migration[5.0] def change return if column_exists? :users, :charged_at add_column :users, :charged_at, :datetime end end
daniel-sim/common
config/initializers/shopify_app.rb
<reponame>daniel-sim/common # Non-Shopify apps can use Common so just try to configure here and fail gracefully if no ShopifyApp configuration provided ShopifyApp.try (:configure) do |config| # For non-common, application specific webhooks be sure to do config.webhooks.push() rather than overwriting those here # TODO: Check and document what happens when adding/removing webhooks from here for existing shops? # https://pluginseo.ngrok.io config.webhooks = [ { topic: 'app/uninstalled', address: "#{Settings.webhook_url}/webhooks/app_uninstalled", format: 'json' }, { topic: 'shop/update', address: "#{Settings.webhook_url}/webhooks/shop_update", format: 'json' }, ] # This would be nice to organise the jobs: # config.webhook_jobs_namespace = 'shopify/webhooks' # ...however that's only supported in a later ShopifyApp version. Fix is to upgrade all apps to use the latest ShopifyApp and ShopifyAPI end
daniel-sim/common
app/controllers/passwords_controller.rb
class PasswordsController < ApiBaseController skip_before_action :authenticate_user_from_token! def update @user = User.reset_password_by_token(change_password_params.merge(reset_password_token: params[:id])) if @user && @user.errors.empty? @user.update_attribute(:confirmed, true) render json: {}, meta: { success: true }, serializer: EmptySerializer else render json: {}, meta: { success: false, errors: @user.errors }, status: :unprocessable_entity, serializer: EmptySerializer end end private def change_password_params params.require(:change_password).permit(:password, :password_confirmation) end end
daniel-sim/common
spec/lib/pr/common/sign_in_service_spec.rb
<reponame>daniel-sim/common<filename>spec/lib/pr/common/sign_in_service_spec.rb require "rails_helper" describe PR::Common::SignInService do let(:shop) { create(:shop, :with_user) } let(:user) { shop.user } describe ".track" do it "sends tracking analytics" do expect(Analytics) .to receive(:identify) .with(user_id: user.id, traits: { email: user.email, promo_code: nil }) expect(Analytics) .to receive(:track) .with(user_id: user.id, event: "Shop Signed In", properties: { email: user.email, promo_code: nil }) described_class.track(shop) end context "with a promo code" do let(:code) { "THE_CODE" } before { shop.create_promo_code!(code: code) } it "includes promo codes in tracking details" do expect(Analytics) .to receive(:identify) .with(user_id: user.id, traits: { email: user.email, promo_code: code }) expect(Analytics) .to receive(:track) .with(user_id: user.id, event: "Shop Signed In", properties: { email: user.email, promo_code: code }) described_class.track(shop) end end end end
daniel-sim/common
spec/dummy/db/migrate/20180903181059_add_fields_from_users.rb
<reponame>daniel-sim/common class AddFieldsFromUsers < ActiveRecord::Migration[5.2] def change add_column :users, :active_charge, :boolean, default: false add_column :users, :shop_id, :integer end end
daniel-sim/common
lib/pr/common.rb
require "pr/common/version" require "pr/common/engine" require "pr/common/configuration" require "pr/common/shopify_errors" require "pr/common/tokenable" require "pr/common/token_authenticable" require "pr/common/affiliate_redirect" require "pr/common/models/application_record" require "pr/common/models/user" require "pr/common/models/shop" require "pr/common/models/time_period" require "pr/common/models/promo_code" require "pr/common/models/admin" require "pr/common/user_service" require "pr/common/shopify_service" require "pr/common/webhook_service" require "pr/common/sustained_analytics_service" require "pr/common/params_promo_code_service" require "pr/common/session_promo_code_service" require "pr/common/charge_service" require "pr/common/sign_in_service" require "pr/common/controller_concerns/promo_codes" module PR module Common def self.configure yield config end def self.config @config ||= Configuration.new end def self.config=(config) @config = config end end end
daniel-sim/common
app/jobs/app_uninstalled_job.rb
class AppUninstalledJob < PR::Common::ApplicationJob def perform(params) with_analytics do shop = Shop.find_by(shopify_domain: params[:shop_domain]) PR::Common::ShopifyService .new(shop: shop) .update_shop(shopify_plan: shop.shopify_plan, uninstalled: true) end end end
daniel-sim/common
lib/pr/common/models/user.rb
<gh_stars>0 module PR module Common module Models # This is a stake in the ground to gradually improve our messy User code # As much as possible should be in Common # We will work towards this by including this module in our apps and moving generic pieces here # So please include PR::Common::Models::User module User extend ActiveSupport::Concern included do enum provider: { shopify: 0, tictail: 1 } %i[has_active_charge? active_charge?].each do |name| send(:define_method, name, -> { active_charge }) end def subscription_length return if charged_at.blank? (DateTime.now - charged_at.to_datetime).to_i end end class_methods do # add class methods here end # Legacy # can't unfortunately put this as a has_one # because ShopifyApp::SessionsController creates the Shop before a User def shop return unless shopify? if shop_id.blank? shop = ::Shop.find_by(shopify_domain: username.slice("shopify-")) self.shop = shop end ::Shop.find_by(id: shop_id) end def shop=(shop) self.shop_id = shop.id save! end end end end end
daniel-sim/common
spec/support/factory_bot.rb
RSpec.configure do |config| config.include FactoryBot::Syntax::Methods end FactoryBot.definition_file_paths = %w(spec/factories) FactoryBot.find_definitions
daniel-sim/common
spec/lib/pr/common/models/time_period_spec.rb
<reponame>daniel-sim/common<gh_stars>0 require "rails_helper" describe PR::Common::Models::TimePeriod do let(:user) { create(:user) } it do is_expected.to define_enum_for(:kind) .with_values %i[installed reinstalled reopened uninstalled closed] end context "when newly created" do let(:time_period) { described_class.create! } it "has a non-nil `start_time`" do expect(time_period.reload.start_time).not_to be_nil end it "defaults to an installed kind" do expect(time_period).to be_installed end end describe ".not_yet_ended" do let(:current_time) { Time.zone.local(2017, 1, 2) } around { |example| Timecop.freeze(current_time, &example.method(:run)) } it "includes time periods that have an end time not set" do time_period = create(:time_period) expect(described_class.not_yet_ended.pluck(:id)).to include(time_period.id) end it "includes time periods that have an end time in the future" do time_period = create(:time_period, end_time: Time.zone.local(2017, 1, 3)) expect(described_class.not_yet_ended.pluck(:id)).to include(time_period.id) end it "does not include periods that have an end time in the past" do time_period = create(:time_period, end_time: Time.zone.local(2017, 1, 1)) expect(described_class.not_yet_ended.pluck(:id)).not_to include(time_period.id) end it "does not include periods that have an end time of now" do time_period = create(:time_period, end_time: current_time) expect(described_class.not_yet_ended.pluck(:id)).not_to include(time_period.id) end end describe ".whilst_in_use" do it "includes installed time period" do time_period = create(:time_period, :installed) expect(described_class.whilst_in_use.pluck(:id)).to include(time_period.id) end it "includes reinstalled time period" do time_period = create(:time_period, :reinstalled) expect(described_class.whilst_in_use.pluck(:id)).to include(time_period.id) end it "includes reopened time period" do time_period = create(:time_period, :reopened) expect(described_class.whilst_in_use.pluck(:id)).to include(time_period.id) end it "does not include uninstalled time period" do time_period = create(:time_period, :uninstalled) expect(described_class.whilst_in_use.pluck(:id)).not_to include(time_period.id) end it "does not include closed time period" do time_period = create(:time_period, :closed) expect(described_class.whilst_in_use.pluck(:id)).not_to include(time_period.id) end end describe "#lapsed_days" do subject(:time_period) { described_class.new(start_time: start_time, end_time: end_time) } let(:current_time) { Time.zone.local(2018, 1, 10, 0, 0, 1) } let(:end_time) { nil } around { |example| Timecop.freeze(current_time, &example.method(:run)) } context "with no end time" do context "when time period started just now" do let(:start_time) { current_time } it "returns 0" do expect(time_period.lapsed_days).to eq 0 end end context "when time period started 1 second ago" do let(:start_time) { current_time - 1.second } it "rounds up to 1" do expect(time_period.lapsed_days).to eq 1 end end context "when time period started exactly 1 day ago" do let(:start_time) { current_time - 1.day } it "returns 1" do expect(time_period.lapsed_days).to eq 1 end end context "when time period started just over 10 days ago" do let(:start_time) { Time.zone.local(2018, 1, 1) } it "returns 10" do expect(time_period.lapsed_days).to eq 10 end end end context "with an end time" do let(:start_time) { Time.zone.local(2018, 1, 1) } let(:end_time) { Time.zone.local(2018, 1, 5, 0, 0, 1) } it "ignores the current time and returns the lapsed days between start to end time" do expect(time_period.lapsed_days).to eq 5 end end end describe "#lapsed_days_since_last_shop_retained_analytic" do let(:current_time) { Time.zone.local(2018, 1, 10, 0, 0, 1) } around { |example| Timecop.freeze(current_time, &example.method(:run)) } context "when shop_retained_analytic_sent_at is nil" do subject(:time_period) do described_class.new(start_time: Time.zone.local(2018, 1, 1), shop_retained_analytic_sent_at: nil) end it "is calculated from the `start_time`" do expect(time_period.lapsed_days_since_last_shop_retained_analytic).to eq 10 end end context "when shop_retained_analytic_sent_at is set" do subject(:time_period) do described_class.new(start_time: Time.zone.local(2018, 1, 1), shop_retained_analytic_sent_at: Time.zone.local(2018, 1, 6)) end it "is calculated from the `last_shop_retained_analytic_at`" do expect(time_period.lapsed_days_since_last_shop_retained_analytic).to eq 5 end end end describe "#in_use?" do %i[installed reinstalled reopened].each do |kind| context "when time period is #{kind}" do subject(:time_period) { build(:time_period, kind) } it "returns true" do expect(time_period).to be_in_use end end end %i[uninstalled closed].each do |kind| context "when time period is #{kind}" do subject(:time_period) { build(:time_period, kind) } it "returns false" do expect(time_period).not_to be_in_use end end end end describe "#converted_to_paid?" do context "when converted_to_paid_at is set" do subject(:time_period) { build(:time_period, converted_to_paid_at: Time.current) } it "returns true" do expect(time_period).to be_converted_to_paid end end context "when converted_to_paid_at is not set" do subject(:time_period) { build(:time_period) } it "returns false" do expect(time_period).not_to be_converted_to_paid end end end describe "#ended?" do context "when end_time is set" do subject(:time_period) { build(:time_period, end_time: Time.current) } it "returns true" do expect(time_period).to be_ended end end context "when end_time is not set" do subject(:time_period) { build(:time_period) } it "returns false" do expect(time_period).not_to be_ended end end end describe "#paid_now" do subject(:time_period) { build(:time_period) } let(:current_time) { Time.zone.local(2017, 1, 2) } around { |example| Timecop.freeze(current_time, &example.method(:run)) } context "when passed a time" do let(:time) { Time.zone.local(2017, 1, 1) } it "sets period_last_paid_at to the current time" do expect { time_period.paid_now(time) } .to change(time_period, :period_last_paid_at) .from(nil) .to(time) end it "increments periods_paid" do expect { time_period.paid_now(time) } .to change(time_period, :periods_paid) .from(0) .to(1) end end context "when not passed a time" do it "sets period_last_paid_at to the current time" do expect { time_period.paid_now } .to change(time_period, :period_last_paid_at) .from(nil) .to(Time.current) end it "increments periods_paid" do expect { time_period.paid_now } .to change(time_period, :periods_paid) .from(0) .to(1) end end end describe "#paid_now!" do subject(:time_period) { create(:time_period) } let(:current_time) { Time.zone.local(2017, 1, 2) } around { |example| Timecop.freeze(current_time, &example.method(:run)) } context "when passed a time" do let(:time) { Time.zone.local(2017, 1, 1) } it "persists period_last_paid_at to passed" do expect { time_period.paid_now!(time) } .to change { time_period.reload.period_last_paid_at } .from(nil) .to(time) end it "increments periods_paid" do expect { time_period.paid_now!(time) } .to change { time_period.reload.periods_paid } .from(0) .to(1) end end context "when not passed a time" do it "sets period_last_paid_at to the current time" do expect { time_period.paid_now! } .to change { time_period.reload.period_last_paid_at } .from(nil) .to(Time.current) end it "increments periods_paid" do expect { time_period.paid_now! } .to change { time_period.reload.periods_paid } .from(0) .to(1) end end end describe "#usd_paid" do subject(:time_period) { build(:time_period, monthly_usd: 3.50) } context "when no periods were paid" do it "returns 0" do expect(time_period.usd_paid).to eq 0 end end context "when periods were paid" do before { time_period.periods_paid = 5 } it "returns the number of payments multiplied by the monthly cost" do expect(time_period.usd_paid).to eq 17.50 end end end end
daniel-sim/common
app/controllers/promo_codes_controller.rb
<reponame>daniel-sim/common<filename>app/controllers/promo_codes_controller.rb<gh_stars>0 class PromoCodesController < ApplicationController STATUS_VALID = "valid".freeze STATUS_ERROR = "error".freeze def check service = ParamsPromoCodeService.new(params) render json: response_json(service) end private def response_json(service) if service.error { status: STATUS_ERROR, message: service.error } else { status: STATUS_VALID, message: "Success: Promotion applied!" } end end end
daniel-sim/common
db/migrate/20190514130737_common_add_value_to_promo_codes.rb
class CommonAddValueToPromoCodes < ActiveRecord::Migration[5.0] def change add_column :promo_codes, :value, :decimal, precision: 5, scale: 2, default: 100.0, null: false end end
daniel-sim/common
db/migrate/20180912223800_add_referrer_to_users.rb
class AddReferrerToUsers < ActiveRecord::Migration[5.0] def change # prevent this migration failing for apps that already have a # referrer on users return if column_exists? :users, :referrer add_column :users, :referrer, :string end end
daniel-sim/common
app/controllers/admin/base_controller.rb
<filename>app/controllers/admin/base_controller.rb module Admin class BaseController < ActionController::Base layout "admin" before_action :authenticate_admin! end end
daniel-sim/common
lib/pr/common/session_promo_code_service.rb
<filename>lib/pr/common/session_promo_code_service.rb class SessionPromoCodeService KEY = :promo_code def initialize(session) @session = session end def maybe_apply_to_shop(shop) return unless redeemable? PR::Common::Models::PromoCode.transaction do return unless redeemable? # check again now that we've locked the table Rails.logger.info("Applying promo code. code=#{code}, shop=#{shop.shopify_domain}") shop.update!(promo_code: record) end end def store(promo_code) @session[KEY] = promo_code.code end def clear @session.delete(KEY) end private def redeemable? record&.redeemable? end def record @record ||= PR::Common::Models::PromoCode.find_by(code: code) end def code @session[KEY] end end
daniel-sim/common
app/jobs/pr/common/sustained_analytics_job.rb
<filename>app/jobs/pr/common/sustained_analytics_job.rb<gh_stars>0 module PR module Common class SustainedAnalyticsJob < ApplicationJob queue_as :low_priority def perform with_analytics { PR::Common::SustainedAnalyticsService.perform } end end end end
daniel-sim/common
lib/pr/common/models/admin.rb
require "devise" module PR module Common module Models class Admin < ApplicationRecord extend Devise::Models devise :database_authenticatable, :validatable, :rememberable self.table_name = "admins" has_many :promo_codes, class_name: "PR::Common::Models::PromoCode", inverse_of: :created_by, foreign_key: :created_by_id end end end end
daniel-sim/common
spec/dummy/db/migrate/20180829195156_create_shop.rb
class CreateShop < ActiveRecord::Migration[5.2] def change create_table :shops do |t| t.string :plan_name t.string :shopify_domain t.string :shopify_token, null: false end end end
daniel-sim/common
spec/jobs/shop_update_job_spec.rb
<reponame>daniel-sim/common require "rails_helper" describe ShopUpdateJob do let(:shopify_domain) { "the_domain" } let(:shop) { create(:shop, shopify_domain: shopify_domain, user: build(:user)) } let(:service) { PR::Common::ShopifyService.new(shop: shop) } let(:plan) { "the_plan" } let(:email) { "<EMAIL>" } before do allow(Analytics).to receive(:flush) allow(Shop) .to receive(:find_by) .with(shopify_domain: shopify_domain) .and_return(shop) allow(PR::Common::ShopifyService) .to receive(:new) .with(shop: shop) .and_return(service) end describe "#perform" do before { skip("We need to get user creation in as a hotfix. That broke the specs.") } it "calls out to PR::Common::ShopifyService#update_shop" do expect(service) .to receive(:update_shop) .with(shopify_plan: plan, uninstalled: false) described_class.perform_now( shop_domain: shopify_domain, webhook: { plan_name: plan } ) end it "calls out to PR::Common::ShopifyService#update_user" do expect(service) .to receive(:update_user) .with(email: email) described_class.perform_now( shop_domain: shopify_domain, webhook: { email: email } ) end end end
daniel-sim/common
db/migrate/20190514090235_common_create_promo_codes.rb
class CommonCreatePromoCodes < ActiveRecord::Migration[5.0] def change create_table :promo_codes do |t| t.column :code, :string, null: false, unique: true, index: true t.column :description, :string t.timestamps end end end
daniel-sim/common
lib/pr/common/controller_concerns/promo_codes.rb
<filename>lib/pr/common/controller_concerns/promo_codes.rb module PR module Common module PromoCodes extend ActiveSupport def maybe_reconcile_promo_codes(shop) maybe_remove_existing_promo_code(shop) maybe_apply_promo_code(shop) end private # We only want to remove promo codes for shops that are reinstalling def maybe_remove_existing_promo_code(shop) return if shop.installed? shop.update!(promo_code: nil) end def maybe_apply_promo_code(shop) session_service = SessionPromoCodeService.new(session) session_service.maybe_apply_to_shop(shop) session_service.clear end def maybe_store_promo_code SessionPromoCodeService.new(session).clear params_service = ParamsPromoCodeService.new(params) return unless params_service.present? if params_service.error flash[:error] = params_service.error render :new, promo_code: params_service.code, shop: params[:shop] return end SessionPromoCodeService.new(session).store(params_service.record) end end end end
daniel-sim/common
lib/pr/common/models/shop.rb
<filename>lib/pr/common/models/shop.rb require "shopify_app/shop" require "shopify_app/session_storage" module PR module Common module Models module Shop PLAN_FROZEN = "frozen".freeze PLAN_CANCELLED = "cancelled".freeze PLAN_LOCKED = "locked".freeze PLAN_AFFILIATE = "affiliate".freeze PLAN_FRAUDULENT = "fraudulent".freeze INACTIVE_PLANS = [PLAN_CANCELLED, PLAN_FROZEN, PLAN_LOCKED, PLAN_FRAUDULENT].freeze extend ActiveSupport::Concern include ::ShopifyApp::Shop include ::ShopifyApp::SessionStorage included do delegate :charged_at, to: :user delegate :charged_at=, to: :user scope :with_active_plan, -> { where.not(shopify_plan: INACTIVE_PLANS) } scope :with_active_charge, -> { joins(:user).where(users: { active_charge: true }) } scope :installed, -> { where(uninstalled: false) } belongs_to :promo_code, required: false, class_name: "PR::Common::Models::PromoCode" has_one :user has_many :time_periods, dependent: :destroy, class_name: "PR::Common::Models::TimePeriod" before_validation :reconcile_time_periods # TODO: # This ensures that every pre-existing shop has a time period before it is # operated on. # This should be removed once all existing shops in all apps already have a time period. after_find -> { reconcile_time_periods && save }, if: -> { time_periods.blank? } end def status return :uninstalled if uninstalled case shopify_plan when PLAN_FROZEN, PLAN_CANCELLED, PLAN_FRAUDULENT then return :inactive when PLAN_LOCKED then return :locked end :active end def installed? !uninstalled? end def inactive? !active? end def active? active_shopify_plan? && user&.active_charge && !uninstalled end def active_shopify_plan? shopify_plan && !inactive_shopify_plan? end def inactive_shopify_plan? INACTIVE_PLANS.include? shopify_plan end def frozen? shopify_plan == PLAN_FROZEN end def cancelled? shopify_plan == PLAN_CANCELLED end alias closed? cancelled? def affiliate? shopify_plan == PLAN_AFFILIATE end def current_time_period time_periods.not_yet_ended.order(:start_time).last end def total_days_installed time_periods.whilst_in_use.sum(&:lapsed_days) end def total_periods_paid time_periods.sum(:periods_paid) end def total_usd_paid time_periods.sum(&:usd_paid) end def app_plan super || PR::Common.config.default_app_plan end private def reconcile_time_periods maybe_build_uninstalled_time_period && return maybe_build_closed_time_period && return maybe_build_reinstalled_time_period && return maybe_build_reopened_time_period && return maybe_build_installed_time_period end def maybe_build_uninstalled_time_period return unless uninstalled? return true if current_time_period&.uninstalled? # current time period is already uninstalled reconcile_time_period(:uninstalled) true end def maybe_build_closed_time_period return unless closed? return true if current_time_period&.closed? # current time period is already closed reconcile_time_period(:closed) true end # When not uninstalled but current time period is uninstalled def maybe_build_reinstalled_time_period return if uninstalled? return unless current_time_period&.uninstalled? reconcile_time_period(:reinstalled) true end # When not closed but current time period is closed def maybe_build_reopened_time_period return if closed? return unless current_time_period&.closed? reconcile_time_period(:reopened) true end def maybe_build_installed_time_period return if current_time_period build_new_time_period(:installed) true end def reconcile_time_period(kind) current_time = DateTime.current current_time_period.update!(end_time: current_time) if current_time_period.present? build_new_time_period(kind, start_time: current_time) end def build_new_time_period(kind, start_time: DateTime.current) time_periods.reload new_params = { start_time: start_time, kind: kind } if (time_period = time_periods.last).present? && kind != :reinstalled new_params.merge!( converted_to_paid_at: time_period.converted_to_paid_at, monthly_usd: time_period.monthly_usd, period_last_paid_at: time_period.period_last_paid_at ) end time_periods.build(new_params) end end end end end
daniel-sim/common
db/migrate/20181009084529_make_plan_name_nullable.rb
class MakePlanNameNullable < ActiveRecord::Migration[5.0] def change change_column_null :shops, :plan_name, true end end
daniel-sim/common
lib/pr/common/models/time_period.rb
<reponame>daniel-sim/common<gh_stars>0 module PR module Common module Models # Shops have multiple time periods. # Time periods may not overlap. # # When a new shop is created: # - a new TimePeriod should be created with start_time NOW(), end_time NULL, and kind :installed # # When a shop is uninstalled: # - its current time period's end_time should be set to NOW() # - a new TimePeriod should be created with start_time NOW(), end_time NULL, and kind :uninstalled # # When a shop is reinstalled: # - its current time period's end_time should be set to NOW() # - a new TimePeriod should be created with start_time NOW(), end_time NULL, and kind :reinstalled # # When a shop is closed: # - its current time period's end_time should be set to NOW() # - a new TimePeriod should be created with start_time NOW(), end_time NULL, and kind :reinstalled # # When a shop is reopened: # - its current time period's end_time should be set to NOW() # - a new TimePeriod should be created with start_time NOW(), end_time NULL, and kind :reopened # # - Time periods for a shop should never overlap. # - A start_time for a TimePeriod can match an end_time of another. # - All TimePeriods except the current one *must* have an end_time set. class TimePeriod < ApplicationRecord self.table_name = "time_periods" KINDS_IN_USE = %i[installed reinstalled reopened].freeze scope :not_yet_ended, -> { where("end_time IS NULL OR end_time > ?", Time.current) } scope :whilst_in_use, -> { where(kind: KINDS_IN_USE) } belongs_to :shop enum kind: { installed: 0, reinstalled: 1, reopened: 2, uninstalled: 3, closed: 4 } def lapsed_days(current_time = Time.current) upper_bound = end_time || current_time ((upper_bound - start_time) / 1.day).ceil end def lapsed_days_since_last_shop_retained_analytic(current_time = Time.current) last_shop_retained_analytic = shop_retained_analytic_sent_at || start_time ((current_time - last_shop_retained_analytic) / 1.day).ceil end def converted_to_paid? !!converted_to_paid_at end def ended? !!end_time end def in_use? kind.to_sym.in? KINDS_IN_USE end def paid_now(current_time = Time.current) assign_attributes(period_last_paid_at: current_time, periods_paid: periods_paid.next) end def paid_now!(current_time = Time.current) paid_now(current_time) save! end def usd_paid periods_paid * monthly_usd end end end end end
daniel-sim/common
spec/factories/time_periods.rb
<filename>spec/factories/time_periods.rb FactoryBot.define do factory :time_period, class: PR::Common::Models::TimePeriod do trait :installed do kind { :installed } end trait :reinstalled do kind { :reinstalled } end trait :reopened do kind { :reopened } end trait :uninstalled do kind { :uninstalled } end trait :closed do kind { :closed } end end end
daniel-sim/common
spec/lib/pr/common/shopify_service_spec.rb
<gh_stars>0 require "rails_helper" describe PR::Common::ShopifyService do subject(:service) { described_class.new(shop: shop) } let(:user) { build(:user) } let(:shop) { create(:shop, app_plan: "foobar", user: user) } let(:promo_code) { PR::Common::Models::PromoCode.create(code: "THE_CODE", value: 50.0) } describe "#determine_price" do context "when the config's price method is set to a lambda" do let(:pricing_method) { -> (shop, args) { [shop, args] } } around do |example| old_config = PR::Common.config new_config = PR::Common::Configuration.new new_config.pricing_method = pricing_method PR::Common.config = new_config example.run PR::Common.config = old_config end it "calls the lambda with the shop and any other args" do expect(service.determine_price(foo: :bar)).to eq [shop, foo: :bar] end end context "when shop has a plan whose pricing is defined" do before { shop.update!(shopify_plan: "plus") } it "returns the defined price" do expected_price = { key: :plus, price: 25.99, trial_days: 0, shopify_plan: "plus", name: "Plus", terms: "Plus terms" } expect(service.determine_price).to eq expected_price end it "applies promo codes" do shop.update!(promo_code: promo_code) # half price expect(service.determine_price[:price]).to eq 13.00 end end context "when shop has no plan whose pricing is defined" do before { shop.update!(shopify_plan: "foobar") } it "returns the pricing plan without a plan name" do expected_price = { key: :generic, price: 10.0, trial_days: 7, name: "Generic with trial", terms: "Generic terms" } expect(service.determine_price).to eq expected_price end it "applies promo codes" do shop.update!(promo_code: promo_code) # half price expect(service.determine_price[:price]).to eq 5.00 end end end describe "#reconcile_with_shopify" do context "when shop has no user" do let(:shop) { create(:shop, app_plan: "foobar") } before do allow(ShopifyAPI::Shop) .to receive(:current) .and_return(ShopifyAPI::Shop.new(plan_name: "basic", email: "<EMAIL>")) end it "creates a user for it" do expect(shop.user).not_to be_present service.reconcile_with_shopify expect(shop.user).to be_persisted expect(shop.user.email).to eq "<EMAIL>" end end context "when shop response has an error" do before do allow(ShopifyAPI::Shop) .to receive(:current) .and_raise(ActiveResource::ClientError.new(OpenStruct.new(code: code))) allow(Analytics).to receive(:track) end context "where error is a 401" do let(:code) { 401 } it "does not change the shopify_plan" do expect(shop.shopify_plan).to eq "affiliate" service.reconcile_with_shopify expect(shop.reload.shopify_plan).to eq "affiliate" end it "sets the shop to uninstalled" do expect { service.reconcile_with_shopify } .to change(shop, :uninstalled) .from(false) .to(true) end end context "where error is a 402" do let(:code) { 402 } it "sets shopify_plan to frozen" do expect(shop.shopify_plan).to eq "affiliate" service.reconcile_with_shopify expect(shop.reload.shopify_plan).to eq "frozen" end end context "where error is a 403" do let(:code) { 403 } it "sets shopify_plan to frozen" do expect { service.reconcile_with_shopify } .to change { shop.reload.shopify_plan } .from("affiliate") .to("fraudulent") end end context "where error is a 404" do let(:code) { 404 } context "when shop is an affiliate" do it "sets shopify_plan to cancelled" do expect(shop.shopify_plan).to eq "affiliate" service.reconcile_with_shopify expect(shop.reload.shopify_plan).to eq "cancelled" end end context "when shop is not an affiliate" do before { shop.update!(shopify_plan: "basic") } it "sets shopify_plan to cancelled" do service.reconcile_with_shopify expect(shop.reload.shopify_plan).to eq "cancelled" end it "calls track_cancelled" do expect(service).to receive(:track_cancelled) service.reconcile_with_shopify end end end context "when error is a 423" do let(:code) { 423 } it "sets shopify_plan to locked" do expect(shop.shopify_plan).to eq "affiliate" service.reconcile_with_shopify expect(shop.reload.shopify_plan).to eq "locked" end end end end describe "#maybe_update_shopify_plan" do context "when shopify plan is unchanged" do it "does not track shopify plan updated" do expect(service).not_to receive(:track_shopify_plan_updated) service.maybe_update_shopify_plan(shop.shopify_plan) end end context "when existing shopify plan is not set" do it "does not track shopify plan updated" do shop.update!(shopify_plan: nil) expect(service).not_to receive(:track_shopify_plan_updated) service.maybe_update_shopify_plan("enterprise") end end context "when existing shopify plan differs" do it "tracks shopify plan updated" do shop.update!(shopify_plan: "enterprise") expect(service).to receive(:track_shopify_plan_updated).with("bar") service.maybe_update_shopify_plan("bar") end end end describe "#maybe_reopen" do context "when shop goes from cancelled to another plan" do before { shop.update!(shopify_plan: Shop::PLAN_CANCELLED) } it "resets charged_at to current time" do # This is a smelly test as we don't want to actually update the charged_at, but # only set it, as `update_shop` should handle saving. # Consider refactoring to test using `update_shop`. allow(User).to receive_message_chain("shopify.find_by").and_return(user) Timecop.freeze do expect(user).to receive(:charged_at=).with(Time.current) service.maybe_reopen("business") end end it "sends an identify analytic" do analytic_params = { user_id: shop.user.id, traits: { email: shop.user.email, status: :active, shopifyPlan: "enterprise", promo_code: nil } } expect(Analytics).to receive(:identify).with(analytic_params) service.maybe_reopen("enterprise") end it "sends an 'Shop Reopened' track analytic" do analytic_params = { user_id: shop.user.id, event: "Shop Reopened", properties: { email: shop.user.email, "registration method": "shopify", email: shop.user.email, shopify_plan: "enterprise", promo_code: nil } } expect(Analytics).to receive(:track).with(analytic_params) service.maybe_reopen("enterprise") end end context "when shop is not cancelled" do it "does not change charged_at" do # This is a smelly test as we don't want to actually update the charged_at, but # only set it, as `update_shop` should handle saving. # Consider refactoring to test using `update_shop`. allow(User).to receive_message_chain("shopify.find_by").and_return(user) expect(user).not_to receive(:charged_at=) service.maybe_reopen("business") end it "does not send any analytics" do expect(Analytics).not_to receive(:track) expect(Analytics).not_to receive(:identify) service.maybe_reopen("enterprise") end end end describe "#maybe_reinstall_or_uninstall" do context "when reinstalling" do before do shop.update!(uninstalled: true) shop.current_time_period.update!(monthly_usd: 50.0) end it "sends an identify analytic" do analytic_params = { user_id: shop.user.id, traits: { email: shop.user.email, status: :active, shopifyPlan: "enterprise", appPlan: nil, # this gets reset to default monthlyUsd: 0, # this gets reset to 0 trial: false, activeCharge: false, promo_code: nil } } expect(Analytics).to receive(:identify).with(analytic_params) service.maybe_reinstall_or_uninstall("enterprise", false) end it "sends an 'App Reinstalled' analytic" do analytic_params = { user_id: shop.user.id, event: "App Reinstalled", properties: { "registration method": "shopify", email: shop.user.email, shopify_plan: "enterprise", promo_code: nil } } expect(Analytics).to receive(:track).with(analytic_params) service.maybe_reinstall_or_uninstall("enterprise", false) end end context "when uninstalling" do it "sends an identify analytic" do analytic_params = { user_id: shop.user.id, traits: { email: shop.user.email, status: :uninstalled, subscriptionLength: nil, currentDaysInstalled: shop.current_time_period.lapsed_days, totalDaysInstalled: shop.total_days_installed, currentPeriodsPaid: shop.current_time_period.periods_paid, totalPeriodsPaid: shop.total_periods_paid, monthlyUsd: shop.current_time_period.monthly_usd.to_f, currentUsdPaid: shop.current_time_period.usd_paid.to_f, totalUsdPaid: shop.total_usd_paid.to_f, } } expect(Analytics).to receive(:identify).with(analytic_params) service.maybe_reinstall_or_uninstall("enterprise", true) end it "sends an 'App Uninstalled' analytic" do analytic_params = { user_id: shop.user.id, event: "App Uninstalled", properties: { email: shop.user.email, subscription_length: nil, current_days_installed: shop.current_time_period.lapsed_days, total_days_installed: shop.total_days_installed, current_periods_paid: shop.current_time_period.periods_paid, total_periods_paid: shop.total_periods_paid, monthly_usd: shop.current_time_period.monthly_usd.to_f, current_usd_paid: shop.current_time_period.usd_paid.to_f, total_usd_paid: shop.total_usd_paid.to_f, } } expect(Analytics).to receive(:track).with(analytic_params) service.maybe_reinstall_or_uninstall("enterprise", true) end end context "when neither uninstalling or reinstalling" do it "does not send any analytics" do expect(Analytics).not_to receive(:track) expect(Analytics).not_to receive(:identify) service.maybe_reinstall_or_uninstall("enterprise", false) end end end describe "#track_shopify_plan_updated" do it "sends an identify analytic" do expect(Analytics).to receive(:identify).with( user_id: shop.user.id, traits: { email: shop.user.email, shopifyPlan: "enterprise" } ) service.track_shopify_plan_updated("enterprise") end it "sends an track analytic" do expect(Analytics).to receive(:track).with( user_id: shop.user.id, event: "Shopify Plan Updated", properties: { email: shop.user.email, pre_shopify_plan: shop.shopify_plan, post_shopify_plan: "enterprise" } ) service.track_shopify_plan_updated("enterprise") end end describe "#track_handed_off" do it "sends an identify analytic" do analytic_params = { user_id: shop.user.id, traits: { email: shop.user.email, shopifyPlan: "enterprise" } } expect(Analytics).to receive(:identify).with(analytic_params) service.track_handed_off("enterprise") end it "sends an 'App Handed Off' track analytic" do analytic_params = { user_id: shop.user.id, event: "Shop Handed Off", properties: { email: shop.user.email, shopify_plan: "enterprise" } } expect(Analytics).to receive(:track).with(analytic_params) service.track_handed_off("enterprise") end end describe "#track_cancelled" do it "sends an identify analytic" do analytic_params = { user_id: shop.user.id, traits: { email: shop.user.email, status: :inactive, subscriptionLength: shop.user.subscription_length, currentDaysInstalled: shop.current_time_period.lapsed_days, totalDaysInstalled: shop.total_days_installed, currentPeriodsPaid: shop.current_time_period.periods_paid, totalPeriodsPaid: shop.total_periods_paid, monthlyUsd: shop.current_time_period.monthly_usd.to_f, currentUsdPaid: shop.current_time_period.usd_paid.to_f, totalUsdPaid: shop.total_usd_paid.to_f } } expect(Analytics).to receive(:identify).with(analytic_params) service.track_cancelled end it "sends a 'Shop Closed' track analytic" do analytic_params = { user_id: shop.user.id, event: "Shop Closed", properties: { email: shop.user.email, subscription_length: shop.user.subscription_length, current_days_installed: shop.current_time_period.lapsed_days, total_days_installed: shop.total_days_installed, current_periods_paid: shop.current_time_period.periods_paid, total_periods_paid: shop.total_periods_paid, monthly_usd: shop.current_time_period.monthly_usd.to_f, current_usd_paid: shop.current_time_period.usd_paid.to_f, total_usd_paid: shop.total_usd_paid.to_f } } expect(Analytics).to receive(:track).with(analytic_params) service.track_cancelled end end describe "#track_installed" do it "sends an identify analytic" do analytic_params = { user_id: shop.user.id, traits: { email: shop.user.email, status: :active, shopifyPlan: "affiliate", appPlan: "foobar", promo_code: nil } } expect(Analytics).to receive(:identify).with(analytic_params) service.track_installed end it "sends an 'App Installed' track analytic" do analytic_params = { user_id: shop.user.id, event: "App Installed", properties: { "registration method": "shopify", email: shop.user.email, shopify_plan: "affiliate", promo_code: nil } } expect(Analytics).to receive(:track).with(analytic_params) service.track_installed end end end
daniel-sim/common
spec/dummy/app/models/shop.rb
<reponame>daniel-sim/common class Shop < ApplicationRecord include PR::Common::Models::Shop has_one :user end
daniel-sim/common
db/migrate/20190118073208_common_add_app_plan_to_shops.rb
class CommonAddAppPlanToShops< ActiveRecord::Migration[5.0] def change add_column :shops, :app_plan, :string add_index :shops, :app_plan end end
daniel-sim/common
lib/pr/common/affiliate_redirect.rb
<gh_stars>0 module PR module Common class AffiliateRedirect def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) @request = Rack::Request.new(env) return handle_referral if referrer? [status, headers, body] end private def referrer? @request.env['rack.request.query_hash']['ref'] && PR::Common.config.referrer_redirect end def handle_referral handle_promo_code [ 302, {'Location' => PR::Common.config.referrer_redirect, 'Content-Type' => 'text/html'}, ['Found'] ] end def handle_promo_code service = SessionPromoCodeService.new(@request.session) service.clear return if (code = @request.params["promo_code"]).blank? promo_code = PR::Common::Models::PromoCode.find_by(code: code) return if promo_code.blank? service.store(promo_code) end end end end
daniel-sim/common
lib/pr/common/charge_service.rb
module PR module Common class ChargeService def self.determine_app_plan_from_charge(charge) PR::Common.config.pricing.detect { |price| price[:name] == charge.name }&.[](:key) end def initialize(shop) @shop = shop @user = shop.user end def create_charge(price, base_url) ShopifyAPI::RecurringApplicationCharge.current&.cancel price.positive? ? create_nonfree_charge(base_url) : create_free_charge end def activate_charge(charge) app_plan = self.class.determine_app_plan_from_charge(charge) activate_user(app_plan, charge) charge end # Fetches plan name from shopify and determines price from it def up_to_date_price PR::Common::ShopifyService .new(shop: @shop) .determine_price(api_shop: api_shop) end private def create_free_charge app_plan = PR::Common::ShopifyService .new(shop: @shop) .determine_price&.[](:key) @shop.update(app_plan: app_plan) activate_user(app_plan) end def create_nonfree_charge(base_url) ShopifyAPI::RecurringApplicationCharge .create(charge_params(base_url)) end def charge_params(base_url) PR::Common::ShopifyService .new(shop: @shop) .determine_price(api_shop: api_shop) .merge(test: !Rails.env.production?, return_url: return_url(base_url)) .except(:key) end def return_url(base_url) "#{base_url}#{Rails.application.routes.url_helpers.callback_charges_path}?access_token=#{@user.access_token}" end def activate_user(app_plan, charge = nil) @user.update(active_charge: true, charged_at: Time.current) @shop.update(app_plan: app_plan) @shop.current_time_period.update(monthly_usd: charge&.price || 0) send_charge_activated_analytics(app_plan, charge&.price || 0) end def send_charge_activated_analytics(app_plan, price) # This currently assumes that all paying users have a trial first. # We use `false` if there is no promo code because amplitude doesn't # accept nil values. Analytics.identify( user_id: @user.id, traits: { email: @user.email, appPlan: app_plan, monthlyUsd: price, trial: price.to_f.positive?, promo_code: @user.shop.promo_code&.code || false } ) Analytics.track( user_id: @user.id, event: "Charge Activated", properties: { email: @user.email, monthly_usd: price, app_plan: app_plan, promo_code: @user.shop.promo_code&.code || false } ) end def api_shop @api_shop ||= ShopifyAPI::Shop.current end end end end
daniel-sim/common
db/migrate/20180915214900_add_plan_name_to_shops.rb
class AddPlanNameToShops < ActiveRecord::Migration[5.0] def change # prevent this migration failing for apps that already have a # plan_name on shops return if column_exists? :shops, :plan_name add_column :shops, :plan_name, :string end end
daniel-sim/common
lib/pr/common/sustained_analytics_service.rb
<reponame>daniel-sim/common<filename>lib/pr/common/sustained_analytics_service.rb class PR::Common::SustainedAnalyticsService DAYS_BETWEEN_SHOP_RETAINED_ANALYTIC = Rails.env.staging? ? 1 : 7 DAYS_UNTIL_PAYMENT_CHARGED = Rails.env.staging? ? 1 : 30 # Strictly speaking, this should depend on the trial_days of various # prices. Potentially to be implemented in the future. DAYS_UNTIL_CONVERTED_TO_PAID = Rails.env.staging? ? 1 : 7 # We allow passing in a current_time so that any comparisons / updates are done # with that time in mind. When run on a schedule, this job may differ slightly from day to day # so passing a normalized current time helps. def initialize(shop, options = {}) @shop = shop @current_time_period = shop.current_time_period @user = shop.user @current_time = options.fetch(:current_time, Time.current) end def perform return unless @current_time_period return unless @current_time_period.in_use? return if @current_time_period.ended? maybe_converted_to_paid maybe_shop_retained maybe_payment_charged end private def maybe_shop_retained return if DAYS_BETWEEN_SHOP_RETAINED_ANALYTIC > @current_time_period.lapsed_days_since_last_shop_retained_analytic(@current_time) send_shop_retained_analytics @current_time_period.update!(shop_retained_analytic_sent_at: @current_time) end def send_shop_retained_analytics return if @user.blank? current_days_installed = @current_time_period.lapsed_days total_days_installed = @shop.total_days_installed Analytics.identify( user_id: @user.id, traits: { email: @user.email, currentDaysInstalled: current_days_installed, totalDaysInstalled: total_days_installed } ) Analytics.track( user_id: @user.id, event: "Shop Retained", properties: { email: @user.email, current_days_installed: current_days_installed, total_days_installed: total_days_installed } ) end def maybe_converted_to_paid return if @current_time_period.converted_to_paid? return if @current_time_period.monthly_usd.zero? return unless @shop.charged_at return if (@shop.charged_at + DAYS_UNTIL_CONVERTED_TO_PAID.days) > @current_time convert_to_paid && payment_charged end def convert_to_paid send_converted_to_paid_analytics @current_time_period.update!(converted_to_paid_at: @current_time) end def send_converted_to_paid_analytics return if @user.blank? Analytics.identify( user_id: @user.id, traits: { email: @user.email, trial: false, monthlyUsd: @current_time_period.monthly_usd, appPlan: @shop.app_plan } ) Analytics.track( user_id: @user.id, event: "Converted to Paid", properties: { email: @user.email, monthly_usd: @current_time_period.monthly_usd, app_plan: @shop.app_plan } ) end def maybe_payment_charged return unless @current_time_period.converted_to_paid? last_payment_charged = @current_time_period.period_last_paid_at || @current_time_period.converted_to_paid_at return if (last_payment_charged + DAYS_UNTIL_PAYMENT_CHARGED.days) > @current_time payment_charged end def payment_charged @current_time_period.paid_now!(@current_time) @shop.reload send_payment_charged_analytics end def send_payment_charged_analytics return if @user.blank? current_periods_paid = @current_time_period.periods_paid total_periods_paid = @shop.total_periods_paid monthly_usd = @current_time_period.monthly_usd.to_f current_usd_paid = @current_time_period.usd_paid.to_f total_usd_paid = @shop.total_usd_paid.to_f Analytics.identify( user_id: @user.id, traits: { email: @user.email, currentPeriodsPaid: current_periods_paid, totalPeriodsPaid: total_periods_paid, monthlyUsd: monthly_usd, currentUsdPaid: current_usd_paid, totalUsdPaid: total_usd_paid } ) Analytics.track( user_id: @user.id, event: "Payment Charged", properties: { email: @user.email, current_periods_paid: current_periods_paid, total_periods_paid: total_periods_paid, monthly_usd: monthly_usd, current_usd_paid: current_usd_paid, total_usd_paid: total_usd_paid } ) end end
daniel-sim/common
app/controllers/webhooks_controller.rb
class WebhooksController < ShopifyApp::WebhooksController def receive # Backwards-compatible uninstalled webhook at /webhooks/. # Can be removed later. if webhook_type.blank? && request.headers['HTTP_X_SHOPIFY_TOPIC'] == 'app/uninstalled' params[:type] = 'app_uninstalled' end super end end
daniel-sim/common
spec/lib/pr/common/models/promo_code_spec.rb
<gh_stars>0 require "rails_helper" describe PR::Common::Models::PromoCode do subject(:promo_code) { described_class.new(code: "oneTwoThree") } it { is_expected.to have_many :shops } it { is_expected.to validate_presence_of :code } it { is_expected.to validate_numericality_of(:value).is_greater_than_or_equal_to(0) } it { is_expected.to belong_to(:created_by).class_name("PR::Common::Models::Admin") } it "upcases the code on save" do expect { promo_code.save! } .to change(promo_code, :code) .from("oneTwoThree") .to("ONETWOTHREE") end it "does not allow non-unique values" do promo_code.save! duplicate_code = described_class.new(code: promo_code.code) duplicate_code.valid? expect(duplicate_code.errors.details[:code].first[:error]).to eq :taken end describe "#redeemable?" do subject { promo_code.redeemable? } context "when there is no expiry time" do it { is_expected.to eq true } end context "when the expiry time is in the future" do around do |example| Timecop.freeze do promo_code.update!(expires_at: Time.current + 1.second) example.run end end it { is_expected.to eq true } end context "when the expiry time is now" do around do |example| Timecop.freeze do promo_code.update!(expires_at: Time.current) example.run end end it { is_expected.to eq false } end context "when the expiry time is in the past" do around do |example| Timecop.freeze do promo_code.update!(expires_at: Time.current - 1.second) example.run end end it { is_expected.to eq false } end end end
daniel-sim/common
app/controllers/forgotten_password_requests_controller.rb
<filename>app/controllers/forgotten_password_requests_controller.rb class ForgottenPasswordRequestsController < ApiBaseController skip_before_action :authenticate_user_from_token! def create # with providers like Shopify, users can have the same email address # in future we should aim to move all authentication methods into Common users = User.where(email: forgotten_password_requests_params[:email]) if users.count == 1 NewUserMailer.new_password(users[0]).deliver_now elsif users.count > 1 NewUserMailer.new_password_duplicate_emails(users).deliver_now end render json: {}, meta: { success: true }, serializer: EmptySerializer end private def forgotten_password_requests_params params.require(:forgotten_password_request).permit(:email) end end
daniel-sim/common
app/jobs/shop_update_reconcile_job.rb
<reponame>daniel-sim/common<filename>app/jobs/shop_update_reconcile_job.rb class ShopUpdateReconcileJob < PR::Common::ApplicationJob queue_as :low_priority def self.enqueue Shop.installed.with_active_plan.pluck(:id).each(&method(:perform_later)) end def perform(shop_id) # Set this back to the beginning of the hour to ensure that scheduled jobs # run at "exactly" the same time each day. current_time = Time.current.beginning_of_hour with_analytics do shop = Shop.find(shop_id) logger.info "Reconciling shop #{shop.shopify_domain}" reconciled = PR::Common::ShopifyService.new(shop: shop).reconcile_with_shopify logger.info "Failed to reconcile shop #{shop.shopify_domain}" unless reconciled if shop.uninstalled logger.info "Reconciling shop #{shop.shopify_domain} found it uninstalled; "\ "will not proceed" end return if shop.uninstalled logger.info "Recording sustained analytics for shop #{shop.shopify_domain}" PR::Common::SustainedAnalyticsService.new(shop, current_time: current_time).perform end end end
daniel-sim/common
app/controllers/signups_controller.rb
<reponame>daniel-sim/common class SignupsController < ApiBaseController skip_before_action :authenticate_user_from_token! before_action :generate_anonymous # this method risks getting very messy # when we work on it next we should think about what the responsibility of this method is- # - register a user, responding with errors or success # - only require email # - if no password provided, generate one and send mail # - be agnostic to other generic params and just save them to the user # - for example, if a 'website' param is provided, save it to the user, if a 'favourite_food' param is provided, save it to the user # - then it is the responsibility of the API caller to do special things on a successful registration: not this method # meaning: # - strip out JobCreationService call from here # - remove special logic for 'name' and 'website' params: just treat them as generic def create existing_user = User.find_by(email: signup_params[:email].downcase, provider: nil) @user = nil meta = if existing_user and !signup_params[:password] if !existing_user.confirmed? # create their job, but don't sign them in if params[:job] JobCreationService.new(filled_roles: job_params[:filled_roles], recommended_for_id: job_params[:recommended_for_id], description: job_params[:description], creating_user: existing_user, job_type: job_params[:job_type]).save end NewUserMailer.new_password(existing_user).deliver_now { signup_success: false, require_password: true, confirmed: false } else # ask them for password { signup_success: false, require_password: true, confirmed: true } end elsif existing_user # check their password is correct and if so create job if existing_user.valid_password?(signup_params[:password]) # create their job @user = existing_user sign_in @user, store: false { signup_success: true, existing_account: true } else { signup_success: false, require_password: true, password_invalid: true } end else # no existing user, so create this one if params['signup']['name'] params['signup']['name'] = ActionController::Base.helpers.strip_tags(params['signup']['name']) end unless signup_params[:password] params['signup']['password'] = <PASSWORD>.base64 send_password_instruction = true end @user = User.new(signup_params.merge(confirmed: false)) token = request.headers['Authorization'] if token if user = User.find_by(access_token: token, anonymous: true) @user = user @user.website = signup_params[:website] @user.password = signup_params[:password] @user.email = signup_params[:email] @user.anonymous = false @user.username = signup_params[:email] end end if @user.save sign_in @user, store: false NewUserMailer.welcome(@user).deliver_now if PR::Common.config.send_welcome_email if send_password_instruction NewUserMailer.new_password(@user).deliver_now else NewUserMailer.confirm(@user).deliver_now if PR::Common.config.send_confirmation_email end { signup_success: true, existing_account: false } else { signup_success: false, existing_account: false, errors: @user.errors } end end render json: @user, meta: meta, serializer: SessionSerializer end private def generate_anonymous if params[:signup][:anonymous] signup_params = PR::Common.config.signup_params params[:signup][:email] = "help+anonymous_#{Time.now.to_i}#{rand(100)}@<EMAIL>" params[:signup][:password] = <PASSWORD> if signup_params.include? :password params[:signup][:name] = 'anonymous' if signup_params.include? :name params[:signup][:anonymous] = true end end def signup_params params.require(:signup).permit(PR::Common.config.signup_params) end def job_params params.require(:job).permit(:job_type, :fixer_id, :recommended_for_id, :description, :filled_roles => [:id, :name, :admin]) end end
daniel-sim/common
lib/pr/common/shopify_errors.rb
module PR module Common module ShopifyErrors def self.convert(exception, shopify_domain = nil) return exception if shopify_domain.blank? case exception when ActiveResource::ClientError return convert_from_client_error(exception, shopify_domain) when ActiveResource::UnauthorizedAccess return ShopUninstalled.new(shopify_domain, exception.message) when ActiveResource::ServerError return ServerError.new(shopify_domain, exception.message) when JSON::ParserError return JsonError.new(shopify_domain, exception.message) end exception end def self.convert_from_client_error(exception, shopify_domain) case exception.message when "Failed. Response code = 423. Response message = Locked." return ShopLocked.new(shopify_domain, exception.message) when "Failed. Response code = 402. Response message = Payment Required." return ShopFrozen.new(shopify_domain, exception.message) end exception end class Base < StandardError def initialize(shopify_domain = nil, message = nil) @shopify_domain = shopify_domain @message = message end def to_s "".tap do |message| message << "#{@message}. " if @message message << "shop=#{@shopify_domain}" end end end class ShopLocked < Base; end class ShopFrozen < Base; end class ShopUninstalled < Base; end class ServerError < Base; end class JsonError < Base; end end end end
daniel-sim/common
app/controllers/shops_controller.rb
<gh_stars>0 class ShopsController < ApplicationController def callback shop = Shop.find_by(shopify_domain: shop_params[:myshopify_domain]) PR::Common::ShopifyService .new(shop: shop) .update_shop(shopify_plan: shop_params[:plan_name], uninstalled: shop.uninstalled) end private def shop_params params.permit(:myshopify_domain, :plan_name) end end
daniel-sim/common
spec/dummy/config/initializers/common_initializer.rb
PR::Common.configure do |config| config.signup_params = %i[email website password <PASSWORD>] config.send_welcome_email = false config.send_confirmation_email = false config.referrer_redirect = 'http://localhost:3000/login' config.pricing = [ { key: :staff_business_free, price: 0, trial_days: 0, shopify_plan: "staff_business", name: "Staff Business", terms: "Staff Business terms" }, { key: :affiliate_free, price: 0, trial_days: 0, shopify_plan: "affiliate", name: "Affiliate", terms: "Affiliate terms" }, { key: :plus, price: 25.99, trial_days: 0, shopify_plan: "plus", name: "Plus", terms: "Plus terms" }, { key: :generic, price: 10.0, trial_days: 7, name: "Generic with trial", terms: "Generic terms" } ] end
daniel-sim/common
spec/lib/pr/common/charge_service_spec.rb
<reponame>daniel-sim/common<filename>spec/lib/pr/common/charge_service_spec.rb require "rails_helper" # See spec/dummy/config/initializers/common_initializer.rb for # test pricing describe PR::Common::ChargeService do let(:user) { create(:user) } let(:shop) { create(:shop, user: user) } let(:base_url) { "http://localhost" } let(:service) { described_class.new(shop) } shared_examples "post charge-activation" do it "sets the user's active charge to true" do expect { subject } .to change(user, :active_charge) .from(false) .to(true) end it "updates the user's charged_at time to now" do Timecop.freeze do expect { subject } .to change(user, :charged_at) .from(nil) .to(Time.current) end end it "updates the shop's app_plan to the price key" do expect { subject } .to change(shop, :app_plan) .from(nil) .to(described_class.determine_app_plan_from_charge(charge).to_s) end it "sends an identify analytic" do expect(Analytics).to receive(:identify) .with( user_id: user.id, traits: { email: user.email, monthlyUsd: charge.price, appPlan: described_class.determine_app_plan_from_charge(charge), trial: price.positive?, promo_code: false } ) subject end it "sends a 'Charge Activated' track analytic" do expect(Analytics).to receive(:track) .with( user_id: user.id, event: "Charge Activated", properties: { email: user.email, monthly_usd: charge.price, app_plan: described_class.determine_app_plan_from_charge(charge), promo_code: false } ) subject end end describe ".determine_app_plan_from_charge" do context "when the app plan exists" do let(:charge) { ShopifyAPI::RecurringApplicationCharge.new(name: "Staff Business") } it "returns the charge's key" do expect(described_class.determine_app_plan_from_charge(charge)).to eq :staff_business_free end end context "when the app plan does not exist" do let(:charge) { ShopifyAPI::RecurringApplicationCharge.new(name: "foobar") } it "returns nil" do expect(described_class.determine_app_plan_from_charge(charge)).to be_nil end end end describe "#create_charge" do subject { service.create_charge(price, base_url) } before do allow(ShopifyAPI::RecurringApplicationCharge) .to receive(:current) .and_return nil allow(ShopifyAPI::Shop) .to receive(:current) .and_return(ShopifyAPI::Shop.new(plan_name: "basic")) allow(ShopifyAPI::RecurringApplicationCharge) .to receive(:create) end shared_examples "cancels existing charge" do context "when there is an existing charge" do let(:fake_recurring_application_charge) { OpenStruct.new(cancel: true) } before do allow(ShopifyAPI::RecurringApplicationCharge) .to receive(:current) .and_return fake_recurring_application_charge end it "cancels it" do expect(fake_recurring_application_charge).to receive(:cancel) subject end end context "when there is no existing charge" do it "does not try to cancel it" do expect { subject }.not_to raise_error end end end context "when price is 0" do let(:price) { 0 } let(:charge) { ShopifyAPI::RecurringApplicationCharge.new(price: price, name: "Affiliate") } include_examples "cancels existing charge" include_examples "post charge-activation" end context "when price is above 0" do let(:price) { 10.0 } include_examples "cancels existing charge" it "creates the charge" do expect(ShopifyAPI::RecurringApplicationCharge) .to receive(:create) .with( price: price, trial_days: 7, name: "Generic with trial", terms: "Generic terms", test: true, return_url: "http://localhost/charges/callback?access_token=#{user.access_token}" ) subject end end end describe "#activate_charge" do subject { service.activate_charge(charge) } before { allow(charge).to receive(:activate) } let(:price) { 10.0 } let(:charge) { ShopifyAPI::RecurringApplicationCharge.new(price: price, name: "Generic with trial") } include_examples "post charge-activation" it "activates the charge" do expect(charge).to receive(:activate) subject end end describe "#up_to_date_price" do it "calls out to 'PR::Common::ShopifyService#determine_price' with return from Shopify API" do api_shop = ShopifyAPI::Shop.new(plan_name: "foo") fake_service = PR::Common::ShopifyService.new(shop: shop) allow(ShopifyAPI::Shop) .to receive(:current) .and_return(api_shop) allow(PR::Common::ShopifyService) .to receive(:new) .with(shop: shop) .and_return(fake_service) expect(fake_service) .to receive(:determine_price) .with(api_shop: api_shop) described_class.new(shop).up_to_date_price end end end
daniel-sim/common
config/initializers/analytics_ruby.rb
<gh_stars>0 Analytics = Segment::Analytics.new( write_key: ENV.fetch("segment_write_key", ""), on_error: proc { |status, msg| print msg } )
daniel-sim/common
db/migrate/20190116102258_common_create_time_periods.rb
<gh_stars>0 class CommonCreateTimePeriods < ActiveRecord::Migration[5.0] def change create_table :time_periods do |t| t.column :start_time, :datetime, null: false, default: -> { "NOW()" }, index: true t.column :end_time, :datetime, index: true t.integer :kind, default: 0, null: false, index: true t.column :shop_retained_analytic_sent_at, :datetime, index: true t.belongs_to :shop, index: true t.timestamps end end end
daniel-sim/common
spec/jobs/app_uninstalled_job_spec.rb
require 'rails_helper' describe AppUninstalledJob do let(:shop) { create(:shop, user: build(:user)) } before { allow(Analytics).to receive(:flush) } describe "#perform" do it "set the shop to uninstalled" do expect { described_class.perform_now(shop_domain: shop.shopify_domain) } .to change { shop.reload.uninstalled } .from(false) .to(true) end it "sends an 'App Uninstalled' analytic" do analytic_params = { user_id: shop.user.id, event: "App Uninstalled", properties: { email: shop.user.email, subscription_length: nil, current_days_installed: 1, total_days_installed: 1, current_periods_paid: 0, total_periods_paid: 0, monthly_usd: 0.0, current_usd_paid: 0.0, total_usd_paid: 0.0 } } expect(Analytics).to receive(:track).with(analytic_params) described_class.perform_now(shop_domain: shop.shopify_domain) end end end
daniel-sim/common
lib/pr/common/user_service.rb
module PR module Common class UserService def find_or_create_user_by_shopify(email:, shop:, referrer: nil) find_shopify_user(shop: shop, referrer: referrer) || create_shopify_user(email: email, shop: shop, referrer: referrer) end private def create_shopify_user(email:, shop:, referrer:) Rails.logger.info("create_shopify_user for email #{email}, shop #{shop.id}") user = User.create!( username: "shopify-#{shop.shopify_domain}", password: <PASSWORD>, provider: "shopify", website: shop.shopify_domain, shop_id: shop.id, email: email, referrer: referrer ) Rails.logger.info("create_shopify_user created: #{user.present?}, id: #{user&.id}") identify(user, referrer) track_install(user) user end def find_shopify_user(shop:, referrer:) user = User.find_by(username: "shopify-#{shop.shopify_domain}", provider: "shopify") user || return return unless user identify(user, referrer) user end def identify(user, referrer) Analytics.identify( user_id: user.id, traits: { primaryDomain: user.shop.shopify_domain, email: user.email, product: "Shopify", username: user.username, activeCharge: user.active_charge, shopifyPlan: user.shop.shopify_plan, referrer: referrer } ) end def track_install(user) ShopifyService.new(shop: user.shop).track_installed end end end end
daniel-sim/common
db/migrate/20190116101646_common_remove_reinstalled_at_and_reopened_at_from_shops.rb
<filename>db/migrate/20190116101646_common_remove_reinstalled_at_and_reopened_at_from_shops.rb class CommonRemoveReinstalledAtAndReopenedAtFromShops < ActiveRecord::Migration[5.0] def change remove_column :shops, :reinstalled_at, :timestamp remove_column :shops, :reopened_at, :timestamp end end
daniel-sim/common
spec/lib/pr/common/params_promo_code_service_spec.rb
require "rails_helper" describe ParamsPromoCodeService do subject(:service) { described_class.new(params) } let(:code) { "THE-CODE" } let(:promo_code) { PR::Common::Models::PromoCode.create(code: code) } let(:params) { { promo_code: code } } describe "#record" do before { promo_code } it "returns the promo code record from the DB matching the code in params" do expect(service.record).to eq promo_code end end describe "error" do context "when the promo code exists" do before { promo_code } it "returns nil" do expect(service.error).to eq nil end end context "when the promo code is expired" do around do |example| Timecop.freeze do promo_code.update!(expires_at: Time.current) example.run end end it "returns promo code expired text" do expect(service.error).to eq "Promo code expired." end end context "when the promo code does not exist" do it "returns invalid promo code text" do expect(service.error).to eq "Invalid promo code." end end end describe "#present?" do context "when the promo code exists" do before { promo_code } it "returns true" do expect(service.present?).to eq true end end context "when there is no such promo code" do it "returns false" do expect(service.present?).to eq false end end end describe "#code" do it "returns the code from the params" do expect(service.code).to eq code end end end
daniel-sim/common
lib/pr/common/shopify_service.rb
module PR module Common class ShopifyService def initialize(shop:) @shop = shop @user = @shop.user end def update_user(email:) @user.update(email: email) end def update_shop(options = {}) # This method used to explicitly require "shopify_plan" and "uninstalled" only as params shopify_plan = options[:shopify_plan] = options.fetch(:shopify_plan, @shop.shopify_plan) uninstalled = options[:uninstalled] = options.fetch(:uninstalled, @shop.uninstalled) maybe_update_shopify_plan(shopify_plan) maybe_reinstall_or_uninstall(shopify_plan, uninstalled) maybe_reopen(shopify_plan) maybe_hand_off_or_cancel(shopify_plan) @shop.assign_attributes(options) @user&.save! # the check is legacy; some shops do not have a user, and we can't always create one. @shop.save! end def maybe_reinstall_or_uninstall(shopify_plan, uninstall) if newly_reinstalled?(uninstall) @shop.app_plan = nil @user.charged_at = nil track_reinstalled(shopify_plan) elsif newly_uninstalled?(uninstall) track_uninstalled @user.active_charge = false end end def maybe_reopen(shopify_plan) return unless newly_reopened?(shopify_plan) track_reopened(shopify_plan) @user.charged_at = Time.current end def maybe_update_shopify_plan(shopify_plan) return unless @shop.shopify_plan return unless shopify_plan_differs?(shopify_plan) track_shopify_plan_updated(shopify_plan) end def track_shopify_plan_updated(shopify_plan) Rails.logger.info "track_shopify_plan_updated for user #{@user.id}, shop #{@shop.id}" return if @user.blank? Analytics.identify( user_id: @user.id, traits: { email: @user.email, shopifyPlan: shopify_plan } ) Analytics.track( user_id: @user.id, event: "Shopify Plan Updated", properties: { email: @user.email, pre_shopify_plan: @shop.shopify_plan, post_shopify_plan: shopify_plan } ) end def maybe_hand_off_or_cancel(shopify_plan) if handed_off?(shopify_plan) track_handed_off(shopify_plan) elsif cancelled?(shopify_plan) track_cancelled end end def newly_reinstalled?(uninstalled) @shop.uninstalled? && !uninstalled end def newly_uninstalled?(uninstalled) !@shop.uninstalled? && uninstalled end # Cancelled -> something else def newly_reopened?(shopify_plan) @shop.cancelled? && shopify_plan != ::Shop::PLAN_CANCELLED end # Handoff means that the plan goes from "affiliate" to "frozen" def handed_off?(shopify_plan) @shop.affiliate? && shopify_plan == ::Shop::PLAN_FROZEN end # Shop was not previously cancelled but is now def cancelled?(shopify_plan) !@shop.cancelled? && shopify_plan == ::Shop::PLAN_CANCELLED end def track_cancelled Rails.logger.info "track_cancelled for user #{@user.id}, shop #{@shop.id}" return if @user.blank? shop = @user.shop current_time_period = shop.current_time_period Analytics.identify( user_id: @user.id, traits: { email: @user.email, status: :inactive, subscriptionLength: @user.subscription_length, currentDaysInstalled: current_time_period.lapsed_days, totalDaysInstalled: shop.total_days_installed, currentPeriodsPaid: current_time_period.periods_paid, totalPeriodsPaid: shop.total_periods_paid, monthlyUsd: current_time_period.monthly_usd.to_f, currentUsdPaid: current_time_period.usd_paid.to_f, totalUsdPaid: shop.total_usd_paid.to_f } ) Analytics.track( user_id: @user.id, event: "Shop Closed", properties: { email: @user.email, subscription_length: @user.subscription_length, current_days_installed: current_time_period.lapsed_days, total_days_installed: shop.total_days_installed, current_periods_paid: current_time_period.periods_paid, total_periods_paid: shop.total_periods_paid, monthly_usd: current_time_period.monthly_usd.to_f, current_usd_paid: current_time_period.usd_paid.to_f, total_usd_paid: shop.total_usd_paid.to_f } ) end def track_installed Rails.logger.info "track_installed for user #{@user.id}, shop #{@shop.id}" return if @user.blank? Analytics.identify( user_id: @user.id, traits: { email: @user.email, status: :active, shopifyPlan: @shop.shopify_plan, appPlan: @shop.app_plan, promo_code: @shop.promo_code&.code } ) Analytics.track( user_id: @user.id, event: "App Installed", properties: { "registration method": "shopify", email: @user.email, shopify_plan: @user.shop.shopify_plan, promo_code: @shop.promo_code&.code } ) end # Set the `pricing_method` in PR::Common::Configuration. # If it's a symbol, it will be called on this service. # If it's callable (e.g. a lambda) then it'll be called with @shop and the args. # If not configured (by default) it will call `:determine_price_by_plan_name`. def determine_price(args = {}) pricing_method = PR::Common.config.pricing_method price = if pricing_method.is_a?(Symbol) send(pricing_method, args) elsif pricing_method.respond_to?(:call) pricing_method.call(@shop, args) else raise "Pricing method is not valid." end maybe_apply_promo_code_to_price(price) end def maybe_apply_promo_code_to_price(price) return price if @shop.promo_code.blank? # promo code is a "percentage" of the total. By default it's 100.0. # 200.0 = double price # 50.0 = half price # 0.0 = free price.merge(price: ((@shop.promo_code.value / 100) * price[:price]).ceil(2)) end def reconcile_with_shopify success = true ShopifyAPI::Session.temp(@shop.shopify_domain, @shop.shopify_token) do begin shopify_shop = ShopifyAPI::Shop.current ensure_user_exists(shopify_shop.email) update_shop(shopify_plan: shopify_shop.plan_name, uninstalled: false) rescue ActiveResource::UnauthorizedAccess => e # we no longer have access to the shop- app uninstalled update_shop(shopify_plan: @shop.shopify_plan, uninstalled: true) success = false rescue ActiveResource::ClientError => e case e.response.code.to_s when "401" then update_shop(shopify_plan: @shop.shopify_plan, uninstalled: true) when "402" then update_shop(shopify_plan: Shop::PLAN_FROZEN, uninstalled: false) when "403" then update_shop(shopify_plan: Shop::PLAN_FRAUDULENT, uninstalled: false) when "404" then update_shop(shopify_plan: Shop::PLAN_CANCELLED, uninstalled: false) when "423" then update_shop(shopify_plan: Shop::PLAN_LOCKED, uninstalled: false) end end ShopifyAPI::Base.clear_session end return success end def remote_shop begin ShopifyAPI::Shop.current rescue StandardError => exception raise ShopifyErrors.convert(exception, @shop.shopify_domain) end end def track_handed_off(shopify_plan) Rails.logger.info "track_handed_off for user #{@user.id}, shop #{@shop.id}" return if @user.blank? Analytics.identify( user_id: @user.id, traits: { email: @user.email, shopifyPlan: shopify_plan } ) Analytics.track( user_id: @user.id, event: "Shop Handed Off", properties: { shopify_plan: shopify_plan, email: @user.email } ) end private # This is here to deal with edge cases in which a user was never created def ensure_user_exists(email) @user ||= PR::Common::UserService.new.find_or_create_user_by_shopify(email: email, shop: @shop) @shop.reload end def determine_price_by_plan_name(args = {}) plan = args[:api_shop] ? args[:api_shop].plan_name : @shop.shopify_plan # List prices in ascending order in config pricing = PR::Common.config.pricing best_price = pricing.last pricing.each do |price| best_price = price if price[:shopify_plan] == plan end best_price end def track_reopened(shopify_plan) Rails.logger.info "track_reopened for user #{@user.id}, shop #{@shop.id}" return if @user.blank? Analytics.identify( user_id: @user.id, traits: { email: @user.email, status: :active, shopifyPlan: shopify_plan, promo_code: @shop.promo_code&.code } ) Analytics.track( user_id: @user.id, event: "Shop Reopened", properties: { "registration method": "shopify", email: @user.email, shopify_plan: shopify_plan, promo_code: @shop.promo_code&.code } ) end def track_reinstalled(shopify_plan) Rails.logger.info "track_reinstalled for user #{@user.id}, shop #{@shop.id}" return if @user.blank? Analytics.identify( user_id: @user.id, traits: { email: @user.email, status: :active, shopifyPlan: shopify_plan, appPlan: @shop.app_plan, monthlyUsd: 0, # always reset to 0 on reinstall activeCharge: @user.active_charge, trial: false, promo_code: @shop.promo_code&.code } ) Analytics.track( user_id: @user.id, event: "App Reinstalled", properties: { "registration method": "shopify", email: @user.email, shopify_plan: shopify_plan, promo_code: @shop.promo_code&.code } ) end def track_uninstalled Rails.logger.info "track_uninstalled for user #{@user.id}, shop #{@shop.id}" return if @user.blank? shop = @user.shop current_time_period = shop.current_time_period Analytics.identify( user_id: @user.id, traits: { email: @user.email, status: :uninstalled, subscriptionLength: @user.subscription_length, currentDaysInstalled: current_time_period.lapsed_days, totalDaysInstalled: shop.total_days_installed, currentPeriodsPaid: current_time_period.periods_paid, totalPeriodsPaid: shop.total_periods_paid, monthlyUsd: current_time_period.monthly_usd.to_f, currentUsdPaid: current_time_period.usd_paid.to_f, totalUsdPaid: shop.total_usd_paid.to_f } ) Analytics.track( user_id: @user.id, event: "App Uninstalled", properties: { email: @user.email, subscription_length: @user.subscription_length, current_days_installed: current_time_period.lapsed_days, total_days_installed: shop.total_days_installed, current_periods_paid: current_time_period.periods_paid, total_periods_paid: shop.total_periods_paid, monthly_usd: current_time_period.monthly_usd.to_f, current_usd_paid: current_time_period.usd_paid.to_f, total_usd_paid: shop.total_usd_paid.to_f } ) end def shopify_plan_differs?(shopify_plan) shopify_plan.to_s != @shop.shopify_plan.to_s end end end end
daniel-sim/common
db/migrate/20190213214625_common_add_no_brainer_indices.rb
class CommonAddNoBrainerIndices < ActiveRecord::Migration[5.0] def change unless ActiveRecord::Base.connection.index_exists?(:shops, :shopify_domain) add_index :shops, :shopify_domain end unless ActiveRecord::Base.connection.index_exists?(:users, :username) add_index :users, :username end unless ActiveRecord::Base.connection.index_exists?(:users, :provider) add_index :users, :provider end end end
daniel-sim/common
db/migrate/20190520170125_common_add_expires_at_to_promo_codes.rb
<gh_stars>0 class CommonAddExpiresAtToPromoCodes < ActiveRecord::Migration[5.0] def change add_column :promo_codes, :expires_at, :timestamp end end
daniel-sim/common
lib/pr/common/params_promo_code_service.rb
class ParamsPromoCodeService KEY = :promo_code def initialize(params) @params = params end def record @record ||= PR::Common::Models::PromoCode.find_by(code: code) end def error return "Invalid promo code." unless record "Promo code expired." unless record.redeemable? end def code @params[KEY] end def present? record.present? end end
daniel-sim/common
app/controllers/charges_controller.rb
class ChargesController < ApplicationController include ShopifyApp::LoginProtection before_action :login_again_if_different_shop around_action :shopify_session before_action :load_user def create price = charge_service.up_to_date_price[:price] charge = charge_service.create_charge(price, request.base_url) # price is free return redirect_to charge_success_path if price.zero? return fullpage_redirect_to(charge.confirmation_url) if charge # charge failed redirect_to charge_failed_path end def callback @charge = ShopifyAPI::RecurringApplicationCharge.find(params[:charge_id]) case @charge.status when "accepted" charge_service.activate_charge(@charge) return redirect_to charge_success_path when "declined" return redirect_to charge_declined_path end redirect_to charge_failed_path end private def charge_service @charge_service ||= PR::Common::ChargeService.new(@user.shop) end def charge_success_path "#{Settings.client_url}/charge/succeed" end def charge_declined_path "#{Settings.client_url}/charge/declined" end def charge_failed_path "#{Settings.client_url}/charge/failed" end def load_user @user = User.find_by!(access_token: params[:access_token]) end end
daniel-sim/common
lib/pr/common/tokenable.rb
<reponame>daniel-sim/common module PR module Common module Tokenable extend ActiveSupport::Concern included do after_create :update_access_token! def update_access_token! self.access_token = "#{self.id}:#{Devise.friendly_token}" save end end end end end
daniel-sim/common
spec/dummy/config/application.rb
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) require "pr/common" module Dummy class Application < Rails::Application Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true # Throws an error unless this is set Rails.application.config.active_job.queue_adapter = :sidekiq end end
daniel-sim/common
spec/jobs/shop_update_reconcile_job_spec.rb
require "rails_helper" describe ShopUpdateReconcileJob do let(:shop) { create(:shop, user: build(:user)) } let(:sustained_analytics_service) { PR::Common::SustainedAnalyticsService.new(shop) } around do |example| Timecop.freeze(Time.new(2019, 1, 1, 5, 28, 31).in_time_zone) { example.run } end before do allow(Analytics).to receive(:flush) allow(PR::Common::SustainedAnalyticsService) .to receive(:new) .with(shop, current_time: Time.new(2019, 1, 1, 5).in_time_zone) # time at start of the hour .and_return(sustained_analytics_service) end context "when shopify_plan changes from affiliate to frozen" do before do allow(ShopifyAPI::Shop).to receive(:current).and_return(OpenStruct.new(plan_name: "frozen")) allow(Analytics).to receive(:track).with(updated_plan_params) allow(Analytics).to receive(:track).with(handed_off_params) end let(:updated_plan_params) do { user_id: shop.user.id, event: "Shopify Plan Updated", properties: { email: shop.user.email, pre_shopify_plan: "affiliate", post_shopify_plan: "frozen" } } end let(:handed_off_params) do { user_id: shop.user.id, event: "Shop Handed Off", properties: { email: shop.user.email, shopify_plan: "frozen" } } end it "sends a 'Shopify Plan Updated' analytic" do expect(Analytics).to receive(:track).with(updated_plan_params) described_class.perform_now(shop.id) end it "sends a 'Shop Handed Off' analytic" do expect(Analytics).to receive(:track).with(handed_off_params) described_class.perform_now(shop.id) end it "calls out to SustainedAnalyticsService" do expect(sustained_analytics_service).to receive(:perform) described_class.perform_now(shop.id) end end context "when shopify_plan changes from affiliate to something other than frozen" do before do allow(ShopifyAPI::Shop).to receive(:current).and_return(OpenStruct.new(plan_name: "enterprise")) allow(Analytics).to receive(:track).with(updated_plan_params) allow(Analytics).to receive(:track).with(handed_off_params) end let(:updated_plan_params) do { user_id: shop.user.id, event: "Shopify Plan Updated", properties: { email: shop.user.email, pre_shopify_plan: "affiliate", post_shopify_plan: "enterprise" } } end let(:handed_off_params) do { user_id: shop.user.id, event: "Shop Handed Off", properties: { email: shop.user.email, shopify_plan: "enterprise" } } end it "sends a 'Shopify Plan Updated' analytic" do expect(Analytics).to receive(:track).with(updated_plan_params) described_class.perform_now(shop.id) end it "does not send a 'Shop Handed Off' analytic" do expect(Analytics).not_to receive(:track).with(handed_off_params) described_class.perform_now(shop.id) end it "calls out to SustainedAnalyticsService" do expect(sustained_analytics_service).to receive(:perform) described_class.perform_now(shop.id) end end context "when shopify_plan does not change" do before do allow(ShopifyAPI::Shop).to receive(:current).and_return(OpenStruct.new(plan_name: shop.shopify_plan)) end it "does not send any analytics" do expect(Analytics).not_to receive(:track) described_class.perform_now(shop.id) end it "calls out to SustainedAnalyticsService" do expect(sustained_analytics_service).to receive(:perform) described_class.perform_now(shop.id) end end context "when reconcilliation fails" do before do allow(ShopifyAPI::Shop) .to receive(:current) .and_raise(ActiveResource::ClientError, OpenStruct.new(code: '402')) end it "does not call out to SustainedAnalyticsService" do expect(sustained_analytics_service).to receive(:perform) described_class.perform_now(shop.id) end end end
daniel-sim/common
spec/requests/shop_spec.rb
require "rails_helper" describe "Shop" do let(:shopify_domain) { "the_domain" } let(:shop) { create(:shop, shopify_domain: shopify_domain) } let(:service) { PR::Common::ShopifyService.new(shop: shop) } let(:plan) { "some new plan" } describe "POST shops/callback" do let(:url) { "/shops/callback" } before do allow(Shop) .to receive(:find_by) .with(shopify_domain: shopify_domain) .and_return(shop) allow(PR::Common::ShopifyService) .to receive(:new) .with(shop: shop) .and_return(service) end it "calls out to PR::Common::ShopifyService.update_shop" do expect(service) .to receive(:update_shop) .with(shopify_plan: plan, uninstalled: shop.uninstalled) post url, params: { myshopify_domain: shopify_domain, plan_name: plan } end end end
daniel-sim/common
config/initializers/shopify_rate_limiting.rb
# https://docs.shopify.com/api/introduction/api-call-limit module ActiveResource # 429 Client Error class RateLimitExceededError < ClientError # :nodoc: end class Connection @@mutex = Mutex.new RATE_LIMIT_SLEEP_SECONDS = ENV["RATE_LIMIT_SLEEP_SECONDS"] || 20 # number of seconds to sleep (by sleeping 20 you reset the clock to get 40 fresh burst calls with the default 2 calls/sec) RATE_LIMIT_BUFFER = ENV["RATE_LIMIT_SLEEP_SECONDS"] || 10 # you don't want to drain the remaining count to 0 in case you need high priority calls def self.rate_limit_timer @@mutex.synchronize { @rate_limit_timer } end def self.rate_limit_timer=(value) @@mutex.synchronize { @rate_limit_timer = value } end private # https://github.com/rails/activeresource/blob/82eb29ab023b3105b29bce31c9a00a3b9a9653aa/lib/active_resource/connection.rb#L117 def request(method, path, *arguments) request_uri = "#{site.scheme}://#{site.host}:#{site.port}#{path}" begin Rails.logger.debug("#{method} #{path} shopify request #{Rake.application.top_level_tasks.join(', ')}") if ENV["DEBUG_SHOPIFY_RATE_LIMITS"] result = ActiveSupport::Notifications.instrument("request.active_resource") do |payload| payload[:method] = method payload[:request_uri] = request_uri payload[:result] = http.send(method, path, *arguments) end handle_rate_limit_response(result) handle_rate_limits(result) handle_response(result) rescue RateLimitExceededError => e Rails.logger.warn "[Rate limit exceeded]" if ENV["DEBUG_SHOPIFY_RATE_LIMITS"] rate_limit_sleep retry rescue Timeout::Error => e raise TimeoutError.new(e.message) rescue OpenSSL::SSL::SSLError => e raise SSLError.new(e.message) end end def handle_rate_limit_response(response) case response.code.to_i when 429 raise RateLimitExceededError.new(response) end end def handle_rate_limits(response) return unless response['x-shopify-shop-api-call-limit'] # Record the current limits # Start a timer from when we last learned about the current limits self.class.rate_limit_timer = Time.now # Print some feedback for debugging Rails.logger.debug "[Rate limit: #{current_rate_limit_call_count(response) || "??"}/#{total_rate_limit_calls(response) || "??"}]" if ENV["DEBUG_SHOPIFY_RATE_LIMITS"] # Sleep if we need to sleep rate_limit_sleep if rate_limit_need_sleep?(response) end def rate_limit_elapsed_seconds return 0 if self.class.rate_limit_timer.nil? Time.now.to_i - self.class.rate_limit_timer.to_i end def rate_limit_sleep sleep_seconds = RATE_LIMIT_SLEEP_SECONDS - rate_limit_elapsed_seconds return if sleep_seconds < 0 Rails.logger.debug "[Rate limit sleeping: #{sleep_seconds} seconds]" if ENV["DEBUG_SHOPIFY_RATE_LIMITS"] Kernel.sleep(sleep_seconds) self.class.rate_limit_timer = nil end def rate_limit_need_sleep?(response) return false if total_rate_limit_calls(response).nil? || current_rate_limit_call_count(response).nil? return false if total_rate_limit_calls(response).to_i - current_rate_limit_call_count(response).to_i > RATE_LIMIT_BUFFER return false if rate_limit_elapsed_seconds > RATE_LIMIT_SLEEP_SECONDS true end def current_rate_limit_call_count(response) response['x-shopify-shop-api-call-limit'].split('/').first end def total_rate_limit_calls(response) response['x-shopify-shop-api-call-limit'].split('/').last end end end
daniel-sim/common
db/migrate/20181204125450_add_reinstalled_at_to_shops.rb
class AddReinstalledAtToShops < ActiveRecord::Migration[5.0] def change return if column_exists? :shops, :reinstalled_at add_column :shops, :reinstalled_at, :timestamp end end
daniel-sim/common
db/migrate/20190118122037_common_add_monthly_usd_to_time_periods.rb
class CommonAddMonthlyUsdToTimePeriods < ActiveRecord::Migration[5.0] def change add_column :time_periods, :monthly_usd, :decimal, default: 0, null: false end end
daniel-sim/common
app/controllers/api_base_controller.rb
<filename>app/controllers/api_base_controller.rb class ApiBaseController < ActionController::Base require 'active_model_serializers' include PR::Common::TokenAuthenticable end
daniel-sim/common
app/helpers/admin_form_helper.rb
module AdminFormHelper def form_group(model, value_key, &block) content_tag(:div, [capture(&block), form_group_error(model, value_key)].compact.join.html_safe, class: form_group_class(model, value_key)) end def form_group_class(model, value_key) return "form-group" if model.errors.blank? return "form-group has-error" if model.errors[value_key].any? "form-group has-success" end def form_group_error(model, value_key) return if model.errors[value_key].blank? content_tag(:p, model.errors[value_key].first, class: "form-input-hint") end end
daniel-sim/common
app/jobs/pr/common/application_job.rb
<filename>app/jobs/pr/common/application_job.rb module PR module Common class ApplicationJob < ActiveJob::Base def with_analytics yield Analytics.flush end end end end
xavriley/synthdef
lib/synthdef/parser.rb
<reponame>xavriley/synthdef require 'bindata' class PascalString < BinData::Primitive uint8 :len, :value => lambda { data.length } string :data, :read_length => :len def get; self.data; end def set(v) self.data = v; end end class SynthInt < BinData::Choice endian :big default_parameter :selection => :check_version default_parameter :copy_on_change => true int16 0 int32 1 end class Synthdef::Parser < BinData::Record def check_version # Returns zero based index for choices file_version == 1 ? 0 : 1 end endian :big string :file_type_id, read_length: 4 int32 :file_version int16 :no_of_synthdefs array :synthdefs, initial_length: lambda { no_of_synthdefs } do pascal_string :name synth_int :no_of_constants array :constants, initial_length: lambda { no_of_constants } do float :constant end synth_int :no_of_params array :params, initial_length: lambda { no_of_params } do float :initial_parameter_value end synth_int :no_of_param_names array :param_names, initial_length: lambda { no_of_param_names } do pascal_string :param_name synth_int :param_index end synth_int :no_of_ugens array :ugens, initial_length: lambda { no_of_ugens } do pascal_string :ugen_name int8 :rate synth_int :no_of_inputs synth_int :no_of_outputs int16 :special, initial_value: 0 array :inputs, initial_length: lambda { no_of_inputs } do synth_int :src if lambda { src == -1 } synth_int :input_constant_index else synth_int :input_ugen_index end end array :outputs, initial_length: lambda { no_of_outputs } do int8 :calculation_rate end end int16 :no_of_variants, initial_value: 0 array :variants, initial_length: lambda { no_of_variants } do pascal_string :variant_name float :variant_param end end end
xavriley/synthdef
spec/spec_helper.rb
require 'pry' require 'synthdef'
xavriley/synthdef
lib/synthdef.rb
<filename>lib/synthdef.rb require "synthdef/version" require "synthdef/graphviz" require "synthdef/parser" class Synthdef def self.read(*args) Parser.read(*args) end def self.has_params?(sdef, param_list) sdef = sdef.snapshot # ensure we cast to Ruby types, not bindata types param_list.map!(&:to_s) sdef[:synthdefs].all? {|s| # check using intersection of arrays (s[:param_names].map {|pn| pn[:param_name] } & param_list) == param_list } end end
xavriley/synthdef
spec/synthdef_spec.rb
require 'spec_helper' require 'active_support' describe Synthdef do let(:synthdef_binary) { IO.read(File.expand_path("../data/recorder.scsyndef", __FILE__)) } let(:complex_synthdef_binary) { IO.read(File.expand_path("../data/hoover.scsyndef", __FILE__)) } it 'reads a basic version 1 synthdef' do parsed_synthdef = Synthdef.read(synthdef_binary).snapshot expect(parsed_synthdef).to be_a(Hash) expect(parsed_synthdef).not_to be_empty expect(parsed_synthdef[:synthdefs].first[:no_of_constants]).to eq(0) expect(parsed_synthdef[:synthdefs].first[:no_of_params]).to eq(2) end it 'reads a complex version 2 synthdef' do parsed_synthdef = Synthdef.read(complex_synthdef_binary).snapshot expect(parsed_synthdef).to be_a(Hash) expect(parsed_synthdef[:file_version]).to eq(2) expect(parsed_synthdef[:no_of_synthdefs]).to eq(1) expect(parsed_synthdef[:synthdefs].first[:no_of_constants]).to eq(32) expect(parsed_synthdef[:synthdefs].first[:constants].last).to eq(0.9056051969528198) expect(parsed_synthdef[:synthdefs].first[:no_of_params]).to eq(31) expect(parsed_synthdef[:synthdefs].first[:param_names].last).to eq({param_name: "out_bus", param_index: 30}) expect(parsed_synthdef[:synthdefs].first[:no_of_ugens]).to eq(141) expect(parsed_synthdef[:synthdefs].first[:ugens].last[:ugen_name]).to eq("Out") expect(parsed_synthdef[:synthdefs].first[:no_of_variants]).to eq(0) end it 'converts a basic version 1 synthdef to a version 2 synthdef' do parsed_synthdef = Synthdef.read(synthdef_binary) parsed_synthdef[:file_version] = 2 converted_synthdef = Synthdef.read(parsed_synthdef.to_binary_s).snapshot expect(converted_synthdef).to be_a(Hash) expect(converted_synthdef).not_to be_empty expect(converted_synthdef[:file_version]).to eq(2) expect(converted_synthdef.to_h.except(:file_version)).to eq(parsed_synthdef.snapshot.to_h.except(:file_version)) end it 'checks for a list of required inputs and outputs' do parsed_synthdef = Synthdef.read(complex_synthdef_binary) required_params = [:note, :out_bus] expect(Synthdef.has_params?(parsed_synthdef, required_params)).to be true end it 'can identify param groups like slideable' it 'can rename output buses' it 'produces a dot file for a graph' it 'renders a pdf of the graph' it 'takes configuration from a json file' it 'can parse a synthdef that uses all types including variants and initial rate' end
xavriley/synthdef
lib/synthdef/graphviz.rb
module Graphviz def graphviz self[:synthdefs].each do |sdef| %Q{ digraph synthdef { #{generate_node_info(sdef)} #{generate_node_connections(sdef)} } }.trim end end def generate_node_info(sdef) sdef[:ugens].each do |ug| case ug[:ugen_name] when "Control" style = ":rate" when "IR" style = "\" shape=invhouse style=\"rounded, dashed, filled, bold\" fillcolor=white fontcolor=black ]; " else style = "\" shape=invhouse style=\"rounded, filled, bold\" fillcolor=black fontcolor=white ]; " end end end def generate_node_connections(sdef) end end
nnikolov96/toy_robot
lib/toy_robot/simulator.rb
<reponame>nnikolov96/toy_robot<filename>lib/toy_robot/simulator.rb<gh_stars>0 module ToyRobot class Simulator attr_reader :robot def initialize(table) @table = table end def place(east, north, facing) return unless @table.valid_location?(east, north) @robot = Robot.new(east, north,facing) end end end
nnikolov96/toy_robot
spec/toy_robot_spec.rb
RSpec.describe ToyRobot do end
nnikolov96/toy_robot
lib/toy_robot/table.rb
module ToyRobot class Table def initialize(width, length) @width = width @length = length end def valid_location?(east, north) (0...@width).cover?(east) && (0...@length).cover?(north) end end end
nnikolov96/toy_robot
spec/toy_robot/simulator_spec.rb
<gh_stars>0 require 'spec_helper' RSpec.describe ToyRobot::Simulator do let(:table) { ToyRobot::Table.new(5, 5) } subject { ToyRobot::Simulator.new(table) } it 'places the robot onto a valid position' do expect(ToyRobot::Robot).to receive(:new) .with(0, 0, 'NORTH') .and_return(double) subject.place(0, 0, 'NORTH') expect(subject.robot).to_not be_nil end it 'cannot place the robot onto an invalid position' do expect(ToyRobot::Robot).to_not receive(:new) subject.place(5, 5, 'NORTH') expect(subject.robot).to be_nil end end
Flatiron-group/tenant_verification
app/controllers/reviews_controller.rb
class ReviewsController < ApplicationController def index review = Review.all render json: review end def show id = params[:id] review = Review.find(id) render json: review end def create # param keys may subject to change depending on the body of the post request new_review = Review.new(review_params) if new_review.valid? Review.create(review_params) # message can be altered for better UI experience in the future render json: {review: review, message: "Review successfully created"} else render json: {message: "There was an error."} end end def update id = params[:id] if Review.update(id).valid? Review.update(id) updated_review = Review.find(id) # message can be altered for better UI experience in the future render json: {review: updated_review, message: "Review successfully updated"} else # message can be altered for better UI experience in the future render json: {message: "Update failed"} end end def destroy review = Review.find(params[:id]) review.destroy render json: review end private def review_params params.require(:review).permit(:start_date, :end_date, :landlord_id, :tenant_id, :address, :comment) end end
Flatiron-group/tenant_verification
db/seeds.rb
<reponame>Flatiron-group/tenant_verification<filename>db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) for x in 1..6 Landlord.create(first_name: "Sam#{x}", last_name: "Guo#{x}", email: "<EMAIL>", password: '<PASSWORD>}') Tenant.create(first_name: "Nancy#{x}", last_name: "Lin#{x}") Review.create(start_date: Date.today, end_date: Date.today, landlord_id: "#{x}", tenant_id: "#{x}", address: "123#{x} Fake St", comment: "Testing#{x} right now") end
Flatiron-group/tenant_verification
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController def create user = Landlord.find_by(email: params[:email]) if user && user.authenticate(params[:password]) user_id = user.id token = JWT.encode({user_id: user_id}, ENV['SECRET_TOKEN']) render json: {token: token} else render json: {error: true} end end def get_current_user token = request.headers['Authorization'] user_id = decoded_token(token)[0]["user_id"] Landlord.find(user_id) end def destroy # not sure what to put here since the token would be destroyed # on the front end end private def decoded_token(token) begin JWT.decode(token, ENV['SECRET_TOKEN']) rescue JTWT::DecodeError nil end end end
Flatiron-group/tenant_verification
test/controllers/tenents_controller_test.rb
require 'test_helper' class TenentsControllerTest < ActionDispatch::IntegrationTest test "should get show" do get tenents_show_url assert_response :success end test "should get create" do get tenents_create_url assert_response :success end test "should get update" do get tenents_update_url assert_response :success end test "should get destroy" do get tenents_destroy_url assert_response :success end end
Flatiron-group/tenant_verification
app/controllers/addresses_controller.rb
class AddressesController < ApplicationController def index address = Address.all render json: address end def show id = params[:id] address = Address.find(id) render json: address end def new address = Address.new render json: address end def create # param keys may subject to change depending on the body of the post request address = Address.new(address_params) if address.valid? # message can be altered for better UI experience in the future address = Address.create(address_params) render json: {address: address, message: "Address successfully created"} else render json: {message: "There was an error."} end end def update address = Address.find(params[:id]) if address.valid? render json: {address: address.update(address_params), message: "Address successfully updated"} else render json: {message: "Update failed"} end end def destroy address = Address.find(params[:id]) address.destroy render json: {message: "Deleted successfully"} end private def address_params params.require(:address).permit(:street1, :street2, :city, :state, :postal) end end