* VRFS-3255 (shopping cart only on /client) , VRFS-3253 - frictionless shopping done with tests

This commit is contained in:
Seth Call 2015-05-15 12:34:35 -05:00
parent 1a133c588d
commit 939f8cdf82
61 changed files with 2198 additions and 412 deletions

View File

@ -283,3 +283,4 @@ payment_history.sql
jam_track_right_private_key.sql
first_downloaded_jamtrack_at.sql
signing.sql
optimized_redeemption.sql

View File

@ -0,0 +1,13 @@
CREATE TABLE machine_fingerprints (
id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id VARCHAR(64) NOT NULL REFERENCES users(id) ON DELETE CASCADE,
fingerprint VARCHAR(20000) NOT NULL UNIQUE,
when_taken VARCHAR NOT NULL,
print_type VARCHAR NOT NULL,
remote_ip VARCHAR(1000) NOT NULL,
jam_track_right_id BIGINT REFERENCES jam_track_rights(id) ON DELETE SET NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE jam_track_rights ADD COLUMN redeemed_and_fingerprinted BOOLEAN DEFAULT FALSE;

View File

@ -103,6 +103,7 @@ require "jam_ruby/models/genre"
require "jam_ruby/models/user"
require "jam_ruby/models/anonymous_user"
require "jam_ruby/models/signup_hint"
require "jam_ruby/models/machine_fingerprint"
require "jam_ruby/models/rsvp_request"
require "jam_ruby/models/rsvp_slot"
require "jam_ruby/models/rsvp_request_rsvp_slot"

View File

@ -774,6 +774,7 @@ module JamRuby
self.opening_jam_track = true
self.save
self.opening_jam_track = false
#self.tick_track_changes
end
def close_jam_track

View File

@ -4,10 +4,11 @@
module JamRuby
class AnonymousUser
attr_accessor :id
attr_accessor :id, :cookies
def initialize(id)
def initialize(id, cookies)
@id = id
@cookies = cookies
end
def shopping_carts
@ -23,7 +24,11 @@ module JamRuby
end
def has_redeemable_jamtrack
APP_CONFIG.one_free_jamtrack_per_user
APP_CONFIG.one_free_jamtrack_per_user && !@cookies[:redeemed_jamtrack]
end
def signup_hint
SignupHint.find_by_anonymous_user_id(@id)
end
end
end

View File

@ -3,6 +3,9 @@ module JamRuby
# describes what users have rights to which tracks
class JamTrackRight < ActiveRecord::Base
include JamRuby::S3ManagerMixin
@@log = Logging.logger[JamTrackRight]
attr_accessible :user, :jam_track, :user_id, :jam_track_id, :download_count
attr_accessible :user_id, :jam_track_id, as: :admin
attr_accessible :url_48, :md5_48, :length_48, :url_44, :md5_44, :length_44
@ -211,6 +214,76 @@ module JamRuby
.where('jam_tracks.id IN (?)', jamtracks)
end
def guard_against_fraud(current_user, fingerprint, remote_ip)
if current_user.blank?
return "no user specified"
end
# admin's get to skip fraud check
if current_user.admin
return nil
end
if fingerprint.nil? || fingerprint.empty?
return "no fingerprint specified"
end
all_fingerprint = fingerprint[:all]
running_fingerprint = fingerprint[:running]
if all_fingerprint.blank?
return "no all fingerprint specified"
end
if running_fingerprint.blank?
return "no running fingerprint specified"
end
if redeemed && !redeemed_and_fingerprinted
# if this is a free JamTrack, we need to check for fraud or accidental misuse
# first of all, does this user have any other JamTracks aside from this one that have already been redeemed it and are marked free?
other_redeemed_freebie = JamTrackRight.where(redeemed:true).where(redeemed_and_fingerprinted: true).where('id != ?', id).where(user_id: current_user.id).first
if other_redeemed_freebie
return "already redeemed another"
end
# can we find a jam track that belongs to someone else with the same fingerprint
match = MachineFingerprint.find_by_fingerprint(all_fingerprint)
if match && match.user != current_user
AdminMailer.alerts(subject: "'All' fingerprint collision by #{current_user.name}",
body: "MachineFingerprint #{match.inspect}\n\nCurrent User: #{current_user.admin_url}")
# try to record the other fingerprint
MachineFingerprint.create(running_fingerprint, current_user, MachineFingerprint::TAKEN_ON_FRAUD_CONFLICT, MachineFingerprint::PRINT_TYPE_ACTIVE, remote_ip, self)
return "other user has 'all' fingerprint"
end
match = MachineFingerprint.find_by_fingerprint(running_fingerprint)
if match && match.user != current_user
AdminMailer.alerts(subject: "'Running' fingerprint collision by #{current_user.name}",
body: "MachineFingerprint #{match.inspect}\n\nCurrent User: #{current_user.admin_url}")
# try to record the other fingerprint
MachineFingerprint.create(all_fingerprint, current_user, MachineFingerprint::TAKEN_ON_FRAUD_CONFLICT, MachineFingerprint::PRINT_TYPE_ALL, remote_ip, self)
return "other user has 'running' fingerprint"
end
# we made it past all checks; let's slap on the redeemed_fingerprint
self.redeemed_and_fingerprinted = true
MachineFingerprint.create(all_fingerprint, current_user, MachineFingerprint::TAKEN_ON_SUCCESSFUL_DOWNLOAD, MachineFingerprint::PRINT_TYPE_ALL, remote_ip, self)
MachineFingerprint.create(running_fingerprint, current_user, MachineFingerprint::TAKEN_ON_SUCCESSFUL_DOWNLOAD, MachineFingerprint::PRINT_TYPE_ACTIVE, remote_ip, self)
save!
end
nil
end
def self.stats
stats = {}

View File

@ -0,0 +1,35 @@
module JamRuby
class MachineFingerprint < ActiveRecord::Base
@@log = Logging.logger[MachineFingerprint]
belongs_to :user, :class_name => "JamRuby::User"
belongs_to :jam_track_right, :class_name => "JamRuby::JamTrackRight"
TAKEN_ON_SUCCESSFUL_DOWNLOAD = 'dl'
TAKEN_ON_FRAUD_CONFLICT = 'fc'
PRINT_TYPE_ALL = 'a'
PRINT_TYPE_ACTIVE = 'r'
validates :user, presence:true
validates :when_taken, :inclusion => {:in => [TAKEN_ON_SUCCESSFUL_DOWNLOAD, TAKEN_ON_FRAUD_CONFLICT]}
validates :fingerprint, presence: true, uniqueness:true
validates :print_type, presence: true, :inclusion => {:in =>[PRINT_TYPE_ALL, PRINT_TYPE_ACTIVE]}
validates :remote_ip, presence: true
def self.create(fingerprint, user, when_taken, print_type, remote_ip, jam_track_right = nil)
mf = MachineFingerprint.new
mf.fingerprint = fingerprint
mf.user = user
mf.when_taken = when_taken
mf.print_type = print_type
mf.remote_ip = remote_ip
mf.jam_track_right = jam_track_right
unless mf.save
@@log.error("unable to create machine fingerprint: #{mf.errors.inspect}")
end
end
end
end

View File

@ -128,6 +128,10 @@ module JamRuby
# just a pain to implement
end
def self.is_only_freebie(shopping_carts_jam_tracks)
shopping_carts_jam_tracks.length == 1 && shopping_carts_jam_tracks[0].product_info[:free]
end
# this method will either return a valid sale, or throw a RecurlyClientError or ActiveRecord validation error (save! failed)
# it may return an nil sale if the JamTrack(s) specified by the shopping carts are already owned
def self.order_jam_tracks(current_user, shopping_carts_jam_tracks)
@ -139,58 +143,76 @@ module JamRuby
sale = create_jam_track_sale(current_user)
if sale.valid?
account = client.get_account(current_user)
if account.present?
if is_only_freebie(shopping_carts_jam_tracks)
sale.process_jam_tracks(current_user, shopping_carts_jam_tracks, nil)
purge_pending_adjustments(account)
sale.recurly_subtotal_in_cents = 0
sale.recurly_tax_in_cents = 0
sale.recurly_total_in_cents = 0
sale.recurly_currency = 'USD'
created_adjustments = sale.process_jam_tracks(current_user, shopping_carts_jam_tracks, account)
sale_line_item = sale.sale_line_items[0]
sale_line_item.recurly_tax_in_cents = 0
sale_line_item.recurly_total_in_cents = 0
sale_line_item.recurly_currency = 'USD'
sale_line_item.recurly_discount_in_cents = 0
sale.save
# now invoice the sale ... almost done
else
begin
invoice = account.invoice!
sale.recurly_invoice_id = invoice.uuid
sale.recurly_invoice_number = invoice.invoice_number
account = client.get_account(current_user)
if account.present?
# now slap in all the real tax/purchase totals
sale.recurly_subtotal_in_cents = invoice.subtotal_in_cents
sale.recurly_tax_in_cents = invoice.tax_in_cents
sale.recurly_total_in_cents = invoice.total_in_cents
sale.recurly_currency = invoice.currency
purge_pending_adjustments(account)
created_adjustments = sale.process_jam_tracks(current_user, shopping_carts_jam_tracks, account)
# now invoice the sale ... almost done
begin
invoice = account.invoice!
sale.recurly_invoice_id = invoice.uuid
sale.recurly_invoice_number = invoice.invoice_number
# now slap in all the real tax/purchase totals
sale.recurly_subtotal_in_cents = invoice.subtotal_in_cents
sale.recurly_tax_in_cents = invoice.tax_in_cents
sale.recurly_total_in_cents = invoice.total_in_cents
sale.recurly_currency = invoice.currency
# and resolve against sale_line_items
sale.sale_line_items.each do |sale_line_item|
found_line_item = false
invoice.line_items.each do |line_item|
if line_item.uuid == sale_line_item.recurly_adjustment_uuid
sale_line_item.recurly_tax_in_cents = line_item.tax_in_cents
sale_line_item.recurly_total_in_cents =line_item.total_in_cents
sale_line_item.recurly_currency = line_item.currency
sale_line_item.recurly_discount_in_cents = line_item.discount_in_cents
found_line_item = true
break
end
# and resolve against sale_line_items
sale.sale_line_items.each do |sale_line_item|
found_line_item = false
invoice.line_items.each do |line_item|
if line_item.uuid == sale_line_item.recurly_adjustment_uuid
sale_line_item.recurly_tax_in_cents = line_item.tax_in_cents
sale_line_item.recurly_total_in_cents =line_item.total_in_cents
sale_line_item.recurly_currency = line_item.currency
sale_line_item.recurly_discount_in_cents = line_item.discount_in_cents
found_line_item = true
break
end
if !found_line_item
@@log.error("can't find line item #{sale_line_item.recurly_adjustment_uuid}")
puts "CANT FIND LINE ITEM"
end
end
if !found_line_item
@@log.error("can't find line item #{sale_line_item.recurly_adjustment_uuid}")
puts "CANT FIND LINE ITEM"
unless sale.save
raise RecurlyClientError, "Invalid sale (at end)."
end
rescue Recurly::Resource::Invalid => e
# this exception is thrown by invoice! if the invoice is invalid
sale.rollback_adjustments(current_user, created_adjustments)
sale = nil
raise ActiveRecord::Rollback # kill all db activity, but don't break outside logic
end
unless sale.save
raise RecurlyClientError, "Invalid sale (at end)."
end
rescue Recurly::Resource::Invalid => e
# this exception is thrown by invoice! if the invoice is invalid
sale.rollback_adjustments(current_user, created_adjustments)
sale = nil
raise ActiveRecord::Rollback # kill all db activity, but don't break outside logic
else
raise RecurlyClientError, "Could not find account to place order."
end
else
raise RecurlyClientError, "Could not find account to place order."
end
else
raise RecurlyClientError, "Invalid sale."
@ -238,30 +260,33 @@ module JamRuby
return
end
# ask the shopping cart to create the correct Recurly adjustment attributes for a JamTrack
adjustments = shopping_cart.create_adjustment_attributes(current_user)
if account
# ask the shopping cart to create the correct Recurly adjustment attributes for a JamTrack
adjustments = shopping_cart.create_adjustment_attributes(current_user)
adjustments.each do |adjustment|
adjustments.each do |adjustment|
# create the adjustment at Recurly (this may not look like it, but it is a REST API)
created_adjustment = account.adjustments.new(adjustment)
created_adjustment.save
# create the adjustment at Recurly (this may not look like it, but it is a REST API)
created_adjustment = account.adjustments.new(adjustment)
created_adjustment.save
# if the adjustment could not be made, bail
raise RecurlyClientError.new(created_adjustment.errors) if created_adjustment.errors.any?
# if the adjustment could not be made, bail
raise RecurlyClientError.new(created_adjustment.errors) if created_adjustment.errors.any?
# keep track of adjustments we created for this order, in case we have to roll them back
created_adjustments << created_adjustment
# keep track of adjustments we created for this order, in case we have to roll them back
created_adjustments << created_adjustment
if ShoppingCart.is_product_purchase?(adjustment)
# this was a normal product adjustment, so track it as such
recurly_adjustment_uuid = created_adjustment.uuid
else
# this was a 'credit' adjustment, so track it as such
recurly_adjustment_credit_uuid = created_adjustment.uuid
if ShoppingCart.is_product_purchase?(adjustment)
# this was a normal product adjustment, so track it as such
recurly_adjustment_uuid = created_adjustment.uuid
else
# this was a 'credit' adjustment, so track it as such
recurly_adjustment_credit_uuid = created_adjustment.uuid
end
end
end
# create one sale line item for every jam track
sale_line_item = SaleLineItem.create_from_shopping_cart(self, shopping_cart, nil, recurly_adjustment_uuid, recurly_adjustment_credit_uuid)
@ -279,7 +304,11 @@ module JamRuby
end
# also if the purchase was a free one, then update the user record to no longer allow redeemed jamtracks
User.where(id: current_user.id).update_all(has_redeemable_jamtrack: false) if shopping_cart.free?
if shopping_cart.free?
User.where(id: current_user.id).update_all(has_redeemable_jamtrack: false)
current_user.has_redeemable_jamtrack = false # make sure model reflects the truth
end
# this can't go in the block above, as it's here to fix bad subscription UUIDs in an update path
if jam_track_right.recurly_adjustment_uuid != recurly_adjustment_uuid

View File

@ -152,6 +152,12 @@ module JamRuby
def self.add_jam_track_to_cart(any_user, jam_track)
cart = nil
ShoppingCart.transaction do
if any_user.has_redeemable_jamtrack
# if you still have a freebie available to you, or if you are an anonymous user, we make sure there is nothing else in your shopping cart
any_user.destroy_all_shopping_carts
end
mark_redeem = ShoppingCart.user_has_redeemable_jam_track?(any_user)
cart = ShoppingCart.create(any_user, jam_track, 1, mark_redeem)
end
@ -173,7 +179,13 @@ module JamRuby
carts[0].save
end
end
end
def port(user, anonymous_user)
ShoppingCart.transaction do
move_to_user(user, anonymous_user, anonymous_user.shopping_carts)
end
end
end
end

View File

@ -6,6 +6,7 @@ module JamRuby
# we use it to figure out what to do with the user after they signup
class SignupHint < ActiveRecord::Base
belongs_to :jam_track, class_name: 'JamRuby::JamTrack'
belongs_to :user, class_name: 'JamRuby::User'
@ -23,6 +24,7 @@ module JamRuby
hint.anonymous_user_id = anonymous_user.id
hint.redirect_location = options[:redirect_location] if options.has_key?(:redirect_location)
hint.want_jamblaster = options[:want_jamblaster] if options.has_key?(:want_jamblaster)
#hint.jam_track = JamTrack.find(options[:jam_track]) if options.has_key?(:jam_track)
hint.expires_at = 15.minutes.from_now
hint.save
hint

View File

@ -953,6 +953,7 @@ module JamRuby
recaptcha_failed = options[:recaptcha_failed]
any_user = options[:any_user]
reuse_card = options[:reuse_card]
signup_hint = options[:signup_hint]
user = User.new
@ -1018,8 +1019,6 @@ module JamRuby
end
end
unless fb_signup.nil?
user.update_fb_authorization(fb_signup)
@ -1072,6 +1071,18 @@ module JamRuby
user.save
# if the user has just one, free jamtrack in their shopping cart, and it matches the signup hint, then auto-buy it
# only_freebie_in_cart =
# signup_hint &&
# signup_hint.jam_track &&
# user.shopping_carts.length == 1 &&
# user.shopping_carts[0].cart_product == signup_hint.jam_track &&
# user.shopping_carts[0].product_info[:free]
#
# if only_freebie_in_cart
# Sale.place_order(user, user.shopping_carts)
# end
user.errors.add("recaptcha", "verification failed") if recaptcha_failed
if user.errors.any?
@ -1577,6 +1588,21 @@ module JamRuby
APP_CONFIG.admin_root_url + "/admin/jam_track_rights?q[user_id_equals]=#{id}&commit=Filter&order=created_at DESC"
end
# these are signup attributes that we default to when not presenting the typical form @ /signup
def self.musician_defaults(remote_ip, confirmation_url, any_user, options)
options = options || {}
options[:remote_ip] = remote_ip
options[:birth_date] = nil
options[:instruments] = [{:instrument_id => 'other', :proficiency_level => 1, :priority => 1}]
options[:musician] = true
options[:skip_recaptcha] = true
options[:invited_user] = nil
options[:fb_signup] = nil
options[:signup_confirm_url] = confirmation_url
options[:any_user] = any_user
options
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64

View File

@ -208,5 +208,125 @@ describe JamTrackRight do
end
end
describe "guard_against_fraud" do
let(:user) {FactoryGirl.create(:user)}
let(:other) {FactoryGirl.create(:user)}
let(:first_fingerprint) { {all: 'all', running: 'running' } }
let(:new_fingerprint) { {all: 'all_2', running: 'running' } }
let(:remote_ip) {'1.1.1.1'}
let(:jam_track_right) { FactoryGirl.create(:jam_track_right, user: user, redeemed: true, redeemed_and_fingerprinted: false) }
let(:jam_track_right_purchased) { FactoryGirl.create(:jam_track_right, user: user, redeemed: false, redeemed_and_fingerprinted: false) }
let(:jam_track_right_other) { FactoryGirl.create(:jam_track_right, user: other, redeemed: true, redeemed_and_fingerprinted: false) }
let(:jam_track_right_other_purchased) { FactoryGirl.create(:jam_track_right, user: other, redeemed: false, redeemed_and_fingerprinted: false) }
it "denies no current_user" do
jam_track_right.guard_against_fraud(nil, first_fingerprint, remote_ip).should eq('no user specified')
end
it "denies no fingerprint" do
jam_track_right.guard_against_fraud(user, nil, remote_ip).should eq('no fingerprint specified')
end
it "allows redemption (success)" do
jam_track_right.guard_against_fraud(user, first_fingerprint, remote_ip).should be_nil
jam_track_right.valid?.should be_true
jam_track_right.redeemed_and_fingerprinted.should be_true
mf = MachineFingerprint.find_by_fingerprint(first_fingerprint[:all])
mf.user.should eq(user)
mf.fingerprint.should eq(first_fingerprint[:all])
mf.when_taken.should eq(MachineFingerprint::TAKEN_ON_SUCCESSFUL_DOWNLOAD)
mf.print_type.should eq(MachineFingerprint::PRINT_TYPE_ALL)
mf.jam_track_right.should eq(jam_track_right)
mf = MachineFingerprint.find_by_fingerprint(first_fingerprint[:running])
mf.user.should eq(user)
mf.fingerprint.should eq(first_fingerprint[:running])
mf.when_taken.should eq(MachineFingerprint::TAKEN_ON_SUCCESSFUL_DOWNLOAD)
mf.print_type.should eq(MachineFingerprint::PRINT_TYPE_ACTIVE)
mf.jam_track_right.should eq(jam_track_right)
end
it "ignores already successfully redeemed" do
jam_track_right.redeemed_and_fingerprinted = true
jam_track_right.save!
jam_track_right.guard_against_fraud(user, new_fingerprint, remote_ip).should be_nil
jam_track_right.valid?.should be_true
# and no new fingerprints
MachineFingerprint.count.should eq(0)
end
it "ignores already normally purchased" do
jam_track_right.guard_against_fraud(user, first_fingerprint, remote_ip)
MachineFingerprint.count.should eq(2)
jam_track_right_purchased.guard_against_fraud(user, new_fingerprint, remote_ip).should be_nil
jam_track_right_purchased.valid?.should be_true
jam_track_right_purchased.redeemed_and_fingerprinted.should be_false # fingerprint should not be set on normal purchase
jam_track_right.redeemed_and_fingerprinted.should be_true # should still be redeemed_and fingerprinted; just checking for weird side-effects
# no new fingerprints
MachineFingerprint.count.should eq(2)
end
it "protects against re-using fingerprint across users (conflicts on all fp)" do
jam_track_right.guard_against_fraud(user, first_fingerprint, remote_ip).should be_nil
MachineFingerprint.count.should eq(2)
first_fingerprint[:running] = 'running_2'
jam_track_right_other.guard_against_fraud(other, first_fingerprint, remote_ip).should eq("other user has 'all' fingerprint")
mf = MachineFingerprint.find_by_fingerprint(first_fingerprint[:running])
mf.user.should eq(other)
mf.fingerprint.should eq(first_fingerprint[:running])
mf.when_taken.should eq(MachineFingerprint::TAKEN_ON_FRAUD_CONFLICT)
mf.print_type.should eq(MachineFingerprint::PRINT_TYPE_ACTIVE)
mf.jam_track_right.should eq(jam_track_right_other)
MachineFingerprint.count.should eq(3)
end
it "protects against re-using fingerprint across users (conflicts on running fp)" do
jam_track_right.guard_against_fraud(user, first_fingerprint, remote_ip).should be_nil
MachineFingerprint.count.should eq(2)
first_fingerprint[:all] = 'all_2'
jam_track_right_other.guard_against_fraud(other, first_fingerprint, remote_ip).should eq("other user has 'running' fingerprint")
mf = MachineFingerprint.find_by_fingerprint(first_fingerprint[:all])
mf.user.should eq(other)
mf.fingerprint.should eq(first_fingerprint[:all])
mf.when_taken.should eq(MachineFingerprint::TAKEN_ON_FRAUD_CONFLICT)
mf.print_type.should eq(MachineFingerprint::PRINT_TYPE_ALL)
mf.jam_track_right.should eq(jam_track_right_other)
MachineFingerprint.count.should eq(3)
end
# if you try to buy a regular jamtrack with a fingerprint belonging to another user? so what. you paid for it
it "allows re-use of fingerprint if jamtrack is a normal purchase" do
jam_track_right.guard_against_fraud(user, first_fingerprint, remote_ip).should be_nil
MachineFingerprint.count.should eq(2)
jam_track_right_other_purchased.guard_against_fraud(other, first_fingerprint, remote_ip).should be_nil
MachineFingerprint.count.should eq(2)
end
it "stops you from redeeming two jamtracks" do
right1 = FactoryGirl.create(:jam_track_right, user: user, redeemed: true, redeemed_and_fingerprinted: true)
jam_track_right.guard_against_fraud(user, first_fingerprint, remote_ip).should eq('already redeemed another')
MachineFingerprint.count.should eq(0)
end
it "let's you download a free jamtrack if you have a second but undownloaded free one" do
right1 = FactoryGirl.create(:jam_track_right, user: user, redeemed: true, redeemed_and_fingerprinted: false)
jam_track_right.guard_against_fraud(user, first_fingerprint, remote_ip).should be_nil
MachineFingerprint.count.should eq(2)
right1.guard_against_fraud(user, first_fingerprint, remote_ip).should eq('already redeemed another')
MachineFingerprint.count.should eq(2)
end
end
end

View File

@ -87,9 +87,9 @@ describe Sale do
sales.should eq(user.sales)
sale = sales[0]
sale.recurly_invoice_id.should_not be_nil
sale.recurly_invoice_id.should be_nil
sale.recurly_subtotal_in_cents.should eq(jam_track_price_in_cents)
sale.recurly_subtotal_in_cents.should eq(0)
sale.recurly_tax_in_cents.should eq(0)
sale.recurly_total_in_cents.should eq(0)
sale.recurly_currency.should eq('USD')
@ -97,7 +97,7 @@ describe Sale do
sale.sale_line_items.length.should == 1
sale_line_item = sale.sale_line_items[0]
sale_line_item.recurly_tax_in_cents.should eq(0)
sale_line_item.recurly_total_in_cents.should eq(jam_track_price_in_cents)
sale_line_item.recurly_total_in_cents.should eq(0)
sale_line_item.recurly_currency.should eq('USD')
sale_line_item.recurly_discount_in_cents.should eq(0)
sale_line_item.product_type.should eq(JamTrack::PRODUCT_TYPE)
@ -109,8 +109,8 @@ describe Sale do
sale_line_item.recurly_plan_code.should eq(jamtrack.plan_code)
sale_line_item.product_id.should eq(jamtrack.id)
sale_line_item.recurly_subscription_uuid.should be_nil
sale_line_item.recurly_adjustment_uuid.should_not be_nil
sale_line_item.recurly_adjustment_credit_uuid.should_not be_nil
sale_line_item.recurly_adjustment_uuid.should be_nil
sale_line_item.recurly_adjustment_credit_uuid.should be_nil
sale_line_item.recurly_adjustment_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_uuid)
sale_line_item.recurly_adjustment_credit_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_credit_uuid)
@ -118,31 +118,11 @@ describe Sale do
recurly_account = client.get_account(user)
adjustments = recurly_account.adjustments
adjustments.should_not be_nil
adjustments.should have(2).items
free_purchase= adjustments[0]
free_purchase.unit_amount_in_cents.should eq((jamtrack.price * 100).to_i)
free_purchase.accounting_code.should eq(ShoppingCart::PURCHASE_FREE)
free_purchase.description.should eq("JamTrack: " + jamtrack.name)
free_purchase.state.should eq('invoiced')
free_purchase.uuid.should eq(sale_line_item.recurly_adjustment_uuid)
free_credit = adjustments[1]
free_credit.unit_amount_in_cents.should eq(-(jamtrack.price * 100).to_i)
free_credit.accounting_code.should eq(ShoppingCart::PURCHASE_FREE_CREDIT)
free_credit.description.should eq("JamTrack: " + jamtrack.name + " (Credit)")
free_credit.state.should eq('invoiced')
free_credit.uuid.should eq(sale_line_item.recurly_adjustment_credit_uuid)
adjustments.should have(0).items
invoices = recurly_account.invoices
invoices.should have(1).items
invoice = invoices[0]
invoice.uuid.should eq(sale.recurly_invoice_id)
invoice.line_items.should have(2).items # should have both adjustments associated
invoice.line_items[0].should eq(free_credit)
invoice.line_items[1].should eq(free_purchase)
invoice.subtotal_in_cents.should eq((jamtrack.price * 100).to_i)
invoice.total_in_cents.should eq(0)
invoice.state.should eq('collected')
invoices.should have(0).items
# verify jam_track_rights data
user.jam_track_rights.should_not be_nil
@ -238,7 +218,7 @@ describe Sale do
# also, verify that no earlier adjustments were affected
recurly_account = client.get_account(user)
adjustments = recurly_account.adjustments
adjustments.should have(2).items
adjustments.should have(0).items # because the only successful purchase was a freebie, there should be no recurly adjustments
end
# this test counts on the fact that two adjustments are made when buying a free JamTrack
@ -246,13 +226,13 @@ describe Sale do
# we can see if the first one is ultimately destroyed
it "rolls back created adjustments if error" do
shopping_cart = ShoppingCart.create user, jamtrack, 1, true
shopping_cart = ShoppingCart.create user, jamtrack, 1, false
# grab the real response; we will modify it to make a nil accounting code
adjustment_attrs = shopping_cart.create_adjustment_attributes(user)
client.find_or_create_account(user, billing_info)
adjustment_attrs[1][:unit_amount_in_cents] = nil # invalid amount
adjustment_attrs[0][:unit_amount_in_cents] = nil # invalid amount
ShoppingCart.any_instance.stub(:create_adjustment_attributes).and_return(adjustment_attrs)
expect { Sale.place_order(user, [shopping_cart]) }.to raise_error(JamRuby::RecurlyClientError)
@ -265,7 +245,7 @@ describe Sale do
end
it "rolls back adjustments created before the order" do
shopping_cart = ShoppingCart.create user, jamtrack, 1, true
shopping_cart = ShoppingCart.create user, jamtrack, 1, false
client.find_or_create_account(user, billing_info)
# create a single adjustment on the account
@ -281,7 +261,7 @@ describe Sale do
recurly_account = client.get_account(user)
adjustments = recurly_account.adjustments
adjustments.should have(2).items # two adjustments are created for a free jamtrack; that should be all there is
adjustments.should have(1).items # two adjustments are created for a free jamtrack; that should be all there is
end
end

View File

@ -21,34 +21,36 @@ describe ShoppingCart do
user.shopping_carts[0].quantity.should == 1
end
it "maintains only one fre JamTrack in ShoppingCart" do
cart1 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
cart1.should_not be_nil
cart1.errors.any?.should be_false
user.reload
cart2 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
cart2.errors.any?.should be_false
user.reload
user.shopping_carts.length.should eq(1)
cart3 = ShoppingCart.add_jam_track_to_cart(user, jam_track2)
cart3.errors.any?.should be_false
user.reload
user.shopping_carts.length.should eq(1)
end
it "should not add duplicate JamTrack to ShoppingCart" do
user.has_redeemable_jamtrack = false
user.save!
cart1 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
cart1.should_not be_nil
cart1.errors.any?.should be_false
user.reload
cart2 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
cart2.errors.any?.should be_true
end
describe "redeemable behavior" do
it "adds redeemable item to shopping cart" do
user.has_redeemable_jamtrack.should be_true
# first item added to shopping cart should be marked for redemption
cart = ShoppingCart.add_jam_track_to_cart(user, jam_track)
cart.marked_for_redeem.should eq(1)
# but the second item should not
user.reload
cart = ShoppingCart.add_jam_track_to_cart(user, jam_track2)
cart.marked_for_redeem.should eq(0)
end
it "removes redeemable item to shopping cart" do
it "removes redeemable item to shopping cart (maintains only one in cart)" do
user.has_redeemable_jamtrack.should be_true
cart1 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
@ -58,12 +60,12 @@ describe ShoppingCart do
cart2.should_not be_nil
cart1.marked_for_redeem.should eq(1)
cart2.marked_for_redeem.should eq(0)
cart2.marked_for_redeem.should eq(1)
ShoppingCart.remove_jam_track_from_cart(user, jam_track)
user.shopping_carts.length.should eq(1)
user.shopping_carts.length.should eq(0)
cart2.reload
cart1.marked_for_redeem.should eq(1)
cart2.marked_for_redeem.should eq(1)
end
end
end

View File

@ -2,7 +2,7 @@ require 'spec_helper'
describe SignupHint do
let(:user) {AnonymousUser.new(SecureRandom.uuid)}
let(:user) {AnonymousUser.new(SecureRandom.uuid, nil)}
describe "refresh_by_anoymous_user" do
it "creates" do

View File

@ -48,6 +48,9 @@
//= require utils
//= require subscription_utils
//= require custom_controls
//= require web/signup_helper
//= require web/signin_helper
//= require web/signin
//= require_directory .
//= require_directory ./dialog
//= require_directory ./wizard

View File

@ -560,20 +560,6 @@
$screen.find("#payment-info-next").on('click', next);
}
function beforeShowOrder() {
step = 3;
renderNavigation();
populateOrderPage();
}
function populateOrderPage() {
rest.getShoppingCarts()
.done(renderOrderPage)
.fail(app.ajaxError);
}
function toggleShippingAsBilling(e) {
e.preventDefault();

View File

@ -19,6 +19,7 @@
var $contentHolder = null;
var $btnNext = null;
var $btnFacebook = null;
var checkoutUtils = context.JK.CheckoutUtilsInstance;
function beforeShow(data) {
renderNavigation();
@ -96,9 +97,23 @@
$signinBtn.text('TRYING...').addClass('disabled')
rest.login({email: email, password: password, remember_me: true})
.done(function() {
window.location = '/client#/checkoutPayment'
window.location.reload();
.done(function(user) {
// now determine where we should send the user
rest.getShoppingCarts()
.done(function(carts) {
if(checkoutUtils.hasOneFreeItemInShoppingCart(carts)) {
window.location = '/client#/redeemComplete'
window.location.reload();
}
else {
window.location = '/client#/checkoutPayment'
window.location.reload();
}
})
.fail(function() {
window.location = '/client#/jamtrackBrowse'
window.location.reload();
})
})
.fail(function(jqXHR) {
if(jqXHR.status == 422) {

View File

@ -43,6 +43,16 @@ class CheckoutUtils
getLastPurchase: () =>
return @lastPurchaseResponse
hasOneFreeItemInShoppingCart: (carts) =>
if carts.length == 0
# nothing is in the user's shopping cart. They shouldn't be here.
return false;
else if carts.length > 1
# the user has multiple items in their shopping cart. They shouldn't be here.
return false;
return carts[0].product_info.free
# global instance
context.JK.CheckoutUtilsInstance = new CheckoutUtils()

View File

@ -89,6 +89,7 @@
rest.openJamTrack({id: context.JK.CurrentSessionModel.id(), jam_track_id: jamTrack.id})
.done(function(response) {
$dialog.data('result', {success:true, jamTrack: jamTrack})
context.JK.CurrentSessionModel.updateSession(response);s
app.layout.closeDialog('open-jam-track-dialog');
})
.fail(function(jqXHR) {

View File

@ -11,11 +11,21 @@
var dialogId = '#signin-dialog';
var $dialog = null;
var signinHelper = null;
var redirectTo = null;
function beforeShow() {
function beforeShow(args) {
logger.debug("showing login form")
signinHelper.reset();
if(args.redirect_to) {
redirectTo = "/client#/redeemComplete"
}
else {
redirectTo = null;
}
if(redirectTo) {
logger.debug("setting redirect to in login dialog")
}
signinHelper.reset(redirectTo);
}
function afterShow() {
@ -24,6 +34,7 @@
function afterHide() {
logger.debug("hiding login form")
redirectTo = null;
}
function initialize(){

View File

@ -206,6 +206,8 @@ context.JK.DownloadJamTrack = class DownloadJamTrack
showInitial: () =>
@logger.debug("showing #{@state.name}")
@sampleRate = context.jamClient.GetSampleRate()
@fingerprint = context.jamClient.SessionGetMacHash()
logger.debug("fingerprint: ", @fingerprint)
@sampleRateForFilename = if @sampleRate == 48 then '48' else '44'
@attempts = @attempts + 1
this.expectTransition()
@ -450,7 +452,7 @@ context.JK.DownloadJamTrack = class DownloadJamTrack
@attemptedEnqueue = true
@ajaxEnqueueAborted = false
@rest.enqueueJamTrack({id: @jamTrack.id, sample_rate: @sampleRate})
@rest.enqueueJamTrack({id: @jamTrack.id, sample_rate: @sampleRate, fingerprint: @fingerprint})
.done(this.processEnqueueJamTrack)
.fail(this.processEnqueueJamTrackFail)
@ -474,9 +476,24 @@ context.JK.DownloadJamTrack = class DownloadJamTrack
else
@logger.debug("DownloadJamTrack: ignoring processEnqueueJamTrack response")
processEnqueueJamTrackFail: () =>
displayUIForGuard:(response) =>
display = switch response.message
when 'no user specified' then 'Please log back in.'
when 'no fingerprint specified' then 'There was a problem communicating between client and server. Please restart JamKazam.'
when 'no all fingerprint specified' then 'There was a problem communicating between client and server. Please restart JamKazam.'
when 'no running fingerprint specified' then 'There was a problem communicating between client and server. Please restart JamKazam.'
when 'already redeemed another' then "It appears you have already redeemed your one free JamTrack for your household. We are sorry, but we cannot let you download this JamTrack free. If you believe this is an error, please contact us at support@jamkazam.com."
when "other user has 'all' fingerprint" then "It appears you have already redeemed your one free JamTrack for your household. We are sorry, but we cannot let you download this JamTrack free. If you believe this is an error, please contact us at support@jamkazam.com."
when "other user has 'running' fingerprint" then "It appears you have already redeemed your one free JamTrack for your household. We are sorry, but we cannot let you download this JamTrack free. If you believe this is an error, please contact us at support@jamkazam.com."
else "Something went wrong #{response.message}. Please restart JamKazam"
processEnqueueJamTrackFail: (jqXHR) =>
unless @ajaxEnqueueAborted
this.transitionError("enqueue-error", "Unable to ask the server to build your JamTrack.")
if jqXHR.status == 403
display = this.displayUIForGuard(JSON.parse(jqXHR.responseText))
this.transitionError("enqueue-error", display)
else
this.transitionError("enqueue-error", "Unable to ask the server to build your JamTrack.")
else
@logger.debug("DownloadJamTrack: ignoring processEnqueueJamTrackFail response")

View File

@ -210,6 +210,7 @@
if (!userProfile.show_jamtrack_guide && userProfile.show_whats_next && userProfile.show_whats_next_count < 10 &&
window.location.pathname.indexOf(gon.client_path) == 0 &&
window.location.hash.indexOf('/checkout') == -1 &&
window.location.hash.indexOf('/redeem') == -1 &&
!app.layout.isDialogShowing('getting-started'))
{
app.layout.showDialog('getting-started');

View File

@ -1662,6 +1662,26 @@
});
}
function signup(data) {
return $.ajax({
type: "POST",
url: '/api/users',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),
});
}
function portOverCarts() {
return $.ajax({
type: "POST",
url: '/api/shopping_carts/port',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data)
})
}
function createAlert(subject, data) {
var message = {subject:subject};
$.extend(message, data);
@ -1825,6 +1845,8 @@
this.playJamTrack = playJamTrack;
this.createSignupHint = createSignupHint;
this.createAlert = createAlert;
this.signup = signup;
this.portOverCarts = portOverCarts;
return this;
};

View File

@ -61,7 +61,7 @@ context.JK.JamTrackPreview = class JamTrackPreview
if @options.master_shows_duration
duration = 'entire song'
if @jamTrack.duration
duration = "0:00 - #{context.JK.prettyPrintSeconds(@jamTrack.duration)}"
duration = "#{context.JK.prettyPrintSeconds(@jamTrack.duration)}"
part = duration
else
part = @jamTrack.name + ' by ' + @jamTrack.original_artist

View File

@ -192,9 +192,23 @@ context.JK.JamTrackScreen=class JamTrackScreen
addToCartJamtrack:(e) =>
e.preventDefault()
params = id: $(e.target).attr('data-jamtrack-id')
$target = $(e.target)
params = id: $target.attr('data-jamtrack-id')
isFree = $(e.target).is('.is_free')
rest.addJamtrackToShoppingCart(params).done((response) =>
context.location = '/client#/shoppingCart'
if(isFree)
if context.JK.currentUserId?
alert("TODO")
context.JK.currentUserFreeJamTrack = true # make sure the user sees no more free notices
context.location = '/client#/redeemComplete'
else
# now make a rest call to buy it
context.location = '/client#/redeemSignup'
else
context.location = '/client#/shoppingCart'
).fail @app.ajaxError
licenseUSWhy:(e) =>
@ -211,15 +225,15 @@ context.JK.JamTrackScreen=class JamTrackScreen
if expand
trackElement.find('.extra').removeClass('hidden')
detailArrow.html('hide tracks <a class="details-arrow arrow-up-orange"></a>')
detailArrow.html('hide tracks <a class="details-arrow arrow-up"></a>')
for track in jamTrack.tracks
trackElement.find("[jamtrack-track-id='#{track.id}']").removeClass('hidden')
else
trackElement.find('.extra').addClass('hidden')
detailArrow.html('preview all tracks <a class="details-arrow arrow-down-orange"></a>')
detailArrow.html('show all tracks <a class="details-arrow arrow-down"></a>')
count = 0
for track in jamTrack.tracks
if count < 2
if count < 6
trackElement.find("[jamtrack-track-id='#{track.id}']").removeClass('hidden')
else
trackElement.find("[jamtrack-track-id='#{track.id}']").addClass('hidden')
@ -281,14 +295,15 @@ context.JK.JamTrackScreen=class JamTrackScreen
if track.part != ''
track.instrument_desc += ' (' + track.part + ')'
free_state = if gon.global.one_free_jamtrack_per_user then 'free' else 'non-free'
if @user
free_state = if @user.free_jamtrack then 'free' else 'non-free'
free_state = if context.JK.currentUserFreeJamTrack then 'free' else 'non-free'
is_free = free_state == 'free'
options =
jamtrack: trackRow
expanded: false
free_state: free_state
free_state: free_state,
is_free: is_free
@jamtrackItem = $(context._.template($('#template-jamtrack').html(), options, variable: 'data'))
that.renderJamtrack(@jamtrackItem, jamtrack)
that.registerEvents(@jamtrackItem)

View File

@ -0,0 +1,264 @@
(function (context, $) {
"use strict";
context.JK = context.JK || {};
context.JK.RedeemCompleteScreen = function (app) {
var EVENTS = context.JK.EVENTS;
var logger = context.JK.logger;
var rest = context.JK.Rest();
var jamTrackUtils = context.JK.JamTrackUtils;
var checkoutUtils = context.JK.CheckoutUtilsInstance;
var $screen = null;
var $navigation = null;
var $templatePurchasedJamTrack = null;
var $thanksPanel = null;
var $jamTrackInBrowser = null;
var $jamTrackInClient = null;
var $purchasedJamTrack = null;
var $purchasedJamTrackHeader = null;
var $purchasedJamTracks = null;
var userDetail = null;
var step = null;
var downloadJamTracks = [];
var purchasedJamTracks = null;
var purchasedJamTrackIterator = 0;
var $backBtn = null;
var $downloadApplicationLink = null;
var $noPurchasesPrompt = null;
var shoppingCartItem = null;
function beforeShow() {
}
function afterShow(data) {
$noPurchasesPrompt.addClass('hidden')
$purchasedJamTracks.empty()
$thanksPanel.addClass("hidden")
$purchasedJamTrackHeader.attr('status', 'in-progress')
$jamTrackInBrowser.addClass('hidden')
$jamTrackInClient.addClass('hidden')
// if there is no current user, but it apperas we have a login cookie, just refresh
if(!context.JK.currentUserId && $.cookie('remember_token')) {
window.location.reload();
}
else {
redeemJamTrack()
}
//prepThanks()
}
function handleShoppingCartResponse(carts) {
if(!checkoutUtils.hasOneFreeItemInShoppingCart(carts)) {
// the user has multiple items in their shopping cart. They shouldn't be here.
logger.error("invalid access of redeemComplete page")
window.location = '/client#/jamtrackBrowse'
}
else {
// ok, we have one, free item. save it for
shoppingCartItem = carts[0];
rest.placeOrder()
.done(function(purchaseResponse) {
context.JK.currentUserFreeJamTrack = false // make sure the user sees no more free notices without having to do a full page refresh
checkoutUtils.setLastPurchase(purchaseResponse)
jamTrackUtils.checkShoppingCart()
//app.refreshUser() // this only causes grief in tests for some reason, and with currentUserFreeJamTrack = false above, this is probably now unnecessary
prepThanks();
})
.fail(function() {
})
}
}
function redeemJamTrack() {
rest.getShoppingCarts()
.done(handleShoppingCartResponse)
.fail(app.ajaxError);
}
function beforeHide() {
if(downloadJamTracks) {
context._.each(downloadJamTracks, function(downloadJamTrack) {
downloadJamTrack.destroy();
downloadJamTrack.root.remove();
})
downloadJamTracks = [];
}
purchasedJamTracks = null;
purchasedJamTrackIterator = 0;
}
function prepThanks() {
showThanks();
}
function showThanks(purchaseResponse) {
var purchaseResponse = checkoutUtils.getLastPurchase();
if(!purchaseResponse || purchaseResponse.length == 0) {
// user got to this page with no context
logger.debug("no purchases found; nothing to show")
$noPurchasesPrompt.removeClass('hidden')
}
else {
if(gon.isNativeClient) {
$jamTrackInClient.removeClass('hidden')
}
else {
$jamTrackInBrowser.removeClass('hidden');
}
$thanksPanel.removeClass('hidden')
handleJamTracksPurchased(purchaseResponse.jam_tracks)
}
}
function handleJamTracksPurchased(jamTracks) {
// were any JamTracks purchased?
var jamTracksPurchased = jamTracks && jamTracks.length > 0;
if(jamTracksPurchased) {
if(gon.isNativeClient) {
$jamTrackInClient.removeClass('hidden')
context.JK.GA.virtualPageView('/redeemInClient');
startDownloadJamTracks(jamTracks)
}
else {
$jamTrackInBrowser.removeClass('hidden');
app.user().done(function(user) {
// cut off time
var cutoff = new Date("May 8, 2015 00:00:00");
if(new Date(user.created_at).getTime() < cutoff.getTime()) {
logger.debug("existing user recorded")
context.JK.GA.virtualPageView('/redeemInBrowserExistingUser');
}
else {
logger.debug("new user recorded")
context.JK.GA.virtualPageView('/redeemInBrowserNewUser');
}
})
app.user().done(function(user) {
if(!user.first_downloaded_client_at) {
$downloadApplicationLink.removeClass('hidden')
}
})
}
}
}
function startDownloadJamTracks(jamTracks) {
// there can be multiple purchased JamTracks, so we cycle through them
purchasedJamTracks = jamTracks;
// populate list of jamtracks purchased, that we will iterate through graphically
context._.each(jamTracks, function(jamTrack) {
var downloadJamTrack = new context.JK.DownloadJamTrack(app, jamTrack, 'small');
var $purchasedJamTrack = $(context._.template(
$templatePurchasedJamTrack.html(),
jamTrack,
{variable: 'data'}
));
$purchasedJamTracks.append($purchasedJamTrack)
// show it on the page
$purchasedJamTrack.append(downloadJamTrack.root)
downloadJamTracks.push(downloadJamTrack)
})
iteratePurchasedJamTracks();
}
function iteratePurchasedJamTracks() {
if(purchasedJamTrackIterator < purchasedJamTracks.length ) {
var downloadJamTrack = downloadJamTracks[purchasedJamTrackIterator++];
// make sure the 'purchasing JamTrack' section can be seen
$purchasedJamTrack.removeClass('hidden');
// the widget indicates when it gets to any transition; we can hide it once it reaches completion
$(downloadJamTrack).on(EVENTS.JAMTRACK_DOWNLOADER_STATE_CHANGED, function(e, data) {
if(data.state == downloadJamTrack.states.synchronized) {
logger.debug("jamtrack " + downloadJamTrack.jamTrack.name + " synchronized;")
//downloadJamTrack.root.remove();
downloadJamTrack.destroy();
// go to the next JamTrack
iteratePurchasedJamTracks()
}
})
logger.debug("jamtrack " + downloadJamTrack.jamTrack.name + " downloader initializing")
// kick off the download JamTrack process
downloadJamTrack.init()
// XXX style-test code
// downloadJamTrack.transitionError("package-error", "The server failed to create your package.")
}
else {
logger.debug("done iterating over purchased JamTracks")
$purchasedJamTrackHeader.attr('status', 'done')
}
}
function events() {
$backBtn.on('click', function(e) {
e.preventDefault();
context.location = '/client#/jamtrackBrowse'
})
}
function initialize() {
var screenBindings = {
'beforeShow': beforeShow,
'afterShow': afterShow,
'beforeHide': beforeHide
};
app.bindScreen('redeemComplete', screenBindings);
$screen = $("#redeemCompleteScreen");
$templatePurchasedJamTrack = $('#template-purchased-jam-track');
$thanksPanel = $screen.find(".thanks-panel");
$jamTrackInBrowser = $screen.find(".jam-tracks-in-browser");
$jamTrackInClient = $screen.find(".jam-tracks-in-client");
$purchasedJamTrack = $thanksPanel.find(".thanks-detail.purchased-jam-track");
$purchasedJamTrackHeader = $purchasedJamTrack.find(".purchased-jam-track-header");
$purchasedJamTracks = $purchasedJamTrack.find(".purchased-list")
$backBtn = $screen.find('.back');
$downloadApplicationLink = $screen.find('.download-jamkazam-wrapper');
$noPurchasesPrompt = $screen.find('.no-purchases-prompt')
if ($screen.length == 0) throw "$screen must be specified";
events();
}
this.initialize = initialize;
return this;
}
})
(window, jQuery);

View File

@ -0,0 +1,244 @@
(function(context,$) {
"use strict";
context.JK = context.JK || {};
context.JK.RedeemSignUpScreen = function(app) {
var logger = context.JK.logger;
var rest = context.JK.Rest();
var $screen = null;
var $signupForm = null;
var $self = $(this);
var $email = null;
var $password = null;
var $firstName = null;
var $lastName = null;
var $signupBtn = null;
var $inputElements = null;
var $contentHolder = null;
var $btnNext = null;
var $btnFacebook = null;
var $termsOfServiceL = null;
var $termsOfServiceR = null;
var shoppingCartItem = null;
var $jamtrackName = null;
var $signinLink = null;
function beforeShow(data) {
renderLoggedInState();
}
function afterShow(data) {
}
function renderLoggedInState(){
if(isLoggedIn()) {
$contentHolder.removeClass('not-signed-in').addClass('signed-in')
}
else {
$jamtrackName.text('')
$contentHolder.addClass('hidden')
$contentHolder.removeClass('signed-in').addClass('not-signed-in')
// now check that the user has one, and only one, free jamtrack in their shopping cart.
rest.getShoppingCarts()
.done(handleShoppingCartResponse)
.fail(app.ajaxError);
}
}
function isLoggedIn() {
return !!context.JK.currentUserId;
}
function events() {
$btnFacebook.on('click', onClickSignupFacebook)
$signupForm.on('submit', signup)
$signupBtn.on('click', signup)
$signinLink.on('click', onSignin);
}
function handleShoppingCartResponse(carts) {
if(carts.length == 0) {
// nothing is in the user's shopping cart. They shouldn't be here.
logger.error("invalid access of redeemJamTrack page")
window.location = '/client#/jamtrackBrowse'
}
else if(carts.length > 1) {
// the user has multiple items in their shopping cart. They shouldn't be here.
logger.error("invalid access of redeemJamTrack page")
window.location = '/client#/jamtrackBrowse'
}
else {
var item = carts[0];
if(item.product_info.free) {
// ok, we have one, free item. save it for
shoppingCartItem = item;
$jamtrackName.text('"' + shoppingCartItem.product_info.name + '"')
$contentHolder.removeClass('hidden')
}
else {
// the user has a non-free, single item in their basket. They shouldn't be here.
logger.error("invalid access of redeemJamTrack page")
window.location = '/client#/jamtrackBrowse'
}
}
var $latestCartHtml = "";
var any_in_us = false
context._.each(carts, function(cart) {
if(cart.product_info.sales_region == 'United States') {
any_in_us = true
}
})
}
function onClickSignupFacebook() {
// tos must already be clicked
var $btn = $(e.target)
$btn.addClass('disabled')
var $field = $termsOfServiceL.closest('.field')
$field.find('.error-text').remove()
logger.debug("field, ", $field, $termsOfServiceL)
if($termsOfServiceL.is(":checked")) {
rest.createSignupHint({redirect_location: '/client#/redeemComplete'})
.done(function() {
// send the user on to facebook signin
window.location = $btn.attr('href');
})
.fail(function() {
app.notify({text:"Facebook Signup is not working properly"});
})
.always(function() {
$btn.removeClass('disabled')
})
}
else {
$field.addClass("error").addClass("transparent");
$field.append("<ul class='error-text'><li>must be accepted</li></ul>");
}
return false;
}
function onSuccessfulSignin() {
// the user has signed in;
// move all shopping carts from the anonymous user to the signed in user
/*rest.portOverCarts()
.done(function() {
logger.debug("ported over carts")
window.location = '/client#/redeemComplete'
})
.fail(function() {
window.location.reload();
})
*/
window.location = '/client#/redeemComplete'
}
function onSignin() {
app.layout.showDialog('signin-dialog', {redirect_to:onSuccessfulSignin});
return false;
}
function signup() {
if($signupBtn.is('.disabled')) {
return false;
}
// clear out previous errors
$signupForm.find('.field.error').removeClass('error')
$signupForm.find('ul.error-text').remove()
var email = $email.val();
var password = $password.val();
var first_name = $firstName.val();
var last_name = $lastName.val();
var terms = $termsOfServiceR.is(':checked')
$signupBtn.text('TRYING...').addClass('disabled')
rest.signup({email: email, password: password, first_name: first_name, last_name: last_name, terms:terms})
.done(function(response) {
window.location = '/client#/redeemComplete'
window.location.reload()
})
.fail(function(jqXHR) {
if(jqXHR.status == 422) {
var response = JSON.parse(jqXHR.responseText)
if(response.errors) {
var $errors = context.JK.format_errors('first_name', response);
if ($errors) $firstName.closest('.field').addClass('error').append($errors);
$errors = context.JK.format_errors('last_name', response);
if ($errors) $lastName.closest('.field').addClass('error').append($errors);
$errors = context.JK.format_errors('password', response);
if ($errors) $password.closest('.field').addClass('error').append($errors);
var $errors = context.JK.format_errors('email', response);
if ($errors) $email.closest('.field').addClass('error').append($errors);
var $errors = context.JK.format_errors('terms_of_service', response);
if ($errors) $termsOfServiceR.closest('.field').addClass('error').append($errors);
}
else {
app.notify({title: 'Unknown Signup Error', text: jqXHR.responseText})
}
}
else {
app.notifyServerError(jqXHR, "Unable to Sign Up")
}
})
.always(function() {
$signupBtn.text('SIGNUP').removeClass('disabled')
})
return false;
}
function initialize() {
var screenBindings = {
'beforeShow': beforeShow,
'afterShow': afterShow
};
app.bindScreen('redeemSignup', screenBindings);
$screen = $("#redeemSignupScreen");
$signupForm = $screen.find(".signup-form");
$signupBtn = $signupForm.find('.signup-submit');
$email = $signupForm.find('input[name="email"]');
$password = $signupForm.find('input[name="password"]');
$firstName = $signupForm.find('input[name="first_name"]');
$lastName = $signupForm.find('input[name="last_name"]');
$inputElements = $signupForm.find('.input-elements');
$contentHolder = $screen.find('.content-holder');
$btnFacebook = $screen.find('.signup-facebook')
$termsOfServiceL = $screen.find('.left-side .terms_of_service input[type="checkbox"]')
$termsOfServiceR = $screen.find('.right-side .terms_of_service input[type="checkbox"]')
$jamtrackName = $screen.find('.jamtrack-name');
$signinLink = $screen.find('.signin')
if($screen.length == 0) throw "$screen must be specified";
events();
}
this.initialize = initialize;
return this;
}
})(window,jQuery);

View File

@ -501,6 +501,7 @@
rest.openJamTrack({id: context.JK.CurrentSessionModel.id(), jam_track_id: jamTrack.id})
.done(function(response) {
// now actually load the jamtrack
context.JK.CurrentSessionModel.updateSession(response);
loadJamTrack(jamTrack);
})
.fail(function(jqXHR) {

View File

@ -156,6 +156,7 @@
}
// did I open up the current JamTrack?
function selfOpenedJamTracks() {
logger.debug("currentSession", currentSession)
return currentSession && (currentSession.jam_track_initiator_id == context.JK.currentUserId)
}

View File

@ -30,23 +30,35 @@
function proceedCheckout(e) {
e.preventDefault();
logger.debug("proceedCheckout")
if (!context.JK.currentUserId) {
logger.debug("proceeding to signin screen because there is no user")
window.location = '/client#/checkoutSignin';
}
else {
var user = app.currentUser();
if(user.has_recurly_account && user.reuse_card) {
logger.debug("proceeding to checkout order screen because we have card info already")
window.location = '/client#/checkoutOrder';
if (context.JK.currentUserFreeJamTrack) {
if(context.JK.currentUserId) {
logger.debug("proceeding to redeem complete screen because user has a free jamtrack and is logged in")
window.location = '/client#/redeemComplete'
}
else {
logger.debug("proceeding to checkout payment screen because we do not have card info")
window.location = '/client#/checkoutPayment';
logger.debug("proceeding to redeem signup screen because user has a free jamtrack and is not logged in")
window.location = '/client#/redeemSignup'
}
}
else {
if (!context.JK.currentUserId) {
logger.debug("proceeding to signin screen because there is no user")
window.location = '/client#/checkoutSignin';
}
else {
var user = app.currentUser();
if(user.has_recurly_account && user.reuse_card) {
logger.debug("proceeding to checkout order screen because we have card info already")
window.location = '/client#/checkoutOrder';
}
else {
logger.debug("proceeding to checkout payment screen because we do not have card info")
window.location = '/client#/checkoutPayment';
}
}
}
}
function removeCart(e) {

View File

@ -20,21 +20,26 @@
var $rememberMe = null;
var useAjax = false;
var EVENTS = context.JK.EVENTS;
function reset() {
var argRedirectTo = null;
function reset(_redirectTo) {
argRedirectTo = _redirectTo;
clear();
}
function clear() {
$signinForm.removeClass('login-error')
$email.val('');
$password.val('');
$rememberMe.attr('checked', 'checked')
}
function login() {
var email = $email.val();
var password = $password.val();
var rememberMe = $rememberMe.is(':checked')
reset();
clear();
$signinBtn.text('TRYING...');
@ -42,6 +47,15 @@
.done(function() {
//app.layout.closeDialog('signin-dialog')
if(argRedirectTo) {
if(argRedirectTo instanceof Function) {
argRedirectTo();
}
else {
window.location.href = argRedirectTo;
}
return;
}
var redirectTo = $.QueryString['redirect-to'];
if(redirectTo) {
logger.debug("redirectTo:" + redirectTo);
@ -68,7 +82,7 @@
function events() {
$signinCancelBtn.click(function(e) {
app.layout.closeDialog('signin-dialog');
app.layout.closeDialog('signin-dialog', true);
e.stopPropagation();
return false;
});

View File

@ -59,6 +59,8 @@
*= require ./checkout_payment
*= require ./checkout_order
*= require ./checkout_complete
*= require ./redeem_signup
*= require ./redeem_complete
*= require ./genreSelector
*= require ./sessionList
*= require ./searchResults
@ -75,4 +77,5 @@
*= require users/syncViewer
*= require ./downloadJamTrack
*= require ./jamTrackPreview
*= require users/signinCommon
*/

View File

@ -314,30 +314,6 @@ a.gold {
color: #cc9900 !important;
}
a.arrow-up {
float:right;
margin-right:5px;
display:block;
margin-top:6px;
width: 0;
height: 0;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom: 7px solid #333;
}
a.arrow-down {
float:right;
margin-right:5px;
display:block;
margin-top:6px;
width: 0;
height: 0;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-top: 7px solid #333;
}
.settings-session-description {
padding:10px;
width:200px;
@ -537,6 +513,32 @@ ul.shortcuts {
padding:2px 8px !important;
}
a.arrow-up {
float:right;
margin-right:5px;
display:block;
margin-top:6px;
width: 0;
height: 0;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom: 7px solid #333;
}
a.arrow-down {
float:right;
margin-right:5px;
display:block;
margin-top:6px;
width: 0;
height: 0;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-top: 7px solid #333;
}
a.arrow-up-orange {
margin-left:5px;
margin-bottom:2px;

View File

@ -31,6 +31,9 @@
}
}
table.jamtrack-table {
table-layout:fixed;
}
.jamtrack-content {
text-align: center;
border: 1px solid #222222;
@ -47,22 +50,41 @@
text-align: left;
}
th.jamtrack-detail {
padding:6px;
}
th.jamtrack-tracks {
padding:6px;
}
th.jamtrack-action {
padding:6px;
text-align:center;
}
td.jamtrack-action {
padding:0;
position:relative;
}
.jamtrack-detail {
@include border_box_sizing;
width: 35%;
width: 25%;
padding: 10px 0 0 10px;
.detail-label {
width: 40%;
width: 80px;
float: left;
margin-top: 5px;
font-weight: 400;
font-size: 11px;
clear:both;
}
.detail-value {
width: 50%;
float: left;
margin-top: 5px;
margin-bottom:15px;
font-size:11px;
}
@ -84,12 +106,37 @@
margin-right: 5px;
padding-top: 5px;
vertical-align: bottom;
color:#fc0;
.arrow-down {
float:none;
margin-left:5px;
margin-top:0;
margin-right:0;
border-top: 4px solid #fc0;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
display:inline-block;
}
.arrow-up {
float:none;
margin-right:0;
margin-left:5px;
margin-bottom:2px;
border-bottom: 4px solid #fc0;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
display:inline-block;
}
}
.jamtrack-tracks {
padding-bottom:30px;
position:relative;
@include border_box_sizing;
width: 45%;
padding: 10px 0px;
width:55%;
//padding: 10px 0px;
.tracks-caption {
margin-top: 5px;
margin-bottom: 10px;
@ -117,12 +164,31 @@
.detail-arrow {
position:absolute;
float: right;
margin-right: 10px;
bottom:14px;
left:12px;
}
.jamtrack-name {
font-size:16px;
white-space: normal;
}
.jamtrack-original-artist {
font-size:16px;
margin-top:10px;
margin-bottom:5px;
white-space: normal;
}
.jamtrack-track {
margin:0 0 8px 7px;
float:left;
padding:0 0 8px 7px;
width: 250px;
@include border_box_sizing;
&.hidden {
display:none;
@ -131,14 +197,23 @@
.jam-track-preview {
font-size:11px;
white-space:nowrap;
}
.jamtrack-action {
@include border_box_sizing;
width: 20%;
// padding: 0px 0px;
text-align: center;
// vertical-align: top;
.jamtrack-action-container {
display: flex;
align-items: center;
justify-content: center;
position:absolute;
height:100%;
width:100%;
}
.play-button {
margin-top: 5px;
}
@ -149,6 +224,7 @@
&.free {
margin-top:0;
display:none;
.free-state {
font-size: 11px;
margin-top: 5px;

View File

@ -0,0 +1,123 @@
@import "client/common.css.scss";
#redeemCompleteScreen {
p {
font-size:14px;
margin:0;
}
.order-prompt {
color:white;
line-height:125%;
}
h2 {
color:white;
background-color:#4d4d4d;
font-weight:normal;
margin: 0 0 10px 0;
font-size:14px;
padding: 3px 0 3px 10px;
height: 14px;
line-height: 14px;
vertical-align: middle;
text-align:left;
}
.action-bar {
margin-top:20px;
}
#checkout-info-help {
margin-right:1px;
}
.checkout-complete-wrapper {
padding:50px;
}
.why-download {
margin-top:20px;
}
.no-purchases-prompt {
}
.jam-tracks-in-browser {
}
.thanks-panel {
span.notice {
font-style:italic;
font-size:12px;
}
br.purchase-downloads {
clear:both;
margin-bottom:20px;
}
.download-jamkazam {
color:$ColorLink;
border-radius: 4px;
border-style:solid;
border-color:#AAA;
border-width:1px;
padding:10px;
margin-top:20px;
display:inline-block;
}
.download-jamkazam-wrapper {
text-align:center;
display:block;
margin-top:35px;
&.hidden {
display:none;
}
}
.thanks-detail.purchased-jam-track {
margin-top:20px;
.purchased-jam-track-header {
font-size: 15px;
margin-bottom:10px;
span {
display:none;
}
&[status="in-progress"] {
span.in-progress-msg {
display:inline;
}
}
&[status="done"] {
span.done-msg {
display:inline;
}
}
}
ul.purchased-list {
float:left;
margin:20px 100px 0 20px;
li {
margin:0;
}
}
.download-jamtrack {
width:auto;
vertical-align: middle; // to make bullets mid-align when error shows
}
}
}
}

View File

@ -0,0 +1,247 @@
@import "client/common.css.scss";
#redeemSignupScreen {
.redeem-signup {
padding:30px;
}
.g-recaptcha {
//transform:scale(0.80);
//transform-origin:0 0;
}
.jamtrack-name {
font-weight:bold;
}
.content-holder {
//margin-top:40px;
color:$ColorTextTypical;
&.signed-in {
.left-side, .right-side {
display:none;
}
.not-signed-in.prompt {
display:none;
}
}
&.not-signed-in {
.already-signed-in {
display:none;
}
}
}
.not-signed-in.prompt {
text-align:center;
}
.already-signed-in {
text-align:center;
h3 {
text-align:center;
}
}
a.forgot-password {
position:absolute;
top:0;
left:0;
font-size:10px;
}
.error-text {
margin:0;
li {
margin-bottom:5px;
}
}
.signup-submit {
margin-right:2px;
}
.signup-facebook {
text-align:center;
}
.signup-later-prompt {
margin:30px 0 30px 0;
text-align:center;
}
.signup-prompt {
float:right;
text-align:left;
margin:30px 0 15px 0;
width:60%;
max-width:300px;
@include border_box_sizing;
span {
text-align:left;
}
}
p {
font-size:14px;
line-height:125%;
}
.login-error {
div.actions {
margin-top:10px;
}
.field {
background-color: #330000;
border: 1px solid #990000;
padding:8px;
}
}
.field {
display:block;
@include border_box_sizing;
padding:6px 8px;
margin:0px -8px;
white-space: nowrap;
&.error {
background-color:#300;
border: solid 1px #900;
li {
list-style:none;
}
}
}
.login-error-msg {
display:none;
margin-top:10px;
text-align:center;
color:#F00;
font-size:11px;
width:60%;
max-width:300px;
@include border_box_sizing;
float:right;
margin-bottom:10px;
}
.login-error .login-error-msg {
display:block;
}
h3
{
color:$ColorTextHighlight;
text-align:left;
font-size:16px;
font-weight:700;
margin-bottom:15px;
}
input {
@include border_box_sizing;
}
.btnNext {
margin:0 auto;
}
.left-side, .right-side {
margin-top:50px;
}
.left-side {
float:left;
width:50%;
@include border_box_sizing;
border-width:0 1px 0 0;
border-color:white;
border-style:solid;
text-align:right;
padding: 0 60px;
margin-bottom:20px;
.actions {
width:60%;
max-width:300px;
@include border_box_sizing;
position:relative;
float:right;
}
.terms_of_service {
text-align:center;
label {
display:inline;
}
font-size:11px;
}
}
a.signin {
text-decoration: underline;
font-size:12px;
margin-left:15px;
}
.left-side-content {
@include border_box_sizing;
float:right;
text-align:center;
}
.right-side {
float:left;
width:50%;
@include border_box_sizing;
padding: 0 60px;
.actions {
margin-top:11px;
margin-left:-8px;
white-space: nowrap;
input {
width:auto;
}
}
input {
width:80%;
max-width:300px;
}
label {
display:inline-block;
width:80px;
text-align:left;
}
.terms_of_service {
input {
width: auto;
margin-left: -2px;
}
label {
display:inline;
}
font-size:11px;
}
}
.facebook-prompt {
margin:40px 0 10px 0;
float:right;
text-align:left;
width:249px;
@include border_box_sizing;
}
}

View File

@ -8,6 +8,10 @@
height:auto;
}
strong {
font-weight:bold;
}
label {
margin-bottom:2px;
}

View File

@ -73,13 +73,23 @@ class ApiJamTracksController < ApiController
def download
if @jam_track_right.valid?
all_fingerprint = params[:all_fp]
running_fingerprint = params[:running_fp]
error = @jam_track_right.guard_against_fraud(current_user, {all:all_fingerprint, running: running_fingerprint}, request.remote_ip)
if error
log.warn("potential fraud detected: #{error}")
render :json => { :message => error }, :status => 403
return
end
sample_rate = params[:sample_rate].nil? ? nil : params[:sample_rate].to_i
if @jam_track_right && @jam_track_right.ready?(sample_rate)
@jam_track_right.update_download_count
@jam_track_right.last_downloaded_at = Time.now
if @jam_track_right.first_downloaded_at.nil?
@jam_track_right.first_downloaded_at = Time.now
end
now = Time.now
@jam_track_right.last_downloaded_at = now
@jam_track_right.first_downloaded_at = now if @jam_track_right.first_downloaded_at.nil?
@jam_track_right.save!
redirect_to @jam_track_right.sign_url(120, sample_rate)
else
@ -92,6 +102,16 @@ class ApiJamTracksController < ApiController
end
def enqueue
fingerprint = params[:fingerprint]
error = @jam_track_right.guard_against_fraud(current_user, fingerprint, request.remote_ip)
if error
log.warn("potential fraud detected: #{error}")
render :json => { :message => error }, :status => 403
return
end
sample_rate = params[:sample_rate].nil? ? nil : params[:sample_rate].to_i
enqueued = @jam_track_right.enqueue_if_needed(sample_rate)
log.debug("jamtrack #{enqueued ? "ENQUEUED" : "NOT ENQUEUED"}: jam_track_right=#{@jam_track_right.id} sample_rate=#{sample_rate} ")

View File

@ -25,26 +25,20 @@ class ApiRecurlyController < ApiController
# keep reuse card up-to-date
User.where(id: current_user.id).update_all(reuse_card: params[:reuse_card_next_time])
else
options = {
remote_ip: request.remote_ip,
first_name: billing_info[:first_name],
last_name: billing_info[:last_name],
email: params[:email],
password: params[:password],
password_confirmation: params[:password],
terms_of_service: terms_of_service,
instruments: [{:instrument_id => 'other', :proficiency_level => 1, :priority => 1}],
birth_date: nil,
location: {:country => billing_info[:country], :state => billing_info[:state], :city => billing_info[:city]},
musician: true,
skip_recaptcha: true,
invited_user: nil,
fb_signup: nil,
signup_confirm_url: ApplicationHelper.base_uri(request) + "/confirm",
any_user: any_user,
reuse_card: reuse_card_next_time
}
options = User.musician_defaults(request.remote_ip, ApplicationHelper.base_uri(request) + "/confirm", any_user, options)
user = UserManager.new.signup(options)
if user.errors.any?
@ -142,6 +136,7 @@ class ApiRecurlyController < ApiController
if error
render json: {errors: {message: error}}, :status => 404
else
set_purchased_jamtrack_cookie
render :json => response, :status => 200
end
rescue RecurlyClientError => x

View File

@ -51,6 +51,15 @@ class ApiShoppingCartsController < ApiController
respond_with responder: ApiResponder, :status => 204
end
# take all shopping carts from anonymous user and copy them to logged in user
def port
if current_user && anonymous_user
ShoppingCart.port(current_user, anonymous_user)
else
render :json => {message: 'one or both users not available'}, :status => 403
end
end
def clear_all
any_user.destroy_all_shopping_carts
render :json=>{}, :status=>200

View File

@ -32,6 +32,43 @@ class ApiUsersController < ApiController
respond_with @user, responder: ApiResponder, :status => 200
end
# in other words, a minimal signup
def create
# today, this only accepts a minimal registration; it could be made to take in more if we wanted
signup_hint = nil
if anonymous_user
signup_hint = anonymous_user.signup_hint
if signup_hint && signup_hint.jam_track.nil?
signup_hint = nil # it doesn't make sense to pass in signup hints that are not free jam-track centric (at least, not today)
end
end
# recaptcha_response: params['g-recaptcha-response']
options = {
first_name: params[:first_name],
last_name: params[:last_name],
email: params[:email],
password: params[:password],
password_confirmation: params[:password],
terms_of_service: params[:terms],
location: {:country => nil, :state => nil, :city => nil},
signup_hint: signup_hint
}
options = User.musician_defaults(request.remote_ip, ApplicationHelper.base_uri(request) + "/confirm", any_user, options)
@user = UserManager.new.signup(options)
if @user.errors.any?
respond_with_model(@user)
else
sign_in @user
new_user(@user, signup_hint) # sets a cookie used for GA analytics (one-time new user stuff in JavaScript)
respond_with_model(@user, new: true, location: lambda { return api_user_detail_url(@user.id) })
end
end
def update
@user = User.find(params[:id])

View File

@ -35,6 +35,7 @@ class ApplicationController < ActionController::Base
cookies.permanent[:user_uuid] = SecureRandom.uuid unless cookies[:user_uuid]
end
private
def add_user_info_to_bugsnag(notif)
# Add some app-specific data which will be displayed on a custom

View File

@ -16,6 +16,7 @@ class ClientsController < ApplicationController
return
end
@in_client_page = true
@minimal_curtain = Rails.application.config.minimal_curtain
gon.recurly_tax_estimate_jam_track_plan = Rails.application.config.recurly_tax_estimate_jam_track_plan
render :layout => 'client'

View File

@ -121,8 +121,37 @@ class SessionsController < ApplicationController
end
fb_signup.save!
redirect_to "#{signup_path}?facebook_signup=#{fb_signup.lookup_id}"
return
# see if we can find a SignupHint for a JamTrack; if so, bounce them back to the redeemComplete page to let them know we bought it
if anonymous_user
signup_hint = anonymous_user.signup_hint
if signup_hint && signup_hint.redirect_location
options = {
first_name: first_name,
last_name: last_name,
email: email,
terms_of_service: true,
location: {:country => nil, :state => nil, :city => nil},
}
options = User.musician_defaults(request.remote_ip, ApplicationHelper.base_uri(request) + "/confirm", any_user, options)
user = UserManager.new.signup(options)
if user.errors.any?
redirect_to signup_hint.redirect_location
return
end
sign_in(user)
new_user(user, signup_hint)
redirect_to signup_hint.redirect_location
return
end
else
redirect_to "#{signup_path}?facebook_signup=#{fb_signup.lookup_id}"
return
end
end
if current_user.nil?

View File

@ -180,23 +180,6 @@ class UsersController < ApplicationController
end
end
# given the current user, and any signup hint (can be nil)
# handle the final destination of the user
def handle_signup_hint(user, signup_hint, default_redirect)
redirect_url = default_redirect
if signup_hint
if signup_hint.want_jamblaster
User.where(id: user.id).update_all(want_jamblaster: true)
end
if signup_hint.redirect_location
redirect_url = signup_hint.redirect_location
end
end
redirect_url
end
def congratulations_fan
@no_user_dropdown = true
render :layout => "web"

View File

@ -2,6 +2,7 @@ module SessionsHelper
def sign_in(user)
set_remember_token(user)
set_purchased_jamtrack_cookie unless user.has_redeemable_jamtrack
self.current_user = user
end
@ -21,6 +22,12 @@ module SessionsHelper
end
end
# should be set whenever a user logs in who has redeemed a free jamtrack, or whenever the user
def set_purchased_jamtrack_cookie
cookies.permanent[:redeemed_jamtrack] = true
end
def complete_sign_in(user, redirect=true)
sign_in user
@ -64,7 +71,7 @@ module SessionsHelper
def anonymous_user
if anon_cookie
@anonymous_user ||= AnonymousUser.new(anon_cookie)
@anonymous_user ||= AnonymousUser.new(anon_cookie, cookies)
else
nil
end
@ -91,6 +98,25 @@ module SessionsHelper
cookies[:new_user] = { musician: user.musician, registrationType: user.user_authorization('facebook') ? 'Facebook' : 'Native', want_jamblaster: want_jamblaster, redirect_location: redirect_location }.to_json
end
# given the current user, and any signup hint (can be nil)
# handle the final destination of the user
def handle_signup_hint(user, signup_hint, default_redirect)
redirect_url = default_redirect
if signup_hint
if signup_hint.want_jamblaster
User.where(id: user.id).update_all(want_jamblaster: true)
end
if signup_hint.redirect_location
redirect_url = signup_hint.redirect_location
end
end
redirect_url
end
def current_user?(user)
user == current_user
end

View File

@ -10,7 +10,7 @@ end
# give back more info if the user being fetched is yourself
if @user == current_user
attributes :email, :original_fpfile, :cropped_fpfile, :crop_selection, :session_settings, :show_whats_next, :show_whats_next_count, :subscribe_email, :auth_twitter, :new_notifications, :sales_count, :reuse_card, :purchased_jamtracks_count, :first_downloaded_client_at
attributes :email, :original_fpfile, :cropped_fpfile, :crop_selection, :session_settings, :show_whats_next, :show_whats_next_count, :subscribe_email, :auth_twitter, :new_notifications, :sales_count, :reuse_card, :purchased_jamtracks_count, :first_downloaded_client_at, :created_at
node :geoiplocation do |user|
geoiplocation = current_user.geoiplocation

View File

@ -1,83 +0,0 @@
#jamtrackScreen.screen.secondary.no-login-required layout='screen' layout-id='jamtrackBrowse'
.content
.content-head
.content-icon=image_tag("content/icon_jamtracks.png", height:19, width:19 )
h1 jamtracks
=render "screen_navigation"
.content-body
=form_tag('', {:id => 'jamtrack-find-form', :class => 'inner-content'}) do
=render(:partial => "web_filter", :locals => {:search_type => Search::PARAM_JAMTRACK})
.filter-body
.content-body-scroller
.profile-wrapper
h2 shop for jamtracks
table.generaltable
thead
tr
th JAMTRACK
th TRACKS INCLUDED / PREVIEW
th.center SHOP
tbody.jamtrack-content
a.btn-next-pager href="/api/jamtracks?page=1" Next
.end-of-jamtrack-list.end-of-list="No more Jamtracks"
script#template-jamtrack type='text/template'
tr.jamtrack-record jamtrack-id="{{data.jamtrack.id}}"
td.jamtrack-detail
.detail-label
| Title:
.detail-value
| {{data.jamtrack.name}}
.clearall.detail-label
| Original Artist:
.detail-value
| {{data.jamtrack.original_artist}}
.clearall.detail-label
| Genre:
.detail-value
| {{data.jamtrack.genres[0]}}
.clearall.detail-label.extra.hidden
| Writer(s):
.detail-value.extra.hidden
| {{data.jamtrack.songwriter}}
.clearall.detail-label.extra.hidden
| Publisher:
.detail-value.extra.hidden
| {{data.jamtrack.publisher}}
td.jamtrack-tracks
.detail-arrow
.jamtrack-detail-btn.orange
="{% if (data.expanded) { %}"
| hide tracks
a.details-arrow.arrow-up-orange
="{% } else { %}"
| preview all tracks
a.details-arrow.arrow-down-orange
="{% } %}"
="{% _.each(data.jamtrack.tracks, function(track) { %}"
.jamtrack-track.hidden jamtrack-track-id="{{track.id}}"
/ .instrument-desc
/ | {{track.instrument_desc}}
/.track-instrument
.jamtrack-preview
.clearall
="{% }); %}"
td.jamtrack-action
/ a.play-button href="#" data-jamtrack-id="{{data.jamtrack.id}}"
/ =image_tag "shared/play_button.png"
.jamtrack-price class="{{data.free_state}}"
| {{"$ " + data.jamtrack.price}}
.free-state.hidden
| (first one is FREE)
="{% if (data.jamtrack.purchased) { %}"
a.jamtrack-add-cart-disabled.button-grey.button-disabled href="javascript:void(0)" PURCHASED
="{% } else if (data.jamtrack.added_cart) { %}"
a.jamtrack-add-cart-disabled.button-grey.button-disabled href="client#/shoppingCart" ALREADY IN CART
="{% } else { %}"
a.jamtrack-add-cart.button-orange href="#" data-jamtrack-id="{{data.jamtrack.id}}" ADD TO CART
="{% }; %}"
="{% if (data.jamtrack.sales_region==JK.AVAILABILITY_US) { %}"
.jamtrack-license
| This JamTrack available only to US customers. &nbsp;&nbsp;&nbsp;&nbsp;
a.license-us-why.orange href="#" why?
="{% }; %}"

View File

@ -0,0 +1,86 @@
#jamtrackScreen.screen.secondary.no-login-required layout='screen' layout-id='jamtrackBrowse'
.content
.content-head
.content-icon=image_tag("content/icon_jamtracks.png", height:19, width:19 )
h1 jamtracks
=render "screen_navigation"
.content-body
=form_tag('', {:id => 'jamtrack-find-form', :class => 'inner-content'}) do
=render(:partial => "web_filter", :locals => {:search_type => Search::PARAM_JAMTRACK})
.filter-body
.content-body-scroller
.profile-wrapper
h2 shop for jamtracks
table.generaltable.jamtrack-table
thead
tr
th.jamtrack-detail JAMTRACK
th.jamtrack-tracks TRACKS INCLUDED / PREVIEW
th.jamtrack-action SHOP
tbody.jamtrack-content
a.btn-next-pager href="/api/jamtracks?page=1" Next
.end-of-jamtrack-list.end-of-list="No more Jamtracks"
script#template-jamtrack type='text/template'
tr.jamtrack-record jamtrack-id="{{data.jamtrack.id}}"
td.jamtrack-detail
.jamtrack-name
| "{{data.jamtrack.name}}"
.jamtrack-original-artist
| by {{data.jamtrack.original_artist}}
br clear="all"
.clearall.detail-label.extra.hidden.song-writer
| Songwriters:
.detail-value.extra.hidden
| {{data.jamtrack.songwriter}}
.clearall.detail-label.extra.hidden
| Publishers:
.detail-value.extra.hidden
| {{data.jamtrack.publisher}}
.clearall.detail-label.extra.hidden
| Genre:
.detail-value.extra.hidden
| {{data.jamtrack.genres[0]}}
.clearall.detail-label.extra.hidden
| Version:
.detail-value.extra.hidden
| {{data.jamtrack.recording_type}}
td.jamtrack-tracks
.detail-arrow
.jamtrack-detail-btn
="{% if (data.expanded) { %}"
| hide tracks
a.details-arrow.arrow-up
="{% } else { %}"
| show all tracks
a.details-arrow.arrow-down
="{% } %}"
="{% _.each(data.jamtrack.tracks, function(track) { %}"
.jamtrack-track.hidden jamtrack-track-id="{{track.id}}"
/ .instrument-desc
/ | {{track.instrument_desc}}
/.track-instrument
.jamtrack-preview
.clearall
="{% }); %}"
td.jamtrack-action
.jamtrack-action-container
.jamtrack-actions
/ a.play-button href="#" data-jamtrack-id="{{data.jamtrack.id}}"
/ =image_tag "shared/play_button.png"
.jamtrack-price class="{{data.free_state}}"
| {{"$ " + data.jamtrack.price}}
="{% if (data.is_free) { %}"
a.jamtrack-add-cart.button-orange.is_free href="#" data-jamtrack-id="{{data.jamtrack.id}}" GET IT FREE!
="{% } else if (data.jamtrack.purchased) { %}"
a.jamtrack-add-cart-disabled.button-grey.button-disabled href="javascript:void(0)" PURCHASED
="{% } else if (data.jamtrack.added_cart) { %}"
a.jamtrack-add-cart-disabled.button-grey.button-disabled href="client#/shoppingCart" ALREADY IN CART
="{% } else { %}"
a.jamtrack-add-cart.button-orange href="#" data-jamtrack-id="{{data.jamtrack.id}}" ADD TO CART
="{% }; %}"
="{% if (data.jamtrack.sales_region==JK.AVAILABILITY_US) { %}"
.jamtrack-license
| This JamTrack available only to US customers. &nbsp;&nbsp;&nbsp;&nbsp;
a.license-us-why.orange href="#" why?
="{% }; %}"

View File

@ -0,0 +1,47 @@
div layout="screen" layout-id="redeemComplete" id="redeemCompleteScreen" class="screen secondary"
.content
.content-head
.content-icon= image_tag("content/icon_shopping_cart.png", {:height => 19, :width => 19})
h1 check out
= render "screen_navigation"
.content-body
.content-body-scroller
.content-wrapper
.checkout-navigation-bar
.checkout-complete-wrapper
.no-purchases-prompt.hidden
| You have not made any purchases recently. Why not go go&nbsp;
a href="/client#/jamtrackBrowse" browse our collection of JamTracks
| ?
.thanks-panel
.jam-tracks-in-browser.hidden
p Thank you for joining our community, and congratulations on getting your first JamTrack!
p.why-download
| JamTracks are full multi-track recordings with lots of special features, so they are not&nbsp;
| just standard audio files. To play with your JamTrack, you'll need to download and install&nbsp;
| our free Mac or Windows app. This is the last step in the process, and you'll be ready to play.&nbsp;
| This free app also lets you play online in real time with other musicians over the Internet at no cost!
a.download-jamkazam-wrapper href="/downloads" rel="external"
.download-jamkazam
| Click Here to Get the Free JamKazam Application
.jam-tracks-in-client.hidden
h2 Congratulations on getting your JamTrack!
.thanks-detail.purchased-jam-track
h2.purchased-jam-track-header status="in-progress"
span.in-progress-msg Downloading Your JamTrack
span.done-msg All purchased JamTracks have been downloaded successfully! You can now play them in a session.
span Each JamTrack will be downloaded sequentially.
br
span.notice Note that you do not have to wait for this to complete in order to use your JamTrack later.
br.clear
ul.purchased-list
.clearall.hidden
.action-bar
.right
a.button-orange.checkout-done href="/client#/home" DONE
.clearall

View File

@ -0,0 +1,67 @@
div layout="screen" layout-id="redeemSignup" id="redeemSignupScreen" class="screen secondary no-login-required"
.content
.content-head
.content-icon= image_tag("content/icon_shopping_cart.png", {:height => 19, :width => 19})
h1 check out
= render "screen_navigation"
.content-body
.content-body-scroller
.redeem-signup
.content-holder
.already-signed-in
h3 YOU ARE ALREADY LOGGED IN
p.carry-on-prompt
| You can go back to browsing.
.actions
a.btnNext.button-orange href="/client#/jamtrackBrowse" BROWSE JAMTRACKS
.not-signed-in.prompt
| To get your free&nbsp;
span.jamtrack-name
| &nbsp;JamTrack, join thousands of musicians in the JamKazam community by registering for your free account.
.left-side
.left-side-content
= link_to image_tag("content/button_facebook_signup.png", {:width => 249, :height => 46}), '/auth/facebook', class: "signup-facebook"
br clear="all"
.field.terms_of_service
input type="checkbox"
label
| I have read and agree to the JamKazam
br
= link_to "terms of service", corp_terms_path, rel: "external"
|.
br clear="all"
.right-side
h3 OR SIGN UP USING YOUR EMAIL
.signup-form
form.signup-form
.input-elements
.field
label.inline First Name:
input name='first_name' autofocus="true" type="text"
.field
label.inline Last Name:
input name='last_name' type="text"
.field
label.inline Email:
input name='email' type="text"
.field
label.inline Password:
input name='password' autofocus="true" type="password"
.field.terms_of_service
input type="checkbox"
label
| I have read and agree to the JamKazam &nbsp;
= link_to "terms of service", corp_terms_path, rel: "external"
|.
.field.recaptcha style="display:none"
- if Rails.application.config.recaptcha_enable
#recaptcha_select name="recaptcha_response_field" class="g-recaptcha" data-sitekey=Rails.application.config.recaptcha_public_key
.actions
input.button-orange.signup-submit type="submit" value="SIGNUP"
= link_to "Already have a JamKazam account? Sign in", "#", class: 'signin'
br clear='all'

View File

@ -37,13 +37,15 @@
<%= render "band_setup_photo" %>
<%= render "users/feed_music_session_ajax" %>
<%= render "users/feed_recording_ajax" %>
<%= render "jamtrack" %>
<%= render "jamtrack_browse" %>
<%= render "jamtrack_landing" %>
<%= render "shopping_cart" %>
<%= render "checkout_signin" %>
<%= render "checkout_payment" %>
<%= render "checkout_order" %>
<%= render "checkout_complete" %>
<%= render "redeem_signup" %>
<%= render "redeem_complete" %>
<%= render "order" %>
<%= render "feed" %>
<%= render "bands" %>
@ -111,12 +113,14 @@
JK.currentUserName = '<%= current_user.name %>';
JK.currentUserMusician = '<%= current_user.musician %>';
JK.currentUserAdmin = <%= current_user.admin %>;
JK.currentUserFreeJamTrack = <%= APP_CONFIG.one_free_jamtrack_per_user && current_user.has_redeemable_jamtrack %>
<% else %>
JK.currentUserId = null;
JK.currentUserAvatarUrl = null;
JK.currentUserName = null;
JK.currentUserMusician = null;
JK.currentUserAdmin = false;
JK.currentUserFreeJamTrack = <%= APP_CONFIG.one_free_jamtrack_per_user && anonymous_user.nil? ? false : anonymous_user.has_redeemable_jamtrack%>
<% end %>
@ -276,6 +280,12 @@
var checkoutCompleteScreen = new JK.CheckoutCompleteScreen(JK.app);
checkoutCompleteScreen.initialize();
var redeemSignUpScreen = new JK.RedeemSignUpScreen(JK.app);
redeemSignUpScreen.initialize();
var redeemCompleteScreen = new JK.RedeemCompleteScreen(JK.app);
redeemCompleteScreen.initialize();
var findMusicianScreen = new JK.FindMusicianScreen(JK.app);
findMusicianScreen.initialize(JK.TextMessageDialogInstance);
@ -309,6 +319,10 @@
var singlePlayerProfileGuardDialog = new JK.SinglePlayerProfileGuardDialog(JK.app);
singlePlayerProfileGuardDialog.initialize();
var signinDialog = new JK.SigninDialog(JK.app);
signinDialog.initialize();
JK.SigninPage(); // initialize signin helper
// do a client update early check upon initialization
JK.ClientUpdateInstance.check()

View File

@ -39,6 +39,6 @@
<%= yield %>
<%= render "shared/ga" %>
<%= render "shared/recurly" %>
<%= render "shared/google_nocaptcha" %>
</body>
</html>

View File

@ -1,7 +1,7 @@
<div id="profile" class="userinfo">
<!-- shopping cart -->
<% if Rails.application.config.jam_tracks_available %>
<% if Rails.application.config.jam_tracks_available && @in_client_page %>
<a id="header-shopping-cart" href="/client#/shoppingCart" class="header-shopping-cart hidden">
<img src="/assets/content/shopping-cart.png"/>
</a>

View File

@ -117,13 +117,13 @@
</div>
</div>
<div class="field terms_of_service">
<small>
<%= f.check_box :terms_of_service %>
<span>I have read and agree to the JamKazam <%= link_to "terms of service", corp_terms_path, :rel => "external" %>
.</span>
</small>
</div>
<div class="field terms_of_service">
<small>
<%= f.check_box :terms_of_service %>
<span>I have read and agree to the JamKazam <%= link_to "terms of service", corp_terms_path, :rel => "external" %>
.</span>
</small>
</div>
<div class="field recaptcha">
<% if Rails.application.config.recaptcha_enable %>

View File

@ -262,6 +262,7 @@ SampleApp::Application.routes.draw do
match '/data_validation' => 'api_users#validate_data', :via => :get
match '/users' => 'api_users#index', :via => :get
match '/users' => 'api_users#create', :via => :post
match '/users/:id' => 'api_users#show', :via => :get, :as => 'api_user_detail'
#match '/users' => 'api_users#create', :via => :post
match '/users/:id' => 'api_users#update', :via => :post

View File

@ -27,6 +27,8 @@ class UserManager < BaseManager
signup_confirm_url = options[:signup_confirm_url]
affiliate_referral_id = options[:affiliate_referral_id]
any_user = options[:any_user]
signup_hint = options[:signup_hint]
recaptcha_failed = false
unless options[:skip_recaptcha] # allow callers to opt-of recaptcha
recaptcha_failed = fb_signup ? false : !@google_client.verify_recaptcha(options[:recaptcha_response])
@ -67,7 +69,8 @@ class UserManager < BaseManager
fb_signup: fb_signup,
signup_confirm_url: signup_confirm_url,
affiliate_referral_id: affiliate_referral_id,
any_user: any_user)
any_user: any_user,
signup_hint: signup_hint)
user
end

View File

@ -11,10 +11,59 @@ describe ApiUsersController do
controller.current_user = user
end
describe "create" do
it "successful" do
email = 'user_create1@jamkazam.com'
post :create, first_name: 'Seth', last_name: 'Call', email: email, password: 'jam123', terms: true, format: 'json'
response.should be_success
found = User.find_by_email(email)
found.city.should be_nil
found.state.should be_nil
found.country.should be_nil
found.musician.should be_true
found.musician_instruments.count.should be(1)
found.last_jam_updated_reason.should eq('r')
found.last_jam_locidispid.should_not be_nil
end
it "no first name" do
email = 'user_create2@jamkazam.com'
post :create, first_name: nil, last_name: 'Call', email: email, password: 'jam123', terms: true, format: 'json'
response.status.should eq(422)
error_data = JSON.parse(response.body)
error_data['errors']['first_name'].should eq(["can't be blank"])
end
it "no email" do
email = nil
post :create, first_name: nil, last_name: 'Call', email: email, password: 'jam123', terms: true, format: 'json'
response.status.should eq(422)
error_data = JSON.parse(response.body)
error_data['errors']['email'].should eq(["can't be blank", "is invalid"])
end
it "short password" do
email = nil
post :create, first_name: nil, last_name: 'Call', email: email, password: 'jam', terms: true, format: 'json'
response.status.should eq(422)
error_data = JSON.parse(response.body)
error_data['errors']['password'].should eq(["is too short (minimum is 6 characters)"])
end
it "no terms" do
email = 'user_create3@jamkazam.com'
post :create, first_name: 'Seth', last_name: 'Call', email: email, password: 'jam123', terms: false, format: 'json'
response.status.should eq(422)
error_data = JSON.parse(response.body)
error_data['errors']['terms_of_service'].should eq(["must be accepted"])
end
end
describe "update mod" do
it "empty mod" do
post :update, id:user.id, mods: {}, :format=>'json'
response.should be_success
user.reload
user.mods_json.should == {}
end

View File

@ -498,6 +498,7 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
end
it "shows one free, one not free item correctly (not-Texas)" do
pending "not possible to have one free and one not-free in shopping cart currently"
ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)
user.reload
ShoppingCart.add_jam_track_to_cart(user, jamtrack_pearljam_evenflow)
@ -521,6 +522,7 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
end
it "shows one free, one not free item correctly (Texas)" do
pending "not possible to have one free and one not-free in shopping cart currently"
ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)
user.reload
ShoppingCart.add_jam_track_to_cart(user, jamtrack_pearljam_evenflow)
@ -673,6 +675,9 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
it "shows purchase error correctly" do
user.has_redeemable_jamtrack = false
user.save!
ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)
@recurlyClient.create_account(user, billing_info)
@ -700,73 +705,29 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
find('h1', text: 'jamtracks')
#find('a', text: 'What is a JamTrack?')
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]").trigger(:click)
find('h1', text: 'shopping cart')
find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
find('.cart-item-price', text: "$ #{0.00}") # 1st one is free!
find('.shopping-sub-total', text:"Subtotal:$ 0.00")
# attempt to checkout
find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)
find('h3', text: 'OR SIGN UP USING YOUR EMAIL')
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(1)
shopping_cart = shopping_carts[0]
shopping_cart.anonymous_user_id.should_not be_nil
shopping_cart.user_id.should be_nil
# we should now be on checkoutSignin
find('h3', text: 'ALREADY A MEMBER OF THE JAMKAZAM COMMUNITY?')
verify_nav(1)
# skip to payment without signing in
find('a.btnNext').trigger(:click)
# this should take us to the payment screen
find('p.payment-prompt')
find('.jamkazam-account-signup')
# fill out all billing info and account info
fill_in 'billing-first-name', with: 'Seth'
fill_in 'billing-last-name', with: 'Call'
fill_in 'billing-address1', with: '10704 Buckthorn Drive'
fill_in 'billing-city', with: 'Austin'
fill_in 'billing-state', with: 'Texas'
fill_in 'billing-zip', with: '78759'
fill_in 'card-number', with: '4111111111111111'
fill_in 'card-verify', with: '012'
fill_in 'checkout-signup-email', with: 'guy@jamkazam.com'
fill_in 'checkout-signup-password', with: 'jam123'
find('#divJamKazamTos ins.iCheck-helper').trigger(:click) # accept TOS
fill_in 'first_name', with: 'Seth'
fill_in 'last_name', with: 'Call'
fill_in 'email', with: 'guy@jamkazam.com'
fill_in 'password', with: 'jam123'
find('.right-side .terms_of_service input').trigger(:click) # accept TOS
# try to submit, and see order page
find('#payment-info-next').trigger(:click)
# now see order page, and everything should appear free
find('p.order-prompt')
find('.order-items-value.order-total', text:'$0.00')
find('.order-items-value.shipping-handling', text:'$0.00')
find('.order-items-value.sub-total', text:'$0.00')
find('.order-items-value.taxes', text:'$0.00')
find('.order-items-value.grand-total', text:'$0.00')
find('.signup-submit').trigger(:click)
find('.jam-tracks-in-browser')
guy = User.find_by_email('guy@jamkazam.com')
# verify that the shopping cart has user_id info updated
shopping_cart.reload
shopping_cart.anonymous_user_id.should be_nil
shopping_cart.user.should eq(guy)
# also verify that there is still only one shopping cart, implying we deleted the anonymous user's shopping cart
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(1)
# click the ORDER button
find('.place-order-center a.button-orange.place-order').trigger(:click)
# and now we should see confirmation, and a notice that we are in a normal browser
find('.thanks-detail.jam-tracks-in-browser')
guy.shopping_carts.length.should eq(0)
guy.reload
jam_track_right = jamtrack_acdc_backinblack.right_for_user(guy)
@ -779,7 +740,7 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
guy.sales.length.should eq(1)
sale = guy.sales.first
sale.sale_line_items.length.should eq(1)
acdc_sale = SaleLineItem.find_by_recurly_adjustment_uuid(jam_track_right.recurly_adjustment_uuid)
acdc_sale = sale.sale_line_items[0]
acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
acdc_sale.product_type.should eq('JamTrack')
acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
@ -789,11 +750,15 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
acdc_sale.sale.should eq(sale)
# this is a little cheat to make the billing info dropdown already say US
guy.country = 'US'
guy.save!
# now, go back to checkout flow again, and make sure we are told there are no free jam tracks
visit "/client#/jamtrackBrowse"
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_pearljam_evenflow.id}\"]").trigger(:click)
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_pearljam_evenflow.id}\"]", text: 'ADD TO CART').trigger(:click)
find('h1', text: 'shopping cart')
find('.cart-item-caption', text: "JamTrack: #{jamtrack_pearljam_evenflow.name}")
find('.cart-item-price', text: "$ #{jamtrack_pearljam_evenflow.price}")
@ -802,6 +767,24 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
# attempt to checkout
find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)
# should be at payment page
# this should take us to the payment screen
find('p.payment-prompt')
# fill out all billing info and account info
fill_in 'billing-first-name', with: 'Seth'
fill_in 'billing-last-name', with: 'Call'
fill_in 'billing-address1', with: '10704 Buckthorn Drive'
fill_in 'billing-city', with: 'Austin'
fill_in 'billing-state', with: 'Texas'
fill_in 'billing-zip', with: '78759'
fill_in 'card-number', with: '4111111111111111'
fill_in 'card-verify', with: '012'
#jk_select('US', '#checkoutPaymentScreen #divBillingCountry #billing-country')
find('#payment-info-next').trigger(:click)
# should be taken straight to order page
# now see order page, and everything should no longer appear free
@ -844,16 +827,38 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
end
it "for existing user" do
it "for existing user with a freebie available (already logged in)" do
fast_signin(user, "/client#/jamtrackBrowse")
find('h1', text: 'jamtracks')
#find('a', text: 'What is a JamTrack?')
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]").trigger(:click)
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)
find('.jam-tracks-in-browser')
user.reload
jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
# make sure it appears the user actually bought the jamtrack!
jam_track_right.should_not be_nil
jam_track_right.redeemed.should be_true
user.has_redeemable_jamtrack.should be_false
end
it "for existing user with no freebie available (already logged in)" do
user.has_redeemable_jamtrack = false
user.save!
fast_signin(user, "/client#/jamtrackBrowse")
find('h1', text: 'jamtracks')
#find('a', text: 'What is a JamTrack?')
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'ADD TO CART').trigger(:click)
find('h1', text: 'shopping cart')
find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
find('.cart-item-price', text: "$ #{0.00}") # 1st one is free!
find('.shopping-sub-total', text:"Subtotal:$ 0.00")
find('.cart-item-price', text: "$ #{jamtrack_acdc_backinblack.price}") # 1st one is free!
find('.shopping-sub-total', text:"Subtotal:$ 1.99")
# attempt to checkout
find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)
@ -878,11 +883,11 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
# now see order page, and everything should appear free
find('p.order-prompt')
find('.order-items-value.order-total', text:'$0.00')
find('.order-items-value.order-total', text:'$1.99')
find('.order-items-value.shipping-handling', text:'$0.00')
find('.order-items-value.sub-total', text:'$0.00')
find('.order-items-value.taxes', text:'$0.00')
find('.order-items-value.grand-total', text:'$0.00')
find('.order-items-value.sub-total', text:'$1.99')
find('.order-items-value.taxes', text:'$0.16')
find('.order-items-value.grand-total', text:'$2.15')
# click the ORDER button
find('.place-order-center a.button-orange.place-order').trigger(:click)
@ -894,11 +899,11 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
# make sure it appears the user actually bought the jamtrack!
jam_track_right.should_not be_nil
jam_track_right.redeemed.should be_true
jam_track_right.redeemed.should be_false
user.has_redeemable_jamtrack.should be_false
end
it "for redeemable user that starts shopping anonymously" do
it "for existing user with a freebie (starts shopping anonymously)" do
user.has_redeemable_jamtrack = true
user.save!
@ -907,11 +912,138 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
find('h1', text: 'jamtracks')
#find('a', text: 'What is a JamTrack?')
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]").trigger(:click)
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)
find('h3', text: 'OR SIGN UP USING YOUR EMAIL')
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(1)
shopping_cart = shopping_carts[0]
shopping_cart.anonymous_user_id.should_not be_nil
shopping_cart.user_id.should be_nil
find('.right-side a.signin').trigger(:click)
# log in dialog should be showing
# try a bogus user/pass first
within('.signin-form') do
fill_in "session[email]", with: user.email
fill_in "session[password]", with: user.password
end
find('.signin-submit').trigger(:click)
# this should log the user in, cause a full-page reload, and the order should be placed or redeemComplete
find('.jam-tracks-in-browser')
user.reload
# verify that the shopping cart has user_id info updated
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(0)
shopping_cart = shopping_carts[0]
user.reload
jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
# make sure it appears the user actually bought the jamtrack!
jam_track_right.should_not be_nil
jam_track_right.redeemed.should be_true
user.has_redeemable_jamtrack.should be_false
# verify sales data
user.sales.length.should eq(1)
sale = user.sales.first
sale.sale_line_items.length.should eq(1)
acdc_sale = sale.sale_line_items[0]
acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
acdc_sale.product_type.should eq('JamTrack')
acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
acdc_sale.quantity.should eq(1)
acdc_sale.free.should eq(1)
acdc_sale.unit_price.should eq(1.99)
acdc_sale.sale.should eq(sale)
end
it "for existing user with a freebie (starts shopping anonymously on 'used' browser)" do
user.has_redeemable_jamtrack = true
user.save!
set_cookie('redeemed_jamtrack', 'true')
# the point of this is to also prove that the free jamtrack does not carry over to the existing user, once they log in
visit "/client#/jamtrackBrowse"
find('h1', text: 'jamtracks')
#find('a', text: 'What is a JamTrack?')
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text:'ADD TO CART').trigger(:click)
find('h1', text: 'shopping cart')
find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
find('.cart-item-price', text: "$ #{0.00}") # 1st one is free!
find('.shopping-sub-total', text:"Subtotal:$ 0.00")
find('.cart-item-price', text: "$ 1.99") # 1st one is free!
find('.shopping-sub-total', text:"Subtotal:$ 1.99")
# attempt to checkout
find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(1)
shopping_cart = shopping_carts[0]
shopping_cart.anonymous_user_id.should_not be_nil
shopping_cart.user_id.should be_nil
# we should now be on checkoutSignin
find('h3', text: 'ALREADY A MEMBER OF THE JAMKAZAM COMMUNITY?')
verify_nav(1)
fill_in "email", with: user.email
fill_in "password", with: user.password
find('.signin-submit').trigger(:click)
# this should log the user in, cause a full-page reload, and the order should be placed or redeemComplete
find('.jam-tracks-in-browser')
user.reload
# verify that the shopping cart has user_id info updated
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(0)
shopping_cart = shopping_carts[0]
user.reload
jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
# make sure it appears the user actually bought the jamtrack!
jam_track_right.should_not be_nil
jam_track_right.redeemed.should be_true
user.has_redeemable_jamtrack.should be_false
# verify sales data
user.sales.length.should eq(1)
sale = user.sales.first
sale.sale_line_items.length.should eq(1)
acdc_sale = sale.sale_line_items[0]
acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
acdc_sale.product_type.should eq('JamTrack')
acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
acdc_sale.quantity.should eq(1)
acdc_sale.free.should eq(1)
acdc_sale.unit_price.should eq(1.99)
acdc_sale.sale.should eq(sale)
end
it "for user with no freebies (starts shopping anonymously on 'used' browser)" do
user.has_redeemable_jamtrack = false
user.save!
set_cookie('redeemed_jamtrack', 'true')
# the point of this is to also prove that the free jamtrack does not carry over to the existing user, once they log in
visit "/client#/jamtrackBrowse"
find('h1', text: 'jamtracks')
#find('a', text: 'What is a JamTrack?')
find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text:'ADD TO CART').trigger(:click)
find('h1', text: 'shopping cart')
find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
find('.cart-item-price', text: "$ 1.99") # 1st one is free!
find('.shopping-sub-total', text:"Subtotal:$ 1.99")
# attempt to checkout
find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)
@ -926,7 +1058,6 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
find('h3', text: 'ALREADY A MEMBER OF THE JAMKAZAM COMMUNITY?')
verify_nav(1)
# try a bogus user/pass first
fill_in "email", with: user.email
fill_in "password", with: user.password
find('.signin-submit').trigger(:click)
@ -947,24 +1078,14 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
# try to submit, and see order page
find('#payment-info-next').trigger(:click)
# now see order page, and everything should appear free
find('p.order-prompt')
find('.order-items-value.order-total', text:'$0.00')
find('.order-items-value.order-total', text:'$1.99')
find('.order-items-value.shipping-handling', text:'$0.00')
find('.order-items-value.sub-total', text:'$0.00')
find('.order-items-value.taxes', text:'$0.00')
find('.order-items-value.grand-total', text:'$0.00')
user.reload
# verify that the shopping cart has user_id info updated
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(1)
shopping_cart = shopping_carts[0]
shopping_cart.anonymous_user_id.should be_nil
shopping_cart.user.should eq(user)
find('.order-items-value.sub-total', text:'$1.99')
find('.order-items-value.taxes', text:'$0.16')
find('.order-items-value.grand-total', text:'$2.15')
# click the ORDER button
find('.place-order-center a.button-orange.place-order').trigger(:click)
@ -972,11 +1093,19 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
# and now we should see confirmation, and a notice that we are in a normal browser
find('.thanks-detail.jam-tracks-in-browser')
user.reload
# verify that the shopping cart has user_id info updated
shopping_carts = ShoppingCart.all
shopping_carts.count.should eq(0)
shopping_cart = shopping_carts[0]
user.reload
jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
# make sure it appears the user actually bought the jamtrack!
jam_track_right.should_not be_nil
jam_track_right.redeemed.should be_true
jam_track_right.redeemed.should be_false
user.has_redeemable_jamtrack.should be_false
# verify sales data
@ -988,7 +1117,7 @@ describe "Checkout", :js => true, :type => :feature, :capybara_feature => true d
acdc_sale.product_type.should eq('JamTrack')
acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
acdc_sale.quantity.should eq(1)
acdc_sale.free.should eq(1)
acdc_sale.free.should eq(0)
acdc_sale.unit_price.should eq(1.99)
acdc_sale.sale.should eq(sale)
end

View File