repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/installment/installment_tracking_spec.rb | spec/models/installment/installment_tracking_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "InstallmentTracking" do
before do
@creator = create(:named_user, :with_avatar)
@installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator)
end
describe "click_summary" do
before do
@installment = create(:installment, id: 13)
end
it "converts encoded urls back into human-readable format" do
CreatorEmailClickSummary.create!(installment_id: 13,
total_unique_clicks: 2,
urls: { "https://www.gumroad.com" => 1,
"https://www.google.com" => 2 })
decoded_hash = { "google.com" => 2,
"gumroad.com" => 1 }
urls = @installment.clicked_urls
expect(urls).to eq decoded_hash
end
end
describe "#click_rate_percent" do
before do
@installment = create(:installment, id: 13, customer_count: 4)
end
it "computes the click rate correctly" do
CreatorEmailClickSummary.create!(installment_id: 13,
total_unique_clicks: 2,
urls: { "https://www.gumroad.com" => 2,
"https://www.google.com" => 1 })
expect(@installment.click_rate_percent).to eq 50.0
end
end
describe "#unique_click_count" do
before do
@installment = create(:installment, customer_count: 4)
end
it "returns 0 if there have been no clicks" do
expect(@installment.unique_click_count).to eq 0
end
it "returns the correct number of clicks" do
CreatorEmailClickSummary.create!(installment_id: @installment.id,
total_unique_clicks: 2,
urls: { "https://www.gumroad.com" => 2,
"https://www.google.com" => 1 })
expect(@installment.unique_click_count).to eq 2
end
it "does not hit CreatorEmailClickSummary model once the cache is set" do
CreatorEmailClickSummary.create!(installment_id: @installment.id,
total_unique_clicks: 4,
urls: { "https://www.gumroad.com" => 2,
"https://www.google.com" => 1 })
# Read once and set the cache
@installment.unique_click_count
expect(CreatorEmailClickSummary).not_to receive(:where).with(installment_id: @installment.id)
unique_click_count = @installment.unique_click_count
expect(unique_click_count).to eq 4
end
end
describe "#unique_open_count" do
before do
@installment = create(:installment, customer_count: 4)
end
it "does not hit CreatorEmailOpenEvent model once the cache is set" do
3.times { CreatorEmailOpenEvent.create!(installment_id: @installment.id) }
# Read once and set the cache
@installment.unique_open_count
expect(CreatorEmailOpenEvent).not_to receive(:where).with(installment_id: @installment.id)
unique_open_count = @installment.unique_open_count
expect(unique_open_count).to eq 3
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/admin/sales_report_spec.rb | spec/models/admin/sales_report_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Admin::SalesReport do
let(:valid_attributes) do
{
country_code: "US",
start_date: "2023-01-01",
end_date: "2023-12-31",
sales_type: GenerateSalesReportJob::ALL_SALES,
}
end
describe "validations" do
context "country_code" do
it "is invalid when country_code is blank" do
sales_report = described_class.new(valid_attributes.merge(country_code: ""))
expect(sales_report).not_to be_valid
expect(sales_report.errors[:country_code]).to include("Please select a country")
end
it "is valid when country_code is present" do
sales_report = described_class.new(valid_attributes)
expect(sales_report).to be_valid
end
end
context "start_date" do
it "is invalid when start_date is blank" do
sales_report = described_class.new(valid_attributes.merge(start_date: ""))
expect(sales_report).not_to be_valid
expect(sales_report.errors[:start_date]).to include("Invalid date format. Please use YYYY-MM-DD format")
end
it "is invalid when start_date is in the future" do
sales_report = described_class.new(valid_attributes.merge(start_date: 1.day.from_now.to_date))
expect(sales_report).not_to be_valid
expect(sales_report.errors[:start_date]).to include("cannot be in the future")
end
it "is invalid when start_date is greater than or equal to end_date" do
sales_report = described_class.new(valid_attributes.merge(start_date: "2023-12-31", end_date: "2023-01-01"))
expect(sales_report).not_to be_valid
expect(sales_report.errors[:start_date]).to include("must be before end date")
end
it "is valid when start_date is less than end_date" do
sales_report = described_class.new(valid_attributes)
expect(sales_report).to be_valid
end
it "is valid when start_date is today and end_date is in the future" do
sales_report = described_class.new(valid_attributes.merge(start_date: Date.current, end_date: Date.current + 1.day))
expect(sales_report).to be_valid
end
end
context "end_date" do
it "is invalid when end_date is blank" do
sales_report = described_class.new(valid_attributes.merge(end_date: ""))
expect(sales_report).not_to be_valid
expect(sales_report.errors[:end_date]).to include("Invalid date format. Please use YYYY-MM-DD format")
end
it "is valid when end_date is present" do
sales_report = described_class.new(valid_attributes)
expect(sales_report).to be_valid
end
end
end
describe "date parsing" do
context "start_date=" do
it "parses a valid date string in YYYY-MM-DD format" do
sales_report = described_class.new(start_date: "2023-01-15")
expect(sales_report.start_date).to eq(Date.new(2023, 1, 15))
end
it "accepts a Date object" do
date = Date.new(2023, 1, 15)
sales_report = described_class.new(start_date: date)
expect(sales_report.start_date).to eq(date)
end
it "returns nil for invalid date string format" do
sales_report = described_class.new(start_date: "01/15/2023")
expect(sales_report.start_date).to be_nil
end
it "returns nil for unparseable date string" do
sales_report = described_class.new(start_date: "2023-13-45")
expect(sales_report.start_date).to be_nil
end
it "returns nil for blank value" do
sales_report = described_class.new(start_date: "")
expect(sales_report.start_date).to be_nil
end
end
context "end_date=" do
it "parses a valid date string in YYYY-MM-DD format" do
sales_report = described_class.new(end_date: "2023-12-31")
expect(sales_report.end_date).to eq(Date.new(2023, 12, 31))
end
it "accepts a Date object" do
date = Date.new(2023, 12, 31)
sales_report = described_class.new(end_date: date)
expect(sales_report.end_date).to eq(date)
end
it "returns nil for invalid date string format" do
sales_report = described_class.new(end_date: "12/31/2023")
expect(sales_report.end_date).to be_nil
end
it "returns nil for unparseable date string" do
sales_report = described_class.new(end_date: "2023-13-45")
expect(sales_report.end_date).to be_nil
end
it "returns nil for blank value" do
sales_report = described_class.new(end_date: "")
expect(sales_report.end_date).to be_nil
end
end
end
describe "accessor predicate methods" do
it "returns true when country_code is present" do
sales_report = described_class.new(country_code: "US")
expect(sales_report.country_code?).to be true
end
it "returns false when country_code is blank" do
sales_report = described_class.new(country_code: "")
expect(sales_report.country_code?).to be false
end
it "returns true when start_date is present" do
sales_report = described_class.new(start_date: "2023-01-01")
expect(sales_report.start_date?).to be true
end
it "returns false when start_date is blank" do
sales_report = described_class.new(start_date: "")
expect(sales_report.start_date?).to be false
end
it "returns true when end_date is present" do
sales_report = described_class.new(end_date: "2023-12-31")
expect(sales_report.end_date?).to be true
end
it "returns false when end_date is blank" do
sales_report = described_class.new(end_date: "")
expect(sales_report.end_date?).to be false
end
end
describe "#generate_later" do
let(:sales_report) { described_class.new(valid_attributes) }
before do
allow($redis).to receive(:lpush)
allow($redis).to receive(:ltrim)
end
it "enqueues a GenerateSalesReportJob" do
sales_report.generate_later
expect(GenerateSalesReportJob).to have_enqueued_sidekiq_job(
"US",
"2023-01-01",
"2023-12-31",
GenerateSalesReportJob::ALL_SALES,
true,
nil
)
end
it "stores job details in Redis with the correct key" do
allow(GenerateSalesReportJob).to receive(:perform_async).and_return("job_123")
expect($redis).to receive(:lpush).with(RedisKey.sales_report_jobs, anything)
expect($redis).to receive(:ltrim).with(RedisKey.sales_report_jobs, 0, 19)
sales_report.generate_later
end
it "stores job details with correct attributes" do
allow(GenerateSalesReportJob).to receive(:perform_async).and_return("job_123")
allow(Time).to receive(:current).and_return(Time.new(2023, 1, 1, 12, 0, 0))
expect($redis).to receive(:lpush) do |key, json_data|
data = JSON.parse(json_data)
expect(data["job_id"]).to eq("job_123")
expect(data["country_code"]).to eq("US")
expect(data["start_date"]).to eq("2023-01-01")
expect(data["end_date"]).to eq("2023-12-31")
expect(data["sales_type"]).to eq("all_sales")
expect(data["enqueued_at"]).to be_present
expect(data["status"]).to eq("processing")
end
sales_report.generate_later
end
it "limits the job history to 20 items" do
allow(GenerateSalesReportJob).to receive(:perform_async).and_return("job_123")
expect($redis).to receive(:ltrim).with(RedisKey.sales_report_jobs, 0, 19)
sales_report.generate_later
end
end
describe ".fetch_job_history" do
context "when job data exists" do
let(:job_data) do
[
{
job_id: "job_1",
country_code: "US",
start_date: "2023-01-01",
end_date: "2023-03-31",
sales_type: GenerateSalesReportJob::ALL_SALES,
enqueued_at: "2023-01-01T00:00:00Z",
status: "processing"
}.to_json,
{
job_id: "job_2",
country_code: "GB",
start_date: "2023-04-01",
end_date: "2023-06-30",
sales_type: GenerateSalesReportJob::ALL_SALES,
enqueued_at: "2023-04-01T00:00:00Z",
status: "completed"
}.to_json
]
end
before do
allow($redis).to receive(:lrange).with(RedisKey.sales_report_jobs, 0, 19).and_return(job_data)
end
it "fetches and parses job history from Redis" do
result = described_class.fetch_job_history
expect(result).to be_an(Array)
expect(result.size).to eq(2)
expect(result[0]["job_id"]).to eq("job_1")
expect(result[1]["job_id"]).to eq("job_2")
end
it "returns the last 20 jobs" do
described_class.fetch_job_history
expect($redis).to have_received(:lrange).with(RedisKey.sales_report_jobs, 0, 19)
end
end
context "when Redis returns empty array" do
before do
allow($redis).to receive(:lrange).with(RedisKey.sales_report_jobs, 0, 19).and_return([])
end
it "returns an empty array" do
result = described_class.fetch_job_history
expect(result).to eq([])
end
end
context "when JSON parsing fails" do
before do
allow($redis).to receive(:lrange).with(RedisKey.sales_report_jobs, 0, 19).and_return(["invalid json"])
end
it "returns an empty array" do
result = described_class.fetch_job_history
expect(result).to eq([])
end
end
end
describe "#errors_hash" do
it "returns errors in the expected format" do
sales_report = described_class.new(country_code: "", start_date: "", end_date: "")
sales_report.valid?
errors = sales_report.errors_hash
expect(errors).to have_key(:sales_report)
expect(errors[:sales_report]).to be_a(Hash)
expect(errors[:sales_report][:country_code]).to include("Please select a country")
expect(errors[:sales_report][:start_date]).to include("Invalid date format. Please use YYYY-MM-DD format")
expect(errors[:sales_report][:end_date]).to include("Invalid date format. Please use YYYY-MM-DD format")
expect(errors[:sales_report][:sales_type]).to include("Invalid sales type, should be all_sales or discover_sales.")
end
it "returns empty hash when there are no errors" do
sales_report = described_class.new(valid_attributes)
sales_report.valid?
errors = sales_report.errors_hash
expect(errors).to eq({ sales_report: {} })
sales_report = described_class.new(valid_attributes.merge(sales_type: GenerateSalesReportJob::DISCOVER_SALES))
sales_report.valid?
errors = sales_report.errors_hash
expect(errors).to eq({ sales_report: {} })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/help_center/category_spec.rb | spec/models/help_center/category_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HelpCenter::Category do
describe "#categories_for_same_audience" do
it "returns the categories with the same audience" do
expect(HelpCenter::Category::ACCESSING_YOUR_PURCHASE.categories_for_same_audience).to contain_exactly(
HelpCenter::Category::ACCESSING_YOUR_PURCHASE,
HelpCenter::Category::BEFORE_YOU_BUY,
HelpCenter::Category::RECEIPTS_AND_REFUNDS,
HelpCenter::Category::ISSUES_WITH_YOUR_PURCHASE
)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/mailer_info/encryption_spec.rb | spec/models/mailer_info/encryption_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe MailerInfo::Encryption do
describe ".encrypt" do
it "returns nil for nil input" do
expect(described_class.encrypt(nil)).to be_nil
end
it "encrypts value with current key version" do
encrypted = described_class.encrypt("test")
expect(encrypted).to start_with("v1:")
expect(encrypted).not_to include("test")
expect(encrypted.split(":").size).to eq(3)
end
it "converts non-string values to string" do
encrypted = described_class.encrypt(123)
expect(encrypted).to start_with("v1:")
expect(described_class.decrypt(encrypted)).to eq("123")
end
end
describe ".decrypt" do
it "returns nil for nil input" do
expect(described_class.decrypt(nil)).to be_nil
end
it "decrypts encrypted value" do
value = "test_value"
encrypted = described_class.encrypt(value)
expect(described_class.decrypt(encrypted)).to eq(value)
end
it "raises error for unknown key version" do
expect do
described_class.decrypt("v999:abc:def")
end.to raise_error("Unknown key version: 999")
end
it "raises error for invalid format" do
expect do
described_class.decrypt("invalid")
end.to raise_error("Unknown key version: 0")
end
end
describe "encryption keys" do
it "uses the highest version as current key" do
allow(described_class).to receive(:encryption_keys).and_return({
1 => "key1",
2 => "key2",
3 => "key3"
})
encrypted = described_class.encrypt("test")
expect(encrypted).to start_with("v3:")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/mailer_info/router_spec.rb | spec/models/mailer_info/router_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe MailerInfo::Router do
let(:domain) { :gumroad }
let(:date) { Date.current }
describe ".determine_email_provider" do
it "raises error for invalid domain" do
expect do
described_class.determine_email_provider(:invalid)
end.to raise_error(ArgumentError, "Invalid domain: invalid")
end
it "returns SendGrid in test environment" do
expect(described_class.determine_email_provider(domain)).to eq(MailerInfo::EMAIL_PROVIDER_SENDGRID)
end
context "when resend feature is active" do
before do
allow(Rails.env).to receive(:test?).and_return(false)
Feature.activate(:resend)
end
context "without counts" do
it "returns SendGrid" do
expect(described_class.determine_email_provider(domain)).to eq(MailerInfo::EMAIL_PROVIDER_SENDGRID)
end
end
it "returns SendGrid when max count is reached" do
described_class.set_max_count(domain, date, 10)
$redis.set(described_class.send(:current_count_key, domain, date:), 10)
expect(described_class.determine_email_provider(domain)).to eq(MailerInfo::EMAIL_PROVIDER_SENDGRID)
end
it "returns Resend based on probability" do
described_class.set_probability(domain, date, 1.0)
described_class.set_max_count(domain, date, 100)
$redis.set(described_class.send(:current_count_key, domain, date:), 0)
allow(Kernel).to receive(:rand).and_return(0.5)
expect(described_class.determine_email_provider(domain)).to eq(MailerInfo::EMAIL_PROVIDER_RESEND)
end
it "returns SendGrid based on probability" do
described_class.set_probability(domain, date, 0.0)
described_class.set_max_count(domain, date, 100)
$redis.set(described_class.send(:current_count_key, domain, date:), 0)
allow(Kernel).to receive(:rand).and_return(0.5)
expect(described_class.determine_email_provider(domain)).to eq(MailerInfo::EMAIL_PROVIDER_SENDGRID)
end
it "increments counter when choosing Resend" do
described_class.set_probability(domain, date, 1.0)
described_class.set_max_count(domain, date, 100)
$redis.set(described_class.send(:current_count_key, domain, date:), 0)
allow(Kernel).to receive(:rand).and_return(0.5)
expect do
described_class.determine_email_provider(domain)
end.to change { $redis.get(described_class.send(:current_count_key, domain, date:)).to_i }.by(1)
end
end
end
describe ".set_probability" do
it "raises error for invalid domain" do
expect do
described_class.set_probability(:invalid, date, 0.5)
end.to raise_error(ArgumentError, "Invalid domain: invalid")
end
it "sets probability in Redis" do
described_class.set_probability(domain, date, 0.5)
key = described_class.send(:probability_key, domain, date:)
expect($redis.get(key).to_f).to eq(0.5)
end
end
describe ".set_max_count" do
it "raises error for invalid domain" do
expect do
described_class.set_max_count(:invalid, date, 100)
end.to raise_error(ArgumentError, "Invalid domain: invalid")
end
it "sets max count in Redis" do
described_class.set_max_count(domain, date, 100)
key = described_class.send(:max_count_key, domain, date:)
expect($redis.get(key).to_i).to eq(100)
end
end
describe ".domain_stats" do
it "raises error for invalid domain" do
expect do
described_class.domain_stats(:invalid)
end.to raise_error(ArgumentError, "Invalid domain: invalid")
end
it "returns stats for domain" do
described_class.set_probability(domain, date, 0.5)
described_class.set_max_count(domain, date, 100)
$redis.set(described_class.send(:current_count_key, domain), 42)
stats = described_class.domain_stats(domain)
expect(stats).to include(
hash_including(
date: date.to_s,
probability: 0.5,
max_count: 100,
current_count: 42
)
)
end
end
describe ".stats" do
it "returns stats for all domains" do
described_class.set_probability(:gumroad, date, 0.5)
described_class.set_max_count(:gumroad, date, 100)
stats = described_class.stats
expect(stats.keys).to match_array(MailerInfo::DeliveryMethod::DOMAINS)
expect(stats[:gumroad]).to be_present
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/mailer_info/header_builder_spec.rb | spec/models/mailer_info/header_builder_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe MailerInfo::HeaderBuilder do
let(:mailer_class) { "CustomerMailer" }
let(:mailer_method) { "test_email" }
let(:mailer_args) { ["test@example.com"] }
describe ".perform" do
it "delegates to instance" do
instance = instance_double(described_class)
allow(described_class).to receive(:new).and_return(instance)
allow(instance).to receive(:perform).and_return({ "test" => "value" })
described_class.perform(
mailer_class:,
mailer_method:,
mailer_args:,
email_provider: MailerInfo::EMAIL_PROVIDER_SENDGRID
)
expect(instance).to have_received(:perform)
end
end
describe "#build_for_sendgrid" do
let(:builder) do
described_class.new(
mailer_class:,
mailer_method:,
mailer_args:,
email_provider: MailerInfo::EMAIL_PROVIDER_SENDGRID
)
end
it "builds basic headers" do
headers = builder.build_for_sendgrid
smtpapi = JSON.parse(headers[MailerInfo::SENDGRID_X_SMTPAPI_HEADER])
expect(smtpapi["environment"]).to eq(Rails.env)
expect(smtpapi["category"]).to eq([mailer_class, "#{mailer_class}.#{mailer_method}"])
expect(smtpapi["unique_args"]["mailer_class"]).to eq(mailer_class)
expect(smtpapi["unique_args"]["mailer_method"]).to eq(mailer_method)
end
context "with receipt email" do
let(:mailer_method) { SendgridEventInfo::RECEIPT_MAILER_METHOD }
let(:purchase) { create(:purchase) }
let(:mailer_args) { [purchase.id, nil] }
it "includes purchase id" do
headers = builder.build_for_sendgrid
smtpapi = JSON.parse(headers[MailerInfo::SENDGRID_X_SMTPAPI_HEADER])
expect(smtpapi["unique_args"]["purchase_id"]).to eq(purchase.id)
end
end
context "with preorder receipt email" do
let(:mailer_method) { SendgridEventInfo::PREORDER_RECEIPT_MAILER_METHOD }
let(:preorder) { create(:preorder) }
let(:mailer_args) { [preorder.id] }
before do
allow_any_instance_of(Preorder).to receive(:authorization_purchase).and_return(create(:purchase))
end
it "includes authorization purchase id" do
headers = builder.build_for_sendgrid
smtpapi = JSON.parse(headers[MailerInfo::SENDGRID_X_SMTPAPI_HEADER])
expect(smtpapi["unique_args"]["purchase_id"]).to eq(preorder.authorization_purchase.id)
end
end
context "with abandoned cart email" do
let(:mailer_method) { EmailEventInfo::ABANDONED_CART_MAILER_METHOD }
let(:workflow_ids) { { "1" => "test" } }
let(:mailer_args) { ["test@example.com", workflow_ids] }
it "includes workflow ids" do
headers = builder.build_for_sendgrid
smtpapi = JSON.parse(headers[MailerInfo::SENDGRID_X_SMTPAPI_HEADER])
expect(smtpapi["unique_args"]["workflow_ids"]).to be_nil # SendGrid doesn't use workflow_ids
expect(smtpapi["unique_args"]["mailer_args"]).to eq(mailer_args.inspect)
expect(smtpapi["unique_args"]["mailer_class"]).to eq(mailer_class)
expect(smtpapi["unique_args"]["mailer_method"]).to eq(mailer_method)
end
end
end
describe "#build_for_resend" do
let(:builder) do
described_class.new(
mailer_class:,
mailer_method:,
mailer_args:,
email_provider: MailerInfo::EMAIL_PROVIDER_RESEND
)
end
it "builds basic headers" do
headers = builder.build_for_resend
expect(headers[MailerInfo.header_name(:email_provider)]).to eq(MailerInfo::EMAIL_PROVIDER_RESEND)
encrypted_env = headers[MailerInfo.header_name(:environment)]
expect(MailerInfo.decrypt(encrypted_env)).to eq(Rails.env)
encrypted_class = headers[MailerInfo.header_name(:mailer_class)]
expect(MailerInfo.decrypt(encrypted_class)).to eq(mailer_class)
encrypted_method = headers[MailerInfo.header_name(:mailer_method)]
expect(MailerInfo.decrypt(encrypted_method)).to eq(mailer_method)
encrypted_category = headers[MailerInfo.header_name(:category)]
expect(JSON.parse(MailerInfo.decrypt(encrypted_category))).to eq([mailer_class, "#{mailer_class}.#{mailer_method}"])
end
context "with receipt email" do
let(:mailer_method) { SendgridEventInfo::RECEIPT_MAILER_METHOD }
let(:purchase) { create(:purchase) }
let(:mailer_args) { [purchase.id, nil] }
it "includes purchase id" do
headers = builder.build_for_resend
encrypted_id = headers[MailerInfo.header_name(:purchase_id)]
expect(MailerInfo.decrypt(encrypted_id)).to eq(purchase.id.to_s)
end
end
context "with preorder receipt email" do
let(:mailer_method) { SendgridEventInfo::PREORDER_RECEIPT_MAILER_METHOD }
let(:preorder) { create(:preorder) }
let(:mailer_args) { [preorder.id] }
before do
allow_any_instance_of(Preorder).to receive(:authorization_purchase).and_return(create(:purchase))
end
it "includes authorization purchase id" do
headers = builder.build_for_resend
encrypted_id = headers[MailerInfo.header_name(:purchase_id)]
expect(MailerInfo.decrypt(encrypted_id)).to eq(preorder.authorization_purchase.id.to_s)
end
end
context "with abandoned cart email" do
let(:mailer_method) { EmailEventInfo::ABANDONED_CART_MAILER_METHOD }
let(:workflow_ids) { { "1" => "test" } }
let(:mailer_args) { ["test@example.com", workflow_ids] }
it "includes workflow ids" do
headers = builder.build_for_resend
encrypted_ids = headers[MailerInfo.header_name(:workflow_ids)]
expect(MailerInfo.decrypt(encrypted_ids)).to eq(workflow_ids.keys.to_json)
end
it "raises error with unexpected args" do
expect do
described_class.new(
mailer_class:,
mailer_method:,
mailer_args: ["test@example.com"],
email_provider: MailerInfo::EMAIL_PROVIDER_RESEND
).build_for_resend
end.to raise_error(ArgumentError, /Abandoned cart email event has unexpected mailer_args size/)
end
end
end
describe "#truncated_mailer_args" do
let(:builder) do
described_class.new(
mailer_class:,
mailer_method:,
mailer_args: ["a" * 30, 123, { key: "value" }],
email_provider: MailerInfo::EMAIL_PROVIDER_SENDGRID
)
end
it "truncates string arguments to 20 chars" do
expect(builder.truncated_mailer_args).to eq(["a" * 20, 123, { key: "value" }])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/mailer_info/delivery_method_spec.rb | spec/models/mailer_info/delivery_method_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe MailerInfo::DeliveryMethod do
describe ".options" do
let(:email_provider) { MailerInfo::EMAIL_PROVIDER_SENDGRID }
context "with invalid domain" do
it "raises ArgumentError" do
expect { described_class.options(domain: :invalid, email_provider:) }
.to raise_error(ArgumentError, "Invalid domain: invalid")
end
end
context "with seller for non-customers domain" do
let(:seller) { create(:user) }
it "raises ArgumentError" do
expect { described_class.options(domain: :gumroad, email_provider:, seller:) }
.to raise_error(ArgumentError, "Seller is only allowed for customers domain")
end
end
context "with SendGrid" do
it "returns basic options" do
expect(described_class.options(domain: :gumroad, email_provider:)).to eq({
address: SENDGRID_SMTP_ADDRESS,
domain: DEFAULT_EMAIL_DOMAIN,
user_name: "apikey",
password: GlobalConfig.get("SENDGRID_GUMROAD_TRANSACTIONS_API_KEY")
})
end
end
context "with Resend" do
let(:email_provider) { MailerInfo::EMAIL_PROVIDER_RESEND }
it "returns basic options" do
expect(described_class.options(domain: :gumroad, email_provider:)).to eq({
address: RESEND_SMTP_ADDRESS,
domain: DEFAULT_EMAIL_DOMAIN,
user_name: "resend",
password: GlobalConfig.get("RESEND_DEFAULT_API_KEY")
})
end
end
context "with seller" do
let(:seller) { create(:user) }
before do
allow(seller).to receive(:mailer_level).and_return(:level_1)
end
it "returns seller-specific options" do
expect(described_class.options(domain: :customers, email_provider:, seller:)).to eq({
address: SENDGRID_SMTP_ADDRESS,
domain: CUSTOMERS_MAIL_DOMAIN,
user_name: "apikey",
password: GlobalConfig.get("SENDGRID_GR_CUSTOMERS_API_KEY")
})
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_gifts_spec.rb | spec/models/purchase/purchase_gifts_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PurchaseGifts", :vcr do
include CurrencyHelper
include ProductsHelper
describe "gifts" do
before do
gifter_email = "gifter@foo.com"
giftee_email = "giftee@foo.com"
@product = create(:product)
gift = create(:gift, gifter_email:, giftee_email:, link: @product)
@gifter_purchase = create(:purchase_in_progress, link: @product, email: gifter_email, chargeable: create(:chargeable))
gift.gifter_purchase = @gifter_purchase
@gifter_purchase.is_gift_sender_purchase = true
@gifter_purchase.process!
@giftee_purchase = gift.giftee_purchase = create(:purchase, link: @product, seller: @product.user, email: giftee_email, price_cents: 0,
stripe_transaction_id: nil, stripe_fingerprint: nil,
is_gift_receiver_purchase: true, purchase_state: "in_progress")
gift.mark_successful
gift.save!
end
it "increments seller's balance only for one purchase" do
expect do
@giftee_purchase.mark_gift_receiver_purchase_successful
@gifter_purchase.update_balance_and_mark_successful!
end.to change {
@product.user.reload.unpaid_balance_cents
}.by(@gifter_purchase.payment_cents)
end
it "sets the state of the giftee purchase to refunded when refunding gifter purchase" do
@giftee_purchase.mark_gift_receiver_purchase_successful
@gifter_purchase.reload.refund_and_save!(create(:admin_user).id)
@giftee_purchase.reload
expect(@giftee_purchase.purchase_state).to eq("gift_receiver_purchase_successful")
expect(@giftee_purchase.stripe_refunded).to be(true)
end
it "creates 1 url_redirect" do
expect do
@giftee_purchase.mark_gift_receiver_purchase_successful
@gifter_purchase.update_balance_and_mark_successful!
end.to change {
UrlRedirect.count
}.by(1)
end
it "emails the buyer" do
@giftee_purchase.mark_gift_receiver_purchase_successful
expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(@giftee_purchase.id).on("critical")
@gifter_purchase.update_balance_and_mark_successful!
expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(@gifter_purchase.id).on("critical")
end
it "emails the seller once" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(ContactingCreatorMailer).to receive(:notify).and_return(mail_double)
@giftee_purchase.mark_gift_receiver_purchase_successful
@gifter_purchase.update_balance_and_mark_successful!
end
describe "gifts with shipping" do
before do
@gifter_purchase = create(:purchase, price_cents: 100_00, chargeable: create(:chargeable))
@gifter_purchase.link.price_cents = 100_00
@gifter_purchase.link.shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 10_00, multiple_items_rate_cents: 5_00)
@gifter_purchase.link.is_physical = true
@gifter_purchase.link.require_shipping = true
@gifter_purchase.link.save!
end
it "does not apply a price or shipping rate to the giftee purchase" do
@gifter_purchase.country = "United States"
@gifter_purchase.zip_code = 94_107
@gifter_purchase.state = "CA"
@gifter_purchase.quantity = 1
@gifter_purchase.save!
@gifter_purchase.process!
expect(@gifter_purchase.price_cents).to eq(110_00)
expect(@gifter_purchase.shipping_cents).to eq(10_00)
expect(@gifter_purchase.total_transaction_cents).to eq(110_00)
@giftee_purchase = create(:purchase, link: @gifter_purchase.link, seller: @gifter_purchase.link.user, email: "giftee_email@gumroad.com",
price_cents: 0, stripe_transaction_id: nil, stripe_fingerprint: nil, is_gift_receiver_purchase: true,
full_name: "Mr.Dumbot Dumstein", country: Compliance::Countries::USA.common_name, state: "CA",
city: "San Francisco", zip_code: "94107", street_address: "1640 17th St",
purchase_state: "in_progress", can_contact: true)
@giftee_purchase.process!
expect(@giftee_purchase.price_cents).to eq(0)
expect(@giftee_purchase.shipping_cents).to eq(0)
expect(@giftee_purchase.total_transaction_cents).to eq(0)
expect(@giftee_purchase.tax_cents).to eq(0)
expect(@giftee_purchase.fee_cents).to eq(0)
end
end
it "makes one url redirect" do
expect do
@giftee_purchase.mark_gift_receiver_purchase_successful
@gifter_purchase.update_balance_and_mark_successful!
end.to change(UrlRedirect, :count).by(1)
expect(@giftee_purchase.url_redirect).to eq UrlRedirect.last
expect(@gifter_purchase.url_redirect).to be(nil)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_zip_spec.rb | spec/models/purchase/purchase_zip_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Purchase Zip Scenarios", :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
let(:ip_address) { "24.7.90.214" }
let(:initial_balance) { 200 }
let(:user) { create(:user, unpaid_balance_cents: initial_balance) }
let(:link) { create(:product, user:) }
let(:chargeable) { create :chargeable }
describe "zip_tax_rate associations" do
before do
link = create(:product)
@purchase1 = create(:purchase, link:, price_cents: 100)
@purchase2 = create(:purchase, link:, price_cents: 100)
@zip_tax_rate1 = create(:zip_tax_rate)
end
it "associates a single zip tax rate with a purchase (when eligible)" do
@purchase1.zip_tax_rate = @zip_tax_rate1
@purchase2.zip_tax_rate = @zip_tax_rate1
@purchase1.save!
@purchase2.save!
expect(@purchase1.reload.zip_tax_rate).to eq(@zip_tax_rate1)
expect(@purchase2.reload.zip_tax_rate).to eq(@zip_tax_rate1)
end
end
describe "zip_code" do
it "is set on successful if ip_address is present" do
purchase = create(:purchase, ip_address: "199.21.86.138", purchase_state: "in_progress")
purchase.process!
purchase.update_balance_and_mark_successful!
expect(purchase.reload.zip_code.length).to eq 5
end
it "is nil on save if ip_address is not present" do
purchase = create(:purchase, ip_address: nil)
purchase.save!
expect(purchase.reload.zip_code).to be(nil)
end
it "is not modified if already set" do
purchase = create(:purchase, ip_address: "8.8.8.8", zip_code: "90210")
purchase.save!
expect(purchase.reload.zip_code).to eq "90210"
end
end
describe "#was_zipcode_check_performed" do
before do
@bad_card = build(:chargeable_decline)
@good_card_without_zip_but_zip_check_would_pass = build(:chargeable, with_zip_code: false)
@good_card_without_zip_but_zip_check_would_fail = build(:chargeable_zip_check_fails, with_zip_code: false)
@good_card_without_zip_but_zip_check_would_unchecked = build(:chargeable_zip_check_unsupported, with_zip_code: false)
@good_card_zip_pass = build(:chargeable, with_zip_code: true)
@good_card_zip_fail = build(:chargeable_zip_check_fails, with_zip_code: true)
@good_card_zip_unchecked = build(:chargeable_zip_check_unsupported, with_zip_code: true)
@purchase = build(:purchase, purchase_state: "in_progress")
end
it "defaults to false" do
expect(@purchase.was_zipcode_check_performed).to be(false)
end
describe "during #process!" do
describe "with no zip code not provided" do
describe "with good card supporting zip code check that would pass" do
before do
@purchase.chargeable = @good_card_without_zip_but_zip_check_would_pass
@purchase.process!
end
it "processes without errors" do
expect(@purchase.errors).to_not be_present
end
it "is set to false" do
expect(@purchase.was_zipcode_check_performed).to be(false)
end
end
describe "with good card supporting zip code check that would fail" do
before do
@purchase.chargeable = @good_card_without_zip_but_zip_check_would_fail
@purchase.process!
end
it "processes without errors" do
expect(@purchase.errors).to_not be_present
end
it "is set to false" do
expect(@purchase.was_zipcode_check_performed).to be(false)
end
end
describe "with good card not supporting zip code check" do
before do
@purchase.chargeable = @good_card_without_zip_but_zip_check_would_unchecked
@purchase.process!
end
it "processes without errors" do
expect(@purchase.errors).to_not be_present
end
it "is set to false" do
expect(@purchase.was_zipcode_check_performed).to be(false)
end
end
describe "with bad card" do
before do
@purchase.chargeable = @bad_card
@purchase.process!
end
it "processes and result in errors" do
expect(@purchase.errors).to be_present
end
it "is set to false" do
expect(@purchase.was_zipcode_check_performed).to be(false)
end
end
end
describe "with zip code provided" do
before do
@purchase.credit_card_zipcode = @zip_code
end
describe "with good card supporting zip code check that would pass" do
before do
@purchase.chargeable = @good_card_zip_pass
@purchase.process!
end
it "processes without errors" do
expect(@purchase.errors).to_not be_present
end
it "is set to true" do
expect(@purchase.was_zipcode_check_performed).to be(true)
end
end
describe "with good card supporting zip code check that would fail" do
before do
@purchase.chargeable = @good_card_zip_fail
@purchase.process!
end
it "processes and result in error" do
expect(@purchase.errors).to be_present
expect(@purchase.stripe_error_code).to eq "incorrect_zip"
end
it "is set to true" do
expect(@purchase.was_zipcode_check_performed).to be(true)
end
end
describe "with good card not supporting zip code check" do
before do
@purchase.chargeable = @good_card_zip_unchecked
@purchase.process!
end
it "processes without errors" do
expect(@purchase.errors).to_not be_present
end
it "is set to false" do
expect(@purchase.was_zipcode_check_performed).to be(false)
end
end
describe "with bad card" do
before do
@purchase.chargeable = @bad_card
@purchase.process!
end
it "processes and result in errors" do
expect(@purchase.errors).to be_present
expect(@purchase.stripe_error_code).to eq "card_declined_generic_decline"
end
it "is set to false" do
expect(@purchase.was_zipcode_check_performed).to be(false)
end
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_installments_spec.rb | spec/models/purchase/purchase_installments_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PurchaseInstallments", :vcr do
include CurrencyHelper
include ProductsHelper
describe ".product_installments" do
it "can return installments for several purchases" do
product = create(:product)
variant = create(:variant, variant_category: create(:variant_category, link: product))
purchase_1 = create(:purchase, link: product, variant_attributes: [variant], price_cents: 100)
installment_1 = create(:installment, link: product, published_at: 30.minutes.ago)
create(:creator_contacting_customers_email_info_sent, purchase: purchase_1, installment: installment_1)
seller_post = create(:seller_installment, seller: product.user, published_at: 15.minutes.ago, json_data: { bought_products: [product.unique_permalink, create(:product).unique_permalink] })
create(:creator_contacting_customers_email_info_sent, purchase: purchase_1, installment: seller_post)
seller_post_2 = create(:seller_installment, seller: product.user, published_at: 20.minutes.ago,
json_data: { bought_products: [product.unique_permalink, create(:product).unique_permalink] })
create(:creator_contacting_customers_email_info_sent,
purchase: create(:purchase, link: create(:product, user: product.user), email: purchase_1.email),
installment: seller_post_2)
seller_post_for_variant = create(:seller_installment, seller: product.user, published_at: 25.minutes.ago, json_data: { bought_products: [create(:product).unique_permalink], bought_variants: [variant.external_id] })
create(:creator_contacting_customers_email_info_sent, purchase: purchase_1, installment: seller_post_for_variant)
create(:seller_installment, seller: product.user, published_at: Time.current, json_data: { bought_products: [create(:product).unique_permalink, create(:product).unique_permalink] })
profile_only_post = create(:installment, link: product, shown_on_profile: true, send_emails: false, published_at: 5.minutes.ago, paid_more_than_cents: 100)
profile_only_post_2 = create(:installment, link: product, shown_on_profile: true, send_emails: false, published_at: 35.minutes.ago) # Published before purchase
purchase_2 = create(:purchase)
installment_2 = create(:installment, link: purchase_2.link, published_at: Time.current)
create(:creator_contacting_customers_email_info_sent, purchase: purchase_2, installment: installment_2)
create(:purchase, link: product, email: purchase_2.email)
purchase_3 = create(:purchase)
installment_3 = create(:installment, link: purchase_3.link, published_at: Time.current)
create(:creator_contacting_customers_email_info_sent, purchase: purchase_3, installment: installment_3, sent_at: 4.minutes.from_now)
profile_only_seller_post = create(:seller_installment, send_emails: false, shown_on_profile: true, seller: purchase_3.link.user, published_at: 10.minutes.ago, json_data: { bought_products: [purchase_3.link.unique_permalink, create(:product).unique_permalink] })
create(:seller_installment, send_emails: false, shown_on_profile: true, seller: create(:user), published_at: Time.current)
expect(Purchase.product_installments(purchase_ids: [purchase_1.id, purchase_3.id])).to match_array([installment_3, profile_only_post, profile_only_seller_post, seller_post, seller_post_2, seller_post_for_variant, installment_1, profile_only_post_2])
expect(Purchase.product_installments(purchase_ids: [purchase_2.id])).to eq([installment_2])
end
context "when purchased product(s) have should_show_all_posts enabled" do
let(:enabled_product) { create(:product, should_show_all_posts: true) }
let(:enabled_product_variant) { create(:variant, variant_category: create(:variant_category, link: enabled_product)) }
let(:enabled_purchase) { create(:purchase, link: enabled_product, seller: enabled_product.user) }
let(:enabled_purchase_with_variant) { create(:purchase, link: enabled_product, variant_attributes: [enabled_product_variant]) }
it "returns all posts for purchases of products" do
enabled_product_post = create(:installment, link: enabled_product, published_at: 1.day.ago)
create(:installment, link: enabled_product, published_at: 1.day.ago, created_before: enabled_purchase.created_at - 1.hour)
enabled_product_variant_post = create(:variant_installment, link: enabled_product, published_at: 1.day.ago, base_variant: enabled_product_variant)
multi_product_post = create(:seller_installment, seller: enabled_product.user, published_at: 1.day.ago, bought_products: [enabled_product.unique_permalink])
multi_product_variant_post = create(:seller_installment, seller: enabled_product.user, published_at: 1.day.ago, bought_products: [create(:product, user: enabled_product.user).unique_permalink], bought_variants: [enabled_product_variant.external_id])
create(:creator_contacting_customers_email_info_sent, purchase: enabled_purchase, installment: enabled_product_post)
disabled_product = create(:product, should_show_all_posts: false)
disabled_product_variant = create(:variant, variant_category: create(:variant_category, link: enabled_product))
disabled_purchase = create(:purchase, link: disabled_product, seller: disabled_product.user)
disabled_purchase_with_variant = create(:purchase, link: disabled_product, variant_attributes: [disabled_product_variant])
create(:installment, link: disabled_product, published_at: 1.day.ago)
create(:variant_installment, link: disabled_product, published_at: 1.day.ago, base_variant: disabled_product_variant)
create(:seller_installment, seller: disabled_product.user, published_at: 1.day.ago, bought_products: [disabled_product.unique_permalink])
create(:seller_installment, seller: disabled_product.user, published_at: 1.day.ago, bought_products: [disabled_product.unique_permalink], bought_variants: [disabled_product_variant.external_id])
expect(Purchase.product_installments(purchase_ids: [disabled_purchase.id, disabled_purchase_with_variant.id])).to be_empty
expect(Purchase.product_installments(purchase_ids: [enabled_purchase.id]).map(&:id)).to match_array [enabled_product_post, multi_product_post].map(&:id)
expect(Purchase.product_installments(purchase_ids: [enabled_purchase_with_variant.id]).map(&:id)).to match_array [enabled_product_post, enabled_product_variant_post, multi_product_post, multi_product_variant_post].map(&:id)
expect(Purchase.product_installments(purchase_ids: [enabled_purchase.id, enabled_purchase_with_variant.id, disabled_purchase.id, disabled_purchase_with_variant.id]).map(&:id)).to match_array [enabled_product_post, enabled_product_variant_post, multi_product_post, multi_product_variant_post].map(&:id)
end
it "excludes past posts that are not directly targeted at the purchased product or variant" do
create(:seller_installment, seller: enabled_product.user, published_at: 1.day.ago)
create(:seller_installment, seller: enabled_product.user, published_at: 1.day.ago, bought_products: [create(:product).unique_permalink])
create(:seller_installment, seller: enabled_product.user, published_at: 1.day.ago, bought_variants: [create(:variant).external_id])
expect(Purchase.product_installments(purchase_ids: [enabled_purchase.id, enabled_purchase_with_variant.id])).to eq []
end
end
end
describe "#product_installments" do
before do
@seller = create(:user)
@product = create(:product, user: @seller)
end
describe "link installments" do
before do
@post1 = create(:installment, link: @product, published_at: 1.week.ago)
@post2 = create(:installment, link: @product, published_at: 1.hour.ago)
@post3 = create(:installment, link: @product)
@post4 = create(:installment, link: @product, published_at: 1.week.ago, deleted_at: Time.current)
@profile_only_post = create(:installment, link: @product, shown_on_profile: true, send_emails: false, published_at: 1.hour.ago)
end
it "only includes published installments" do
purchase = create(:purchase, link: @product, created_at: Time.current, price_cents: 100)
create(:creator_contacting_customers_email_info_sent, purchase:, installment: @post2)
installments = purchase.product_installments
expect(installments.count).to eq(2)
expect(installments.include?(@post1)).to be(false)
expect(installments.include?(@post2)).to be(true)
expect(installments.include?(@post3)).to be(false)
expect(installments.include?(@post4)).to be(false)
expect(installments.include?(@profile_only_post)).to be(true)
end
describe "variant installments" do
it "only includes installments from the purchased variant" do
category = create(:variant_category, title: "title", link: @product)
variant1 = create(:variant, variant_category: category, name: "V1")
variant2 = create(:variant, variant_category: category, name: "V1")
variant_installment1 = create(:installment, link: @product, base_variant: variant1, installment_type: "variant", published_at: Time.current)
create(:installment, link: @product, base_variant: variant2, installment_type: "variant", published_at: 5.minutes.ago)
variant1_profile_only_post = create(:installment, link: @product, shown_on_profile: true, send_emails: false, base_variant: variant1, installment_type: "variant", published_at: 10.minutes.ago)
purchase = create(:purchase, link: @product, created_at: Time.current, price_cents: 100)
purchase.variant_attributes << variant1
create(:creator_contacting_customers_email_info_sent, purchase:, installment: @post2, sent_at: 3.hours.from_now)
create(:creator_contacting_customers_email_info_sent, purchase:, installment: variant_installment1, sent_at: 4.hours.from_now)
installments = purchase.product_installments
expect(installments).to eq([variant_installment1, @post2, variant1_profile_only_post, @profile_only_post])
variant_purchase = create(:purchase, link: @product)
variant_purchase.variant_attributes << variant1
variants_specific_seller_post = create(:seller_installment, seller: @product.user, published_at: 5.hours.ago)
variants_specific_seller_post.bought_variants = [variant1.external_id, create(:variant, variant_category: category).external_id]
variants_specific_seller_post.save!
create(:creator_contacting_customers_email_info_sent, purchase: variant_purchase, installment: variants_specific_seller_post, sent_at: 1.week.ago)
profile_only_seller_post = create(:seller_installment, send_emails: false, shown_on_profile: true, seller: @product.user, published_at: 6.hours.ago)
profile_only_seller_post.bought_variants = [variant1.external_id, create(:variant, variant_category: category).external_id]
profile_only_seller_post.save!
seller_post_other_variants = create(:seller_installment, send_emails: false, shown_on_profile: true, seller: @product.user, published_at: Time.current)
seller_post_other_variants.bought_variants = [variant2. external_id, create(:variant, variant_category: category).external_id]
seller_post_other_variants.save!
installments = variant_purchase.product_installments
expect(installments).to eq([variant1_profile_only_post, @profile_only_post, profile_only_seller_post, variants_specific_seller_post])
end
end
end
describe "workflow installments" do
it "gets installments only from product workflow" do
@product.update!(should_show_all_posts: true)
product_workflow = create(:workflow, seller: @seller, link: @product, created_at: 1.week.ago)
seller_workflow = create(:workflow, seller: @seller, link: nil, created_at: 1.week.ago)
installment1 = create(:installment, workflow: seller_workflow, published_at: Time.current)
create(:installment_rule, installment: installment1, delayed_delivery_time: 3.days)
installment2 = create(:installment, link: @product, workflow: product_workflow, published_at: Time.current)
create(:installment_rule, installment: installment2, delayed_delivery_time: 3.days)
installment3 = create(:installment, link: @product, workflow: product_workflow, published_at: Time.current)
create(:installment_rule, installment: installment3, delayed_delivery_time: 1.day)
installment4 = create(:installment, link: @product, workflow: product_workflow, published_at: Time.current)
create(:installment_rule, installment: installment4, delayed_delivery_time: 3.days)
purchase = create(:purchase, link: @product, created_at: 5.days.ago, price_cents: 100)
create(:creator_contacting_customers_email_info_sent, purchase:, installment: installment2)
create(:creator_contacting_customers_email_info_sent, purchase:, installment: installment3)
installments = purchase.product_installments
expect(installments.count).to eq(2)
expect(installments.include?(installment1)).to be(false)
expect(installments.include?(installment2)).to be(true)
expect(installments.include?(installment3)).to be(true)
expect(installments.include?(installment4)).to be(false)
end
end
describe "link and workflow" do
it "includes installments in the correct order" do
@product.update!(should_show_all_posts: true)
installment1 = create(:installment, link: @product, published_at: 2.days.ago)
past_installment = create(:installment, link: @product, published_at: 1.week.ago)
workflow = create(:workflow, seller: @seller, link: @product, created_at: 1.week.ago)
workflow_installment = create(:installment, workflow:, published_at: 1.day.ago)
create(:installment_rule, installment: workflow_installment, delayed_delivery_time: 1.day)
create(:installment, workflow:, link: @product, published_at: 1.day.ago)
profile_only_installment = create(:installment, link: @product, shown_on_profile: true, send_emails: false, published_at: 1.minutes.ago)
purchase = create(:purchase, link: @product, created_at: 2.days.ago, price_cents: 100)
create(:creator_contacting_customers_email_info_sent, purchase:, installment: installment1, sent_at: 2.minute.ago)
create(:creator_contacting_customers_email_info_opened, purchase:, installment: workflow_installment, sent_at: 1.hour.ago, opened_at: 5.minutes.ago)
installments = purchase.product_installments
expect(installments).to eq([profile_only_installment, installment1, workflow_installment, past_installment])
end
end
describe "mobile api" do
before do
@product = create(:product)
@product.product_files << create(
:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter1.mp4"
)
@purchase = create(:purchase_with_balance, link: @product)
end
it "does not throw an exception when a url redirect for a purchase is nil" do
@purchase.url_redirect = nil
@purchase.save!
expect { @purchase.json_data_for_mobile }.not_to raise_error
end
it "returns update information if available" do
good_installment = create(:installment, link: @product, published_at: Time.current, name: "Good installment")
create(:installment, link: @product, published_at: 10.hours.ago, name: "old published installment")
create(:installment, link: @product, published_at: Time.current, deleted_at: Time.current, name: "deleted installment")
create(:installment, link: @product, name: "should not appear")
create(:creator_contacting_customers_email_info_sent, purchase: @purchase, installment: good_installment)
json_data = @purchase.json_data_for_mobile
expect(json_data[:updates_data]).to eq nil
expect(json_data[:product_updates_data].as_json).to eq [good_installment.installment_mobile_json_data(purchase: @purchase)].as_json
end
it "returns subscription expiration information for a subscription purchase" do
purchase = create(:membership_purchase)
ended_at = 1.day.ago
subscription = purchase.subscription
subscription.update!(deactivated_at: ended_at, failed_at: ended_at)
json_data = purchase.json_data_for_mobile
expect(json_data[:subscription_data]).to be_present
expect(json_data[:subscription_data][:subscribed_at]).to eq subscription.created_at.as_json
expect(json_data[:subscription_data][:id]).to eq subscription.external_id
expect(json_data[:subscription_data][:ended_at]).to eq ended_at.as_json
expect(json_data[:subscription_data][:ended_reason]).to eq "failed_payment"
end
end
describe "creator api" do
before do
@free_purchase = create(:purchase, link: create(:product, price_range: "0+"), price_cents: 0, stripe_transaction_id: nil, stripe_fingerprint: nil)
@paid_purchase = create(:purchase)
end
it "returns the correct json format for free purchase" do
json_response = @free_purchase.as_json(creator_app_api: true)
expect(json_response[:email]).to eq @free_purchase.email
expect(json_response[:timestamp]).to eq "less than a minute ago"
expect(json_response[:created_at]).to eq @free_purchase.created_at
expect(json_response[:price]).to eq "$0"
expect(json_response[:link_name]).to eq @free_purchase.link.name
expect(json_response[:alert]).to eq "New download of #{@free_purchase.link.name}"
end
it "returns the correct json format for nonfree purchase" do
@paid_purchase = create(:purchase)
json_response = @paid_purchase.as_json(creator_app_api: true)
expect(json_response[:email]).to eq @paid_purchase.email
expect(json_response[:timestamp]).to eq "less than a minute ago"
expect(json_response[:created_at]).to eq @paid_purchase.created_at
expect(json_response[:price]).to eq "$1"
expect(json_response[:link_name]).to eq @paid_purchase.link.name
expect(json_response[:alert]).to eq "New sale of #{@paid_purchase.link.name} for #{@paid_purchase.formatted_total_price}"
end
end
it "calls class method .product_installments for current purchase" do
purchase = create(:purchase)
installments_double = double
expect(Purchase).to receive(:product_installments).with(purchase_ids: [purchase.id]).and_return(installments_double)
expect(purchase.product_installments).to eq(installments_double)
end
end
describe "#update_json_data_for_mobile" do
let(:user) { create(:user, credit_card: create(:credit_card)) }
context "for subscriptions" do
let(:product) { create(:subscription_product) }
let(:subscription) { create(:subscription, user:, link: product) }
let(:purchase_1) do create(:purchase, link: product, email: user.email,
is_original_subscription_purchase: true,
subscription:, created_at: 2.days.ago) end
let(:post_1) { create(:installment, link: purchase_1.link, published_at: 1.day.ago) }
let(:subject) { purchase_1.update_json_data_for_mobile }
before do
create(:creator_contacting_customers_email_info_sent, purchase: purchase_1, installment: post_1, sent_at: 1.hour.ago)
end
it "returns posts for all purchases of the product" do
subscription_2 = create(:subscription, user: subscription.user, link: product)
purchase_2 = create(:purchase, link: product, email: subscription_2.user.email,
is_original_subscription_purchase: true,
subscription: subscription_2, created_at: 1.day.ago)
post_2 = create(:installment, link: purchase_2.link, published_at: 1.hour.ago)
create(:creator_contacting_customers_email_info_sent, purchase: purchase_2, installment: post_2, sent_at: 2.hours.ago)
purchase_3 = create(:purchase, link: product, email: subscription_2.user.email,
is_original_subscription_purchase: false,
subscription: subscription_2, created_at: 1.hour.ago)
post_3 = create(:installment, link: purchase_3.link, published_at: Time.current)
create(:creator_contacting_customers_email_info_sent, purchase: purchase_3, installment: post_3, sent_at: 1.hour.from_now)
all_posts = [post_3.external_id, post_1.external_id, post_2.external_id]
expect(purchase_1.update_json_data_for_mobile.size).to eq(3)
expect(purchase_1.update_json_data_for_mobile.map { |post| post[:external_id] }).to eq(all_posts)
expect(purchase_2.update_json_data_for_mobile.size).to eq(3)
expect(purchase_2.update_json_data_for_mobile.map { |post| post[:external_id] }).to eq(all_posts)
expect(purchase_3.update_json_data_for_mobile.size).to eq(3)
expect(purchase_3.update_json_data_for_mobile.map { |post| post[:external_id] }).to eq(all_posts)
end
context "when it is deactivated" do
let(:subscription) { create(:subscription, user:, link: product, deactivated_at: Time.current) }
context "and access is blocked on cancellation" do
let(:product) { create(:subscription_product, block_access_after_membership_cancellation: true) }
it "does not return posts" do
expect(subject).to be_empty
end
end
context "when access not blocked on cancellation" do
let(:product) { create(:subscription_product, block_access_after_membership_cancellation: false) }
it "does return posts" do
expect(subject).to match_array(a_hash_including(external_id: post_1.external_id))
end
end
end
end
context "for products" do
let(:product) { create(:product, is_licensed: true) }
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, price_cents: 100, license: create(:license)) }
let(:installment) { create(:installment, link: purchase.link, published_at: Time.current) }
let(:subject) { purchase.update_json_data_for_mobile }
before do
create(:creator_contacting_customers_email_info, purchase:, installment:)
end
shared_examples "not returns post" do
it "does not return posts" do
expect(subject).to be_empty
end
end
shared_examples "returns post" do
it "does return posts" do
expect(subject).to match_array(a_hash_including(external_id: installment.external_id))
end
end
context "with a failed purchase" do
let(:purchase) { create(:failed_purchase, purchaser: user, email: user.email, link: product) }
include_examples "not returns post"
end
context "with fully refunded purchase" do
let(:purchase) { create(:refunded_purchase, purchaser: user, email: user.email, link: product, price_cents: 100, license: create(:license)) }
include_examples "not returns post"
end
context "with chargedback purchase" do
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, price_cents: 100, license: create(:license), chargeback_date: Time.current) }
include_examples "not returns post"
end
context "with chargedback purchase" do
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, price_cents: 100, license: create(:license), chargeback_date: Time.current) }
include_examples "not returns post"
end
context "with gift sent purchase" do
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, is_gift_sender_purchase: true) }
include_examples "not returns post"
end
context "with chargedback reversed purchase" do
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, price_cents: 100, license: create(:license), chargeback_date: Time.current, chargeback_reversed: true) }
include_examples "returns post"
end
context "with partially refunded purchases" do
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, stripe_partially_refunded: true) }
include_examples "returns post"
end
context "with test purchases" do
let(:purchase) { create(:test_purchase, purchaser: user, email: user.email, link: product) }
include_examples "returns post"
end
context "with gift received purchase" do
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, is_gift_receiver_purchase: true) }
include_examples "returns post"
end
end
context "lapsed subscriptions" do
before do
@purchase = create(:membership_purchase)
@purchase.subscription.update!(cancelled_at: 1.day.ago)
@product = @purchase.link
post = create(:seller_installment, seller: @product.user,
bought_products: [@product.unique_permalink],
published_at: 1.day.ago)
create(:creator_contacting_customers_email_info, installment: post, purchase: @purchase)
end
it "returns an empty array when user should lose access after cancellation" do
@product.update!(block_access_after_membership_cancellation: true)
expect(@purchase.update_json_data_for_mobile).to eq []
end
it "returns content when user should not lose access after cancellation" do
expect(@purchase.update_json_data_for_mobile).not_to be_empty
end
end
context "updated subscriptions" do
it "returns posts associated with all purchases, including the updated original purchase" do
product = create(:membership_product)
subscription = create(:subscription, link: product)
email = generate(:email)
old_purchase = create(:membership_purchase, link: product, subscription:, email:, is_archived_original_subscription_purchase: true)
new_purchase = create(:membership_purchase, link: product, subscription:, email:, purchase_state: "not_charged")
subscription.reload
post_1 = create(:installment, link: product, published_at: 1.day.ago)
create(:creator_contacting_customers_email_info_sent, purchase: new_purchase, installment: post_1, sent_at: 1.hour.ago)
post_2 = create(:installment, link: product, published_at: 1.day.ago)
create(:creator_contacting_customers_email_info_sent, purchase: old_purchase, installment: post_2, sent_at: 1.hour.ago)
expect(old_purchase.update_json_data_for_mobile.map { |post| post[:external_id] }).to match_array [post_1.external_id, post_2.external_id]
expect(new_purchase.update_json_data_for_mobile.map { |post| post[:external_id] }).to match_array [post_1.external_id, post_2.external_id]
end
end
end
describe "#schedule_workflows" do
before do
@product = create(:product)
@workflow = create(:workflow, seller: @product.user, link: @product, created_at: Time.current)
@installment = create(:installment, link: @product, workflow: @workflow, published_at: Time.current)
create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day)
@purchase = create(:purchase, link: @product)
end
it "enqueues SendWorkflowInstallmentWorker for the workflow installments" do
@purchase.schedule_workflows([@workflow])
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@installment.id, 1, @purchase.id, nil, nil)
end
it "schedules matching non-abandoned cart workflow installments" do
abandoned_cart_workflow = create(:abandoned_cart_workflow, published_at: 1.day.ago, seller_id: @purchase.seller_id, bought_products: [@product.unique_permalink])
abandoned_cart_workflow_installment = abandoned_cart_workflow.installments.sole
abandoned_cart_workflow_installment_rule = create(:installment_rule, installment: abandoned_cart_workflow_installment, time_period: "hour", delayed_delivery_time: 24.hours)
@purchase.schedule_workflows(Workflow.all)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(1)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@installment.id, @installment.installment_rule.version, @purchase.id, nil, nil)
expect(SendWorkflowInstallmentWorker).to_not have_enqueued_sidekiq_job(abandoned_cart_workflow_installment.id, abandoned_cart_workflow_installment_rule.version, @purchase.id, nil, nil)
end
end
describe "#schedule_workflows_for_variants" do
before do
@product = create(:product)
vc = create(:variant_category, link: @product)
@variant1 = create(:variant, variant_category: vc)
@variant2 = create(:variant, variant_category: vc)
# product workflow
@product_workflow = create(:workflow, seller: @product.user, link: @product, created_at: Time.current)
@product_installment = create(:installment, link: @product, workflow: @product_workflow, published_at: Time.current)
create(:installment_rule, installment: @product_installment, delayed_delivery_time: 1.day)
# variant 1 workflow
@variant1_workflow = create(:variant_workflow, seller: @product.user, link: @product, base_variant: @variant1)
@variant1_installment = create(:installment, link: @product, workflow: @variant1_workflow, published_at: Time.current)
create(:installment_rule, installment: @variant1_installment, delayed_delivery_time: 1.day)
# variant 2 workflow
@variant2_workflow = create(:variant_workflow, seller: @product.user, link: @product, base_variant: @variant2)
@variant2_installment = create(:installment, link: @product, workflow: @variant2_workflow, published_at: Time.current)
create(:installment_rule, installment: @variant2_installment, delayed_delivery_time: 1.day)
# seller workflow targeting variant 1
@seller_workflow_variant_1 = create(:seller_workflow, seller: @product.user, bought_variants: [@variant1.external_id])
@seller_variant_1_installment = create(:installment, link: @product, workflow: @seller_workflow_variant_1, published_at: Time.current)
create(:installment_rule, installment: @seller_variant_1_installment, delayed_delivery_time: 1.day)
# seller workflow targeting variant 2
@seller_workflow_variant_2 = create(:seller_workflow, seller: @product.user, bought_variants: [@variant2.external_id])
@seller_variant_2_installment = create(:installment, link: @product, workflow: @seller_workflow_variant_2, published_at: Time.current)
create(:installment_rule, installment: @seller_variant_2_installment, delayed_delivery_time: 1.day)
# seller workflow targeting both variants
@seller_workflow_both_variants = create(:seller_workflow, seller: @product.user, bought_variants: [@variant1.external_id, @variant2.external_id])
@seller_both_variants_installment = create(:installment, link: @product, workflow: @seller_workflow_both_variants, published_at: Time.current)
create(:installment_rule, installment: @seller_both_variants_installment, delayed_delivery_time: 1.day)
# seller workflow targeting neither variant
@seller_workflow_neither_variant = create(:seller_workflow, seller: @product.user, bought_variants: [create(:variant).external_id])
@seller_neither_variant_installment = create(:installment, link: @product, workflow: @seller_workflow_neither_variant, published_at: Time.current)
create(:installment_rule, installment: @seller_neither_variant_installment, delayed_delivery_time: 1.day)
# seller workflow targeting product
@seller_workflow_product = create(:seller_workflow, seller: @product.user, bought_products: [@product.unique_permalink])
@seller_product_installment = create(:installment, link: @product, workflow: @seller_workflow_product, published_at: Time.current)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_sales_tax_spec.rb | spec/models/purchase/purchase_sales_tax_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PurchaseSalesTax", :vcr do
include CurrencyHelper
include ProductsHelper
describe "sales tax" do
let(:chargeable) { build(:chargeable) }
let(:price) { 10_00 }
let(:buyer_zip) { nil } # forces using ip by default
let(:link_is_physical) { false }
before(:context) do
@price_cents = 10_00
@fee_cents = 10_00 * 0.129 + 50 + 30 # 10%+50c Gumroad fee + 2.9%+30c cc fee
@buyer_zip = nil # forces using ip by default
@product_is_physical = false
@tax_state = "CA"
@tax_zip = "94107"
@tax_country = "US"
@tax_combined_rate = 0.01
@tax_is_seller_responsible = true
@purchase_country = nil
@purchase_ip_country = nil
@purchase_chargeable_country = nil
@purchase_transaction_amount = nil
@amount_for_gumroad_cents = @fee_cents
@was_product_recommended = false
end
before(:example) do
@seller = create(:user)
@product = create(:product, user: @seller, price_cents: @price_cents)
@product.is_physical = @product_is_physical
@product.require_shipping = @product_require_shipping
@product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0)
@product.save!
@purchase = if @product_is_physical
create(:purchase,
chargeable:,
price_cents: @price_cents,
seller: @seller,
link: @product,
ip_country: @purchase_ip_country,
purchase_state: "in_progress",
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
country: "United States",
state: "CA",
city: "San Francisco",
zip_code: @buyer_zip || "94017",
was_product_recommended: @was_product_recommended)
else
create(:purchase,
chargeable:,
price_cents: @price_cents,
seller: @seller,
link: @product,
zip_code: @buyer_zip,
country: @purchase_country,
ip_country: @purchase_ip_country,
purchase_state: "in_progress",
was_product_recommended: @was_product_recommended)
end
@zip_tax_rate = create(:zip_tax_rate, zip_code: @tax_zip, state: @tax_state, country: @tax_country,
combined_rate: @tax_combined_rate, is_seller_responsible: @tax_is_seller_responsible)
allow(@purchase).to receive(:card_country) { @purchase_chargeable_country }
if @purchase_transaction_amount.present?
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).with(
anything, anything, @purchase_transaction_amount, @amount_for_gumroad_cents, anything, anything, anything
).and_call_original
end
@purchase.process!
end
it "is recorded" do
expect(@purchase).to respond_to(:tax_cents)
expect(@purchase).to respond_to(:gumroad_tax_cents)
end
describe "with a default (not taxable) seller and a purchase without a zip code" do
it "is not included" do
allow(@purchase).to receive(:best_guess_zip).and_return(nil)
expect(@purchase.tax_cents).to be_zero
expect(@purchase.gumroad_tax_cents).to be_zero
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.total_transaction_cents).to eq(10_00)
expect(@purchase.was_purchase_taxable).to be(false)
end
end
describe "with a default (not taxable) seller and a purchase with a zip code" do
@buyer_zip = "94107"
it "is not included" do
expect(@purchase.tax_cents).to be_zero
expect(@purchase.gumroad_tax_cents).to be_zero
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.total_transaction_cents).to eq(10_00)
expect(@purchase.was_purchase_taxable).to be(false)
end
end
describe "with a US taxable seller" do
before(:context) do
@product_is_physical = true
@product_require_shipping = true
@tax_country = "US"
end
describe "when a purchase is made from a non-nexus state" do
before(:context) do
@tax_state = "TX"
end
it "does not have taxes" do
expect(@purchase.tax_cents).to be_zero
expect(@purchase.gumroad_tax_cents).to be_zero
expect(@purchase.total_transaction_cents).to eq(10_00)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.was_purchase_taxable).to be(false)
end
end
describe "when a purchase is made from a taxable state" do
context "when TaxJar is used for tax calculation" do
before(:context) do
@buyer_zip = "98121"
@was_product_recommended = true
end
it "stores purchase_taxjar_info" do
taxjar_info = @purchase.purchase_taxjar_info
expect(taxjar_info).to be_present
expect(taxjar_info.combined_tax_rate).to eq(0.1025)
expect(taxjar_info.state_tax_rate).to eq(0.065)
expect(taxjar_info.county_tax_rate).to eq(0.003)
expect(taxjar_info.city_tax_rate).to eq(0.0115)
expect(taxjar_info.jurisdiction_state).to eq("WA")
expect(taxjar_info.jurisdiction_county).to eq("KING")
expect(taxjar_info.jurisdiction_city).to eq("SEATTLE")
end
end
end
end
describe "VAT" do
before(:context) do
@tax_state = nil
@tax_zip = nil
@tax_country = "GB"
@tax_combined_rate = 0.22
@tax_is_seller_responsible = false
end
describe "in eligible and successful purchase" do
before(:context) do
@purchase_country = "United Kingdom"
@purchase_chargeable_country = "GB"
@purchase_ip_country = "Spain"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 4_29
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "location verification with available zip tax entry" do
before(:context) do
@tax_combined_rate = 0.22
end
describe "IP address in EU , card country in EU, country = ip" do
before(:context) do
@tax_country = "GB"
@purchase_country = "United Kingdom"
@purchase_chargeable_country = "ES"
@purchase_ip_country = "United Kingdom"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 4_29
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address in EU , card country in EU, country = card country" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "ES"
@purchase_ip_country = "United Kingdom"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 4_29
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address in EU , card country in EU, country != either and in EU" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "DE"
@purchase_ip_country = "United Kingdom"
end
before(:example) do
expect(ChargeProcessor).to_not receive(:create_payment_intent_or_charge!).with(anything, anything, chargeable, @purchase_transaction_amount, anything, anything, anything)
end
it "fails validation" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "IP address in EU , card country in EU, country != either and not in EU" do
before(:context) do
@tax_country = "TG"
@purchase_country = "Togo"
@purchase_chargeable_country = "DE"
@purchase_ip_country = "United Kingdom"
end
it "fails validation" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "IP address in EU , card country in EU, IP country = card country, country != either and not in EU" do
before(:context) do
@tax_country = "TG"
@purchase_country = "Togo"
@purchase_chargeable_country = "GB"
@purchase_ip_country = "United Kingdom"
end
it "fails validation" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "IP address in EU , card country not in EU, country != either and in EU" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "AU"
@purchase_ip_country = "United Kingdom"
end
it "fails validation" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "IP address not in EU , card country in EU, country != either and in EU" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "DE"
@purchase_ip_country = "United States"
end
it "fails validation" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "IP address non EU , card country non EU, country != either and in EU" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "IN"
@purchase_ip_country = "United States"
@purchase_transaction_amount = 10_00
end
it "resets tax and proceeds with purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address in EU , card country non EU, country != either and not in EU" do
before(:context) do
@purchase_country = "Togo"
@purchase_chargeable_country = "AU"
@purchase_ip_country = "United Kingdom"
end
it "fails validation" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "IP address non EU , card country non EU, country != either and not in EU" do
before(:context) do
@purchase_country = "Togo"
@purchase_chargeable_country = "IN"
@purchase_ip_country = "United States"
@purchase_transaction_amount = 10_00
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address in EU, card country in EU, country in non-EU and product is physical" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = "GB"
@purchase_ip_country = "United Kingdom"
@product_is_physical = true
@product_require_shipping = true
@purchase_transaction_amount = 10_00
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address in EU, card country in nil, country in EU (matching)" do
before(:context) do
@purchase_country = "United Kingdom"
@purchase_chargeable_country = nil
@purchase_ip_country = "United Kingdom"
@amount_for_gumroad_cents = 3_79
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address EU, card country in nil, country in non-EU" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = nil
@purchase_ip_country = "United Kingdom"
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address non-EU, card country in nil, country in non-EU (matching)" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = nil
@purchase_ip_country = "United States"
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address EU, card country in EU, country is nil" do
before(:context) do
@purchase_country = nil
@purchase_chargeable_country = "GB"
@purchase_ip_country = "United Kingdom"
@amount_for_gumroad_cents = 4_29
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address Australia, card country in Australia, country is nil" do
before(:context) do
@tax_country = "AU"
@tax_combined_rate = 0.10
@purchase_country = nil
@purchase_chargeable_country = "AU"
@purchase_ip_country = "Australia"
@amount_for_gumroad_cents = 4_29
end
it "is GST eligible and GST is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(1_00)
expect(@purchase.total_transaction_cents).to eq(11_00)
end
end
end
describe "validates buyer location election for EU" do
before(:context) do
@purchase_country = "United Kingdom"
@purchase_ip_country = "Spain"
@purchase_chargeable_country = "ES"
end
it "when purchase country cannot be matched with either ip country or credit card country" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "validates buyer location election for Australia" do
before(:context) do
@purchase_country = "United States"
@purchase_ip_country = "Australia"
@purchase_chargeable_country = "AU"
end
it "when purchase country cannot be matched with either ip country or credit card country" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "validates buyer location election for Canada" do
before(:context) do
@purchase_country = "United States"
@purchase_ip_country = "Canada"
@purchase_chargeable_country = "CA"
end
it "raises an error when purchase country cannot be matched with either ip country or credit card country" do
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED)
end
end
describe "physical products" do
before(:context) do
@product_is_physical = true
@product_require_shipping = true
end
it "does not calculate VAT for a physical product" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_balances_spec.rb | spec/models/purchase/purchase_balances_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PurchaseBalances", :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
describe "proper Balance creation and association with purchases" do
let(:physical) { false }
let(:admin_user) { create(:admin_user) }
before do
@user = create(:user)
@product = create(:product, user: @user, is_physical: physical, require_shipping: physical, shipping_destinations: [(create(:shipping_destination) if physical)].compact)
@old_date = Date.today - 10
travel_to(@old_date) do
# purchase_1 = prior to having a merchant account
@purchase_1 = create(:purchase, chargeable: build(:chargeable), seller: @user, link: @product, purchase_state: "in_progress", price_cents: 100, fee_cents: 30,
full_name: "Edgar Gumstein", street_address: "123 Gum Road", state: "CA", city: "San Francisco", zip_code: "94017", country: "United States")
@purchase_1.process!
@purchase_1.update_balance_and_mark_successful!
# purchase_2 = with a merchant account
@merchant_account = create(:merchant_account_stripe, user: @user)
@user.reload
@product.price_cents = 200
@product.save
@purchase_2 = create(:purchase, chargeable: build(:chargeable), seller: @user, link: @product, purchase_state: "in_progress", price_cents: 200, fee_cents: 35,
full_name: "Edgar Gumstein", street_address: "123 Gum Road", state: "CA", city: "San Francisco", zip_code: "94017", country: "United States")
@purchase_2.process!
@purchase_2.update_balance_and_mark_successful!
end
@gumroad_merchant_account = MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)
end
describe "digital" do
let(:physical) { false }
it "associates the balance with the purchase and have the proper amount" do
balance_1, balance_2 = Balance.last(2)
expect(balance_1).to eq @purchase_1.purchase_success_balance
expect(balance_1.date).to eq @old_date
expect(balance_1.amount_cents).to eq 7 # 100c price - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
expect(balance_1.merchant_account).to eq(@gumroad_merchant_account)
expect(balance_2).to eq @purchase_2.purchase_success_balance
expect(balance_2.date).to eq @old_date
expect(balance_2.amount_cents).to eq 94 # 200c price - 20c (10% flat fee) - 50c (fixed fee) - 6c (2.9% cc fee) - 30c (fixed cc fee)
expect(balance_2.merchant_account).to eq(@merchant_account)
expect(@user.unpaid_balance_cents).to eq 101
end
it "uses the same balance for refund/chargeback as the one used for the original purchase (if unpaid)" do
purchase_balance_1 = @purchase_1.purchase_success_balance
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_1.refund_and_save!(admin_user.id)
end
refund_balance_1 = @purchase_1.reload.purchase_refund_balance
expect(refund_balance_1).to eq purchase_balance_1
purchase_balance_2 = @purchase_2.purchase_success_balance
@purchase_2.refund_and_save!(admin_user.id)
refund_balance_2 = @purchase_2.reload.purchase_refund_balance
expect(refund_balance_2).to eq purchase_balance_2
end
it "uses the oldest unpaid balance for refund/chargeback if the original purchase balance is not unpaid" do
purchase_balance_1 = @purchase_1.purchase_success_balance
purchase_balance_1.update_attribute(:state, "paid")
old_unpaid_balance_1 = create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today - 9)
create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today)
purchase_balance_2 = @purchase_2.purchase_success_balance
purchase_balance_2.update_attribute(:state, "paid")
old_unpaid_balance_2 = create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today - 9)
create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today)
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_1.refund_and_save!(admin_user.id)
end
refund_balance_1 = @purchase_1.reload.purchase_refund_balance
expect(refund_balance_1).to eq old_unpaid_balance_1
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_2.refund_and_save!(admin_user.id)
end
refund_balance_2 = @purchase_2.reload.purchase_refund_balance
expect(refund_balance_2).to eq old_unpaid_balance_2
end
it "uses today's balance for refund/chargeback if the original purchase balance is not unpaid and there are no older unpaid balances" do
purchase_balance_1 = @purchase_1.purchase_success_balance
purchase_balance_1.mark_processing!
purchase_balance_1.mark_paid!
old_paid_balance_1 = create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today - 9)
old_paid_balance_1.mark_processing!
old_paid_balance_1.mark_paid!
today_unpaid_balance_1 = create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today)
purchase_balance_2 = @purchase_2.purchase_success_balance
purchase_balance_2.mark_processing!
purchase_balance_2.mark_paid!
old_paid_balance_2 = create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today - 9)
old_paid_balance_2.mark_processing!
old_paid_balance_2.mark_paid!
today_unpaid_balance_2 = create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today)
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_1.refund_and_save!(admin_user.id)
end
refund_balance_1 = @purchase_1.reload.purchase_refund_balance
expect(refund_balance_1).to eq today_unpaid_balance_1
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_2.refund_and_save!(admin_user.id)
end
refund_balance_2 = @purchase_2.reload.purchase_refund_balance
expect(refund_balance_2).to eq today_unpaid_balance_2
end
end
describe "physical" do
let(:physical) { true }
it "associates the balance with the purchase and have the proper amount" do
balance_1, balance_2 = Balance.last(2)
expect(balance_1).to eq @purchase_1.purchase_success_balance
expect(balance_1.date).to eq @old_date
expect(balance_1.amount_cents).to eq 7
expect(balance_1.merchant_account).to eq(@gumroad_merchant_account)
expect(balance_2).to eq @purchase_2.purchase_success_balance
expect(balance_2.date).to eq @old_date
expect(balance_2.amount_cents).to eq 94
expect(balance_2.merchant_account).to eq(@merchant_account)
expect(@user.unpaid_balance_cents).to eq 101
end
it "uses the same balance for refund/chargeback as the one used for the original purchase (if unpaid)" do
purchase_balance_1 = @purchase_1.purchase_success_balance
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_1.refund_and_save!(admin_user.id)
end
refund_balance_1 = @purchase_1.reload.purchase_refund_balance
expect(refund_balance_1).to eq purchase_balance_1
purchase_balance_2 = @purchase_2.purchase_success_balance
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_2.refund_and_save!(admin_user.id)
end
refund_balance_2 = @purchase_2.reload.purchase_refund_balance
expect(refund_balance_2).to eq purchase_balance_2
end
it "uses the oldest unpaid balance for refund/chargeback if the original purchase balance is not unpaid" do
purchase_balance_1 = @purchase_1.purchase_success_balance
purchase_balance_1.update_attribute(:state, "paid")
old_unpaid_balance_1 = create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today - 9)
create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today)
purchase_balance_2 = @purchase_2.purchase_success_balance
purchase_balance_2.update_attribute(:state, "paid")
old_unpaid_balance_2 = create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today - 9)
create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today)
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_1.refund_and_save!(admin_user.id)
end
refund_balance_1 = @purchase_1.reload.purchase_refund_balance
expect(refund_balance_1).to eq old_unpaid_balance_1
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_2.refund_and_save!(admin_user.id)
end
refund_balance_2 = @purchase_2.reload.purchase_refund_balance
expect(refund_balance_2).to eq old_unpaid_balance_2
end
it "uses today's balance for refund/chargeback if the original purchase balance is not unpaid and there are no older unpaid balances" do
purchase_balance_1 = @purchase_1.purchase_success_balance
purchase_balance_1.mark_processing!
purchase_balance_1.mark_paid!
old_paid_balance_1 = create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today - 9)
old_paid_balance_1.mark_processing!
old_paid_balance_1.mark_paid!
today_unpaid_balance_1 = create(:balance, user: @user, merchant_account: @purchase_1.merchant_account, date: Date.today)
purchase_balance_2 = @purchase_2.purchase_success_balance
purchase_balance_2.mark_processing!
purchase_balance_2.mark_paid!
old_paid_balance_2 = create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today - 9)
old_paid_balance_2.mark_processing!
old_paid_balance_2.mark_paid!
today_unpaid_balance_2 = create(:balance, user: @user, merchant_account: @purchase_2.merchant_account, date: Date.today)
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_1.refund_and_save!(admin_user.id)
end
refund_balance_1 = @purchase_1.reload.purchase_refund_balance
expect(refund_balance_1).to eq today_unpaid_balance_1
travel_to(Time.zone.local(2023, 11, 27)) do
@purchase_2.refund_and_save!(admin_user.id)
end
refund_balance_2 = @purchase_2.reload.purchase_refund_balance
expect(refund_balance_2).to eq today_unpaid_balance_2
end
end
end
describe "proper Balance creation and association with affiliate_credit" do
let(:physical) { false }
let(:user) { create(:user) }
let(:product) do
create(:product, user:, is_physical: physical, require_shipping: physical,
shipping_destinations: [(create(:shipping_destination) if physical)].compact)
end
let(:affiliate_user) { create(:affiliate_user) }
let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller: user) }
let!(:product_affiliate) { create(:product_affiliate, product:, affiliate: direct_affiliate, affiliate_basis_points: 15_00) }
let(:chargeable) { build(:chargeable) }
let(:old_date) { Date.today - 10 }
it "associates the balance with the purchase and affiliate_credit and have the proper amount for both" do
travel_to(old_date) do
@purchase_1 = create(:purchase, chargeable:, purchase_state: "in_progress", seller: user, link: product, price_cents: 100, fee_cents: 30,
full_name: "Edgar Gumstein", street_address: "123 Gum Road", state: "CA", city: "San Francisco", zip_code: "94017", country: "United States",
affiliate: direct_affiliate)
@purchase_1.process!
@purchase_1.update_balance_and_mark_successful!
end
affiliate_balance, seller_balance = Balance.last(2)
expect(seller_balance).to eq @purchase_1.purchase_success_balance
expect(@purchase_1.affiliate_credit).to_not be(nil)
expect(seller_balance.date).to eq old_date
expect(seller_balance.amount_cents).to eq(6) # 100c (price) - 15c (affiliate fee) + 14c (affiliate's share of Gumroad fee) - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
expect(affiliate_balance.date).to eq old_date
expect(affiliate_balance.amount_cents).to eq 1
verify_balance(user, 6)
verify_balance(affiliate_user.reload, 1)
end
describe "when the app owner and creator get their own merchant accounts" do
let(:product_2) do
create(:product, user:, is_physical: physical, require_shipping: physical, price_cents: 200,
shipping_destinations: [(create(:shipping_destination) if physical)].compact)
end
let!(:product_affiliate_2) { create(:product_affiliate, product: product_2, affiliate: direct_affiliate, affiliate_basis_points: 20_00) }
before do
travel_to(old_date) do
@purchase_1 = create(:purchase, chargeable:, purchase_state: "in_progress", seller: user, link: product, price_cents: 100, fee_cents: 30,
full_name: "Edgar Gumstein", street_address: "123 Gum Road", state: "CA", city: "San Francisco", zip_code: "94017", country: "United States",
affiliate: direct_affiliate)
@purchase_1.process!
@purchase_1.update_balance_and_mark_successful!
end
@merchant_account = create(:merchant_account, user:)
@gumroad_merchant_account = MerchantAccount.gumroad(@merchant_account.charge_processor_id)
user.reload
travel_to(old_date) do
@purchase_2 = create(:purchase, chargeable: build(:chargeable), purchase_state: "in_progress", seller: user, link: product_2, price_cents: 200, fee_cents: 35,
full_name: "Edgar Gumstein", street_address: "123 Gum Road", state: "CA", city: "San Francisco", zip_code: "94017", country: "United States",
affiliate: direct_affiliate)
@purchase_2.process!
@purchase_2.update_balance_and_mark_successful!
end
end
describe "digital" do
let(:physical) { false }
it "associates the balance with the purchase and affiliate_credit and have the proper amount for both" do
affiliate_balance, seller_balance_1, seller_balance_2 = Balance.last(3)
# seller_balance_1 = balance for purchases prior to having their own merchant account
# seller_balance_2 = should be nil
expect(seller_balance_1).to eq @purchase_1.purchase_success_balance
expect(@purchase_1.affiliate_credit).to_not be(nil)
expect(seller_balance_1.date).to eq old_date
expect(seller_balance_1.amount_cents).to eq(6) # 100c (price) - 15c (affiliate fee) + 14c (affiliate's share of Gumroad fee) - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
expect(seller_balance_1.merchant_account).to eq(@gumroad_merchant_account)
expect(seller_balance_2).to eq @purchase_2.purchase_success_balance
expect(@purchase_2.affiliate_credit).to_not be(nil)
expect(seller_balance_2.date).to eq old_date
expect(seller_balance_2.amount_cents).to eq 76 # 200c (price) - 40c (affiliate fee) + 22c (affiliate's share of Gumroad fee) - 20c (10% flat fee) - 50c (fixed fee) - 6c (2.9% cc fee) - 30c (fixed cc fee)
expect(seller_balance_2.merchant_account).to eq(@merchant_account)
expect(affiliate_balance.date).to eq old_date
expect(affiliate_balance.amount_cents).to eq 19
expect(affiliate_balance.merchant_account).to eq(@gumroad_merchant_account)
verify_balance(user, 82)
verify_balance(affiliate_user.reload, 19)
end
end
describe "physical" do
let(:physical) { true }
it "associates the balance with the purchase and affiliate_credit and have the proper amount for both" do
affiliate_balance, seller_balance_1, seller_balance_2 = Balance.last(3)
# seller_balance_1 = balance for purchases prior to having their own merchant account
# seller_balance_2 = balance for purchases on their own merchant account
expect(seller_balance_1).to eq @purchase_1.purchase_success_balance
expect(@purchase_1.affiliate_credit).to_not be(nil)
expect(seller_balance_1.date).to eq old_date
expect(seller_balance_1.amount_cents).to eq(6) # 100c (price) - 15c (affiliate fee) + 14c (affiliate's share of Gumroad fee) - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
expect(seller_balance_1.merchant_account).to eq(@gumroad_merchant_account)
expect(seller_balance_2).to eq @purchase_2.purchase_success_balance
expect(@purchase_2.affiliate_credit).to_not be(nil)
expect(seller_balance_2.date).to eq old_date
expect(seller_balance_2.amount_cents).to eq 76 # 200c (price) - 40c (affiliate fee) + 22c (affiliate's share of gumroad fee) - 20c (10% flat fee) - 50c (fixed fee) - 6c (2.9% cc fee) - 30c (fixed cc fee)
expect(seller_balance_2.merchant_account).to eq(@merchant_account)
expect(affiliate_balance.date).to eq old_date
expect(affiliate_balance.amount_cents).to eq 19
expect(affiliate_balance.merchant_account).to eq(@gumroad_merchant_account)
verify_balance(user, 82)
verify_balance(affiliate_user.reload, 19)
end
end
end
end
describe "proper Balance creation and association with affiliate_credit with merchant_migration enabled" do
let(:physical) { false }
let(:user) { create(:user) }
let(:product) do
create(:product, user:, is_physical: physical, require_shipping: physical,
shipping_destinations: [(create(:shipping_destination) if physical)].compact)
end
let(:affiliate_user) { create(:affiliate_user) }
let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller: user) }
let!(:product_affiliate) { create(:product_affiliate, product:, affiliate: direct_affiliate, affiliate_basis_points: 15_00) }
let(:chargeable) { build(:chargeable) }
let(:old_date) { Date.today - 10 }
before do
Feature.activate_user(:merchant_migration, user)
create(:user_compliance_info, user:)
end
after do
Feature.deactivate_user(:merchant_migration, user)
end
it "associates the balance with the purchase and affiliate_credit and have the proper amount for both" do
travel_to(old_date) do
@purchase_1 = create(:purchase, chargeable:, purchase_state: "in_progress", seller: user, link: product, price_cents: 100, fee_cents: 30,
full_name: "Edgar Gumstein", street_address: "123 Gum Road", state: "CA", city: "San Francisco", zip_code: "94017", country: "United States",
affiliate: direct_affiliate)
@purchase_1.process!
@purchase_1.update_balance_and_mark_successful!
end
affiliate_balance, seller_balance = Balance.last(2)
expect(seller_balance).to eq @purchase_1.purchase_success_balance
expect(@purchase_1.affiliate_credit).to_not be(nil)
expect(seller_balance.date).to eq old_date
expect(seller_balance.amount_cents).to eq(6) # 100c (price) - 15c (affiliate fee) + 14c (affiliate's share of gumroad fee) - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
expect(affiliate_balance.date).to eq old_date
expect(affiliate_balance.amount_cents).to eq 1
verify_balance(user, 6)
verify_balance(affiliate_user.reload, 1)
end
describe "when the app owner and creator get their own merchant accounts" do
let(:product_2) do
create(:product, user:, is_physical: physical, require_shipping: physical, price_cents: 200,
shipping_destinations: [(create(:shipping_destination) if physical)].compact)
end
let!(:product_affiliate_2) { create(:product_affiliate, product: product_2, affiliate: direct_affiliate, affiliate_basis_points: 20_00) }
before do
travel_to(old_date) do
@purchase_1 = create(:purchase, chargeable:, purchase_state: "in_progress", seller: user, link: product, price_cents: 100, fee_cents: 30,
full_name: "Edgar Gumstein", street_address: "123 Gum Road", state: "CA", city: "San Francisco", zip_code: "94017", country: "United States",
affiliate: direct_affiliate)
@purchase_1.process!
@purchase_1.update_balance_and_mark_successful!
end
@merchant_account = create(:merchant_account_stripe_connect, user:)
@gumroad_merchant_account = MerchantAccount.gumroad(@merchant_account.charge_processor_id)
user.reload
travel_to(old_date) do
@purchase_2 = create(:purchase, chargeable: build(:chargeable, product_permalink: product_2.unique_permalink),
purchase_state: "in_progress", seller: user, link: product_2, price_cents: 200,
fee_cents: 35, full_name: "Edgar Gumstein", street_address: "123 Gum Road",
state: "CA", city: "San Francisco", zip_code: "94017", country: "United States",
affiliate: direct_affiliate)
@purchase_2.process!
@purchase_2.update_balance_and_mark_successful!
end
end
describe "digital" do
let(:physical) { false }
it "associates the balance with the purchase and affiliate_credit and have the proper amount for both" do
affiliate_balance, seller_balance_1 = Balance.last(2)
expect(seller_balance_1).to eq @purchase_1.purchase_success_balance
expect(@purchase_1.affiliate_credit).to_not be(nil)
expect(@purchase_2.affiliate_credit).to_not be(nil)
expect(seller_balance_1.date).to eq old_date
expect(seller_balance_1.amount_cents).to eq(6) # 100c (price) - 15c (affiliate fee) + 14c (affiliate's share of gumroad fee) - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
expect(seller_balance_1.merchant_account).to eq(@gumroad_merchant_account)
expect(affiliate_balance.date).to eq old_date
expect(affiliate_balance.amount_cents).to eq 27
expect(affiliate_balance.merchant_account).to eq(@gumroad_merchant_account)
verify_balance(user, 6)
verify_balance(affiliate_user.reload, 27)
end
end
describe "physical" do
let(:physical) { true }
it "associates the balance with the purchase and affiliate_credit and have the proper amount for both" do
affiliate_balance, seller_balance_1 = Balance.last(2)
expect(seller_balance_1).to eq @purchase_1.purchase_success_balance
expect(@purchase_1.affiliate_credit).to_not be(nil)
expect(@purchase_2.affiliate_credit).to_not be(nil)
expect(seller_balance_1.date).to eq old_date
expect(seller_balance_1.amount_cents).to eq(6) # 100c (price) - 15c (affiliate fee) + 14c (affiliate's share of gumroad fee) - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
expect(seller_balance_1.merchant_account).to eq(@gumroad_merchant_account)
expect(affiliate_balance.date).to eq old_date
expect(affiliate_balance.amount_cents).to eq 27
expect(affiliate_balance.merchant_account).to eq(@gumroad_merchant_account)
verify_balance(user, 6)
verify_balance(affiliate_user.reload, 27)
end
end
end
end
describe "increment_sellers_balance!" do
it "adds a balance to the user" do
user = create(:user)
link = create(:product, user:)
expect(user.unpaid_balance_cents).to eq 0
purchase = create(:purchase, price_cents: 1_00, fee_cents: 30, link:, seller: link.user)
purchase.increment_sellers_balance!
verify_balance(user, 7) # 100c (price) - 10c (10% flat fee) - 50c (fixed fee) - 3c (2.9% cc fee) - 30c (fixed cc fee)
end
describe "increment_sellers_balance! without affiliate_credit without merchant account" do
before do
@seller = create(:user)
@product = create(:product, user: @seller)
@charge = nil
original_charge_processor_charge = ChargeProcessor.method(:create_payment_intent_or_charge!)
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!) do |*args, **kwargs|
charge_intent = original_charge_processor_charge.call(*args, **kwargs)
@charge = charge_intent.charge
charge_intent
end
@purchase = create(:purchase_in_progress, seller: @seller, link: @product, affiliate: @direct_affiliate, chargeable: create(:chargeable))
@purchase.process!
@flow_of_funds = @charge.flow_of_funds
end
it "creates a balance transaction" do
@purchase.increment_sellers_balance!
balance_transaction = BalanceTransaction.last
expect(balance_transaction.user).to eq(@seller)
expect(balance_transaction.merchant_account).to eq(@purchase.merchant_account)
expect(balance_transaction.refund).to eq(@purchase.refunds.last)
expect(balance_transaction.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction.issued_amount_currency).to eq(@flow_of_funds.issued_amount.currency)
expect(balance_transaction.issued_amount_gross_cents).to eq(@purchase.total_transaction_cents)
expect(balance_transaction.issued_amount_gross_cents).to eq(@flow_of_funds.issued_amount.cents)
expect(balance_transaction.issued_amount_net_cents).to eq(@purchase.payment_cents)
expect(balance_transaction.holding_amount_currency).to eq(Currency::USD)
expect(balance_transaction.holding_amount_currency).to eq(@flow_of_funds.gumroad_amount.currency)
expect(balance_transaction.holding_amount_gross_cents).to eq(@purchase.total_transaction_cents)
expect(balance_transaction.holding_amount_gross_cents).to eq(@flow_of_funds.gumroad_amount.cents)
expect(balance_transaction.holding_amount_net_cents).to eq(@purchase.payment_cents)
end
end
describe "increment_sellers_balance! without affiliate_credit with merchant account" do
before do
@seller = create(:user)
@merchant_account = create(:merchant_account_stripe_canada, user: @seller)
@product = create(:product, user: @seller)
@charge = nil
original_charge_processor_charge = ChargeProcessor.method(:create_payment_intent_or_charge!)
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!) do |*args, **kwargs|
charge_intent = original_charge_processor_charge.call(*args, **kwargs)
@charge = charge_intent.charge
charge_intent
end
@purchase = create(:purchase_in_progress, seller: @seller, link: @product, affiliate: @direct_affiliate, chargeable: create(:chargeable))
@purchase.process!
@flow_of_funds = @charge.flow_of_funds
end
it "creates one balance transaction for the purchase" do
@purchase.increment_sellers_balance!
balance_transaction = BalanceTransaction.last
expect(balance_transaction.user).to eq(@seller)
expect(balance_transaction.merchant_account).to eq(@purchase.merchant_account)
expect(balance_transaction.refund).to eq(@purchase.refunds.last)
expect(balance_transaction.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction.issued_amount_currency).to eq(@flow_of_funds.issued_amount.currency)
expect(balance_transaction.issued_amount_gross_cents).to eq(@purchase.total_transaction_cents)
expect(balance_transaction.issued_amount_gross_cents).to eq(@flow_of_funds.issued_amount.cents)
expect(balance_transaction.issued_amount_net_cents).to eq(@purchase.payment_cents)
expect(balance_transaction.holding_amount_currency).to eq(Currency::CAD)
expect(balance_transaction.holding_amount_currency).to eq(@flow_of_funds.merchant_account_gross_amount.currency)
expect(balance_transaction.holding_amount_currency).to eq(@flow_of_funds.merchant_account_net_amount.currency)
expect(balance_transaction.holding_amount_gross_cents).to eq(@flow_of_funds.merchant_account_gross_amount.cents)
expect(balance_transaction.holding_amount_net_cents).to eq(@flow_of_funds.merchant_account_net_amount.cents)
end
end
describe "increment_sellers_balance! with affiliate_credit with merchant account" do
before do
@seller = create(:user)
Feature.deactivate_user(:merchant_migration, @seller)
@merchant_account = create(:merchant_account_stripe_canada, user: @seller)
@product = create(:product, user: @seller, price_cents: 10_00)
@affiliate_user = create(:affiliate_user)
@direct_affiliate = create(:direct_affiliate, affiliate_user: @affiliate_user, seller: @seller, products: [@product])
@charge = nil
original_charge_processor_charge = ChargeProcessor.method(:create_payment_intent_or_charge!)
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!) do |*args, **kwargs|
charge_intent = original_charge_processor_charge.call(*args, **kwargs)
@charge = charge_intent.charge
charge_intent
end
@purchase = create(:purchase_in_progress, seller: @seller, link: @product, affiliate: @direct_affiliate, chargeable: create(:chargeable))
@purchase.process!
@flow_of_funds = @charge.flow_of_funds
end
it "creates an instance of affiliate_credit" do
expect { @purchase.increment_sellers_balance! }.to change { AffiliateCredit.count }.by(1)
end
it "increases each affiliate application owners and sellers balances accordingly" do
@purchase.increment_sellers_balance!
affiliate_user_balance = ((@purchase.price_cents - @purchase.fee_cents) * (@direct_affiliate.affiliate_basis_points / 10_000.0)).floor
verify_balance(@affiliate_user, affiliate_user_balance)
verify_balance(@seller, @purchase.price_cents - @purchase.fee_cents - affiliate_user_balance)
end
it "creates two balance transactions for the purchase" do
@purchase.increment_sellers_balance!
balance_transaction_1, balance_transaction_2 = BalanceTransaction.last(2)
expect(balance_transaction_1.user).to eq(@affiliate_user)
expect(balance_transaction_1.merchant_account).to eq(@purchase.affiliate_merchant_account)
expect(balance_transaction_1.refund).to eq(@purchase.refunds.last)
expect(balance_transaction_1.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction_1.issued_amount_gross_cents).to eq(@purchase.affiliate_credit_cents)
expect(balance_transaction_1.issued_amount_net_cents).to eq(@purchase.affiliate_credit_cents)
expect(balance_transaction_1.holding_amount_currency).to eq(Currency::USD)
expect(balance_transaction_1.holding_amount_gross_cents).to eq(@purchase.affiliate_credit_cents)
expect(balance_transaction_1.holding_amount_net_cents).to eq(@purchase.affiliate_credit_cents)
expect(balance_transaction_2.user).to eq(@seller)
expect(balance_transaction_2.merchant_account).to eq(@purchase.merchant_account)
expect(balance_transaction_2.refund).to eq(@purchase.refunds.last)
expect(balance_transaction_2.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction_2.issued_amount_currency).to eq(@flow_of_funds.issued_amount.currency)
expect(balance_transaction_2.issued_amount_gross_cents).to eq(@purchase.total_transaction_cents)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_taxation_spec.rb | spec/models/purchase/purchase_taxation_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PurchaseTaxation", :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
describe "sales tax with merchant_migration enabled" do
let(:price) { 10_00 }
let(:buyer_zip) { nil } # forces using ip by default
let(:link_is_physical) { false }
let(:merchant_account) { create(:merchant_account_stripe_connect, user: seller) }
before(:context) do
@price_cents = 10_00
@fee_cents = 150
@buyer_zip = nil # forces using ip by default
@product_is_physical = false
@tax_state = "CA"
@tax_zip = "94107"
@tax_country = "US"
@tax_combined_rate = 0.01
@tax_is_seller_responsible = true
@purchase_country = nil
@purchase_ip_country = nil
@purchase_chargeable_country = nil
@purchase_transaction_amount = nil
@amount_for_gumroad_cents = @fee_cents
end
before(:example) do
@seller = create(:user)
@seller.collect_eu_vat = true
@seller.is_eu_vat_exclusive = true
@seller.save!
@merchant_account = create(:merchant_account_stripe_connect, user: @seller)
Feature.activate_user(:merchant_migration, @seller)
create(:user_compliance_info, user: @seller)
@product = create(:product, user: @seller, price_cents: @price_cents)
@product.is_physical = @product_is_physical
@product.require_shipping = @product_require_shipping
@product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0)
@product.save!
@chargeable = build(:chargeable, product_permalink: @product.unique_permalink)
@purchase = if @product_is_physical
create(:purchase,
chargeable: @chargeable,
price_cents: @price_cents,
seller: @seller,
link: @product,
ip_country: @purchase_ip_country,
purchase_state: "in_progress",
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
country: "United States",
state: "CA",
city: "San Francisco",
zip_code: "94017")
else
create(:purchase,
chargeable: @chargeable,
price_cents: @price_cents,
seller: @seller,
link: @product,
zip_code: @buyer_zip,
country: @purchase_country,
ip_country: @purchase_ip_country,
purchase_state: "in_progress")
end
@zip_tax_rate = create(:zip_tax_rate, zip_code: @tax_zip, state: @tax_state, country: @tax_country,
combined_rate: @tax_combined_rate, is_seller_responsible: @tax_is_seller_responsible)
allow(@purchase).to receive(:card_country) { @purchase_chargeable_country }
if @purchase_transaction_amount.present?
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).with(
anything, anything, @purchase_transaction_amount, @amount_for_gumroad_cents, anything, anything, anything
).and_call_original
end
@purchase.process!
end
it "is recorded" do
expect(@purchase).to respond_to(:tax_cents)
expect(@purchase).to respond_to(:gumroad_tax_cents)
end
describe "with a default (not taxable) seller and a purchase without a zip code" do
it "is not included" do
allow(@purchase).to receive(:best_guess_zip).and_return(nil)
expect(@purchase.tax_cents).to be_zero
expect(@purchase.gumroad_tax_cents).to be_zero
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.total_transaction_cents).to eq(10_00)
expect(@purchase.was_purchase_taxable).to be(false)
end
end
describe "VAT" do
before(:context) do
@tax_state = nil
@tax_zip = nil
@tax_country = "GB"
@tax_combined_rate = 0.22
@tax_is_seller_responsible = false
end
describe "in eligible and successful purchase" do
before(:context) do
@purchase_country = "United Kingdom"
@purchase_chargeable_country = "GB"
@purchase_ip_country = "Spain"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 370
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "location verification with available zip tax entry" do
before(:context) do
@tax_combined_rate = 0.22
end
describe "IP address in EU , card country in EU, country = ip" do
before(:context) do
@tax_country = "GB"
@purchase_country = "United Kingdom"
@purchase_chargeable_country = "ES"
@purchase_ip_country = "United Kingdom"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 370
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address in EU , card country in EU, country = card country" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "ES"
@purchase_ip_country = "United Kingdom"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 370
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address non-EU , card country non-EU, country != either and in EU" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "IN"
@purchase_ip_country = "United States"
@purchase_transaction_amount = 10_00
end
it "resets tax and proceeds with purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address non EU , card country non EU, country != either and not in EU" do
before(:context) do
@purchase_country = "Togo"
@purchase_chargeable_country = "IN"
@purchase_ip_country = "United States"
@purchase_transaction_amount = 10_00
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address in EU, card country in EU, country in non-EU and product is physical" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = "GB"
@purchase_ip_country = "United Kingdom"
@product_is_physical = true
@product_require_shipping = true
@purchase_transaction_amount = 10_00
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address in EU, card country in nil, country in EU (matching)" do
before(:context) do
@purchase_country = "United Kingdom"
@purchase_chargeable_country = nil
@purchase_ip_country = "United Kingdom"
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address EU, card country in nil, country in non-EU" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = nil
@purchase_ip_country = "United Kingdom"
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address non-EU, card country in nil, country in non-EU (matching)" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = nil
@purchase_ip_country = "United States"
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
end
end
end
describe "sales tax with native_paypal_payments enabled" do
let(:chargeable) { build(:native_paypal_chargeable) }
let(:price) { 10_00 }
let(:buyer_zip) { nil } # forces using ip by default
let(:is_physical) { false }
let(:seller) do
seller = create(:user)
seller.save!
end
let(:merchant_account) do
create(:merchant_account_paypal, user: seller,
charge_processor_merchant_id: "CJS32DZ7NDN5L",
country: "GB", currency: "gbp")
end
before(:context) do
@price_cents = 10_00
@fee_cents = 150 # 10% flat fee (no processor fee on paypal connect sales)
@buyer_zip = nil # forces using ip by default
@is_physical = false
@tax_state = "CA"
@tax_zip = "94107"
@tax_country = "US"
@tax_combined_rate = 0.01
@tax_is_seller_responsible = true
@purchase_country = nil
@purchase_ip_country = nil
@purchase_chargeable_country = nil
@purchase_transaction_amount = nil
@amount_for_gumroad_cents = @fee_cents
end
before do
@seller = create(:user)
@seller.collect_eu_vat = true
@seller.is_eu_vat_exclusive = true
@seller.save!
@merchant_account = create(:merchant_account_paypal, user: @seller,
charge_processor_merchant_id: "CJS32DZ7NDN5L",
country: "GB", currency: "gbp")
@product = create(:product, user: @seller, price_cents: @price_cents)
@product.is_physical = @is_physical
@product.require_shipping = @require_shipping
@product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0)
@product.save!
@purchase = if @is_physical
create(:purchase,
chargeable:,
price_cents: @price_cents,
seller: @seller,
link: @product,
ip_country: @purchase_ip_country,
purchase_state: "in_progress",
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
country: "United States",
state: "CA",
city: "San Francisco",
zip_code: "94107")
else
create(:purchase,
chargeable:,
price_cents: @price_cents,
seller: @seller,
link: @product,
zip_code: @buyer_zip,
country: @purchase_country,
ip_country: @purchase_ip_country,
purchase_state: "in_progress")
end
@zip_tax_rate = create(:zip_tax_rate, zip_code: @tax_zip, state: @tax_state, country: @tax_country,
combined_rate: @tax_combined_rate, is_seller_responsible: @tax_is_seller_responsible)
allow(@purchase).to receive(:card_country) { @purchase_chargeable_country }
if @purchase_transaction_amount.present?
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).with(
anything, anything, @purchase_transaction_amount, @amount_for_gumroad_cents, anything, anything, anything
).and_call_original
end
@purchase.process!
end
it "stores the tax attributes" do
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
end
describe "with a default (not taxable) seller and a purchase without a zip code" do
it "is not included" do
allow(@purchase).to receive(:best_guess_zip).and_return(nil)
expect(@purchase.tax_cents).to be_zero
expect(@purchase.gumroad_tax_cents).to be_zero
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.total_transaction_cents).to eq(10_00)
expect(@purchase.was_purchase_taxable).to be(false)
end
end
describe "VAT" do
before(:context) do
@tax_state = nil
@tax_zip = nil
@tax_country = "GB"
@tax_combined_rate = 0.22
@tax_is_seller_responsible = false
end
describe "in eligible and successful purchase" do
before(:context) do
@purchase_country = "United Kingdom"
@purchase_chargeable_country = "GB"
@purchase_ip_country = "Spain"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 3_70 # 150c (10% + 50c fee) + 220c (22% vat)
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "location verification with available zip tax entry" do
before(:context) do
@tax_combined_rate = 0.22
end
describe "IP address in EU , card country in EU, country = ip" do
before(:context) do
@tax_country = "GB"
@purchase_country = "United Kingdom"
@purchase_chargeable_country = "ES"
@purchase_ip_country = "United Kingdom"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 3_70 # 100c (10% + 50c fee) + 220c (22% vat)
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address in EU , card country in EU, country = card country" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "ES"
@purchase_ip_country = "United Kingdom"
@purchase_transaction_amount = 12_20
@amount_for_gumroad_cents = 3_70 # 100c (10% + 50c fee) + 220c (22% vat)
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address non EU , card country non EU, country != either and in EU" do
before(:context) do
@tax_country = "ES"
@purchase_country = "Spain"
@purchase_chargeable_country = "IN"
@purchase_ip_country = "United States"
@purchase_transaction_amount = 10_00
end
it "resets tax and proceeds with purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address non EU , card country non EU, country != either and not in EU" do
before(:context) do
@purchase_country = "Togo"
@purchase_chargeable_country = "IN"
@purchase_ip_country = "United States"
@purchase_transaction_amount = 10_00
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address in EU, card country in EU, country in non-EU and product is physical" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = "GB"
@purchase_ip_country = "United Kingdom"
@is_physical = true
@require_shipping = true
@purchase_transaction_amount = 10_00
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address in EU, card country in nil, country in EU (matching)" do
before(:context) do
@purchase_country = "United Kingdom"
@purchase_chargeable_country = nil
@purchase_ip_country = "United Kingdom"
end
it "is VAT eligible and VAT is applied to purchase" do
expect(@purchase.was_purchase_taxable).to be(true)
expect(@purchase.was_tax_excluded_from_price).to be(true)
expect(@purchase.zip_tax_rate).to eq(@zip_tax_rate)
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(2_20)
expect(@purchase.total_transaction_cents).to eq(12_20)
end
end
describe "IP address EU, card country in nil, country in non-EU" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = nil
@purchase_ip_country = "United Kingdom"
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
describe "IP address non-EU, card country in nil, country in non-EU (matching)" do
before(:context) do
@purchase_country = "United States"
@purchase_chargeable_country = nil
@purchase_ip_country = "United States"
end
it "no tax is applied to the purchase" do
expect(@purchase.was_purchase_taxable).to be(false)
expect(@purchase.was_tax_excluded_from_price).to be(false)
expect(@purchase.zip_tax_rate).to be_nil
expect(@purchase.tax_cents).to eq(0)
expect(@purchase.gumroad_tax_cents).to eq(0)
expect(@purchase.total_transaction_cents).to eq(10_00)
end
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_refunds_spec.rb | spec/models/purchase/purchase_refunds_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PurchaseRefunds", :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
describe "refund purchase" do
let(:merchant_account) { nil }
before do
@initial_balance = 200
@user = create(:user)
merchant_account
@product = create(:product, user: @user)
@purchase = create(:purchase_in_progress, link: @product, chargeable: create(:chargeable))
@purchase.process!
@purchase.mark_successful!
@event = create(:event, event_name: "purchase", purchase_id: @purchase.id, link_id: @product.id)
@balance = if merchant_account
create(:balance, user: @user, amount_cents: @initial_balance, merchant_account:, holding_currency: Currency::CAD)
else
create(:balance, user: @user, amount_cents: @initial_balance)
end
@initial_num_paid_download = @product.sales.paid.count
end
it "only refunds with stripe id" do
expect(ChargeProcessor).to_not receive(:refund!)
@purchase.stripe_transaction_id = nil
@purchase.refund_and_save!(@user.id)
end
it "updates refund status" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id)
@purchase.reload
expect(@purchase.refunds.first.status).to eq("succeeded")
end
it "updates refund processor refund id" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase).to receive(:debit_processor_fee_from_merchant_account!).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id)
expect(@purchase.reload.refunds.first.processor_refund_id).to_not be(nil)
end
it "refunds idempotent" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id)
@purchase.reload
expect(@purchase.stripe_refunded).to_not be(false)
@purchase.refund_and_save!(@user.id)
end
it "refunds when stripe_partially_refunded" do
@purchase.stripe_partially_refunded = true
@purchase.save!
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id)
@purchase.reload
expect(@purchase.stripe_refunded).to_not be(false)
end
it "creates a balance transaction for the refund" do
charge_refund = nil
original_charge_processor_refund = ChargeProcessor.method(:refund!)
expect(ChargeProcessor).to receive(:refund!) do |*args, **kwargs|
charge_refund = original_charge_processor_refund.call(*args, **kwargs)
charge_refund
end
@purchase.refund_and_save!(@user.id)
flow_of_funds = charge_refund.flow_of_funds
balance_transaction = BalanceTransaction.where.not(refund_id: nil).last
expect(balance_transaction.user).to eq(@user)
expect(balance_transaction.merchant_account).to eq(@purchase.merchant_account)
expect(balance_transaction.refund).to eq(@purchase.refunds.last)
expect(balance_transaction.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction.issued_amount_currency).to eq(flow_of_funds.issued_amount.currency)
expect(balance_transaction.issued_amount_gross_cents).to eq(-1 * @purchase.total_transaction_cents)
expect(balance_transaction.issued_amount_gross_cents).to eq(flow_of_funds.issued_amount.cents)
expect(balance_transaction.issued_amount_net_cents).to eq(-1 * @purchase.payment_cents)
expect(balance_transaction.holding_amount_currency).to eq(Currency::USD)
expect(balance_transaction.holding_amount_currency).to eq(flow_of_funds.gumroad_amount.currency)
expect(balance_transaction.holding_amount_gross_cents).to eq(flow_of_funds.gumroad_amount.cents)
expect(balance_transaction.holding_amount_net_cents).to eq(-1 * @purchase.payment_cents)
end
it "updates balance of seller and # paid downloads" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
@purchase.refund_and_save!(@user.id)
@user.reload
verify_balance(@user, @initial_balance - @purchase.payment_cents - @purchase.processor_fee_cents)
expect(@purchase.purchase_refund_balance).to eq @balance
@product.reload
expect(@product.sales.paid.count).to_not eq @initial_num_paid_download
@product.sales.paid.count == @initial_num_paid_download - 1
end
describe "partial refund with amount" do
it "updates refund status" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id, amount_cents: @purchase.total_transaction_cents - 10)
@purchase.reload
expect(@purchase.refunds.first.status).to eq("succeeded")
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to be(true)
end
it "refunds idempotent" do
expect(ChargeProcessor).to_not receive(:refund!)
@purchase.stripe_refunded = true
@purchase.save!
@purchase.refund_and_save!(@user.id, amount_cents: 10)
@purchase.reload
expect(@purchase.stripe_refunded).to_not be(false)
expect(@purchase.stripe_partially_refunded).to_not be(true)
end
it "updates refund processor refund id" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_partially_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id, amount_cents: @purchase.total_transaction_cents - 10)
@purchase.reload
expect(@purchase.stripe_partially_refunded).to be(true)
expect(@purchase.refunds.first.processor_refund_id).to_not be(nil)
end
it "allows refund multiple times" do
expect(ChargeProcessor).to receive(:refund!).twice.with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id, amount_cents: @purchase.total_transaction_cents - 50)
@purchase.reload
expect(@purchase.refunds.first.status).to eq("succeeded")
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to be(true)
@purchase.refund_and_save!(@user.id, amount_cents: 10)
@purchase.reload
expect(@purchase.stripe_partially_refunded).to be(true)
end
it "fully refunds if amount goes over total transaction cents" do
expect(ChargeProcessor).to receive(:refund!).twice.with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to_not be(true)
@purchase.refund_and_save!(@user.id, amount_cents: @purchase.total_transaction_cents - 50)
@purchase.reload
expect(@purchase.refunds.first.status).to eq("succeeded")
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to be(true)
@purchase.refund_and_save!(@user.id, amount_cents: 50)
@purchase.reload
expect(@purchase.stripe_partially_refunded).to_not be(true)
expect(@purchase.stripe_refunded).to be(true)
end
it "updates balance of seller" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
@purchase.refund_and_save!(@user.id, amount_cents: 50)
@user.reload
verify_balance(@user, @initial_balance - @purchase.amount_refunded_cents + @purchase.fee_refunded_cents - @purchase.refunds.sum(&:retained_fee_cents))
expect(@purchase.purchase_refund_balance).to eq @balance
end
it "updates balance of seller for multiple refunds" do
expect(ChargeProcessor).to receive(:refund!).twice.with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
@purchase.refund_and_save!(@user.id, amount_cents: 10)
@user.reload
verify_balance(@user, @initial_balance - @purchase.amount_refunded_cents + @purchase.refunds.sum { |refund| refund.fee_cents - refund.retained_fee_cents })
expect(@purchase.purchase_refund_balance).to eq @balance
@purchase.reload
@purchase.refund_and_save!(@user.id, amount_cents: 20)
@user.reload
verify_balance(@user, @initial_balance - @purchase.amount_refunded_cents + @purchase.refunds.sum { |refund| refund.fee_cents - refund.retained_fee_cents })
expect(@purchase.purchase_refund_balance).to eq @balance
end
it "updates balance of seller for multiple refunds finally marking it as fully refunded" do
expect(ChargeProcessor).to receive(:refund!).twice.with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
@purchase.refund_and_save!(@user.id, amount_cents: 10)
@user.reload
verify_balance(@user, @initial_balance - @purchase.amount_refunded_cents + @purchase.refunds.sum { |refund| refund.fee_cents - refund.retained_fee_cents })
expect(@purchase.purchase_refund_balance).to eq @balance
@purchase.reload
@purchase.refund_and_save!(@user.id, amount_cents: 90)
@user.reload
@purchase.reload
expect(@purchase.stripe_partially_refunded).to_not be(true)
expect(@purchase.stripe_refunded).to be(true)
verify_balance(@user, @initial_balance - @purchase.amount_refunded_cents + @purchase.refunds.sum { |refund| refund.fee_cents - refund.retained_fee_cents })
expect(@purchase.purchase_refund_balance).to eq @balance
end
it "notifies customer about the refund" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(CustomerMailer).to receive(:partial_refund).with(@purchase.email, @purchase.link.id, @purchase.id, 50, "partially").and_call_original
@purchase.refund_and_save!(@user.id, amount_cents: 50)
end
it "reindexes ES document" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
ElasticsearchIndexerWorker.jobs.clear
@purchase.refund_and_save!(@user.id, amount_cents: 50)
expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("index", "record_id" => @purchase.id, "class_name" => "Purchase")
end
describe "with non USD currency" do
before do
@product = create(:product, user: @user, price_currency_type: :gbp, price_cents: 100)
@purchase = create(:purchase_in_progress, link: @product, chargeable: create(:chargeable))
@purchase.process!
@purchase.mark_successful!
end
it "handles partial refunds with passed amount" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to_not be(true)
expect(@purchase.refund_and_save!(@user.id, amount_cents: 50)).to be(true)
@purchase.reload
expect(@purchase.refunds.first.status).to eq("succeeded")
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to be(true)
end
describe "user has a merchant account" do
let(:merchant_account) { create(:merchant_account_stripe_canada, user: @user) }
it "creates a balance transaction for the refund" do
charge_refund = nil
original_charge_processor_refund = ChargeProcessor.method(:refund!)
expect(ChargeProcessor).to receive(:refund!) do |*args, **kwargs|
charge_refund = original_charge_processor_refund.call(*args, **kwargs)
charge_refund
end
expect(@purchase).to receive(:debit_processor_fee_from_merchant_account!).and_call_original
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to_not be(true)
travel_to(Time.zone.local(2023, 10, 6)) do
expect(@purchase.refund_and_save!(@user.id, amount_cents: 50)).to be(true)
end
@purchase.reload
expect(@purchase.refunds.first.status).to eq("succeeded")
expect(@purchase.stripe_refunded).to_not be(true)
expect(@purchase.stripe_partially_refunded).to be(true)
expect(@purchase.refunds.first.retained_fee_cents).to eq(4)
flow_of_funds = charge_refund.flow_of_funds
balance_transaction = BalanceTransaction.where.not(refund_id: nil).last
expect(balance_transaction.user).to eq(@user)
expect(balance_transaction.merchant_account).to eq(merchant_account)
expect(balance_transaction.merchant_account).to eq(@purchase.merchant_account)
expect(balance_transaction.refund).to eq(@purchase.refunds.last)
expect(balance_transaction.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction.issued_amount_currency).to eq(flow_of_funds.issued_amount.currency)
expect(balance_transaction.issued_amount_gross_cents).to eq(-50)
expect(balance_transaction.issued_amount_gross_cents).to eq(flow_of_funds.issued_amount.cents)
expect(balance_transaction.issued_amount_net_cents).to eq(-18)
expect(balance_transaction.holding_amount_currency).to eq(Currency::CAD)
expect(balance_transaction.holding_amount_currency).to eq(flow_of_funds.merchant_account_gross_amount.currency)
expect(balance_transaction.holding_amount_currency).to eq(flow_of_funds.merchant_account_net_amount.currency)
expect(balance_transaction.holding_amount_gross_cents).to eq(flow_of_funds.merchant_account_gross_amount.cents)
expect(balance_transaction.holding_amount_net_cents).to eq(flow_of_funds.merchant_account_net_amount.cents)
credit = @purchase.seller.credits.last
expect(credit.amount_cents).to eq(-4)
end
end
end
end
describe "user has a merchant account" do
let(:merchant_account) { create(:merchant_account_stripe_canada, user: @user) }
it "creates a balance transaction for the refund" do
charge_refund = nil
original_charge_processor_refund = ChargeProcessor.method(:refund!)
expect(ChargeProcessor).to receive(:refund!) do |*args, **kwargs|
charge_refund = original_charge_processor_refund.call(*args, **kwargs)
charge_refund
end
travel_to(Time.zone.local(2023, 10, 6)) do
@purchase.refund_and_save!(@user.id)
end
flow_of_funds = charge_refund.flow_of_funds
balance_transaction = BalanceTransaction.where.not(refund_id: nil).last
expect(balance_transaction.user).to eq(@user)
expect(balance_transaction.merchant_account).to eq(merchant_account)
expect(balance_transaction.merchant_account).to eq(@purchase.merchant_account)
expect(balance_transaction.refund).to eq(@purchase.refunds.last)
expect(balance_transaction.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction.issued_amount_currency).to eq(flow_of_funds.issued_amount.currency)
expect(balance_transaction.issued_amount_gross_cents).to eq(-1 * @purchase.total_transaction_cents)
expect(balance_transaction.issued_amount_gross_cents).to eq(flow_of_funds.issued_amount.cents)
expect(balance_transaction.issued_amount_net_cents).to eq(-1 * @purchase.payment_cents)
expect(balance_transaction.holding_amount_currency).to eq(Currency::CAD)
expect(balance_transaction.holding_amount_currency).to eq(flow_of_funds.merchant_account_gross_amount.currency)
expect(balance_transaction.holding_amount_currency).to eq(flow_of_funds.merchant_account_net_amount.currency)
expect(balance_transaction.holding_amount_gross_cents).to eq(flow_of_funds.merchant_account_gross_amount.cents)
expect(balance_transaction.holding_amount_net_cents).to eq(flow_of_funds.merchant_account_net_amount.cents)
end
it "updates balance of seller and # paid downloads" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
travel_to(Time.zone.local(2023, 10, 6)) do
@purchase.refund_and_save!(@user.id)
end
@user.reload
verify_balance(@user, @initial_balance - @purchase.price_cents + @purchase.fee_cents - @purchase.processor_fee_cents)
expect(@purchase.purchase_refund_balance).to eq @balance
@product.reload
expect(@product.sales.paid.count).to_not eq @initial_num_paid_download
@product.sales.paid.count == @initial_num_paid_download - 1
end
it "does not try to reverse the associated transfer if purchase is chargedback and chargeback is won" do
purchase = create(:purchase, link: @product, charge_processor_id: "stripe", stripe_transaction_id: "ch_2O4xEq9e1RjUNIyY0XEY66sA",
merchant_account:, price_cents: 10_00)
purchase.chargeback_date = Date.today
purchase.chargeback_reversed = true
purchase.save!
charge_refund = nil
original_stripe_refund = Stripe::Refund.method(:create)
expect(Stripe::Refund).to receive(:create).with({ charge: purchase.stripe_transaction_id }) do |*args|
charge_refund = original_stripe_refund.call(*args)
charge_refund
end
expect(ChargeProcessor).to receive(:refund!).with(purchase.charge_processor_id, purchase.stripe_transaction_id,
amount_cents: nil, merchant_account: purchase.merchant_account,
reverse_transfer: false, paypal_order_purchase_unit_refund: nil,
is_for_fraud: false).and_call_original
expect(purchase).to receive(:debit_processor_fee_from_merchant_account!)
purchase.refund_and_save!(create(:admin_user).id)
expect(charge_refund.transfer_reversal).to be nil
end
end
describe "user has a merchant account not charge processor alive" do
let(:merchant_account) { create(:merchant_account_stripe_canada, user: @user, charge_processor_alive_at: nil) }
it "creates a balance transaction for the refund" do
charge_refund = nil
original_charge_processor_refund = ChargeProcessor.method(:refund!)
expect(ChargeProcessor).to receive(:refund!) do |*args, **kwargs|
charge_refund = original_charge_processor_refund.call(*args, **kwargs)
charge_refund
end
@purchase.refund_and_save!(@user.id)
flow_of_funds = charge_refund.flow_of_funds
balance_transaction = BalanceTransaction.where.not(refund_id: nil).last
expect(balance_transaction.user).to eq(@user)
expect(balance_transaction.merchant_account).not_to eq(merchant_account)
expect(balance_transaction.merchant_account).to eq(@purchase.merchant_account)
expect(balance_transaction.refund).to eq(@purchase.refunds.last)
expect(balance_transaction.issued_amount_currency).to eq(Currency::USD)
expect(balance_transaction.issued_amount_currency).to eq(flow_of_funds.issued_amount.currency)
expect(balance_transaction.issued_amount_gross_cents).to eq(-1 * @purchase.total_transaction_cents)
expect(balance_transaction.issued_amount_gross_cents).to eq(flow_of_funds.issued_amount.cents)
expect(balance_transaction.issued_amount_net_cents).to eq(-1 * @purchase.payment_cents)
expect(balance_transaction.holding_amount_currency).to eq(Currency::USD)
expect(balance_transaction.holding_amount_currency).to eq(flow_of_funds.issued_amount.currency)
expect(balance_transaction.holding_amount_gross_cents).to eq(-1 * @purchase.total_transaction_cents)
expect(balance_transaction.holding_amount_gross_cents).to eq(flow_of_funds.issued_amount.cents)
expect(balance_transaction.holding_amount_net_cents).to eq(-1 * @purchase.payment_cents)
end
end
it "refunds successfully a single purchase which is part of a combined charge on a non-usd PayPal merchant account" do
merchant_account = create(:merchant_account_paypal, user: @product.user, charge_processor_merchant_id: "HXQPE2F4AZ494", currency: "cad")
purchase = build(:purchase, link: @product, merchant_account:,
paypal_order_id: "0BX01387XY3573432",
stripe_transaction_id: "5HR31200C31692256",
charge_processor_id: "paypal")
purchase.charge = create(:charge, processor_transaction_id: purchase.stripe_transaction_id)
expect(purchase.merchant_account_id).to eq(merchant_account.id)
expect(purchase.charge.purchases.many?).to be false
purchase.refund!(refunding_user_id: purchase.seller.id)
expect(purchase.stripe_refunded?).to be true
expect(purchase.refunds.last.amount_cents).to eq(purchase.total_transaction_cents)
end
it "works when link is sold out" do
link = create(:product, max_purchase_count: 1)
purchase = create(:purchase, link:, seller: link.user)
expect(-> { purchase.refund_and_save!(link.user.id) }).to_not raise_error
end
it "creates a refund event" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
calculated_fingerprint = "3dfakl93klfdjsa09rn"
allow(Digest::MD5).to receive(:hexdigest).and_return(calculated_fingerprint)
@purchase.refund_and_save!(@user.id)
expect(Event.last.event_name).to eq "refund"
expect(@purchase.reload.is_refund_chargeback_fee_waived).to be(false)
end
it "creates a refund object" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
calculated_fingerprint = "3dfakl93klfdjsa09rn"
allow(Digest::MD5).to receive(:hexdigest).and_return(calculated_fingerprint)
@purchase.refund_and_save!(@user.id)
expect(Refund.last.purchase).to eq @purchase
expect(Refund.last.amount_cents).to eq @purchase.price_cents
expect(Refund.last.refunding_user_id).to eq @user.id
end
it "returns true if refunds without error" do
expect(ChargeProcessor).to receive(:refund!).and_call_original
expect(@purchase.refund_and_save!(@user.id)).to be(true)
end
it "returns false if charge processor indicates request invalid" do
expect(ChargeProcessor).to receive(:refund!).and_raise(ChargeProcessorInvalidRequestError)
expect(@purchase.refund_and_save!(@user.id)).to be(false)
end
it "returns false if charge processor unavailable" do
expect(ChargeProcessor).to receive(:refund!).and_raise(ChargeProcessorUnavailableError)
expect(@purchase.refund_and_save!(@user.id)).to be(false)
end
it "returns false if charge processor indicates already refunded" do
expect(ChargeProcessor).to receive(:refund!).and_raise(ChargeProcessorAlreadyRefundedError)
expect(@purchase.refund_and_save!(@user.id)).to be(false)
end
describe "refund with tax" do
describe "with sales tax" do
before do
@purchase = create(:purchase_in_progress, link: @product, chargeable: create(:chargeable))
@purchase.process!
@purchase.mark_successful!
@purchase.tax_cents = 16
@purchase.save!
end
it "refunds total transaction amount" do
expect(@purchase).to receive(:debit_processor_fee_from_merchant_account!).and_call_original
expect(@purchase.refund_and_save!(@user.id)).to be(true)
expect(Refund.last.purchase).to eq @purchase
expect(Refund.last.amount_cents).to eq @purchase.price_cents
expect(Refund.last.creator_tax_cents).to eq @purchase.tax_cents
expect(Refund.last.gumroad_tax_cents).to eq @purchase.gumroad_tax_cents
end
it "refunds with given amount cents" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase).to receive(:debit_processor_fee_from_merchant_account!).and_call_original
expect(@purchase.refund_and_save!(@user.id, amount_cents: 50)).to be(true)
refund = Refund.last
expect(refund.purchase).to eq @purchase
expect(refund.amount_cents).to eq 50
expect(refund.total_transaction_cents).to eq(50) # 42 + 8 creator tax cents
expect(refund.creator_tax_cents).to eq 8
expect(refund.gumroad_tax_cents).to eq 0
end
end
end
describe "refunds with vat" do
before do
@zip_tax_rate = create(:zip_tax_rate, combined_rate: 0.20, is_seller_responsible: false, country: "AT", state: nil, zip_code: nil)
seller = @product.user
seller.zip_tax_rates << @zip_tax_rate
seller.save!
@purchase = create(:purchase_in_progress, link: @product, zip_tax_rate: @zip_tax_rate, chargeable: create(:chargeable), country: "Austria")
@purchase.process!
@purchase.mark_successful!
end
it "refunds total transaction amount" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase).to receive(:debit_processor_fee_from_merchant_account!).and_call_original
expect(@purchase.refund_and_save!(@user.id)).to be(true)
expect(Refund.last.purchase).to eq @purchase
expect(Refund.last.amount_cents).to eq @purchase.price_cents
expect(Refund.last.total_transaction_cents).to eq(@purchase.price_cents + @purchase.gumroad_tax_cents)
expect(Refund.last.creator_tax_cents).to eq @purchase.tax_cents
expect(Refund.last.gumroad_tax_cents).to eq @purchase.gumroad_tax_cents
end
it "refunds with given amount cents" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
expect(@purchase).to receive(:debit_processor_fee_from_merchant_account!).and_call_original
expect(@purchase.refund_and_save!(@user.id, amount_cents: 50)).to be(true)
refund = Refund.last
expect(refund.purchase).to eq @purchase
expect(refund.amount_cents).to eq 50
expect(refund.total_transaction_cents).to eq(60) # 50 + 10 gumroad vat tax cents
expect(refund.creator_tax_cents).to eq 0
expect(refund.gumroad_tax_cents).to eq 10
stripe_refund = Stripe::Refund.retrieve(refund.processor_refund_id)
expect(stripe_refund.amount).to eq 60
end
it "refunds with given amount_refundable_cents" do
expect(ChargeProcessor).to receive(:refund!).with(@purchase.charge_processor_id, @purchase.stripe_transaction_id, anything).and_call_original
amount_refundable_cents = @purchase.amount_refundable_cents
total_transaction_cents = @purchase.total_transaction_cents
expect(@purchase.refund_and_save!(@user.id, amount_cents: @purchase.amount_refundable_cents)).to be(true)
refund = Refund.last
expect(refund.purchase).to eq @purchase
expect(refund.amount_cents).to eq amount_refundable_cents
expect(refund.total_transaction_cents).to eq total_transaction_cents
expect(refund.creator_tax_cents).to eq 0
expect(refund.gumroad_tax_cents).to eq(total_transaction_cents - amount_refundable_cents)
end
describe "refund Gumroad taxes" do
it "refunds all taxes collected by Gumroad" do
expect(ChargeProcessor).to receive(:refund!)
.with(@purchase.charge_processor_id, @purchase.stripe_transaction_id,
amount_cents: 20,
reverse_transfer: false,
merchant_account: @purchase.merchant_account,
paypal_order_purchase_unit_refund: false)
.and_call_original
expect(@purchase).not_to receive(:debit_processor_fee_from_merchant_account!).and_call_original
@purchase.refund_gumroad_taxes!(refunding_user_id: @product.user.id, note: "VAT_ID_1234_Dummy")
expect(Refund.last.purchase).to eq @purchase
expect(Refund.last.refunding_user_id).to eq @product.user.id
expect(Refund.last.amount_cents).to eq 0
expect(Refund.last.total_transaction_cents).to eq 20
expect(Refund.last.creator_tax_cents).to eq 0
expect(Refund.last.gumroad_tax_cents).to eq 20
expect(Refund.last.note).to eq "VAT_ID_1234_Dummy"
expect(Refund.last.processor_refund_id).to be_present
expect(@purchase.reload.stripe_refunded).to be(false)
end
it "does not deduct the refunded tax amount from the connect account" do
merchant_account = create(:merchant_account_stripe_canada, user: @user)
purchase = create(:purchase_in_progress, link: @product, zip_tax_rate: @zip_tax_rate, chargeable: create(:chargeable))
purchase.process!
purchase.mark_successful!
purchase.gumroad_tax_cents = 20
purchase.total_transaction_cents = purchase.gumroad_tax_cents + purchase.price_cents
purchase.save!
expect(purchase.merchant_account).to eq(merchant_account)
charge_refund = nil
original_stripe_refund = Stripe::Refund.method(:create)
expect(Stripe::Refund).to receive(:create).with({ charge: purchase.stripe_transaction_id, amount: 20 }) do |*args|
charge_refund = original_stripe_refund.call(*args)
charge_refund
end
purchase.refund_gumroad_taxes!(refunding_user_id: purchase.seller.id, note: "VAT_ID_1234_Dummy")
expect(charge_refund.transfer_reversal).to be nil
end
it "does not refund in excess if Gumroad taxes were already refunded - full refund" do
expect(ChargeProcessor).to receive(:refund!)
.with(@purchase.charge_processor_id,
@purchase.stripe_transaction_id,
amount_cents: 20,
reverse_transfer: false,
merchant_account: @purchase.merchant_account,
paypal_order_purchase_unit_refund: false).and_call_original
@purchase.refund_gumroad_taxes!(refunding_user_id: nil)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_process_spec.rb | spec/models/purchase/purchase_process_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Purchase Process", :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
shared_examples_for "skipping chargeable steps" do |for_test_purchase|
it "does not call Stripe" do
expect(Stripe::PaymentIntent).not_to receive(:create)
purchase.process!
end
it "sets fee_cents" do
purchase.process!
purchase.save!
expect(purchase.reload.fee_cents).to eq 93
end
describe "taxes" do
before do
ZipTaxRate.find_or_create_by(country: "GB").update(combined_rate: 0.20)
purchase.country = Compliance::Countries::GBR.common_name
purchase.ip_country = Compliance::Countries::GBR.common_name
end
it "runs the taxation logic" do
purchase.process!
purchase.save!
purchase.reload
expect(purchase.fee_cents).to eq(93)
expect(purchase.gumroad_tax_cents).to eq(20)
expect(purchase.is_test_purchase?).to be(true) if for_test_purchase
end
end
describe "shipping" do
describe "physical product with paid shipping" do
before do
product.update!(is_physical: true, require_shipping: true)
product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 30_00, multiple_items_rate_cents: 10_00)
purchase.update!(full_name: "barnabas", street_address: "123 barnabas street", city: "barnabasville", state: "CA", country: "United States", zip_code: "94114")
end
it "runs the shipping calculation logic" do
purchase.process!
expect(purchase.shipping_cents).to eq(30_00)
expect(purchase.is_test_purchase?).to be(true) if for_test_purchase
end
end
end
end
let(:ip_address) { "24.7.90.214" }
let(:initial_balance) { 200 }
let(:user) { create(:user, unpaid_balance_cents: initial_balance) }
let(:link) { create(:product, user:) }
let(:chargeable) { create :chargeable }
describe "#process!" do
let(:link) { create(:product) }
let(:purchase) do
build(:purchase, link:, ip_address:, purchase_state: "in_progress",
chargeable: build(:chargeable, expiry_date: "12 / 2023"))
end
describe "card values" do
it "has correct card values for normal product" do
purchase.perceived_price_cents = 100
purchase.save_card = false
purchase.process!
purchase.update_balance_and_mark_successful!
expect(purchase.card_visual).to eq "**** **** **** 4242"
expect(purchase.card_expiry_month).to eq 12
expect(purchase.card_expiry_year).to eq 2023
expect(purchase.card_type).to eq "visa"
end
end
describe "major steps involving the chargeable" do
it "gives chargeable from load_chargeable_for_charging --> prepare_chargeable_for_charge!" do
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, chargeable:)
expect(purchase).to receive(:load_chargeable_for_charging).and_return(chargeable)
expect(purchase).to receive(:prepare_chargeable_for_charge!).with(chargeable).and_call_original
purchase.process!
end
it "gives chargeable from prepare_chargeable_for_charge! --> create_charge_intent" do
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, chargeable:)
expect(purchase).to receive(:prepare_chargeable_for_charge!).and_return(chargeable)
expect(purchase).to receive(:create_charge_intent).with(chargeable, anything).and_call_original
purchase.process!
end
describe "#load_chargeable_for_charging" do
it "sets a card error in the errors if one is set as a card params error" do
purchase = build(:purchase_with_balance, card_data_handling_error: CardDataHandlingError.new("Bad card dude", "cvc_check_failed"))
purchase.process!
expect(purchase.errors[:base]).to be_present
expect(purchase.stripe_error_code).to eq "cvc_check_failed"
expect(purchase.charge_processor_id).to be_present
end
it "sets a stripe unavailable error in the errors if some other error is set as a card params error" do
purchase = build(:purchase_with_balance, card_data_handling_error: CardDataHandlingError.new("Wtf", nil))
purchase.process!
expect(purchase.errors[:base]).to be_present
expect(purchase.stripe_error_code).to be(nil)
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
expect(purchase.charge_processor_id).to be_present
end
it "uses the chargeable if one is set" do
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, chargeable:)
expect(purchase).to receive(:prepare_chargeable_for_charge!).with(chargeable).and_call_original
purchase.process!
end
it "uses a chargeable credit card if no chargeable is set, but purchaser with saved card exists" do
user = build(:user)
credit_card = build(:credit_card)
credit_card.users << user
purchase = build(:purchase_with_balance, purchaser: user)
expect(purchase).to receive(:prepare_chargeable_for_charge!).and_call_original
purchase.process!
end
it "uses a chargeable credit card if no chargeable is set, no purchaser with saved card exists, but credit card is already set on purchase" do
credit_card = build(:credit_card)
purchase = build(:purchase_with_balance, credit_card:)
expect(purchase).to receive(:prepare_chargeable_for_charge!).and_call_original
purchase.process!
end
it "sets errors if no chargeable is set, no purchaser with saved card exists, and no credit card is set on purchase" do
purchase = build(:purchase_with_balance)
purchase.process!
expect(purchase.errors[:base]).to be_present
expect(purchase.stripe_error_code).to be(nil)
expect(purchase.error_code).to eq PurchaseErrorCode::CREDIT_CARD_NOT_PROVIDED
end
end
describe "#validate_chargeable_for_charging" do
it "errors if a chargeable is set backed by multiple charge processors" do
chargeable = Chargeable.new([
StripeChargeablePaymentMethod.new(StripePaymentMethodHelper.success.to_stripejs_payment_method_id, customer_id: nil, zip_code: nil, product_permalink: "xx"),
BraintreeChargeableNonce.new(Braintree::Test::Nonce::PayPalFuturePayment, nil)
])
purchase = build(:purchase, purchase_state: "in_progress", chargeable:)
expect { purchase.process! }.to raise_error(RuntimeError, /A chargeable backed by multiple charge processors was provided in purchase/)
end
it "does not error if chargeable is backed by a single charge processor" do
chargeable = build(:chargeable)
purchase = build(:purchase, purchase_state: "in_progress", chargeable:)
expect(purchase).to receive(:validate_chargeable_for_charging).with(chargeable).and_call_original
purchase.process!
expect(purchase.errors[:base]).to be_empty
end
end
describe "#prepare_chargeable_for_charge!" do
it "does not try to resave chargeable if it's a saved card we're using for the purchase" do
users_credit_card = create(:credit_card)
user = create(:user, credit_card: users_credit_card)
purchase = build(:purchase_with_balance, purchaser: user, save_card: true)
purchase.process!(off_session: false)
expect(purchase.credit_card).to eq users_credit_card
end
it "saves card if purchaser has asked to save and return new chargeable for that saved card" do
user = create(:user)
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, purchaser: user, save_card: true, chargeable:)
expect(purchase).to receive(:prepare_chargeable_for_charge!).with(chargeable).and_call_original
expect(purchase).to receive(:create_charge_intent).with(an_instance_of(Chargeable), anything).and_call_original
purchase.process!(off_session: false)
expect(purchase.credit_card).to eq CreditCard.last
expect(user.reload.credit_card).to eq CreditCard.last
end
it "saves the card to the user if the purchase is made with PayPal" do
user = create(:user)
chargeable = build(:paypal_chargeable)
purchase = build(:purchase_with_balance, purchaser: user, save_card: true, chargeable:)
expect(purchase).to receive(:prepare_chargeable_for_charge!).with(chargeable).and_call_original
expect(purchase).to receive(:create_charge_intent).with(an_instance_of(Chargeable), anything).and_call_original
purchase.process!
expect(purchase.credit_card).to eq CreditCard.last
expect(user.reload.credit_card).to eq CreditCard.last
end
it "saves card if preorder and return new chargeable for that saved card" do
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, chargeable:, is_preorder_authorization: true)
expect(purchase).to receive(:prepare_chargeable_for_charge!).with(chargeable).and_call_original
expect(purchase).to_not receive(:create_charge_intent)
purchase.process!
expect(purchase.credit_card).to eq CreditCard.last
end
it "saves card if subscription and return new chargeable for that saved card" do
chargeable = build(:chargeable)
link = create(:membership_product_with_preset_tiered_pricing)
tier = link.tiers.first
purchase = build(:purchase_with_balance, chargeable:, link:, variant_attributes: [tier], price: link.default_price)
expect(purchase).to receive(:prepare_chargeable_for_charge!).with(chargeable).and_call_original
expect(purchase).to receive(:create_charge_intent).with(an_instance_of(Chargeable), anything).and_call_original
purchase.process!(off_session: false)
expect(purchase.credit_card).to eq CreditCard.last
end
it "prepares chargeable" do
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, chargeable:)
expect(chargeable).to receive(:prepare!).and_call_original
purchase.process!
end
it "sets info on purchase about card" do
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, chargeable:)
expect(purchase).to receive(:stripe_fingerprint=).exactly(2).times.and_call_original
expect(purchase).to receive(:card_type=).exactly(1).times.with("visa").and_call_original
expect(purchase).to receive(:card_country=).with("US").and_call_original
expect(purchase).to receive(:credit_card_zipcode=).with(chargeable.zip_code).and_call_original
allow(purchase).to receive(:card_visual=).with(nil).and_call_original
expect(purchase).to receive(:card_visual=).with("**** **** **** 4242").at_least(1).times.and_call_original
expect(purchase).to receive(:card_expiry_month=).at_least(1).times.and_call_original
expect(purchase).to receive(:card_expiry_year=).at_least(1).times.and_call_original
purchase.process!
end
describe "card country" do
it "leaves card country unset if card country on chargeable is blank" do
chargeable = build(:chargeable)
allow(chargeable).to receive(:country).and_return(nil)
allow_any_instance_of(StripeCharge).to receive(:card_country).and_return("US")
purchase = build(:purchase_with_balance, chargeable:, card_country: nil)
expect(purchase).to receive(:stripe_fingerprint=).exactly(2).times.and_call_original
expect(purchase).to receive(:card_type=).exactly(1).times.with("visa").and_call_original
expect(purchase).to receive(:card_country=).with(nil).and_call_original # when preparing chargeable
expect(purchase).to receive(:credit_card_zipcode=).with(chargeable.zip_code).and_call_original
allow(purchase).to receive(:card_visual=).with(nil).and_call_original
expect(purchase).to receive(:card_visual=).with("**** **** **** 4242").at_least(1).times.and_call_original
expect(purchase).to receive(:card_expiry_month=).at_least(1).times.and_call_original
expect(purchase).to receive(:card_expiry_year=).at_least(1).times.and_call_original
purchase.process!
expect(purchase.card_country).to be_nil
expect(purchase.card_country_source).to be_nil
end
end
describe "charge processor errors" do
describe "new chargeable" do
let(:chargeable) { build(:chargeable) }
let(:purchase) { build(:purchase_with_balance, chargeable:) }
describe "charge processor unavailable" do
before do
expect(chargeable).to receive(:prepare!).and_raise(ChargeProcessorUnavailableError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor invalid request" do
before do
expect(chargeable).to receive(:prepare!).and_raise(ChargeProcessorInvalidRequestError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor card error" do
before do
expect(chargeable).to receive(:prepare!) { raise ChargeProcessorCardError, "card-error-code" }
purchase.process!
end
it "sets card error code" do
expect(purchase.stripe_error_code).to eq "card-error-code"
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
end
describe "new chargeable and save card" do
let(:chargeable) { build(:chargeable) }
let(:user) { create(:user) }
let(:purchase) { build(:purchase_with_balance, chargeable:, save_card: true, purchaser: user) }
describe "charge processor unavailable" do
before do
expect(chargeable).to receive(:prepare!).and_raise(ChargeProcessorUnavailableError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor invalid request" do
before do
expect(chargeable).to receive(:prepare!).and_raise(ChargeProcessorInvalidRequestError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor card error" do
before do
expect(chargeable).to receive(:prepare!) { raise ChargeProcessorCardError, "card-error-code" }
purchase.process!
end
it "sets card error code" do
expect(purchase.stripe_error_code).to eq "card-error-code"
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
end
end
end
describe "#create_charge_intent" do
it "sends charge chargeable" do
chargeable = build(:chargeable)
purchase = build(:purchase_with_balance, chargeable:)
expect(purchase).to receive(:create_charge_intent).with(chargeable, anything).and_call_original
purchase.process!
end
it "does not update payment intent id on the associated credit card when mandate options are not present" do
purchase = build(:purchase_with_balance, chargeable: build(:chargeable), credit_card: create(:credit_card, card_country: "IN"))
allow(purchase).to receive(:mandate_options_for_stripe).and_return nil
expect(purchase.credit_card).not_to receive(:update!)
purchase.process!
end
it "updates payment intent id on the associated credit card when mandate options are present" do
purchase = build(:purchase_with_balance, chargeable: build(:chargeable), credit_card: create(:credit_card, card_country: "IN"))
mandate_options = { payment_method_options: {} }
allow(purchase).to receive(:mandate_options_for_stripe).and_return mandate_options
expect(purchase.credit_card).to receive(:update!).and_call_original
purchase.process!
end
describe "charge processor errors" do
describe "new chargeable" do
let(:chargeable) { build(:chargeable) }
let(:purchase) { build(:purchase_with_balance, chargeable:) }
describe "charge processor unavailable" do
before do
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).and_raise(ChargeProcessorUnavailableError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor invalid request" do
before do
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).and_raise(ChargeProcessorInvalidRequestError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor card error" do
before do
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!) { raise ChargeProcessorCardError, "card-error-code" }
purchase.process!
end
it "sets card error code" do
expect(purchase.stripe_error_code).to eq "card-error-code"
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
end
describe "new chargeable and save card" do
let(:chargeable) { build(:chargeable) }
let(:user) { create(:user) }
let(:purchase) { build(:purchase_with_balance, chargeable:, save_card: true, purchaser: user) }
describe "charge processor unavailable" do
before do
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).and_raise(ChargeProcessorUnavailableError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor invalid request" do
before do
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).and_raise(ChargeProcessorInvalidRequestError)
purchase.process!
end
it "sets error code" do
expect(purchase.error_code).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
describe "charge processor card error" do
before do
expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!) { raise ChargeProcessorCardError, "card-error-code" }
purchase.process!
end
it "sets card error code" do
expect(purchase.stripe_error_code).to eq "card-error-code"
end
it "sets errors" do
expect(purchase.errors).to be_present
end
end
end
end
end
end
describe "purchase with perceived_price_cents too low" do
let(:link) { create(:product, price_cents: 200) }
before do
purchase.perceived_price_cents = 100
purchase.save_card = false
purchase.ip_address = ip_address
purchase.process!
end
it "creates the purchase object with the right error code" do
expect(purchase.errors).to be_present
expect(purchase.reload.error_code).to eq "perceived_price_cents_not_matching"
end
end
describe "purchase with high price" do
let(:link) { create(:product, price_cents: 100, customizable_price: true) }
before do
@chargeable = build(:chargeable)
@purchase = build(:purchase, link:, chargeable: @chargeable, perceived_price_cents: 500_001, save_card: false,
ip_address:, price_range: "5000.01")
@purchase.process!
end
it "creates the purchase object with the right error code" do
expect(@purchase.errors).to be_present
expect(@purchase.reload.error_code).to eq "price_too_high"
end
end
describe "purchase with low contirbution amount" do
let(:link) { create(:product, price_cents: 0, customizable_price: true) }
before do
purchase.perceived_price_cents = 30
purchase.price_range = ".30"
purchase.process!
end
it "creates the purchase object with the right error code" do
expect(purchase.errors).to be_present
expect(purchase.reload.error_code).to eq "contribution_too_low"
end
end
describe "purchase with negative seller revenue" do
let(:product) { create(:product, price_cents: 100) }
let(:affiliate) { create(:direct_affiliate, affiliate_basis_points: 7500, products: [product]) }
let(:affiliate_purchase) { create(:purchase, link: product, seller: product.user, affiliate:, save_card: false, ip_address:, chargeable:) }
before do
allow_any_instance_of(Purchase).to receive(:determine_affiliate_balance_cents).and_return(90)
affiliate_purchase.process!
end
it "creates a purchase object with the correct error code" do
expect(affiliate_purchase.error_code).to eq "net_negative_seller_revenue"
expect(affiliate_purchase.errors.to_a).to eq(["Your purchase failed because the product is not correctly set up. Please contact the creator for more information."])
end
end
describe "purchase of product with customizable price and offer codes" do
before do
@pwyw_product = create(:product, user: create(:user), price_cents: 50_00, customizable_price: true)
@pwyw_offer_code = OfferCode.create!(user: @pwyw_product.user, code: "10off", amount_cents: 10_00, currency_type: Currency::USD)
end
describe "intended purchase price greater than minimum after offer codes" do
before(:each) do
@purchase = create(:purchase, link: @pwyw_product, chargeable: create(:paypal_chargeable), save_card: false,
price_range: 1, perceived_price_cents: 44_00,
offer_code: @pwyw_offer_code, discount_code: @pwyw_offer_code.code)
end
it "allows / creates a purchase and does not return an error code" do
expect(@purchase.errors).to_not be_present
end
it "records discount details" do
@purchase.process!
discount = @purchase.purchase_offer_code_discount
expect(discount).to be
expect(discount.offer_code).to eq @pwyw_offer_code
expect(discount.offer_code_amount).to eq 10_00
expect(discount.offer_code_is_percent).to eq false
expect(discount.pre_discount_minimum_price_cents).to eq 50_00
end
end
describe "intended purchase price greater than minimum after offer codes" do
before(:each) do
@purchase = create(:purchase, link: @pwyw_product, chargeable: create(:paypal_chargeable), save_card: false,
price_range: 1, perceived_price_cents: 39_00,
offer_code: @pwyw_offer_code, discount_code: @pwyw_offer_code.code)
end
it "creates the purchase object with the right error code" do
expect(@purchase.errors).to be_present
expect(@purchase.reload.error_code).to eq "perceived_price_cents_not_matching"
end
it "records discount details" do
@purchase.process!
discount = @purchase.purchase_offer_code_discount
expect(discount).to be
expect(discount.offer_code).to eq @pwyw_offer_code
expect(discount.offer_code_amount).to eq 10_00
expect(discount.offer_code_is_percent).to eq false
expect(discount.pre_discount_minimum_price_cents).to eq 50_00
end
end
end
describe "with commas" do
before do
@product = create(:product, price_cents: 100)
@chargeable = build(:chargeable)
end
it "sets the correct price on the purchase" do
@purchase = build(:purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 100, save_card: false,
ip_address:, price_range: "13,50")
@purchase.process!
expect(@purchase.price_cents).to eq 1350
expect(@purchase.total_transaction_cents).to eq 1350
end
it "sets the correct price on the purchase" do
@purchase = build(:purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 100, save_card: false,
ip_address:, price_range: "13,5")
@purchase.process!
expect(@purchase.price_cents).to eq 1350
expect(@purchase.total_transaction_cents).to eq 1350
end
end
describe "multi-quantity purchase" do
before do
@product = create(:physical_product, price_cents: 500, max_purchase_count: 10)
@chargeable = build(:chargeable)
end
describe "setting price_cents" do
it "sets the correct price cents based off the link price and quantity" do
purchase = create(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 500, save_card: false, ip_address:, quantity: 5)
purchase.process!
expect(purchase.errors).to be_empty
expect(purchase.price_cents).to eq 2500
end
end
describe "validating product quantity" do
it "lets the purchase go through when quantity is less than products available" do
purchase = create(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 500, save_card: false, ip_address:, quantity: 5)
purchase.process!
expect(purchase.errors).to be_empty
expect(purchase.successful?).to eq true
expect(purchase.quantity).to eq 5
end
it "lets the purchase go through when quantity is equal to products available" do
purchase = build(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 5000, save_card: false, ip_address:, quantity: 10)
purchase.variant_attributes << @product.skus.is_default_sku.first
purchase.process!
expect(purchase.errors).to be_empty
expect(purchase.successful?).to eq true
expect(purchase.quantity).to eq 10
end
it "does not let the purchase go through when quantity is greater than products available" do
purchase = build(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 7500, save_card: false, ip_address:, quantity: 15)
purchase.process!
expect(purchase.errors).to be_present
expect(purchase.error_code).to eq "exceeding_product_quantity"
expect(purchase.quantity).to eq 15
end
end
describe "validating variant quantity" do
before do
@category = create(:variant_category, title: "sizes", link: @product)
@variant = create(:variant, name: "small", price_difference_cents: 300, variant_category: @category, max_purchase_count: 5)
@product.update_attribute(:skus_enabled, false)
end
it "lets the purchase go through when quantity is less than variants available" do
purchase = create(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 2400, save_card: false, ip_address:, quantity: 3)
purchase.variant_attributes << @variant
purchase.process!
expect(purchase.errors).to be_empty
expect(purchase.successful?).to eq true
expect(purchase.quantity).to eq 3
end
it "lets the purchase go through when quantity is equal to variants available" do
purchase = build(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 4000, save_card: false, ip_address:, quantity: 5)
purchase.variant_attributes << @variant
purchase.process!
expect(purchase.errors).to be_empty
expect(purchase.successful?).to eq true
expect(purchase.quantity).to eq 5
end
it "does not let the purchase go through when quantity is greater than variants available" do
purchase = build(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 8000, save_card: false, ip_address:, quantity: 10)
purchase.variant_attributes << @variant
purchase.process!
expect(purchase.errors).to be_present
expect(purchase.error_code).to eq "exceeding_variant_quantity"
expect(purchase.quantity).to eq 10
end
end
describe "validating offer code quantity" do
before do
@offer = create(:offer_code, products: [@product], code: "sxsw", amount_cents: 100, max_purchase_count: 5)
end
it "lets the purchase go through when quantity is less than offer codes available" do
purchase = create(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 1200, save_card: false, ip_address:, offer_code: @offer, quantity: 3)
purchase.discount_code = @offer.code
purchase.process!
expect(purchase.errors).to be_empty
expect(purchase.successful?).to eq true
expect(purchase.quantity).to eq 3
end
it "lets the purchase go through when quantity is equal to offer codes available" do
purchase = build(:physical_purchase, link: @product, chargeable: @chargeable, perceived_price_cents: 2000, save_card: false, ip_address:, offer_code: @offer, quantity: 5)
purchase.variant_attributes << @product.skus.is_default_sku.first
purchase.discount_code = @offer.code
purchase.process!
expect(purchase.errors).to be_empty
expect(purchase.successful?).to eq true
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_notification_spec.rb | spec/models/purchase/purchase_notification_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Purchase Notifications", :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
let(:ip_address) { "24.7.90.214" }
let(:initial_balance) { 200 }
let(:user) { create(:user, unpaid_balance_cents: initial_balance) }
let(:link) { create(:product, user:) }
let(:chargeable) { create :chargeable }
describe "#send_notification_webhook" do
it "schedules a `PostToPingEndpointsWorker` job" do
purchase = create(:purchase)
purchase.send_notification_webhook
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(purchase.id, purchase.url_parameters)
end
it "does not schedule a PostToPingEndpointsWorker job if the transaction creating the purchase was rolled back" do
Purchase.transaction do
create(:purchase).send_notification_webhook
raise ActiveRecord::Rollback
end
expect(PostToPingEndpointsWorker.jobs.size).to eq(0)
end
it "schedules a PostToPingEndpointsWorker job if the transaction creating the purchase was committed" do
purchase = nil
Purchase.transaction do
purchase = create(:purchase)
purchase.send_notification_webhook
end
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(purchase.id, purchase.url_parameters)
end
describe "with offer code" do
before do
@product = create(:product, price_cents: 600, user: create(:user, notification_endpoint: "http://notification.com"))
@offer_code = create(:offer_code, products: [@product], code: "sxsw", amount_cents: 200)
@purchase = create(:purchase, link: @product, seller: @product.user, price_cents: 400, email: "sahil@sahil.com",
full_name: "sahil lavingia", purchase_state: "in_progress", offer_code: @offer_code)
end
it "sends the notification webhook" do
@purchase.send_notification_webhook
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(@purchase.id, nil)
end
end
describe "with gifting" do
before do
@product = create(:product, price_cents: 600, user: create(:user, notification_endpoint: "http://notification.com"))
gifter_email = "gifter@foo.com"
giftee_email = "giftee@foo.com"
gift = create(:gift, gifter_email:, giftee_email:, link: @product)
@gifter_purchase = create(:purchase, link: @product, seller: @product.user, price_cents: @product.price_cents,
full_name: "sahil lavingia", email: gifter_email, purchase_state: "in_progress")
gift.gifter_purchase = @gifter_purchase
@gifter_purchase.is_gift_sender_purchase = true
@gifter_purchase.save!
@giftee_purchase = gift.giftee_purchase = create(:purchase, link: @product, seller: @product.user, email: giftee_email, price_cents: 0,
stripe_transaction_id: nil, stripe_fingerprint: nil,
is_gift_receiver_purchase: true, purchase_state: "in_progress")
gift.mark_successful
gift.save!
end
it "sends the notification webhook for giftee purchase" do
@giftee_purchase.send_notification_webhook
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(@giftee_purchase.id, nil)
end
it "does not send the notification webhook for gifter purchase" do
@gifter_purchase.send_notification_webhook
expect(PostToPingEndpointsWorker).to_not have_enqueued_sidekiq_job(@product.user.id,
@product.id,
@gifter_purchase.email,
@gifter_purchase.price_cents,
@product.price_currency_type,
false,
nil,
{},
{},
nil,
nil,
false,
false,
"sahil lavingia",
@gifter_purchase.id)
end
end
describe "recurring charge" do
let(:product) do
create(:membership_product, price_cents: 600, user: create(:user, notification_endpoint: "http://notification.com"))
end
let(:recurring_purchase) do
create(:recurring_membership_purchase, link: product, seller: product.user, purchase_state: "in_progress", price_cents: product.price_cents)
end
it "does not send the notification webhook" do
recurring_purchase.send_notification_webhook
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(recurring_purchase.id, nil)
end
end
end
describe "#send_notification_webhook_from_ui" do
before do
product = create(:product, user: create(:user, notification_endpoint: "http://notification.com"))
gifter_email = "gifter@foo.com"
giftee_email = "giftee@foo.com"
gift = create(:gift, gifter_email:, giftee_email:, link: product)
@gifter_purchase = create(:purchase, :gift_sender,
link: product, seller: product.user, price_cents: product.price_cents,
email: gifter_email, purchase_state: "in_progress", gift_given: gift)
@giftee_purchase = create(:purchase, :gift_receiver,
link: product, seller: product.user, email: giftee_email, price_cents: 0,
stripe_transaction_id: nil, stripe_fingerprint: nil, gift_received: gift,
purchase_state: "in_progress")
gift.mark_successful
gift.save!
end
it "when called for the giftee purchase it sends the notification webhook for the giftee purchase" do
@giftee_purchase.send_notification_webhook_from_ui
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(@giftee_purchase.id, nil)
expect(PostToPingEndpointsWorker).to_not have_enqueued_sidekiq_job(@gifter_purchase.id, nil)
end
it "when called for the gifter purchase it sends the notification webhook for the giftee purchase" do
@gifter_purchase.send_notification_webhook_from_ui
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(@giftee_purchase.id, nil)
expect(PostToPingEndpointsWorker).to_not have_enqueued_sidekiq_job(@gifter_purchase.id, nil)
end
end
describe "#send_refunded_notification_webhook" do
it "enqueues the post to ping job for refunded notification" do
purchase = create(:purchase)
purchase.send(:send_refunded_notification_webhook)
expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(purchase.id, nil, ResourceSubscription::REFUNDED_RESOURCE_NAME)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase/purchase_subscription_spec.rb | spec/models/purchase/purchase_subscription_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PurchaseSubscription", :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
describe "subscriptions" do
describe "original subscription purchase" do
before do
tier_prices = [
{ monthly: { enabled: true, price: 2 }, quarterly: { enabled: true, price: 12 },
biannually: { enabled: true, price: 20 }, yearly: { enabled: true, price: 30 },
every_two_years: { enabled: true, price: 50 } },
{ monthly: { enabled: true, price: 4 }, quarterly: { enabled: true, price: 13 },
biannually: { enabled: true, price: 21 }, yearly: { enabled: true, price: 31 },
every_two_years: { enabled: true, price: 51 } }
]
@product = create(:membership_product_with_preset_tiered_pricing, recurrence_price_values: tier_prices)
@seller = @product.user
@buyer = create(:user)
@purchase = create(:membership_purchase, link: @product, seller: @seller, subscription: @subscription, price_cents: 200, purchase_state: "in_progress")
@subscription = @purchase.subscription
@buyer = @purchase.purchaser
end
describe "when set to successful" do
it "increments seller's balance" do
expect { @purchase.update_balance_and_mark_successful! }.to change {
@purchase.link.user.reload.unpaid_balance_cents
}.by(@purchase.payment_cents)
end
it "creates url_redirect" do
expect { @purchase.update_balance_and_mark_successful! }.to change {
UrlRedirect.count
}
end
describe "subscription jobs" do
it "enqueues a recurring charge" do
freeze_time do
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(@subscription.id).at(1.month.from_now)
end
end
describe "renewal reminders" do
before { allow(@subscription).to receive(:send_renewal_reminders?).and_return(true) }
it "schedules a renewal reminder if the billing period is quarterly" do
freeze_time do
payment_option = @subscription.last_payment_option
payment_option.update!(price: @product.prices.find_by(recurrence: "quarterly"))
reminder_time = 3.months.from_now - BasePrice::Recurrence::RECURRENCE_TO_RENEWAL_REMINDER_EMAIL_DAYS["quarterly"]
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeReminderWorker).to have_enqueued_sidekiq_job(@subscription.id).at(reminder_time)
end
end
it "schedules a renewal reminder if the billing period is biannually" do
freeze_time do
payment_option = @subscription.last_payment_option
payment_option.update!(price: @product.prices.find_by(recurrence: "biannually"))
reminder_time = 6.months.from_now - BasePrice::Recurrence::RECURRENCE_TO_RENEWAL_REMINDER_EMAIL_DAYS["biannually"]
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeReminderWorker).to have_enqueued_sidekiq_job(@subscription.id).at(reminder_time)
end
end
it "schedules a renewal reminder if the billing period is yearly" do
freeze_time do
payment_option = @subscription.last_payment_option
payment_option.update!(price: @product.prices.find_by(recurrence: "yearly"))
reminder_time = 1.year.from_now - BasePrice::Recurrence::RECURRENCE_TO_RENEWAL_REMINDER_EMAIL_DAYS["yearly"]
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeReminderWorker).to have_enqueued_sidekiq_job(@subscription.id).at(reminder_time)
end
end
it "schedules a renewal reminder if the billing period is every two years" do
freeze_time do
payment_option = @subscription.last_payment_option
payment_option.update!(price: @product.prices.find_by(recurrence: "every_two_years"))
reminder_time = 2.years.from_now - BasePrice::Recurrence::RECURRENCE_TO_RENEWAL_REMINDER_EMAIL_DAYS["every_two_years"]
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeReminderWorker).to have_enqueued_sidekiq_job(@subscription.id).at(reminder_time)
end
end
it "schedules a renewal reminder if the billing period is monthly" do
freeze_time do
payment_option = @subscription.last_payment_option
payment_option.update!(price: @product.prices.find_by(recurrence: "monthly"))
reminder_time = 1.month.from_now - BasePrice::Recurrence::RECURRENCE_TO_RENEWAL_REMINDER_EMAIL_DAYS["monthly"]
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeReminderWorker).to have_enqueued_sidekiq_job(@subscription.id).at(reminder_time)
end
end
it "does not schedule a renewal reminder irrespective of the billing period if the feature is disabled" do
allow(@subscription).to receive(:send_renewal_reminders?).and_return(false)
freeze_time do
payment_option = @subscription.last_payment_option
payment_option.update!(price: @product.prices.find_by(recurrence: "quarterly"))
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeReminderWorker.jobs.count).to eq(0)
end
end
end
describe "with shipping information" do
before do
@product = create(:product, user: @seller, is_recurring_billing: true, subscription_duration: :monthly, require_shipping: true)
@subscription = create(:subscription, link: @product)
@purchase = create(:purchase, is_original_subscription_purchase: true, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, price_cents: 200, fee_cents: 10, purchase_state: "successful",
full_name: "Edgar Gumstein", street_address: "123 Gum Road", country: "USA", state: "CA",
city: "San Francisco", subscription: @subscription, zip_code: "94117")
end
it "is valid without shipping information" do
@recurring_charge = build(:purchase, is_original_subscription_purchase: false, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, price_cents: 200, fee_cents: 10,
purchase_state: "in_progress", subscription: @subscription)
expect(@recurring_charge.update_balance_and_mark_successful!).to be(true)
end
end
describe "yearly subscriptions" do
before do
@product = create(:product, user: @seller, is_recurring_billing: true, subscription_duration: :yearly)
@subscription = create(:subscription, link: @product)
@purchase = build(:purchase, is_original_subscription_purchase: true, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, subscription: @subscription, price_cents: 200, fee_cents: 10, purchase_state: "in_progress")
end
it "enqueues a recurring charge" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
freeze_time do
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(@subscription.id).at(1.year.from_now)
end
end
end
describe "quarterly subscriptions" do
before do
@product = create(:product, user: @seller, is_recurring_billing: true, subscription_duration: :quarterly)
@subscription = create(:subscription, link: @product)
@purchase = build(:purchase, is_original_subscription_purchase: true, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, subscription: @subscription, price_cents: 200, fee_cents: 10, purchase_state: "in_progress")
end
it "enqueues a recurring charge" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
freeze_time do
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(@subscription.id).at(3.months.from_now)
end
end
end
describe "biannually subscriptions" do
before do
@product = create(:product, user: @seller, is_recurring_billing: true, subscription_duration: :biannually)
@subscription = create(:subscription, link: @product)
@purchase = build(:purchase, is_original_subscription_purchase: true, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, subscription: @subscription, price_cents: 200, fee_cents: 10, purchase_state: "in_progress")
end
it "enqueues a recurring charge" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
freeze_time do
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(@subscription.id).at(6.months.from_now)
end
end
end
describe "every two years subscriptions" do
before do
@product = create(:product, user: @seller, is_recurring_billing: true, subscription_duration: :every_two_years)
@subscription = create(:subscription, link: @product)
@purchase = build(:purchase, is_original_subscription_purchase: true, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, subscription: @subscription, price_cents: 200, fee_cents: 10, purchase_state: "in_progress")
end
it "enqueues a recurring charge" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
freeze_time do
@purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(@subscription.id).at(2.years.from_now)
end
end
end
end
end
end
describe "recurring subscription purchase" do
context "for a digital product" do
let(:seller) { create(:named_seller) }
let(:link) { create(:product, user: seller, is_recurring_billing: true, subscription_duration: :monthly) }
let(:buyer) { create(:user) }
let(:subscription) { create(:subscription, link:) }
let(:purchase) do
build(:purchase, credit_card: create(:credit_card), purchaser: buyer, link:, seller:,
price_cents: 200, fee_cents: 10, purchase_state: "in_progress", subscription:)
end
before do
create(:purchase, subscription:, is_original_subscription_purchase: true)
index_model_records(Purchase)
end
describe "when set to successful" do
it "increments seller's balance" do
expect { purchase.update_balance_and_mark_successful! }.to change {
seller.reload.unpaid_balance_cents
}.by(purchase.payment_cents)
end
it "creates url_redirect" do
expect { purchase.update_balance_and_mark_successful! }.to change {
UrlRedirect.count
}
end
it "enqueues a job to send the receipt" do
purchase.update_balance_and_mark_successful!
expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(purchase.id).on("critical")
end
it "sends an email to the creator" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(ContactingCreatorMailer).to receive(:notify).and_return(mail_double)
purchase.update_balance_and_mark_successful!
end
it "does not send an email to the creator if notifications are disabled" do
expect(ContactingCreatorMailer).to_not receive(:mail)
seller.update!(enable_recurring_subscription_charge_email: true)
Sidekiq::Testing.inline! do
purchase.update_balance_and_mark_successful!
end
end
it "does not send a push notification to the creator if notifications are disabled" do
seller.update!(enable_recurring_subscription_charge_push_notification: true)
Sidekiq::Testing.inline! do
purchase.update_balance_and_mark_successful!
end
expect(PushNotificationWorker.jobs.size).to eq(0)
end
it "bills the original amount even when subscription and variant prices change" do
category = create(:variant_category, title: "sizes", link:)
variant = create(:variant, name: "small", price_difference_cents: 300, variant_category: category, max_purchase_count: 5)
subscription = create(:subscription, link:)
purchase = build(:purchase, subscription:, is_original_subscription_purchase: true, seller: link.user, link:)
purchase.variant_attributes << variant
purchase.save!
link.update!(price_cents: 9999)
variant.update!(price_difference_cents: 500)
travel_to(1.day.from_now) do
subscription.charge!
end
expect(subscription.purchases.size).to be 2
expect(subscription.purchases.last.price_cents).to be purchase.price_cents
end
describe "monthly charges" do
let(:link) { create(:product, user: seller, is_recurring_billing: true, subscription_duration: :monthly) }
it "enqueues a recurring charge" do
freeze_time do
purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(subscription.id).at(1.month.from_now)
end
end
end
describe "yearly charges" do
let(:link) { create(:product, user: seller, is_recurring_billing: true, subscription_duration: :yearly) }
it "enqueues a recurring charge" do
freeze_time do
purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(subscription.id).at(1.year.from_now)
end
end
end
describe "quarterly charges" do
let(:link) { create(:product, user: seller, is_recurring_billing: true, subscription_duration: :quarterly) }
it "enqueues a recurring charge" do
freeze_time do
purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(subscription.id).at(3.months.from_now)
end
end
end
describe "biannually charges" do
let(:link) { create(:product, user: seller, is_recurring_billing: true, subscription_duration: :biannually) }
it "enqueues a recurring charge" do
freeze_time do
purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(subscription.id).at(6.months.from_now)
end
end
end
describe "every two years charges" do
let(:link) { create(:product, user: seller, is_recurring_billing: true, subscription_duration: :every_two_years) }
it "enqueues a recurring charge" do
freeze_time do
purchase.update_balance_and_mark_successful!
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(subscription.id).at(2.years.from_now)
end
end
end
it "is successful even if the product is unpublished" do
link.update_attribute(:purchase_disabled_at, Time.current)
purchase.update_balance_and_mark_successful!
expect(purchase.reload.successful?).to be(true)
end
end
describe "when subscription is invalid" do
before do
@seller = create(:user)
@product = create(:subscription_product, user: @seller)
@buyer = create(:user)
@subscription = create(:subscription, link: @product)
create(:purchase, subscription: @subscription, is_original_subscription_purchase: true)
@subscription.cancelled_at = Time.current
@subscription.save
@purchase = build(:purchase, is_original_subscription_purchase: false, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, price_cents: 200, fee_cents: 10,
purchase_state: "in_progress", subscription: @subscription.reload)
end
it "purchase is not valid" do
expect(@purchase.save).to be(true)
expect(@purchase.error_code).to eq "subscription_inactive"
end
end
end
context "for a physical product" do
let(:seller) { create(:named_seller) }
let(:product) do
product = create(:physical_product, user: seller, is_recurring_billing: true, subscription_duration: :monthly)
product.shipping_destinations.first.update!(country_code: Compliance::Countries::USA.alpha2)
product
end
let(:subscription) { create(:subscription, link: product) }
let(:original_purchase) do
create(:physical_purchase, link: product, subscription:, is_original_subscription_purchase: true)
end
before do
expect(original_purchase.shipping_cents).to eq(0) # Creates the original purchase as well
end
it "uses the original shipping cost" do
# Set a new shipping cost
product.shipping_destinations.first.update!(one_item_rate_cents: 500, multiple_items_rate_cents: 500)
purchase = create(:physical_purchase, credit_card: create(:credit_card), purchaser: create(:user),
link: product, seller:, price_cents: 200, fee_cents: 10,
purchase_state: "in_progress", subscription:)
purchase.process!
expect(purchase.shipping_cents).to eq(0)
end
end
end
describe "with dollars and cents price difference" do
before do
@buyer = create(:user)
@seller = create(:user)
@product = create(:product, user: @seller, is_recurring_billing: true, subscription_duration: :monthly)
@subscription = create(:subscription, link: @product)
@purchase = create(:purchase, is_original_subscription_purchase: true, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, price_cents: 250, subscription: @subscription, purchase_state: "in_progress")
expect(@purchase.update_balance_and_mark_successful!).to be(true)
end
it "recurring charges are valid" do
@recurring_charge = build(:purchase, is_original_subscription_purchase: false, credit_card: create(:credit_card), purchaser: @buyer,
link: @product, seller: @seller, price_cents: 250,
subscription: @subscription, purchase_state: "in_progress")
@recurring_charge.process!
expect(@recurring_charge.errors.present?).to be(false)
expect(@recurring_charge.update_balance_and_mark_successful!).to be(true)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/payment_option/installment_plan_snapshot_spec.rb | spec/models/payment_option/installment_plan_snapshot_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "PaymentOption installment plan snapshots" do
let(:seller) { create(:user) }
let(:product) { create(:product, user: seller, price_cents: 14700) }
let(:installment_plan) { create(:product_installment_plan, link: product, number_of_installments: 3, recurrence: "monthly") }
let(:subscription) { create(:subscription, link: product, user: seller) }
let(:payment_option) { create(:payment_option, subscription: subscription, installment_plan: installment_plan) }
describe "association" do
it "has one installment_plan_snapshot" do
expect(payment_option).to respond_to(:installment_plan_snapshot)
end
it "can build an installment_plan_snapshot" do
snapshot = payment_option.build_installment_plan_snapshot(
number_of_installments: 3,
recurrence: "monthly",
total_price_cents: 14700
)
expect(snapshot).to be_a(InstallmentPlanSnapshot)
expect(snapshot.payment_option).to eq(payment_option)
expect(snapshot.number_of_installments).to eq(3)
expect(snapshot.recurrence).to eq("monthly")
expect(snapshot.total_price_cents).to eq(14700)
end
end
describe "snapshot creation" do
it "creates snapshot with correct attributes" do
payment_option.build_installment_plan_snapshot(
number_of_installments: installment_plan.number_of_installments,
recurrence: installment_plan.recurrence,
total_price_cents: 14700
)
payment_option.save!
snapshot = payment_option.installment_plan_snapshot
expect(snapshot).to be_present
expect(snapshot.number_of_installments).to eq(3)
expect(snapshot.recurrence).to eq("monthly")
expect(snapshot.total_price_cents).to eq(14700)
end
end
describe "price protection" do
let!(:snapshot) do
create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 3,
recurrence: "monthly",
total_price_cents: 14700)
end
context "when product price increases" do
it "maintains original installment amounts" do
expect(snapshot.total_price_cents).to eq(14700)
expect(snapshot.number_of_installments).to eq(3)
payments = snapshot.calculate_installment_payment_price_cents
expect(payments).to eq([4900, 4900, 4900])
end
end
context "when product price decreases" do
it "maintains original installment amounts" do
product.update!(price_cents: 10000)
snapshot.reload
expect(snapshot.total_price_cents).to eq(14700)
payments = snapshot.calculate_installment_payment_price_cents
expect(payments).to eq([4900, 4900, 4900])
end
end
end
describe "installment configuration protection" do
let!(:snapshot) do
create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 3,
recurrence: "monthly",
total_price_cents: 14700)
end
context "when installment count changes" do
it "maintains original count when changed from 3 to 2" do
installment_plan.update!(number_of_installments: 2)
snapshot.reload
expect(snapshot.number_of_installments).to eq(3)
expect(installment_plan.reload.number_of_installments).to eq(2)
end
it "maintains original count when changed from 3 to 5" do
installment_plan.update!(number_of_installments: 5)
snapshot.reload
expect(snapshot.number_of_installments).to eq(3)
expect(installment_plan.reload.number_of_installments).to eq(5)
end
end
end
describe "backwards compatibility" do
context "when no snapshot exists" do
it "can still access installment_plan through payment_option" do
expect(payment_option.installment_plan_snapshot).to be_nil
expect(payment_option.installment_plan).to eq(installment_plan)
expect(payment_option.installment_plan.number_of_installments).to eq(3)
expect(payment_option.installment_plan.recurrence).to eq("monthly")
end
end
context "when snapshot exists" do
let!(:snapshot) do
create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 5,
recurrence: "weekly",
total_price_cents: 20000)
end
it "can access both snapshot and live plan" do
expect(payment_option.installment_plan_snapshot.number_of_installments).to eq(5)
expect(payment_option.installment_plan_snapshot.recurrence).to eq("weekly")
expect(payment_option.installment_plan.number_of_installments).to eq(3)
expect(payment_option.installment_plan.recurrence).to eq("monthly")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/file_group_download_all.rb | spec/shared_examples/file_group_download_all.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "a product with 'Download all' buttons on file embed groups" do
before do
file1 = create(:product_file, display_name: "File 1")
file2 = create(:product_file, display_name: "File 2")
@file3 = create(:product_file, display_name: "File 3")
file4 = create(:product_file, display_name: "File 4")
file5 = create(:product_file, display_name: "File 5")
file6 = create(:product_file, filetype: "link", url: "https://www.google.com")
file7 = create(:product_file, filetype: "link", url: "https://www.gumroad.com")
file8 = create(:product_file, filetype: "link", url: "https://www.twitter.com")
@file9 = create(:product_file, display_name: "File 9")
file10 = create(:product_file, display_name: "File 10", size: 400000000)
file11 = create(:product_file, display_name: "File 11", size: 300000000)
product.product_files = [file1, file2, @file3, file4, file5, file6, file7, file8, @file9, file10, file11]
folder1_id = SecureRandom.uuid
folder2_id = SecureRandom.uuid
page1_description = [
{ "type" => "fileEmbedGroup",
"attrs" => { "name" => "folder 1", "uid" => folder1_id },
"content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup",
"attrs" => { "name" => "", "uid" => SecureRandom.uuid },
"content" => [{ "type" => "fileEmbed", "attrs" => { "id" => @file3.external_id, "uid" => SecureRandom.uuid } }] },
{ "type" => "fileEmbedGroup",
"attrs" => { "name" => "only 1 downloadable file", "uid" => SecureRandom.uuid },
"content" => [{ "type" => "fileEmbed", "attrs" => { "id" => file8.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => @file9.external_id, "uid" => SecureRandom.uuid } }] }
]
page2_description = [
{ "type" => "fileEmbedGroup",
"attrs" => { "name" => "Page 2 folder", "uid" => folder2_id },
"content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file5.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup",
"attrs" => { "name" => "no downloadable files", "uid" => SecureRandom.uuid },
"content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file6.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file7.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup",
"attrs" => { "name" => "total file size exceeds limit", "uid" => SecureRandom.uuid },
"content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file10.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file11.external_id, "uid" => SecureRandom.uuid } },
] }
]
create(:rich_content, entity: product, title: "Page 1", description: page1_description)
create(:rich_content, entity: product, title: "Page 2", description: page2_description)
@page1_folder_archive = product.product_files_archives.new(folder_id: folder1_id)
@page1_folder_archive.set_url_if_not_present
@page1_folder_archive.product_files = [file1, file2]
@page1_folder_archive.save!
@page1_folder_archive.mark_in_progress!
@page1_folder_archive.mark_ready!
@page2_folder_archive = product.product_files_archives.new(folder_id: folder2_id)
@page2_folder_archive.set_url_if_not_present
@page2_folder_archive.product_files = [file4, file5]
@page2_folder_archive.save!
@page2_folder_archive.mark_in_progress!
@page2_folder_archive.mark_ready!
end
it "shows 'Download all' buttons on file embed groups" do
visit(url)
within_file_group("folder 1") do
expect(page).to have_disclosure("Download all")
end
within_file_group("Untitled") do
# for the single-file case, we use a link for the direct download URL
# since no async zipping is required
download_path = if url_redirect.present?
url_redirect_download_product_files_path(url_redirect.token, { product_file_ids: [@file3.external_id] })
else
download_product_files_path({ product_file_ids: [@file3.external_id], product_id: product.external_id })
end
select_disclosure "Download all" do
expect(page).to have_link("Download file", href: download_path)
end
end
select_tab("Page 2")
within_file_group("no downloadable files") do
expect(page).to_not have_disclosure("Download all")
end
within_file_group("total file size exceeds limit") do
expect(page).to_not have_disclosure("Download all")
end
expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).with(@page2_folder_archive.s3_key, @page2_folder_archive.s3_filename).and_return("https://example.com/zip-archive.zip")
within_file_group("Page 2 folder") do
select_disclosure "Download all" do
click_on "Download as ZIP"
end
end
expect(page).to have_current_path "https://example.com/zip-archive.zip"
end
it "downloads the individual file when pressing 'Download all' for a file embed group with only 1 downloadable file" do
expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).with(@file9.s3_key, @file9.s3_filename, is_video: false).and_return("https://example.com/file.srt")
visit(url)
within_file_group("only 1 downloadable file") do
select_disclosure "Download all" do
click_on "Download file"
end
wait_for_ajax
end
end
it "shows 'Zipping files...' when the folder archive is not ready when pressing 'Download all'" do
@page1_folder_archive.mark_deleted!
visit(url)
within_file_group("folder 1") do
select_disclosure "Download all" do
click_on "Download as ZIP"
expect(page).to have_button("Zipping files...", disabled: true)
end
end
if url_redirect.present?
# For the download page
expect_any_instance_of(UrlRedirectsController).to receive(:url_redirect_download_archive_url).with(url_redirect.token, { folder_id: @page1_folder_archive.folder_id }).and_return("https://example.com/zip-archive.zip")
@page1_folder_archive.mark_undeleted!
expect(page).to have_alert(text: "Your ZIP file is ready! Download")
expect(page).to have_link("Download", href: "https://example.com/zip-archive.zip")
else
# For the product edit page
expect_any_instance_of(SignedUrlHelper).to receive(:download_folder_archive_url).with(@page1_folder_archive.folder_id, { variant_id: nil, product_id: product.external_id }).and_return("https://example.com/zip-archive.zip")
@page1_folder_archive.mark_undeleted!
expect(page).to have_current_path "https://example.com/zip-archive.zip"
end
end
it "saves the files to Dropbox when pressing 'Save to Dropbox'" do
visit(url)
expect_any_instance_of(url_redirect.present? ? UrlRedirectsController : ProductFilesUtilityController).to receive(:download_product_files).and_call_original
product.product_files.delete_all # otherwise the dropbox call fails on the client
within_file_group("folder 1") do
select_disclosure "Download all" do
click_on "Save to Dropbox"
wait_for_ajax
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/discover_layout.rb | spec/shared_examples/discover_layout.rb | # frozen_string_literal: true
require "spec_helper"
shared_examples_for "discover navigation when layout is discover" do |selected_taxonomy: nil|
it "shows the discover layout when the param is passed" do
visit discover_url
expect(page).to have_link("Log in")
expect(page).to have_link("Start selling")
expect(page).to have_field("Search products")
expect(find("[role=menubar]")).to have_text("All 3D Audio Business & Money Comics & Graphic Novels Design Drawing & Painting Education Fiction Books Films", normalize_ws: true)
expect(page).to have_selector("[aria-current=true]", text: selected_taxonomy) if selected_taxonomy
visit non_discover_url
expect(page).not_to have_link("Login")
expect(page).not_to have_selector("[role=menubar]")
end
it "sorts discover categories using recommended products" do
buyer = create(:buyer_user)
purchase = create(:purchase, purchaser: buyer, email: buyer.email)
SalesRelatedProductsInfo.find_or_create_info(
purchase.link.id,
create(:product, taxonomy: Taxonomy.find_by(slug: "design")).id
).update!(sales_count: 20)
rebuild_srpis_cache
login_as buyer
visit discover_url
expect(find("[role=menubar]")).to have_text("All Design 3D Audio Business & Money Comics & Graphic Novels More", normalize_ws: true)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/admin_commentable_concern.rb | spec/shared_examples/admin_commentable_concern.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "Admin::Commentable" do
let(:admin_user) { create(:admin_user) }
let(:commentable_object) { raise NotImplementedError, "Define commentable_object in the spec" }
let(:route_params) { raise NotImplementedError, "Define route_params in the spec" }
before do
sign_in admin_user
end
describe "GET index" do
context "when there are comments" do
let!(:comment1) do
create(:comment,
commentable: commentable_object,
author: admin_user,
content: "First comment",
comment_type: "note",
created_at: 2.days.ago)
end
let!(:comment2) do
create(:comment,
commentable: commentable_object,
author: admin_user,
content: "Second comment",
comment_type: "note",
created_at: 1.day.ago)
end
let!(:unrelated_comment) do
create(:comment,
commentable: create(:user),
author: admin_user,
content: "Unrelated comment",
comment_type: "note",
created_at: 3.days.ago)
end
it "returns all comments in descending order" do
get :index, params: route_params, format: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response["comments"]).to be_an(Array)
expect(json_response["comments"].length).to eq(2)
expect(json_response["pagination"]).to be_present
expect(json_response["comments"]).to eq(
[
{
"id" => comment2.id,
"content" => "Second comment",
"author" => {
"id" => admin_user.id,
"name" => admin_user.name,
"email" => admin_user.email
},
"author_name" => admin_user.username,
"comment_type" => "note",
"updated_at" => comment2.updated_at.iso8601
},
{
"id" => comment1.id,
"content" => "First comment",
"author" => {
"id" => admin_user.id,
"name" => admin_user.name,
"email" => admin_user.email
},
"author_name" => admin_user.username,
"comment_type" => "note",
"updated_at" => comment1.updated_at.iso8601
}
]
)
end
it "paginates comments correctly" do
# Request page 1 with per_page=1
get :index, params: route_params.merge(page: 1, per_page: 1), format: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response["comments"].length).to eq(1)
expect(json_response["comments"].first["id"]).to eq(comment2.id)
expect(json_response["comments"].first["content"]).to eq("Second comment")
expect(json_response["pagination"]).to be_present
expect(json_response["pagination"]["page"]).to eq(1)
expect(json_response["pagination"]["count"]).to eq(2)
# Request page 2 with per_page=1
get :index, params: route_params.merge(page: 2, per_page: 1), format: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response["comments"].length).to eq(1)
expect(json_response["comments"].first["id"]).to eq(comment1.id)
expect(json_response["comments"].first["content"]).to eq("First comment")
expect(json_response["pagination"]).to be_present
expect(json_response["pagination"]["page"]).to eq(2)
expect(json_response["pagination"]["count"]).to eq(2)
end
end
it "returns empty array when there are no comments" do
get :index, params: route_params, format: :json
expect(response).to have_http_status(:success)
json_response = response.parsed_body
expect(json_response["comments"]).to eq([])
end
end
describe "POST create" do
let(:valid_comment_params) do
{
content: "This is a test comment",
comment_type: Comment::COMMENT_TYPE_FLAGGED
}
end
it "creates a new comment for the commentable" do
expect do
post :create, params: route_params.merge(comment: valid_comment_params), format: :json
end.to change { commentable_object.comments.count }.by(1)
expect(response).to have_http_status(:success)
comment = commentable_object.comments.last
expect(response.parsed_body["success"]).to be true
expect(response.parsed_body["comment"]).to eq(
"id" => comment.id,
"content" => "This is a test comment",
"author" => {
"id" => admin_user.id,
"name" => admin_user.name,
"email" => admin_user.email
},
"author_name" => admin_user.name,
"comment_type" => "flagged",
"updated_at" => comment.updated_at.iso8601
)
end
it "associates the comment with the current admin user" do
post :create, params: route_params.merge(comment: valid_comment_params), format: :json
comment = commentable_object.comments.last
expect(comment.author).to eq(admin_user)
end
it "returns an error when content is missing" do
invalid_params = valid_comment_params.merge(content: "")
expect do
post :create, params: route_params.merge(comment: invalid_params), format: :json
end.not_to change { commentable_object.comments.count }
expect(response).to have_http_status(:unprocessable_entity)
expect(response.parsed_body["success"]).to be false
expect(response.parsed_body["error"]).to include("can't be blank")
end
it "creates a comment with 'note' type when comment_type is not provided" do
invalid_params = valid_comment_params.except(:comment_type)
expect do
post :create, params: route_params.merge(comment: invalid_params), format: :json
end.to change { commentable_object.comments.count }.by(1)
expect(response).to have_http_status(:success)
expect(response.parsed_body["success"]).to be true
expect(commentable_object.comments.last.comment_type).to eq(Comment::COMMENT_TYPE_NOTE)
end
it "returns an error when content is too long" do
invalid_params = valid_comment_params.merge(content: "a" * 10_001)
expect do
post :create, params: route_params.merge(comment: invalid_params), format: :json
end.not_to change { commentable_object.comments.count }
expect(response).to have_http_status(:unprocessable_entity)
json_response = response.parsed_body
expect(json_response["success"]).to be false
expect(json_response["error"]).to include("too long")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/with_workflow_form_context.rb | spec/shared_examples/with_workflow_form_context.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "with workflow form 'context' in response" do
let!(:product1) { create(:product_with_digital_versions, name: "Product 1", user:) }
let!(:product2) { create(:product, name: "Product 2", user:, archived: true) }
let!(:membership) { create(:membership_product, name: "Membership product", user:) }
let!(:physical_product) { create(:physical_product, name: "Physical product", user:, skus_enabled: true) }
let!(:sku1) { create(:sku, link: physical_product, name: "Blue - Large") }
let!(:sku2) { create(:sku, link: physical_product, name: "Green - Small") }
it "includes workflow form 'context' in the response" do
expect(result.keys).to include(:context)
expect(result[:context].keys).to match_array(%i[products_and_variant_options affiliate_product_options timezone currency_symbol countries aws_access_key_id gumroad_address s3_url user_id eligible_for_abandoned_cart_workflows])
expect(result[:context][:products_and_variant_options]).to match_array([
{ id: product1.unique_permalink, label: "Product 1", product_permalink: product1.unique_permalink, archived: false, type: "product" },
{ id: product1.alive_variants.first.external_id, label: "Product 1 — Untitled 1", product_permalink: product1.unique_permalink, archived: false, type: "variant" },
{ id: product1.alive_variants.second.external_id, label: "Product 1 — Untitled 2", product_permalink: product1.unique_permalink, archived: false, type: "variant" },
{ id: membership.unique_permalink, label: "Membership product", product_permalink: membership.unique_permalink, archived: false, type: "product" },
{ id: membership.tiers.first.external_id, label: "Membership product — Untitled", product_permalink: membership.unique_permalink, archived: false, type: "variant" },
{ id: physical_product.unique_permalink, label: "Physical product", product_permalink: physical_product.unique_permalink, archived: false, type: "product" },
{ id: sku1.external_id, label: "Physical product — Blue - Large", product_permalink: physical_product.unique_permalink, archived: false, type: "variant" },
{ id: sku2.external_id, label: "Physical product — Green - Small", product_permalink: physical_product.unique_permalink, archived: false, type: "variant" },
])
expect(result[:context][:affiliate_product_options]).to match_array([
{ id: product1.unique_permalink, label: "Product 1", product_permalink: product1.unique_permalink, archived: false, type: "product" },
{ id: membership.unique_permalink, label: "Membership product", product_permalink: membership.unique_permalink, archived: false, type: "product" },
{ id: physical_product.unique_permalink, label: "Physical product", product_permalink: physical_product.unique_permalink, archived: false, type: "product" },
])
timezone = ActiveSupport::TimeZone[user.timezone].now.strftime("%Z")
expect(result[:context][:timezone]).to eq(timezone)
expect(result[:context][:currency_symbol]).to eq("$")
expect(result[:context][:countries]).to match_array(["United States"] + Compliance::Countries.for_select.map { _1.last }.without("United States"))
expect(result[:context][:aws_access_key_id]).to eq(AWS_ACCESS_KEY)
expect(result[:context][:s3_url]).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}")
expect(result[:context][:user_id]).to eq(user.external_id)
expect(result[:context][:gumroad_address]).to eq(GumroadAddress.full)
expect(result[:context][:eligible_for_abandoned_cart_workflows]).to eq(user.eligible_for_abandoned_cart_workflows?)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/max_purchase_count_concern.rb | spec/shared_examples/max_purchase_count_concern.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "MaxPurchaseCount concern" do |factory_name|
it "automatically constrains the max_purchase_count" do
object = create(factory_name)
object.update!(max_purchase_count: 999_999_999_999)
expect(object.max_purchase_count).to eq(10_000_000)
object.update!(max_purchase_count: -100)
expect(object.max_purchase_count).to eq(0)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/products_navigation.rb | spec/shared_examples/products_navigation.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "tab navigation on products page" do
it "shows the correct tabs" do
create(:product, user: seller)
visit url
within find("[role=tablist]") do
expect(find(:tab_button, "All products")[:href]).to eq(products_url(host: DOMAIN))
expect(find(:tab_button, "Affiliated")[:href]).to eq(products_affiliated_index_url(host: DOMAIN))
expect(find(:tab_button, "Collabs")[:href]).to eq(products_collabs_url(host: DOMAIN))
expect(page).not_to have_tab_button("Archived")
end
end
it "conditionally shows additional tabs" do
create(:product, user: seller, archived: true)
visit(products_path)
within find("[role=tablist]") do
expect(find(:tab_button, "Archived")[:href]).to eq(products_archived_index_url(host: DOMAIN))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/receipt_presenter_concern.rb | spec/shared_examples/receipt_presenter_concern.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_context "when is a preorder authorization" do
let(:preorder_link) { create(:preorder_link, link: purchase.link, release_at: DateTime.parse("Dec 1 2223 10AM PST")) }
before do
preorder = create(:preorder, preorder_link:, seller: product.user, state: "authorization_successful")
purchase.update!(preorder:, is_preorder_authorization: true)
end
end
RSpec.shared_context "when is a gift sender purchase" do
let(:gift) { create(:gift, link: product, gift_note: "Hope you like it!", giftee_email: "giftee@example.com") }
before do
purchase.update!(is_gift_sender_purchase: true, gift_given: gift)
end
end
RSpec.shared_context "when the purchase has a license" do
let!(:license) { create(:license, purchase:, link: purchase.link) }
before do
purchase.link.update!(is_licensed: true)
end
end
RSpec.shared_context "when the purchase is for a physical product" do
let(:product) { create(:product, :is_physical) }
let(:purchase) { create(:physical_purchase, link: product) }
end
RSpec.shared_context "when the purchase is recurring subscription" do
let(:shipping_attributes) { {} }
let(:purchase_attributes) { {}.merge(shipping_attributes) }
let(:purchase) { create(:recurring_membership_purchase, link: product, **purchase_attributes) }
let(:sizes_category) { create(:variant_category, title: "sizes", link: product) }
let(:small_variant) { create(:variant, name: "small", price_difference_cents: 300, variant_category: sizes_category) }
let(:colors_category) { create(:variant_category, title: "colors", link: product) }
let(:red_variant) { create(:variant, name: "red", price_difference_cents: 300, variant_category: colors_category) }
before do
purchase.subscription.price.update!(recurrence: BasePrice::Recurrence::MONTHLY)
purchase.variant_attributes << small_variant
purchase.variant_attributes << red_variant
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/authorize_called.rb | spec/shared_examples/authorize_called.rb | # frozen_string_literal: true
require "spec_helper"
# Checks that `authorize` is called with correct policy for each controller action
# Pulls all controller actions programmatically from Routes.
#
RSpec.shared_examples_for "authorize called for controller" do |policy_klass|
controller_path = described_class.to_s.underscore.sub(/_?controller\z/, "")
@all_routes ||= Rails.application.routes.routes.map do |route|
OpenStruct.new(
controller: route.defaults[:controller],
action: route.defaults[:action],
verb: route.verb.downcase.to_sym
)
end
controller_action_infos = @all_routes.select { |route_info| route_info.controller == controller_path }
controller_action_infos.each do |route_info|
it_behaves_like "authorize called for action", route_info.verb, route_info.action do
let(:policy_klass) { policy_klass }
end
end
end
# Checks that `authorize` is called with correct policy for a given action
# Accepted shared variables:
# * record (required)
# * policy_klass (optional)
# * policy_method (optional)
# * request_params (optional)
# * request_format (optional)
#
RSpec.shared_examples_for "authorize called for action" do |verb, action|
it "calls authorize with correct arguments on #{verb}: #{action}" do
klass = defined?(policy_klass) && policy_klass || Pundit::PolicyFinder.new(record).policy
method = defined?(policy_method) ? policy_method : :"#{action}?"
format = defined?(request_format) ? request_format : :html
mocked_policy = instance_double(klass, method => false)
allow(klass).to receive(:new).and_return(mocked_policy)
public_send(verb, action, params: defined?(request_params) ? request_params : {}, as: format)
expect(klass).to(
have_received(:new).with(controller.pundit_user, record),
"Expected #{klass} to be called via `authorize` with correct arguments"
)
end
end
# Sets `logged_in_user` as a different instance than `current_seller` for controller specs
# Accepted shared variable:
# * seller (required)
#
RSpec.shared_context "with user signed in with given role for seller" do |role|
let(:user_with_role_for_seller) do
identifier = "#{role}forseller"
seller = create(:user, username: identifier, name: "#{role.to_s.humanize}ForSeller", email: "#{identifier}@example.com")
seller
end
before do
create(:team_membership, user: user_with_role_for_seller, seller:, role:)
cookies.encrypted[:current_seller_id] = seller.id
sign_in user_with_role_for_seller
end
end
TeamMembership::ROLES.excluding(TeamMembership::ROLE_OWNER).each do |role|
# Available shared contexts for controller specs:
# include_context "with user signed in as accountant for seller"
# include_context "with user signed in as admin for seller"
# include_context "with user signed in as marketing for seller"
# include_context "with user signed in as support for seller"
#
RSpec.shared_context "with user signed in as #{role} for seller" do
include_context "with user signed in with given role for seller", role
end
end
# Switches seller account to a different instance than `logged_in_user` for integration specs
# Accepted shared variable:
# * seller (required)
#
RSpec.shared_context "with switching account to user with given role for seller" do |options|
let(:user_with_role_for_seller) do
identifier = "#{options[:role]}forseller"
seller = create(:user, username: identifier, name: "#{options[:role].to_s.humanize}ForSeller", email: "#{identifier}@example.com")
seller
end
before do
create(:team_membership, user: user_with_role_for_seller, seller:, role: options[:role])
login_as user_with_role_for_seller
visit(options[:host] ? settings_main_url(host: options[:host]) : settings_main_path)
within "nav[aria-label='Main']" do
toggle_disclosure(user_with_role_for_seller.name)
choose(seller.display_name)
end
wait_for_ajax
visit(options[:host] ? settings_main_url(host: options[:host]) : settings_main_path)
within "nav[aria-label='Main']" do
expect(page).to have_text(seller.display_name(prefer_email_over_default_username: true))
end
end
end
TeamMembership::ROLES.excluding(TeamMembership::ROLE_OWNER).each do |role|
RSpec.shared_context "with switching account to user as #{role} for seller" do |options = {}|
options.merge!(role:)
# Available shared contexts for request specs:
# include_context "with switching account to user as accountant for seller"
# include_context "with switching account to user as admin for seller"
# include_context "with switching account to user as marketing for seller"
# include_context "with switching account to user as support for seller"
#
include_context "with switching account to user with given role for seller", options
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/admin_base_controller_concern.rb | spec/shared_examples/admin_base_controller_concern.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "inherits from Admin::BaseController" do
it { expect(controller.class.ancestors.include?(Admin::BaseController)).to eq(true) }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/sellers_base_controller_concern.rb | spec/shared_examples/sellers_base_controller_concern.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "inherits from Sellers::BaseController" do
it { expect(controller.class.ancestors.include?(Sellers::BaseController)).to eq(true) }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/versionable_concern.rb | spec/shared_examples/versionable_concern.rb | # frozen_string_literal: true
require "spec_helper"
# options contains a hash with versionable fields for factory as keys, and each
# field's value is an array of 2 values: before and after. After value is optional.
# Sample spec integration:
#
# it_behaves_like "Versionable concern", :user, {
# email: %w(user@example.com),
# payment_address: %w(old-paypal@example.com paypal@example.com)
# }
#
RSpec.shared_examples_for "Versionable concern" do |factory_name, options|
with_versioning do
it "returns version infos" do
fields = options.keys
object = create(factory_name, options.transform_values { |values| values.first })
object.update!(
options.transform_values { |values| values.second }.select { |_f, value| value.present? }
)
version_one, version_two = object.versions_for(*fields)
expect(version_one.class).to eq(Versionable::VersionInfoStruct)
expect(version_one.created_at).to be_present
expect(HashWithIndifferentAccess.new(version_one.changes)).to eq(
HashWithIndifferentAccess.new(options.select { |field, values| values.size == 2 })
)
expect(version_two.changes.keys).to eq(fields.map(&:to_s))
end
it "ignores versions without changes" do
fields = options.keys
object = create(factory_name, options.transform_values { |values| values.first })
object.versions.update_all(object_changes: nil)
expect(object.versions_for(*fields)).to eq([])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/with_sorting_and_pagination.rb | spec/shared_examples/with_sorting_and_pagination.rb | # frozen_string_literal: true
require "spec_helper"
def product_names(response)
response.parsed_body["entries"].map { _1["name"] }
end
RSpec.shared_examples_for "an API for sorting and pagination" do |action|
it "correctly sorts and paginates the records" do
if default_order.present?
order = default_order.map(&:name)
get action, params: { page: 1, sort: nil }
expect(product_names(response)).to eq(order.first(2))
get action, params: { page: 2, sort: nil }
expect(product_names(response)).to eq(order.last(2))
end
# For columns that reverse the order of all records when toggling direction
columns.each do |key, order|
order = order.map(&:name)
get action, params: { page: 1, sort: { key:, direction: "asc" } }
expect(product_names(response)).to eq(order.first(2))
get action, params: { page: 1, sort: { key:, direction: "desc" } }
expect(product_names(response)).to eq(order.reverse.first(2))
get action, params: { page: 2, sort: { key:, direction: "asc" } }
expect(product_names(response)).to eq(order.last(2))
get action, params: { page: 2, sort: { key:, direction: "desc" } }
expect(product_names(response)).to eq(order.reverse.last(2))
end
# For columns that group records into two categories and reorders those categories when toggling direction
boolean_columns.each do |key, order|
order = order.map(&:name)
get action, params: { page: 1, sort: { key:, direction: "asc" } }
expect(product_names(response)).to eq(order.first(2))
get action, params: { page: 1, sort: { key:, direction: "desc" } }
expect(product_names(response)).to eq(order.last(2))
get action, params: { page: 2, sort: { key:, direction: "asc" } }
expect(product_names(response)).to eq(order.last(2))
get action, params: { page: 2, sort: { key:, direction: "desc" } }
expect(product_names(response)).to eq(order.first(2))
end
end
end
RSpec.shared_examples_for "a table with sorting" do |table_name|
it "correctly sorts the records" do
table = find(:table, table_name)
if default_order.present?
order = default_order.map(&:name)
within table do
expect(page).to have_nth_table_row_record(1, order.first, exact_text: false)
expect(page).to have_nth_table_row_record(2, order.second, exact_text: false)
end
end
# For columns that reverse the order of all records when toggling direction
columns.each do |column, order|
order = order.map(&:name)
within table do
find(:columnheader, column).click
wait_for_ajax
end
expect(page).to have_nth_table_row_record(1, order.first, exact_text: false)
expect(page).to have_nth_table_row_record(2, order.second, exact_text: false)
within table do
find(:columnheader, column).click
wait_for_ajax
end
expect(page).to have_nth_table_row_record(1, order.reverse.first, exact_text: false)
expect(page).to have_nth_table_row_record(2, order.reverse.second, exact_text: false)
end
# For columns that group records into two categories and reorders those categories when toggling direction
boolean_columns.each do |column, order|
order = order.map(&:name)
within table do
find(:columnheader, column).click
wait_for_ajax
end
expect(page).to have_nth_table_row_record(1, order.first, exact_text: false)
expect(page).to have_nth_table_row_record(2, order.second, exact_text: false)
within table do
find(:columnheader, column).click
wait_for_ajax
end
expect(page).to have_nth_table_row_record(1, order.third, exact_text: false)
expect(page).to have_nth_table_row_record(2, order.fourth, exact_text: false)
end
end
end
RSpec.shared_context "with products and memberships" do |archived: false|
let!(:membership1) { create(:subscription_product, name: "Membership 1", archived:, user: seller, price_cents: 1000, created_at: 4.days.ago) }
let!(:membership2) { create(:subscription_product, name: "Membership 2", archived:, user: seller, price_cents: 900, created_at: Time.current) }
let!(:membership3) { create(:membership_product_with_preset_tiered_pwyw_pricing, name: "Membership 3", archived:, user: seller, purchase_disabled_at: 2.days.ago, created_at: 2.days.ago) }
let!(:membership4) { create(:membership_product_with_preset_tiered_pricing, name: "Membership 4", archived:, user: seller, purchase_disabled_at: Time.current, created_at: 3.days.ago) }
let!(:product1) { create(:product, name: "Product 1", archived:, user: seller, price_cents: 1000, created_at: Time.current) }
let!(:product2) { create(:product, name: "Product 2", archived:, user: seller, price_cents: 500, created_at: 4.days.ago) }
let!(:product3) { create(:product, name: "Product 3", archived:, user: seller, price_cents: 300, purchase_disabled_at: 2.days.ago, created_at: 2.days.ago) }
let!(:product4) { create(:product, name: "Product 4", archived:, user: seller, price_cents: 400, purchase_disabled_at: Time.current, created_at: 3.days.ago) }
before do
membership3.tier_category.variants.each do |tier|
recurrence_values = BasePrice::Recurrence.all.index_with do |recurrence_key|
{
enabled: true,
price: "8",
suggested_price: "8.5"
}
end
tier.save_recurring_prices!(recurrence_values)
end
create(:purchase, link: membership1, is_original_subscription_purchase: true, subscription: create(:subscription, link: membership1, cancelled_at: nil), created_at: 2.days.ago)
2.times { create(:membership_purchase, is_original_subscription_purchase: true, link: membership3, seller:, subscription: create(:subscription, link: membership3, cancelled_at: nil), price_cents: 800) }
4.times { create(:purchase, link: membership2, is_original_subscription_purchase: true, subscription: create(:subscription, link: membership2, cancelled_at: nil), created_at: 2.days.ago) }
create_list(:purchase, 2, link: product1)
create_list(:purchase, 3, link: product2)
create_list(:purchase, 4, link: product3)
create_list(:purchase, 6, link: product4)
index_model_records(Purchase)
index_model_records(Link)
membership1.product_cached_values.create!
membership2.product_cached_values.create!
membership3.product_cached_values.create!
membership4.product_cached_values.create!
product1.product_cached_values.create!
product2.product_cached_values.create!
product3.product_cached_values.create!
product4.product_cached_values.create!
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/collaborator_access.rb | spec/shared_examples/collaborator_access.rb | # frozen_string_literal: true
require "spec_helper"
# Checks that a collaborator on a product can access the endpoint
# Accepted shared variables:
# * product (required)
# * request_params (optional)
# * request_format (optional)
# * response_status (optional)
# * response_attributes (optional)
RSpec.shared_examples_for "collaborator can access" do |verb, action|
it "allows a collaborator to access #{verb} /#{action}" do
collaborator = create(:collaborator, seller: product.user, products: [product])
sign_in collaborator.affiliate_user
as = defined?(request_format) ? request_format : :html
params = defined?(request_params) ? request_params : {}
status = defined?(response_status) ? response_status : 200
public_send(verb, action, params:, as:)
expect(response.status).to eq status
expect(JSON.parse(response.body)).to include(response_attributes) if defined?(response_attributes)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/authorized_helper_api_method.rb | spec/shared_examples/authorized_helper_api_method.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "helper api authorization required" do |verb, action|
before do
request.headers["Authorization"] = "Bearer #{GlobalConfig.get("HELPER_TOOLS_TOKEN")}"
end
context "when the token is invalid" do
it "returns 401 error" do
request.headers["Authorization"] = "Bearer invalid_token"
public_send(verb, action)
expect(response).to have_http_status(:unauthorized)
expect(response.body).to eq({ success: false, message: "authorization is invalid" }.to_json)
end
end
context "when the token is missing" do
it "returns 401 error" do
request.headers["Authorization"] = nil
public_send(verb, action)
expect(response).to have_http_status(:unauthorized)
expect(response.body).to eq({ success: false, message: "unauthenticated" }.to_json)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/order_association_with_cart_post_checkout.rb | spec/shared_examples/order_association_with_cart_post_checkout.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "order association with cart post checkout" do
let!(:user_cart) { create(:cart, user:, browser_guid:) }
let!(:guest_cart) { create(:cart, :guest, browser_guid:) }
context "when the user is signed in" do
before do
sign_in_user_action
end
it "associates the order with the user cart and deletes it" do
expect do
call_action
end.to change { Order.count }.from(0).to(1)
expect(user_cart.reload.order).to eq(Order.last)
expect(user_cart).to be_deleted
expect(guest_cart.reload.order).to be_nil
expect(guest_cart).to be_alive
end
end
context "when the user is not logged in" do
it "associates the order with the guest cart and deletes it" do
expect do
call_action
end.to change { Order.count }.from(0).to(1)
expect(guest_cart.reload.order).to eq(Order.last)
expect(guest_cart).to be_deleted
expect(user_cart.reload.order).to be_nil
expect(user_cart).to be_alive
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/deletable_concern.rb | spec/shared_examples/deletable_concern.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "Deletable concern" do |factory_name|
it "marks object as deleted" do
object = create(factory_name)
expect do
object.mark_deleted!
end.to change { object.deleted? }.from(false).to(true)
end
it "marks object as alive" do
object = create(factory_name)
object.mark_deleted!
expect do
object.mark_undeleted!
end.to change { object.alive? }.from(false).to(true)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/affiliate_cookie_concern.rb | spec/shared_examples/affiliate_cookie_concern.rb | # frozen_string_literal: true
require "spec_helper"
require "ipaddr"
RSpec.shared_examples_for "AffiliateCookie concern" do
before do
@frozen_time = Time.current
travel_to(@frozen_time)
end
it "sets affiliate cookie" do
make_request
expected_cookie_options = {
expires: direct_affiliate.class.cookie_lifetime.from_now.utc,
value: @frozen_time.to_i.to_s,
httponly: true,
domain: determine_domain(request.url)
}
cookie = parse_cookie(response.header["Set-Cookie"], request.url, direct_affiliate.cookie_key)
expected_cookie_options.each do |key, value|
expect(cookie.send(key)).to eq(value)
end
end
it "does not set affiliate cookie if affiliate is not alive and is affiliated to other creators" do
direct_affiliate_2 = create(:direct_affiliate, affiliate_user: direct_affiliate.affiliate_user, seller: create(:user))
direct_affiliate_3 = create(:direct_affiliate, affiliate_user: direct_affiliate.affiliate_user, seller: create(:user))
direct_affiliate.mark_deleted!
make_request
cookie_1 = parse_cookie(response.header["Set-Cookie"], request.url, direct_affiliate.cookie_key)
cookie_2 = parse_cookie(response.header["Set-Cookie"], request.url, direct_affiliate_2.cookie_key)
cookie_3 = parse_cookie(response.header["Set-Cookie"], request.url, direct_affiliate_3.cookie_key)
expect(cookie_1).to be(nil)
expect(cookie_2).to be(nil)
expect(cookie_3).to be(nil)
end
context "when direct affiliate is deleted and other direct affiliates exist" do
it "sets affiliate cookie to last alive direct affiliate" do
direct_affiliate.update!(deleted_at: Time.current)
direct_affiliate_2 = create(:direct_affiliate, affiliate_user: direct_affiliate.affiliate_user, seller: direct_affiliate.seller, created_at: 1.hour.ago)
create(:product_affiliate, product: direct_affiliate.products.last, affiliate: direct_affiliate_2, affiliate_basis_points: 20_00)
make_request
expected_cookie_options = {
expires: direct_affiliate_2.class.cookie_lifetime.from_now.utc,
value: @frozen_time.to_i.to_s,
httponly: true,
domain: determine_domain(request.url)
}
cookie = parse_cookie(response.header["Set-Cookie"], request.url, direct_affiliate_2.cookie_key)
expected_cookie_options.each do |key, value|
expect(cookie.send(key)).to eq(value)
end
end
end
private
# Cannot stub `#cookies` to check if the arguments passed are correct as other parts of the app use encrypted
# cookies (i.e. current_seller_id) which will not work with a simple Hash object stubbed
# As browsers do not include cookie attributes in requests to the server — they only send the cookie's name and
# value - the alternative is to actually retrieve the cookie from the Set-Cookie response header
#
def parse_cookie(set_cookie, origin_url, cookie_name)
Array.wrap(set_cookie)
.lazy
.flat_map { |cookie_string| HTTP::Cookie.parse(cookie_string, origin_url) }
.find { |cookie| CGI.unescape(cookie.name) == cookie_name }
end
def determine_domain(url)
uri = Addressable::URI.parse(url)
IPAddr.new(uri.host)
uri.host
rescue IPAddr::InvalidAddressError
uri.domain
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/authentication_required.rb | spec/shared_examples/authentication_required.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "authentication required for action" do |verb, action|
before do
sign_out :user
end
it "redirects to the login page" do
public_send(verb, action, params: defined?(request_params) ? request_params : {})
expect(response).to be_a_redirect
# Do a match as response.location contains `next` query string params
expect(response.location).to match(login_url)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/policy_examples.rb | spec/shared_examples/policy_examples.rb | # frozen_string_literal: true
RSpec.shared_examples_for "an access-granting policy" do
it "grants access" do
seller_context = SellerContext.new(user: context_user, seller: context_seller)
expect(subject).to permit(seller_context, record)
end
end
RSpec.shared_examples_for "an access-granting policy for roles" do |access_roles|
access_roles.each do |access_role|
context "when the user is a #{access_role}" do
let(:context_user) { send(access_role) }
it_behaves_like "an access-granting policy"
end
end
end
RSpec.shared_examples_for "an access-denying policy" do
it "denies access" do
seller_context = SellerContext.new(user: context_user, seller: context_seller)
expect(subject).not_to permit(seller_context, record)
end
end
RSpec.shared_examples_for "an access-denying policy for roles" do |access_roles|
access_roles.each do |access_role|
context "when the user is a #{access_role}" do
let(:context_user) { send(access_role) }
it_behaves_like "an access-denying policy"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/authorized_oauth_v1_api_method.rb | spec/shared_examples/authorized_oauth_v1_api_method.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "authorized oauth v1 api method" do
it "errors out if you aren't authenticated" do
raise "no @action in before block of test" unless @action
raise "no @params in before block of test" unless @params
get @action, params: @params
expect(response.status).to eq(401)
expect(response.body.strip).to be_empty
end
end
RSpec.shared_examples_for "authorized oauth v1 api method only for edit_products scope" do
it "errors out if you aren't authenticated" do
raise "no @action in before block of test" unless @action
raise "no @params in before block of test" unless @params
raise "no @app in before block of test" unless @app
raise "no @user in before block of test" unless @user
@token = create("doorkeeper/access_token", application: @app, resource_owner_id: @user.id, scopes: "view_public view_sales")
get @action, params: @params.merge(access_token: @token.token)
expect(response.status).to eq(403)
expect(response.body.strip).to be_empty
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/paginated_api.rb | spec/shared_examples/paginated_api.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "a paginated API" do
it "contains pagination meta in the response body" do
get @action, params: @params
expect(response.status).to eq(200)
expect(response.parsed_body[@response_key_name].size).to eq(@records.size)
expect(response.parsed_body["meta"]["pagination"].keys).to match_array(%w[count items last next page pages prev])
end
it "can paginate and customize the number of items per page" do
get @action, params: @params
expect(response.status).to eq(200)
expect(response.parsed_body[@response_key_name].size).to eq(@records.size)
get @action, params: @params.merge(items: 1)
expect(response.status).to eq(200)
expect(response.parsed_body[@response_key_name].size).to eq(1)
first_page_result = response.parsed_body[@response_key_name].first
get @action, params: @params.merge(items: 1, page: 2)
expect(response.status).to eq(200)
expect(response.parsed_body[@response_key_name].size).to eq(1)
second_page_result = response.parsed_body[@response_key_name].first
expect(first_page_result).not_to eq(second_page_result)
end
it "returns 400 error if page param is incorrect" do
get @action, params: @params.merge(page: 1_000)
expect(response.status).to eq(400)
expect(response.parsed_body["error"]["message"]).to include("expected :page in 1..1")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/with_filtering_support.rb | spec/shared_examples/with_filtering_support.rb | # frozen_string_literal: true
require "spec_helper"
shared_examples_for "common customer recipient filter validation behavior" do |audience_type:|
context "when #{audience_type} #{described_class.to_s.downcase}" do
context "when no param filters are set" do
let(:params) do
{
bought_products: [],
bought_variants: [],
not_bought_products: [],
not_bought_variants: [],
affiliate_products: [],
paid_more_than: "",
paid_less_than: "",
created_after: "",
created_before: "",
bought_from: ""
}
end
it "returns true" do
is_expected.to eq(true)
end
end
context "when valid param filters are set" do
let(:params) do
{
bought_products: "B",
bought_variants: ["123"],
not_bought_products: "N",
not_bought_variants: "NV",
affiliate_products: ["A"],
paid_more_than: "5",
paid_less_than: "10",
created_after: "Sun Feb 28 2021",
created_before: "Mon Mar 1 2021",
bought_from: "United States"
}
end
it "sets the filter attributes" do
add_and_validate_filters
expect(filterable_object.bought_products).to contain_exactly("B")
expect(filterable_object.bought_variants).to contain_exactly("123")
expect(filterable_object.not_bought_products).to contain_exactly("N")
expect(filterable_object.not_bought_variants).to contain_exactly("NV")
expect(filterable_object.affiliate_products).to contain_exactly("A")
expect(filterable_object.paid_more_than_cents).to eq(500)
expect(filterable_object.paid_less_than_cents).to eq(1000)
expect(filterable_object.created_after).to be_present
expect(filterable_object.created_before).to be_present
expect(filterable_object.bought_from).to eq("United States")
end
context "when paid_more_than_cents and paid_less_than_cents are given" do
let(:params) do
{
paid_more_than_cents: 1200,
paid_less_than_cents: 1400,
paid_more_than: nil,
paid_less_than: nil
}
end
it "sets the filter attributes" do
add_and_validate_filters
expect(filterable_object.paid_more_than_cents).to eq(1200)
expect(filterable_object.paid_less_than_cents).to eq(1400)
end
end
end
context "when paid more is greater than paid less" do
let(:params) do
{
bought_products: [product.unique_permalink],
bought_variants: [],
not_bought_products: [],
not_bought_variants: [],
affiliate_products: [],
paid_more_than: "100",
paid_less_than: "99",
created_after: "",
created_before: "",
bought_from: ""
}
end
it "returns false and adds a base error to the object" do
is_expected.to eq(false)
expect(filterable_object.reload.errors[:base]).to contain_exactly("Please enter valid paid more than and paid less than values.")
end
context "when paid_more_than_cents and paid_less_than_cents are given" do
let(:params) do
{
paid_more_than_cents: 1500,
paid_less_than_cents: 1000,
paid_more_than: nil,
paid_less_than: nil
}
end
it "returns false and adds a base error to the object" do
is_expected.to eq(false)
expect(filterable_object.reload.errors[:base]).to contain_exactly("Please enter valid paid more than and paid less than values.")
end
end
end
context "when created_after is greater than created_before" do
let(:params) do
{
affiliate_products: [],
bought_products: [],
bought_variants: [],
not_bought_products: [],
not_bought_variants: [],
paid_more_than: "",
paid_less_than: "",
created_after: "Mon Mar 1 2021",
created_before: "Sun Feb 28 2021",
bought_from: ""
}
end
it "returns false and adds a base error to the object" do
is_expected.to eq(false)
expect(filterable_object.reload.errors[:base]).to contain_exactly("Please enter valid before and after dates.")
end
end
end
end
shared_examples_for "common non-customer recipient filter validation behavior" do |audience_type:|
context "when #{audience_type} #{described_class.to_s.downcase}" do
context "when no param filters are set" do
let(:params) do
{
affiliate_products: [],
bought_products: [],
bought_variants: [],
not_bought_products: [],
not_bought_variants: [],
paid_more_than: "",
paid_less_than: "",
created_after: "",
created_before: "",
bought_from: ""
}
end
it "returns true" do
is_expected.to eq(true)
end
end
context "when paid more is greater than paid less" do
let(:params) do
{
affiliate_products: [],
bought_products: [product.unique_permalink],
bought_variants: [],
not_bought_products: [],
not_bought_variants: [],
paid_more_than: "100",
paid_less_than: "99",
created_after: "",
created_before: "",
bought_from: ""
}
end
it "returns true and does not add a base error to the object" do
is_expected.to eq(true)
expect(filterable_object.reload.errors.any?).to eq(false)
end
end
context "when created_after is greater than created_before" do
let(:params) do
{
affiliate_products: [],
bought_products: [],
bought_variants: [],
not_bought_products: [],
not_bought_variants: [],
paid_more_than: "",
paid_less_than: "",
created_after: "Mon Mar 1 2021",
created_before: "Sun Feb 28 2021",
bought_from: ""
}
end
it "returns false and adds a base error to the object" do
is_expected.to eq(false)
expect(filterable_object.reload.errors[:base]).to contain_exactly("Please enter valid before and after dates.")
end
end
context "when valid param filters are set" do
let(:params) do
{
bought_products: "B",
bought_variants: ["123"],
not_bought_products: "N",
not_bought_variants: "NV",
affiliate_products: ["A"],
paid_more_than: "5",
paid_less_than: "10",
created_after: "Sun Feb 28 2021",
created_before: "Mon Mar 1 2021",
bought_from: "United States"
}
end
it "sets the filter attributes" do
add_and_validate_filters
# We don't store bought filters when targeting everyone
if audience_type == "audience"
expect(filterable_object.affiliate_products).to eq(nil)
expect(filterable_object.bought_products).to eq(nil)
expect(filterable_object.bought_variants).to eq(nil)
else
expect(filterable_object.affiliate_products).to contain_exactly("A")
expect(filterable_object.bought_products).to contain_exactly("B")
expect(filterable_object.bought_variants).to contain_exactly("123")
end
expect(filterable_object.not_bought_products).to contain_exactly("N")
expect(filterable_object.not_bought_variants).to contain_exactly("NV")
expect(filterable_object.paid_more_than_cents).to eq(nil)
expect(filterable_object.paid_less_than_cents).to eq(nil)
expect(filterable_object.created_after).to be_present
expect(filterable_object.created_before).to be_present
expect(filterable_object.bought_from).to eq(nil)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/creator_dashboard_page.rb | spec/shared_examples/creator_dashboard_page.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "creator dashboard page" do |title|
it "marks the correct navigation link as active" do
visit path
within "nav", aria: { label: "Main" } do
expect(page).to have_link(title, aria: { current: "page" })
end
visit "#{path}/"
within "nav", aria: { label: "Main" } do
expect(page).to have_link(title, aria: { current: "page" })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/shared_examples/merge_guest_cart_with_user_cart.rb | spec/shared_examples/merge_guest_cart_with_user_cart.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.shared_examples_for "merge guest cart with user cart" do
let(:browser_guid) { "123" }
let(:guest_cart) { create(:cart, :guest, browser_guid:) }
let(:user_cart) { create(:cart, user:, browser_guid:) }
let(:product1) { create(:product) }
let(:product2) { create(:product) }
let(:product2_variant) { create(:variant, variant_category: create(:variant_category, link: product2)) }
let(:product3) { create(:product) }
let!(:guest_cart_product1) { create(:cart_product, cart: guest_cart, product: product1) }
let!(:guest_cart_product2) { create(:cart_product, cart: guest_cart, product: product2, option: product2_variant) }
let!(:user_cart_product) { create(:cart_product, cart: user_cart, product: product3) }
let(:expects_json_response) { false }
it "merges the guest cart with the user's cart" do
cookies[:_gumroad_guid] = browser_guid
expect(MergeCartsService).to receive(:new).with(source_cart: guest_cart, target_cart: user_cart, user:, browser_guid:).and_call_original
expect do
expect do
call_action
end.not_to change { Cart.count }
end.to change { user_cart.reload.alive_cart_products.count }.from(1).to(3)
if expects_json_response
expect(response).to be_successful
expect(response.parsed_body["redirect_location"]).to eq(expected_redirect_location)
else
expect(response).to redirect_to(expected_redirect_location)
end
expect(guest_cart.reload.deleted?).to be(true)
expect(user_cart.reload.deleted?).to be(false)
expect(user_cart.user).to eq(user)
expect(user_cart.alive_cart_products.pluck(:product_id, :option_id)).to match_array([[product1.id, nil], [product2.id, product2_variant.id], [product3.id, nil]])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/mongoer_spec.rb | spec/modules/mongoer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Mongoer" do
it "does not throw exception if invalid character used" do
Mongoer.safe_write("Link", "email" => "f@flick.com", "email for google.com" => "sid@sid.com")
result = MONGO_DATABASE["Link"].find("email" => "f@flick.com").limit(1).first
expect(result["email for googleU+FFOEcom"]).to_not be(nil)
end
describe ".async_update" do
it "enqueues a Sidekiq job" do
Mongoer.async_update("a", "b", { "c" => "d" })
expect(UpdateInMongoWorker).to have_enqueued_sidekiq_job("a", "b", { "c" => "d" })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/external_id_spec.rb | spec/modules/external_id_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "ExternalId" do
before do
@purchase = create(:purchase)
end
describe "#find_by_external_id!" do
it "finds the correct object if it exists" do
encrypted_id = ObfuscateIds.encrypt(@purchase.id)
expect(Purchase.find_by_external_id!(encrypted_id).id).to eq @purchase.id
end
it "raises an exception if the object does not exist" do
encrypted_id = ObfuscateIds.encrypt(@purchase.id)
@purchase.delete
expect { Purchase.find_by_external_id!(encrypted_id) }.to raise_exception(ActiveRecord::RecordNotFound)
end
end
describe "#find_by_external_id_numeric!" do
it "finds the correct object if it exists" do
expect(Purchase.find_by_external_id_numeric!(@purchase.external_id_numeric).id).to eq @purchase.id
end
it "raises an exception if the object does not exist" do
@purchase.delete
expect { Purchase.find_by_external_id_numeric!(@purchase.external_id_numeric) }.to raise_exception(ActiveRecord::RecordNotFound)
end
end
describe "by_external_ids" do
it "returns array of correct objects" do
purchase2 = create(:purchase)
encrypted_id = ObfuscateIds.encrypt(@purchase.id)
encrypted_id2 = ObfuscateIds.encrypt(purchase2.id)
expect(Purchase.by_external_ids([encrypted_id, encrypted_id2])).to eq [@purchase, purchase2]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/timestamp_scopes_spec.rb | spec/modules/timestamp_scopes_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TimestampScopes do
before do
@purchase = create(:purchase, created_at: Time.utc(2020, 3, 9, 6, 30)) # Sun, 08 Mar 2020 23:30:00 PDT -07:00
end
describe ".created_between" do
it "returns records matching range" do
expect(Purchase.created_between(Time.utc(2020, 3, 3)..Time.utc(2020, 3, 6))).to match_array([])
expect(Purchase.created_between(Date.new(2020, 3, 3)..Date.new(2020, 3, 6))).to match_array([])
expect(Purchase.created_between(Time.utc(2020, 3, 5)..Time.utc(2020, 3, 10))).to match_array([@purchase])
expect(Purchase.created_between(Date.new(2020, 3, 5)..Date.new(2020, 3, 10))).to match_array([@purchase])
end
end
describe ".column_between_with_offset" do
it "returns records matching range and offset" do
expect(Purchase.column_between_with_offset("created_at", Date.new(2020, 3, 8)..Date.new(2020, 3, 8), "+00:00")).to match_array([])
expect(Purchase.column_between_with_offset("created_at", Date.new(2020, 3, 9)..Date.new(2020, 3, 9), "+00:00")).to match_array([@purchase])
expect(Purchase.column_between_with_offset("created_at", Date.new(2020, 3, 8)..Date.new(2020, 3, 8), "-07:00")).to match_array([@purchase])
end
end
describe ".created_at_between_with_offset" do
it "returns records created within range and offset" do
expect(Purchase.created_at_between_with_offset(Date.new(2020, 3, 8)..Date.new(2020, 3, 8), "+00:00")).to match_array([])
expect(Purchase.created_at_between_with_offset(Date.new(2020, 3, 9)..Date.new(2020, 3, 9), "+00:00")).to match_array([@purchase])
expect(Purchase.created_at_between_with_offset(Date.new(2020, 3, 8)..Date.new(2020, 3, 8), "-07:00")).to match_array([@purchase])
end
end
describe ".created_between_dates_in_timezone" do
it "returns records matching range" do
expect(Purchase.created_between_dates_in_timezone(Date.new(2020, 3, 8)..Date.new(2020, 3, 8), "America/Los_Angeles")).to match_array([@purchase])
expect(Purchase.created_between_dates_in_timezone(Date.new(2020, 3, 8)..Date.new(2020, 3, 8), "UTC")).to match_array([])
end
end
describe ".created_before_end_of_date_in_timezone" do
it "returns records matching date" do
expect(Purchase.created_before_end_of_date_in_timezone(Date.new(2020, 3, 8), "America/Los_Angeles")).to match_array([@purchase])
expect(Purchase.created_before_end_of_date_in_timezone(Date.new(2020, 3, 9), "America/Los_Angeles")).to match_array([@purchase])
expect(Purchase.created_before_end_of_date_in_timezone(Date.new(2020, 3, 8), "UTC")).to match_array([])
expect(Purchase.created_before_end_of_date_in_timezone(Date.new(2020, 3, 9), "UTC")).to match_array([@purchase])
end
end
describe ".created_on_or_after_start_of_date_in_timezone" do
it "returns records matching date" do
expect(Purchase.created_on_or_after_start_of_date_in_timezone(Date.new(2020, 3, 8), "America/Los_Angeles")).to match_array([@purchase])
expect(Purchase.created_on_or_after_start_of_date_in_timezone(Date.new(2020, 3, 8), "UTC")).to match_array([@purchase])
expect(Purchase.created_on_or_after_start_of_date_in_timezone(Date.new(2020, 3, 9), "UTC")).to match_array([@purchase])
expect(Purchase.created_on_or_after_start_of_date_in_timezone(Date.new(2020, 3, 10), "UTC")).to match_array([])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/with_product_files_spec.rb | spec/modules/with_product_files_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe WithProductFiles do
describe "associations" do
context "has many `product_folders`" do
it "does not return deleted folders" do
product = create(:product)
folder_1 = create(:product_folder, link: product)
create(:product_folder, link: product)
expect do
folder_1.mark_deleted!
end.to change { product.product_folders.count }.by(-1)
end
end
end
describe "#needs_updated_entity_archive?" do
it "returns false when irrelevant changes are made to a product's rich content" do
product_file1 = create(:product_file, display_name: "First file")
product = create(:product, product_files: [product_file1])
page1 = create(:rich_content, entity: product, title: "Page 1", description: [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => SecureRandom.uuid } },
])
archive = product.product_files_archives.create!(product_files: product.product_files)
archive.mark_in_progress!
archive.mark_ready!
expect(product.needs_updated_entity_archive?).to eq(false)
page1.description << { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Irrelevant change" }] }
page1.save!
expect(product.needs_updated_entity_archive?).to eq(false)
end
it "returns false when the product contains only stream-only files" do
product = create(:product, product_files: [create(:streamable_video, stream_only: true), create(:streamable_video, stream_only: true)])
expect(product.needs_updated_entity_archive?).to eq(false)
end
it "returns false when the product contains stampable PDFs" do
product = create(:product, product_files: [create(:product_file), create(:readable_document, pdf_stamp_enabled: true)])
expect(product.needs_updated_entity_archive?).to eq(false)
end
it "returns true when an entity archive has not been created yet" do
product_file1 = create(:product_file, display_name: "First file")
product = create(:product, product_files: [product_file1])
create(:rich_content, entity: product, title: "Page 1", description: [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => SecureRandom.uuid } },
])
expect(product.needs_updated_entity_archive?).to eq(true)
end
it "returns true when relevant changes have been made to an entity's rich content" do
file1 = create(:product_file, display_name: "First file")
file2 = create(:product_file, display_name: "Second file")
product = create(:product, product_files: [file1, file2])
description = [
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => SecureRandom.uuid }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } },
] }]
page1 = create(:rich_content, entity: product, title: "Page 1", description:)
expect(product.needs_updated_entity_archive?).to eq(true)
archive = product.product_files_archives.create!(product_files: product.product_files)
archive.mark_in_progress!
archive.mark_ready!
page1.description.first["attrs"]["name"] = "New folder name!"
page1.save!
expect(Link.find(product.id).needs_updated_entity_archive?).to eq(true)
end
end
describe "#map_rich_content_files_and_folders" do
context "when there is no rich content provider" do
it "returns an empty hash" do
entity = create(:installment)
entity.product_files = [create(:product_file), create(:product_file)]
expect(entity.map_rich_content_files_and_folders).to eq({})
end
end
context "when the rich content has no files" do
it "returns an empty hash" do
product = create(:product)
expect(product.map_rich_content_files_and_folders).to eq({})
end
end
context "when the rich content has files" do
context "when the rich content has only one untitled default page" do
it "does not include the fallback page title in the mapping" do
product_file1 = create(:product_file, display_name: "First file")
product_file2 = create(:product_file, display_name: "Second file")
product = create(:product)
product.product_files = [product_file1, product_file2]
product.save!
page1 = create(:rich_content, entity: product, description: [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "This is a paragraph" }] },
{ "type" => "fileEmbed", "attrs" => { "id" => product_file2.external_id, "uid" => SecureRandom.uuid } }
])
expect(product.map_rich_content_files_and_folders).to eq(
product_file1.id => { page_id: page1.external_id,
page_title: page1.title.presence,
folder_id: nil,
folder_name: nil,
file_id: product_file1.external_id,
file_name: product_file1.name_displayable },
product_file2.id => { page_id: page1.external_id,
page_title: page1.title.presence,
folder_id: nil,
folder_name: nil,
file_id: product_file2.external_id,
file_name: product_file2.name_displayable }
)
end
end
context "when the rich content has multiple pages" do
it "includes the custom page titles as well as the incremented untitled page titles in the mapping" do
product_file1 = create(:product_file, display_name: "First file")
product_file2 = create(:product_file, display_name: "Second file")
product_file3 = create(:product_file, display_name: "Third file")
product = create(:product)
product.product_files = [product_file1, product_file2, product_file3]
product.save!
page1 = create(:rich_content, entity: product, description: [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => SecureRandom.uuid } },
])
page2 = create(:rich_content, entity: product, title: "Page 2", description: [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file2.external_id, "uid" => SecureRandom.uuid } },
])
page3 = create(:rich_content, entity: product, description: [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file3.external_id, "uid" => SecureRandom.uuid } },
])
page1.title = "Untitled 1"
page3.title = "Untitled 2"
expect(product.map_rich_content_files_and_folders).to eq(
product_file1.id => { page_id: page1.external_id,
page_title: page1.title.presence,
folder_id: nil,
folder_name: nil,
file_id: product_file1.external_id,
file_name: product_file1.name_displayable },
product_file2.id => { page_id: page2.external_id,
page_title: page2.title.presence,
folder_id: nil,
folder_name: nil,
file_id: product_file2.external_id,
file_name: product_file2.name_displayable },
product_file3.id => { page_id: page3.external_id,
page_title: page3.title.presence,
folder_id: nil,
folder_name: nil,
file_id: product_file3.external_id,
file_name: product_file3.name_displayable }
)
end
end
context "when the rich content has file groups" do
it "includes the custom folder names as well as the incremented untitled folder names in the mapping" do
product_file1 = create(:product_file, display_name: "First file")
product_file2 = create(:product_file, display_name: "Second file")
product_file3 = create(:product_file, display_name: "Third file")
product_file4 = create(:product_file, display_name: "Fourth file")
product_file5 = create(:product_file, display_name: "Fifth file")
product = create(:product)
product.product_files = [product_file1, product_file2, product_file3, product_file4, product_file5]
product.save!
page2_folder1 = { "name" => "", "uid" => SecureRandom.uuid }
page2_folder2 = { "name" => "", "uid" => SecureRandom.uuid }
page3_folder1 = { "name" => "Folder 3", "uid" => SecureRandom.uuid }
page1 = create(:rich_content, entity: product, title: "Page 1", description: [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => SecureRandom.uuid } },
])
page2 = create(:rich_content, entity: product, title: "Page 2", description: [
{ "type" => "fileEmbedGroup", "attrs" => page2_folder1, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file2.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup", "attrs" => page2_folder2, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file3.external_id, "uid" => SecureRandom.uuid } },
] },
])
page3 = create(:rich_content, entity: product, title: "Page 3", description: [
{ "type" => "fileEmbedGroup", "attrs" => page3_folder1, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file4.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => product_file5.external_id, "uid" => SecureRandom.uuid } },
] },
])
product_files_archive = product.product_files_archives.create
product_files_archive.product_files = product.product_files
product_files_archive.mark_in_progress!
product_files_archive.mark_ready!
expect(product.map_rich_content_files_and_folders).to eq(
product_file1.id => { page_id: page1.external_id,
page_title: page1.title.presence,
folder_id: nil,
folder_name: nil,
file_id: product_file1.external_id,
file_name: product_file1.name_displayable },
product_file2.id => { page_id: page2.external_id,
page_title: page2.title.presence,
folder_id: page2_folder1["uid"],
folder_name: "Untitled 1",
file_id: product_file2.external_id,
file_name: product_file2.name_displayable },
product_file3.id => { page_id: page2.external_id,
page_title: page2.title.presence,
folder_id: page2_folder2["uid"],
folder_name: "Untitled 2",
file_id: product_file3.external_id,
file_name: product_file3.name_displayable },
product_file4.id => { page_id: page3.external_id,
page_title: page3.title.presence,
folder_id: page3_folder1["uid"],
folder_name: page3_folder1["name"],
file_id: product_file4.external_id,
file_name: product_file4.name_displayable },
product_file5.id => { page_id: page3.external_id,
page_title: page3.title.presence,
folder_id: page3_folder1["uid"],
folder_name: page3_folder1["name"],
file_id: product_file5.external_id,
file_name: product_file5.name_displayable }
)
end
end
end
end
describe "#has_stream_only_files?" do
let(:product) { create(:product) }
it "returns false if product has no files" do
expect(product.has_stream_only_files?).to eq(false)
end
it "returns false if product only has non-streamable files" do
product.product_files << create(:readable_document)
product.product_files << create(:non_streamable_video)
expect(product.has_stream_only_files?).to eq(false)
end
it "returns false if product has streamable files that are not marked as stream-only" do
product.product_files << create(:streamable_video)
expect(product.has_stream_only_files?).to eq(false)
end
it "returns true if product has streamable files that are marked as stream-only" do
product.product_files << create(:readable_document)
product.product_files << create(:streamable_video)
product.product_files << create(:streamable_video, stream_only: true)
expect(product.has_stream_only_files?).to eq(true)
end
end
describe "#stream_only?" do
let(:product) { create(:product) }
it "returns false if product has a file that is not stream-only" do
product.product_files << create(:streamable_video, stream_only: true)
product.product_files << create(:readable_document)
expect(product.stream_only?).to eq(false)
end
it "returns true if product only has stream-only files" do
product.product_files << create(:streamable_video, stream_only: true)
product.product_files << create(:streamable_video, stream_only: true)
expect(product.stream_only?).to eq(true)
end
end
describe "#save_files!" do
context "when called on a Link record" do
let(:product) { create(:product_with_pdf_files_with_size) }
it "enqueues a `PdfUnstampableNotifierJob` job when new stampable files are added" do
product_files_params = product.product_files.each_with_object([]) { |file, params| params << { external_id: file.external_id, url: file.url } }
product_files_params << { external_id: SecureRandom.uuid, pdf_stamp_enabled: false, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/nyt.pdf" }
product_files_params << { external_id: SecureRandom.uuid, pdf_stamp_enabled: true, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf" }
expect do
product.save_files!(product_files_params)
end.to change { product.product_files.alive.count }.by(2)
expect(PdfUnstampableNotifierJob).to have_enqueued_sidekiq_job(product.id)
end
it "does not enqueue a `PdfUnstampableNotifierJob` job when new non-stampable files are added" do
product_files_params = product.product_files.each_with_object([]) { |file, params| params << { external_id: file.external_id, url: file.url } }
product_files_params << { external_id: SecureRandom.uuid, pdf_stamp_enabled: false, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf" }
expect do
product.save_files!(product_files_params)
end.to change { product.product_files.alive.count }.by(1)
expect(PdfUnstampableNotifierJob.jobs.size).to eq(0)
end
it "enqueues a `PdfUnstampableNotifierJob` job when existing files are marked as stampable" do
expect(product.product_files.pdf.any?).to eq(true)
product_files_params = product.product_files.each_with_object([]) { |file, params| params << { external_id: file.external_id, url: file.url, pdf_stamp_enabled: file.pdf? } }
expect do
product.save_files!(product_files_params)
end.not_to change { product.product_files.alive.count }
expect(PdfUnstampableNotifierJob).to have_enqueued_sidekiq_job(product.id)
end
it "does not enqueue a `PdfUnstampableNotifierJob` job when existing files are marked as non-stampable" do
expect(product.product_files.pdf.present?).to eq(true)
product.product_files.pdf.each { |file| file.update!(pdf_stamp_enabled: true) }
product_files_params = product.product_files.each_with_object([]) { |file, params| params << { external_id: file.external_id, url: file.url, pdf_stamp_enabled: false } }
expect do
product.save_files!(product_files_params)
end.not_to change { product.product_files.alive.count }
expect(PdfUnstampableNotifierJob.jobs.size).to eq(0)
end
it "does not enqueue a `PdfUnstampableNotifierJob` job when existing files are removed" do
expect do
product.save_files!([])
end.to change { product.product_files.alive.count }.by(-3)
expect(PdfUnstampableNotifierJob.jobs.size).to eq(0)
end
it "does not enqueue a `PdfUnstampableNotifierJob` job when no changes are made to files" do
product_files_params = product.product_files.each_with_object([]) { |file, acc| acc << { external_id: file.external_id, url: file.url } }
expect do
product.save_files!(product_files_params)
end.not_to change { product.product_files.alive.count }
expect(PdfUnstampableNotifierJob.jobs.size).to eq(0)
end
it "does not enqueue a `PdfUnstampableNotifierJob` job for a non-product resource" do
post = create(:installment)
expect do
post.save_files!([{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf" }])
end.to change { post.product_files.alive.count }.by(1)
expect(PdfUnstampableNotifierJob.jobs.size).to eq(0)
end
it "sets content_updated_at when new files are added" do
product_files_params = product.product_files.each_with_object([]) { |file, acc| acc << { external_id: file.external_id, url: file.url } }
product_files_params << { external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pic.jpg" }
product_files_params << { external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4" }
freeze_time do
expect do
product.save_files!(product_files_params)
end.to change { product.product_files.alive.count }.by(2)
expect(product.content_updated_at_changed?).to eq true
expect(product.content_updated_at).to eq Time.current
end
end
it "does not set content_updated_at when existing files are removed" do
expect do
product.save_files!([{ external_id: product.product_files.first.external_id, url: product.product_files.first.url }])
end.to change { product.product_files.alive.count }.by(-2)
expect(product.content_updated_at_changed?).to eq false
end
it "updates file attributes" do
product_files_params = product.product_files.each_with_object([]) { |file, acc| acc << { external_id: file.external_id, url: file.url } }
product_files_params[0].merge!({ position: 2, display_name: "new book name", description: "new_description" })
product_files_params << { external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pic.jpg", size: 2, position: 0 }
product_files_params << { external_id: SecureRandom.uuid, url: "http://www.gum.road", size: "", filetype: "link", position: 1, display_name: "link file" }
expect do
product.save_files!(product_files_params)
end.to change { product.product_files.alive.count }.by(2)
book_file = product.product_files[0].reload
expect(book_file.display_name).to eq("new book name")
expect(book_file.description).to eq("new_description")
expect(book_file.position).to eq(2)
pic_file = product.product_files[3].reload
expect(pic_file.position).to eq(0)
link_file = product.product_files[4].reload
expect(link_file.filetype).to eq("link")
expect(link_file.display_name).to eq("link file")
expect(link_file.position).to eq(1)
end
it "raises error on the product if url is invalid when creating an external link file" do
product_files_params = product.product_files.each_with_object([]) { |file, acc| acc << { external_id: file.external_id, url: file.url } }
product_files_params << { external_id: SecureRandom.uuid, url: "gum.road", size: "", filetype: "link" }
expect do
product.save_files!(product_files_params)
end.to change { product.product_files.alive.count }.by(0)
.and raise_error(ActiveRecord::RecordInvalid)
expect(product.errors.full_messages).to include("gum.road is not a valid URL.")
end
it "preserves folder_id on file if folder is deleted" do
product = create(:product)
folder_1 = create(:product_folder, link: product, name: "Test Folder 1")
folder_2 = create(:product_folder, link: product, name: "Test Folder 2")
file_1 = create(:product_file, link: product, description: "pencil", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png", folder_id: folder_1.id)
file_2 = create(:product_file, link: product, description: "manual", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf", folder_id: folder_2.id)
product_files_params = product.product_files.each_with_object([]) { |file, acc| acc << { external_id: file.external_id, url: file.url, folder_id: file.folder_id } }
folder_2.mark_deleted!
product_files_params[1].merge!({ folder_id: nil })
product.save_files!(product_files_params)
expect(product.product_folders.reload.count).to eq(1)
expect(folder_2.reload.deleted?).to eq(true)
expect(file_1.reload.folder_id).to eq(folder_1.id)
expect(file_2.reload.folder_id).to eq(folder_2.id)
end
it "preserves folder_id on file if folder does not exist" do
product = create(:product)
file = create(:readable_document, link: product, folder_id: 1000)
product.save_files!([{ external_id: file.external_id, url: file.url, folder_id: nil }])
expect(file.reload.folder_id).to eq(1000)
end
it "sets folder_id to nil if file is moved out of folder" do
product = create(:product)
folder = create(:product_folder, link: product)
file_1 = create(:readable_document, folder:, link: product)
file_2 = create(:streamable_video, folder:, link: product)
file_3 = create(:listenable_audio, link: product)
product_files_params = product.product_files.each_with_object([]) { |file, acc| acc << { external_id: file.external_id, url: file.url, folder_id: file.folder_id } }
product_files_params[1].merge!({ folder_id: nil })
product.save_files!(product_files_params)
expect(file_1.reload.folder_id).to eq(folder.id)
expect(file_2.reload.folder_id).to eq(nil)
expect(file_3.reload.folder_id).to eq(nil)
end
it "respects the `modified` flag if present on file" do
product = create(:product)
file_1 = create(:readable_document, display_name: "name 1", link: product)
file_2 = create(:streamable_video, display_name: "name 2", link: product)
file_3 = create(:listenable_audio, display_name: "name 3", link: product)
product_files_params = [
{
external_id: file_1.external_id,
display_name: "new name 1",
url: file_1.url,
modified: "false"
},
{
external_id: file_2.external_id,
display_name: "new name 2",
url: file_2.url,
modified: "true"
},
{
# Files without a `modified` flag are treated as `modified: true`
external_id: file_3.external_id,
display_name: "new name 3",
url: file_2.url,
}
]
product.save_files!(product_files_params)
expect(file_1.reload.display_name).to eq "name 1"
expect(file_2.reload.display_name).to eq "new name 2"
expect(file_3.reload.display_name).to eq "new name 3"
end
end
context "when called on an Installment record" do
let(:installment) { create(:installment) }
it "does not enqueue a `PdfUnstampableNotifierJob` job when a new file is added" do
expect do
installment.save_files!([{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pic.jpg" }])
end.to change { installment.product_files.alive.count }.by(1)
expect(PdfUnstampableNotifierJob.jobs.size).to eq(0)
end
it "does not enqueue a `PdfUnstampableNotifierJob` job when a file is removed" do
installment.save_files!([{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pic.jpg" }])
expect do
installment.save_files!([])
end.to change { installment.product_files.alive.count }.by(-1)
expect(PdfUnstampableNotifierJob.jobs.size).to eq(0)
end
it "generates the product files archive" do
expect do
installment.save_files!([{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pic.jpg" }])
end.to change { installment.product_files.alive.count }.by(1)
expect(installment.product_files_archives.size).to eq(1)
expect(installment.product_files_archives.alive.size).to eq(1)
expect(installment.product_files_archives.alive.first.url.split("/").last).to include(installment.name.split(" ").first)
end
end
end
describe "#folder_to_files_mapping" do
it "returns an empty hash when there aren't folders with files" do
file1 = create(:product_file, display_name: "First file")
product = create(:product)
product.product_files = [file1]
create(:rich_content, entity: product, title: "Page 1", description: [
{ "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } },
])
create(:rich_content, entity: product, title: "Page 2", description: [
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ignore me" }] },
])
expect(product.folder_to_files_mapping).to eq({})
end
it "returns the proper mapping when there are folders with files" do
file1 = create(:product_file, display_name: "First file")
file2 = create(:product_file, display_name: "Second file")
file3 = create(:product_file, display_name: "Third file")
file4 = create(:product_file, display_name: "Fourth file")
product = create(:product)
product.product_files = [file1, file2, file3, file4]
product.save!
page2_folder1 = { "name" => "", "uid" => SecureRandom.uuid }
page2_folder2 = { "name" => "", "uid" => SecureRandom.uuid }
create(:rich_content, entity: product, title: "Page 1", description: [
{ "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } },
])
create(:rich_content, entity: product, title: "Page 2", description: [
{ "type" => "fileEmbedGroup", "attrs" => page2_folder1, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup", "attrs" => page2_folder2, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } },
] },
])
expect(product.folder_to_files_mapping).to eq(
page2_folder1["uid"] => [file2.id],
page2_folder2["uid"] => [file3.id, file4.id],
)
end
end
describe "#generate_folder_archives!" do
it "generates folder archives for valid folders in the rich content" do
file1 = create(:product_file, display_name: "First file")
file2 = create(:product_file, display_name: "Second file")
file3 = create(:product_file, display_name: "Third file")
file4 = create(:product_file, display_name: "Fourth file")
file5 = create(:product_file, display_name: "Fifth file")
file6 = create(:product_file, display_name: "Sixth file")
product = create(:product)
product.product_files = [file1, file2, file3, file4, file5, file6]
product.save!
create(:rich_content, entity: product, title: "Page 1", description: [
{ "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } },
])
create(:rich_content, entity: product, title: "Page 2", description: [
# This won't have a folder archive since it contains only one file embed
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "", "uid" => SecureRandom.uuid }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "", "uid" => SecureRandom.uuid }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "", "uid" => SecureRandom.uuid }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file5.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file6.external_id, "uid" => SecureRandom.uuid } },
] }
])
expect { product.generate_folder_archives! }.to change { product.product_files_archives.folder_archives.alive.count }.from(0).to(2)
end
it "regenerates file group archives containing the provided files" do
product = create(:product)
file1 = create(:product_file, link: product)
file2 = create(:product_file, link: product)
folder_id = SecureRandom.uuid
description = [
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => folder_id }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } },
] }]
create(:rich_content, entity: product, description:)
archive = product.product_files_archives.create!(folder_id:, product_files: product.product_files)
archive.mark_in_progress!
archive.mark_ready!
expect { product.generate_folder_archives! }.to_not change { archive.reload.deleted? }
expect { product.generate_folder_archives!(for_files: [file1]) }.to change { archive.reload.deleted? }.from(false).to(true)
expect(product.product_files_archives.folder_archives.alive.size).to eq(1)
expect(product.product_files_archives.folder_archives.alive.first.folder_id).to eq(folder_id)
end
end
describe "#generate_entity_archive!" do
it "generates an entity archive" do
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/sendable_to_kindle_spec.rb | spec/modules/sendable_to_kindle_spec.rb | # frozen_string_literal: true
describe SendableToKindle do
describe "#send_to_kindle" do
before do
@product_file = create(:product_file)
end
it "raises an error if the kindle email is invalid" do
expect { @product_file.send_to_kindle("example@example.org") }.to raise_error(ArgumentError).with_message("Please enter a valid Kindle email address")
expect { @product_file.send_to_kindle("EXAMPLE123.-23[]@KINDLE.COM") }.to raise_error(ArgumentError).with_message("Please enter a valid Kindle email address")
expect { @product_file.send_to_kindle(".a12@KINDLE.COM") }.to raise_error(ArgumentError).with_message("Please enter a valid Kindle email address")
expect { @product_file.send_to_kindle("example..23@KINDLE.COM") }.to raise_error(ArgumentError).with_message("Please enter a valid Kindle email address")
expect { @product_file.send_to_kindle("example..@KINDLE.COM") }.to raise_error(ArgumentError).with_message("Please enter a valid Kindle email address")
expect { @product_file.send_to_kindle("\"example.23\"@KINDLE.COM") }.to raise_error(ArgumentError).with_message("Please enter a valid Kindle email address")
expect { @product_file.send_to_kindle("example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789example123456789@KINDLE.COM") }.to raise_error(ArgumentError).with_message("Please enter a valid Kindle email address")
end
it "does not raise an error if the kindle email is valid" do
expect { @product_file.send_to_kindle("example@kindle.com") }.to_not raise_error(ArgumentError)
expect { @product_file.send_to_kindle("ExAmple123@KINDLE.com") }.to_not raise_error(ArgumentError)
expect { @product_file.send_to_kindle("ExAmple.123@KINDLE.com") }.to_not raise_error(ArgumentError)
expect { @product_file.send_to_kindle("ExAmple_123@KINDLE.com") }.to_not raise_error(ArgumentError)
expect { @product_file.send_to_kindle("ExAmple__123@KINDLE.com") }.to_not raise_error(ArgumentError)
expect { @product_file.send_to_kindle("ExAmple-123@KINDLE.com") }.to_not raise_error(ArgumentError)
expect { @product_file.send_to_kindle("ExAmple--123@KINDLE.com") }.to_not raise_error(ArgumentError)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/elasticsearch_model_async_callbacks_spec.rb | spec/modules/elasticsearch_model_async_callbacks_spec.rb | # frozen_string_literal: true
describe ElasticsearchModelAsyncCallbacks do
before do
@model = create_mock_model
@model.include(described_class)
@model.const_set("ATTRIBUTE_TO_SEARCH_FIELDS", "title" => "title")
@multiplier = 2 # we're queuing index and updates jobs twice to mitigate replica lag issues
end
after do
destroy_mock_model(@model)
end
describe "record creation" do
it "enqueues sidekiq job" do
@record = @model.create!(title: "original")
expect(ElasticsearchIndexerWorker.jobs.size).to eq(1 * @multiplier)
expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("index", "record_id" => @record.id, "class_name" => @model.name)
end
it "enqueues sidekiq job even if no permitted value has changed" do
@record = @model.create!
expect(ElasticsearchIndexerWorker.jobs.size).to eq(1 * @multiplier)
expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("index", "record_id" => @record.id, "class_name" => @model.name)
end
end
describe "record update" do
before do
@record = @model.create!
ElasticsearchIndexerWorker.jobs.clear
end
it "enqueues sidekiq job" do
@record.update!(title: "new", subtitle: "new")
expect(ElasticsearchIndexerWorker.jobs.size).to eq(1 * @multiplier)
expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("update", "record_id" => @record.id, "fields" => ["title"], "class_name" => @model.name)
end
it "enqueues single sidekiq job when multiple attributes are saved separately in the same transaction" do
@model::ATTRIBUTE_TO_SEARCH_FIELDS.merge!({ "subtitle" => "subtitle" })
ApplicationRecord.transaction do
@record.update!(title: "new")
@record.update!(subtitle: "new")
end
expect(ElasticsearchIndexerWorker.jobs.size).to eq(1 * @multiplier)
expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("update", "record_id" => @record.id, "fields" => ["title", "subtitle"], "class_name" => @model.name)
end
it "does not queue sidekiq jobs for ES indexing if no permitted column values have changed" do
@record.update!(user_id: 1)
expect(ElasticsearchIndexerWorker.jobs).to be_empty
@record.update!(subtitle: "new")
expect(ElasticsearchIndexerWorker.jobs.size).to eq(0)
end
end
describe "record deletion" do
before do
@record = @model.create!
ElasticsearchIndexerWorker.jobs.clear
end
it "queues sidekiq job" do
@record.destroy!
expect(ElasticsearchIndexerWorker.jobs.size).to eq(1)
expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("delete", "record_id" => @record.id, "class_name" => @model.name)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/obfuscate_ids_spec.rb | spec/modules/obfuscate_ids_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "ObfuscateIds" do
let(:raw_id) { Faker::Number.number(digits: 10) }
it "decrypts the id correctly" do
encrypted_id = ObfuscateIds.encrypt(raw_id)
expect(encrypted_id).to_not eq raw_id.to_s
encrypted_id_without_padding = ObfuscateIds.encrypt(raw_id, padding: false)
expect(encrypted_id_without_padding).to_not eq raw_id.to_s
expect(ObfuscateIds.decrypt(encrypted_id)).to eq raw_id
expect(ObfuscateIds.decrypt(encrypted_id_without_padding)).to eq raw_id
end
describe "numeric encryption of id" do
# Numeric encryption is limited to binary representations of 30 bits
# meaning the max value for which we can encrypt is 2^30 - 1 = 1,073,741,823
let(:raw_id) { rand(1..2**30) }
it "decrypts the id correctly" do
encrypted_id = ObfuscateIds.encrypt_numeric(raw_id)
expect(encrypted_id).to_not eq raw_id.to_s
expect(ObfuscateIds.decrypt_numeric(encrypted_id)).to eq raw_id
end
it "raises an error if the id is greater than the max value" do
expect { ObfuscateIds.encrypt_numeric(2**30) }.to raise_error(ArgumentError)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/immutable_spec.rb | spec/modules/immutable_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Immutable do
let(:today) { Date.today }
# This can be any model, but I'm using the UserComplianceInfo model for the tests. I could not
# find a way to create a mock model which included JsonData.
let(:model) do
build(:user_compliance_info)
end
describe "creating" do
it "is able to create a record" do
model.save!
end
end
describe "updating" do
before do
model.save!
end
describe "no changes" do
it "is able to update a record with no changes" do
model.save!
end
end
describe "changes allowed" do
before do
model.deleted_at = Time.current
end
it "is able to update the record" do
model.save!
end
end
describe "changes not allowed" do
before do
model.first_name = "Santa Clause"
end
it "isn't able to update the record" do
expect { model.save! }.to raise_error(Immutable::RecordImmutable)
end
end
end
describe "#dup_and_save" do
let(:model) { create(:user_compliance_info, birthday: today - 30.years) }
describe "changes are valid" do
before do
@result, @new_model = model.dup_and_save do |new_model|
new_model.birthday = today - 20.years
end
model.reload
@new_model.reload
end
it "returns a result of true" do
expect(@result).to eq(true)
end
it "returns a duplicate of the model" do
expect(@new_model.class).to eq(model.class)
expect(@new_model.first_name).to eq(model.first_name)
expect(@new_model.last_name).to eq(model.last_name)
end
it "returns a model with the change made" do
expect(@new_model.birthday).not_to eq(model.birthday)
expect(@new_model.birthday).to eq(today - 20.years)
end
it "returns a duplicate of the model with an id since its been persisted" do
expect(@new_model.id).to be_present
end
it "marks the original model as deleted" do
expect(model).to be_deleted
end
end
describe "changes are valid, original values are invalid" do
before do
model.update_column("birthday", today)
@result, @new_model = model.dup_and_save do |new_model|
new_model.birthday = today - 20.years
end
model.reload
@new_model.reload
end
it "returns a result of true" do
expect(@result).to eq(true)
end
it "returns a duplicate of the model" do
expect(@new_model.class).to eq(model.class)
expect(@new_model.first_name).to eq(model.first_name)
expect(@new_model.last_name).to eq(model.last_name)
end
it "returns a model with the change made" do
expect(@new_model.birthday).not_to eq(model.birthday)
expect(@new_model.birthday).to eq(today - 20.years)
end
it "returns a duplicate of the model with an id since its been persisted" do
expect(@new_model.id).to be_present
end
it "marks the original model as deleted" do
expect(model).to be_deleted
end
end
describe "changes are invalid" do
before do
@result, @new_model = model.dup_and_save do |new_model|
new_model.birthday = today
end
model.reload
end
it "returns a result of true" do
expect(@result).to eq(false)
end
it "returns a duplicate of the model" do
expect(@new_model.class).to eq(model.class)
expect(@new_model.first_name).to eq(model.first_name)
expect(@new_model.last_name).to eq(model.last_name)
end
it "returns a model with the change made" do
expect(@new_model.birthday).not_to eq(model.birthday)
expect(@new_model.birthday).to eq(today)
end
it "returns a duplicate of the model without an id since it hasn't been persisted" do
expect(@new_model.id).to eq(nil)
# Note: We can't use `persisted?` here to test if it's been persisted, because the model was rolled back
# it's persisted flag got set to that of the record it duplicated and it will be true, even though it isn't.
end
it "does not mark the original model as deleted" do
expect(model).not_to be_deleted
end
end
end
describe "#dup_and_save!" do
let(:model) { create(:user_compliance_info, birthday: today - 30.years) }
describe "changes are valid" do
before do
@result, @new_model = model.dup_and_save! do |new_model|
new_model.birthday = today - 20.years
end
model.reload
@new_model.reload
end
it "returns a result of true" do
expect(@result).to eq(true)
end
it "returns a duplicate of the model" do
expect(@new_model.class).to eq(model.class)
expect(@new_model.first_name).to eq(model.first_name)
expect(@new_model.last_name).to eq(model.last_name)
end
it "returns a model with the change made" do
expect(@new_model.birthday).not_to eq(model.birthday)
expect(@new_model.birthday).to eq(today - 20.years)
end
it "returns a duplicate of the model with an id since its been persisted" do
expect(@new_model.id).to be_present
end
it "marks the original model as deleted" do
expect(model).to be_deleted
end
end
describe "changes are invalid" do
it "raises a validation error" do
expect do
model.dup_and_save! do |new_model|
new_model.birthday = today
end
end.to raise_error(ActiveRecord::RecordInvalid)
end
describe "after the error is raised" do
before do
@model_id = model.id
expect do
model.dup_and_save! do |new_model|
new_model.birthday = today
end
end.to raise_error(ActiveRecord::RecordInvalid)
end
it "does not have created a new record" do
model = UserComplianceInfo.find(@model_id)
expect(model.user.user_compliance_infos.count).to eq(1)
end
it "does not mark the original model as deleted" do
model = UserComplianceInfo.find(@model_id)
expect(model).not_to be_deleted
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/with_file_properties_spec.rb | spec/modules/with_file_properties_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe WithFileProperties do
PROPERTIES = %i[size duration width height framerate bitrate pagelength].freeze
def stub_for_word_doc
output_double = double
allow(output_double).to receive(:output).and_return("Number of Pages = 2")
allow(Subexec).to receive(:run).and_return(output_double)
end
def stub_for_pdf
output_double = double
allow(output_double).to receive(:page_count).and_return("6")
allow(PDF::Reader).to receive(:new).and_return(output_double)
end
def stub_for_ppt
output_double = double
allow(output_double).to receive(:output).and_return("Number of Slides = 7")
allow(Subexec).to receive(:run).and_return(output_double)
end
before do
allow(FFMPEG::Movie).to receive(:new) do |path|
extension = File.extname(path)
if extension.match(FILE_REGEX["audio"])
double.tap do |song_double|
allow(song_double).to receive(:duration).and_return(46)
allow(song_double).to receive(:bitrate).and_return(128)
end
elsif extension.match(FILE_REGEX["video"])
double.tap do |movie_double|
allow(movie_double).to receive(:duration).and_return(13)
allow(movie_double).to receive(:frame_rate).and_return(60)
allow(movie_double).to receive(:height).and_return(240)
allow(movie_double).to receive(:width).and_return(320)
allow(movie_double).to receive(:bitrate).and_return(125_779)
end
else
raise "Unsupported path: #{path}"
end
end
end
{ audio: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3",
filename: "magic.mp3", filegroup: "audio", constraints: { size: 466_312, duration: 46, bitrate: 128 } },
exe: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.exe",
filename: "test.exe", filegroup: "executable", constraints: { size: 118 } },
archive: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.zip",
filename: "test.zip", filegroup: "archive", constraints: { size: 67_852 } },
psd: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/index.psd",
filename: "index.psd", filegroup: "image", constraints: { size: 132_284 } },
text: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/blah.txt",
filename: "blah.txt", filegroup: "document", constraints: { size: 52 } },
video: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/small.m4v",
filename: "small.m4v", filegroup: "video",
constraints: { size: 208_857, width: 320, height: 240, duration: 13, framerate: 60, bitrate: 125_779 } },
image: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/kFDzu.png",
filename: "kFDzu.png", filegroup: "image", constraints: { size: 47_684, width: 1633, height: 512 } },
pdf_document: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/billion-dollar-company-chapter-0.pdf",
filename: "billion-dollar-company-chapter-0.pdf", filegroup: "document",
constraints: { size: 111_237, pagelength: 6 }, stubbing_method: :stub_for_pdf },
word_document_docx: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/sample_doc.docx",
filename: "sample_doc.docx", filegroup: "document",
constraints: { size: 156_126, pagelength: 4 } },
word_document: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test_doc.doc",
filename: "test_doc.doc", filegroup: "document", constraints: { size: 28_672, pagelength: 2 },
stubbing_method: :stub_for_word_doc },
epub: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/sample.epub",
filename: "test.epub", filegroup: "document", constraints: { size: 881_436, pagelength: 13 } },
powerpoint: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.ppt",
filename: "test.ppt", filegroup: "document",
constraints: { size: 954_368, pagelength: 7 }, stubbing_method: :stub_for_ppt },
powerpoint_pptx: { fake_uri: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.pptx",
filename: "test.pptx", filegroup: "document",
constraints: { size: 1_346_541, pagelength: 2 } } }.each do |file_type, properties|
describe "#{file_type} files" do
before do
send(properties[:stubbing_method]) if properties[:stubbing_method]
@product_file = create(:product_file, url: properties[:fake_uri])
s3_double = double
allow(s3_double).to receive(:content_length).and_return(properties[:constraints][:size])
allow(s3_double).to receive(:get) do |options|
File.open(options[:response_target], "w+") do |f|
f.write(File.open("#{Rails.root}/spec/support/fixtures/#{properties[:filename]}").read)
end
end
allow(@product_file).to receive(:s3_object).and_return(s3_double)
allow(@product_file).to receive(:confirm_s3_key!)
@product_file.analyze
end
it "has the correct filegroup for #{file_type}" do
expect(@product_file.filegroup).to eq properties[:filegroup]
end
it "has the correct properties" do
PROPERTIES.each do |property|
expect(@product_file.send(property)).to eq properties[:constraints][property]
end
end
end
end
describe "videos" do
before do
@video_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/sample.mov")
@file_path = file_fixture("sample.mov").to_s
end
it "sets the metadata and the analyze_completed flag" do
expected_metadata = {
bitrate: 27_506,
duration: 4,
framerate: 60,
height: 132,
width: 176
}
expect do
@video_file.assign_video_attributes(@file_path)
@video_file.reload
expected_metadata.each do |property, value|
expect(@video_file.public_send(property)).to eq(value)
end
end.to change { @video_file.analyze_completed? }.from(false).to(true)
end
context "when auto-transcode is disabled for the product" do
it "doesn't transcode the video and sets product.transcode_videos_on_purchase to true" do
@video_file.assign_video_attributes(@file_path)
expect(TranscodeVideoForStreamingWorker.jobs.size).to eq(0)
expect(@video_file.link.transcode_videos_on_purchase?).to eq true
end
end
context "when auto-transcode is enabled for the product" do
before do
allow(@video_file.link).to receive(:auto_transcode_videos?).and_return(true)
end
it "transcodes the video" do
@video_file.assign_video_attributes(@file_path)
expect(TranscodeVideoForStreamingWorker).to have_enqueued_sidekiq_job(@video_file.id, @video_file.class.name)
end
end
end
describe "epubs" do
before do
@epub_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sample.epub")
file_path = file_fixture("sample.epub")
@epub_file.assign_epub_document_attributes(file_path)
end
it "sets the pagelength" do
expect(@epub_file.pagelength).to eq 10
end
it "returns nil in pagelength for json" do
@epub_file.pagelength = 10
@epub_file.save!
@epub_file.reload
expect(@epub_file.as_json[:pagelength]).to be_nil
expect(@epub_file.mobile_json_data[:pagelength]).to be_nil
end
it "sets the epub section information" do
epub_section_info = @epub_file.epub_section_info
expect(epub_section_info.keys).to eq %w[i s1a s1b s2a s2b s3a s3b s4a s4b s5]
expect(epub_section_info["s1a"]["section_number"]).to eq 2
expect(epub_section_info["s1a"]["section_name"]).to eq "Childhood"
expect(epub_section_info["s3a"]["section_number"]).to eq 6
expect(epub_section_info["s3a"]["section_name"]).to eq "Manhood"
end
end
describe "very large files" do
before do
@product_file = create(:product_file)
@product_file.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/some-video-file.mov"
s3_double = double
allow(s3_double).to receive(:content_length).and_return(2_000_000_000)
allow(@product_file).to receive(:s3_object).and_return(s3_double)
allow(@product_file).to receive(:confirm_s3_key!)
@product_file.analyze
end
it "does not have framerate, resolution, duraration" do
expect(@product_file.framerate).to be(nil)
expect(@product_file.width).to be(nil)
expect(@product_file.height).to be(nil)
expect(@product_file.duration).to be(nil)
end
end
describe "long file names" do
before do
@product_file = create(:product_file)
@product_file.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/5635138219475/1dc6d2b8f68c4da9b944e8930602057c/original/SET GS สปาหน้าเด็ก หน้าใส ไร้สิว อ่อนเยาว์ สวย เด้ง.jpg"
s3_double = double
allow(s3_double).to receive(:content_length).and_return(1000)
allow(s3_double).to receive(:get) do |options|
File.open(options[:response_target], "w+") do |f|
f.write("")
end
end
allow(@product_file).to receive(:s3_object).and_return(s3_double)
allow(@product_file).to receive(:confirm_s3_key!)
end
it "does not throw an exception due to long tempfile name" do
expect { @product_file.analyze }.to_not raise_error
end
end
it "raises a descriptive exception if the S3 object doesn't exist" do
file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/missing.txt")
expect do
file.analyze
end.to raise_error(Aws::S3::Errors::NotFound, /Key = attachments\/missing.txt .* ProductFile.id = #{file.id}/)
end
context "with a incorrect s3_key" do
it "corrects it and succeeds in analyzing the file" do
s3_directory = "#{SecureRandom.hex}/#{SecureRandom.hex}/original"
Aws::S3::Resource.new.bucket(S3_BUCKET).object("#{s3_directory}/file.pdf").upload_file(
File.new("spec/support/fixtures/test.pdf"),
content_type: "application/pdf"
)
file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{s3_directory}/incorrect-file-name.pdf")
file.analyze
file.reload
expect(file.s3_key).to eq(s3_directory + "/file.pdf")
expect(file.filetype).to eq("pdf")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/money_formatter_spec.rb | spec/modules/money_formatter_spec.rb | # frozen_string_literal: true
describe MoneyFormatter do
describe "#format" do
describe "usd" do
it "returns the correct string" do
expect(MoneyFormatter.format(400, :usd)).to eq "$4.00"
end
it "returns correctly when no symbol desired" do
expect(MoneyFormatter.format(400, :usd, symbol: false)).to eq "4.00"
end
end
describe "jpy" do
it "returns the correct string" do
expect(MoneyFormatter.format(400, :jpy)).to eq "¥400"
end
end
describe "aud" do
it "returns the correct currency symbol" do
expect(MoneyFormatter.format(400, :aud)).to eq "A$4.00"
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/twitter_cards_spec.rb | spec/modules/twitter_cards_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TwitterCards, :vcr do
describe "#twitter_product_card" do
it "renders a bunch of meta tags" do
link = build(:product, unique_permalink: "abcABC")
metas = TwitterCards.twitter_product_card(link)
expect(metas).to match("<meta property=\"twitter:card\" value=\"summary\" />")
expect(metas).to match("twitter:title")
expect(metas).to match(link.name)
expect(metas).to match(link.price_formatted.delete("$"))
expect(metas).to_not match("image")
expect(metas).to_not match("creator")
end
it "renders preview if image" do
link = build(:product, preview: fixture_file_upload("kFDzu.png", "image/png"))
thumbnail = Thumbnail.new(product: link)
blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png")
blob.analyze
thumbnail.file.attach(blob)
thumbnail.save!
metas = TwitterCards.twitter_product_card(link)
expect(metas).to match("<meta property=\"twitter:card\" value=\"summary_large_image\" />")
expect(metas).to match("image")
expect(metas).to match(link.main_preview.url)
end
it "renders twitter user if available" do
user = build(:user, twitter_handle: "gumroad")
link = build(:product, unique_permalink: "abcABC", user:)
metas = TwitterCards.twitter_product_card(link)
expect(metas).to match("creator")
expect(metas).to match("@gumroad")
end
it "falls back to the old twitter cards if the link doesn't have a preview image" do
link = build(:product, filegroup: "archive", size: 10)
metas = TwitterCards.twitter_product_card(link)
expect(metas).to_not match("<meta property=\"twitter:card\" value=\"product\" />")
expect(metas).to match("<meta property=\"twitter:card\" value=\"summary\" />")
end
it "falls back to the old twitter cards if the link's preview isn't an image" do
link = build(:product, filegroup: "archive", preview: Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "thing.mov"), "video/quicktime"))
metas = TwitterCards.twitter_product_card(link)
expect(metas).to_not match("<meta property=\"twitter:card\" value=\"product\" />")
expect(metas).to match("<meta property=\"twitter:card\" value=\"player\" />")
end
it "does not uri escape the preview image url" do
link = create(:product)
create(:asset_preview, link:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/file with spaces.png")
link.product_files << create(:product_file, link:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil1.png")
link.save!
link.reload
metas = TwitterCards.twitter_product_card(link)
expect(metas).to match(link.main_preview.url)
end
it "does not uri escape the preview image url but it should html-escape it if necessary" do
link = create(:product)
create(:asset_preview, link:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/file_with_double_quotes\".png")
link.product_files << create(:product_file, link:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil1.png")
link.save!
link.reload
metas = TwitterCards.twitter_product_card(link)
expect(metas).to match(link.main_preview.url)
end
it "uses the card description if provided" do
link = build(:product, unique_permalink: "abcABC")
metas = TwitterCards.twitter_product_card(link, product_description: "This is a test description")
expect(metas).to match('<meta property="twitter:description" value="This is a test description"')
end
it "uses the link description if no card description is provided" do
link = build(:product, unique_permalink: "abcABC", description: "This is a test description")
metas = TwitterCards.twitter_product_card(link)
expect(metas).to match('<meta property="twitter:description" value="This is a test description"')
end
end
describe "#twitter_post_card" do
context "when post has no embedded images" do
it "renders twitter meta tags for small summary" do
post = build(:installment, name: "Friday dispatch", message: "<p>Important message</p>")
metas = TwitterCards.twitter_post_card(post)
expect(metas).to match('<meta property="twitter:domain" value="Gumroad" />')
expect(metas).to match('<meta property="twitter:card" value="summary" />')
expect(metas).to match('<meta property="twitter:title" value="Friday dispatch"')
expect(metas).to match('<meta property="twitter:description" value="Important message"')
end
end
context "when post has an embedded image" do
it "renders twitter meta tags for large summary with image" do
post = build(
:installment,
name: "Friday dispatch",
message: <<~HTML.strip
<p>Important message</p>
<figure>
<img src="path/to/image.jpg">
<p class="figcaption">Image description</p>
</figure>
HTML
)
metas = TwitterCards.twitter_post_card(post)
expect(metas).to match('<meta property="twitter:domain" value="Gumroad" />')
expect(metas).to match('<meta property="twitter:card" value="summary_large_image" />')
expect(metas).to match('<meta property="twitter:title" value="Friday dispatch"')
expect(metas).to match('<meta property="twitter:description" value="Important message Image description"')
expect(metas).to match('<meta property="twitter:image" value="path/to/image.jpg"')
expect(metas).to match('<meta property="twitter:image:alt" value="Image description"')
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/integrations_spec.rb | spec/modules/integrations_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Integrations do
describe "#find_integration_by_name" do
context "when called on a Link record" do
# TODO: Change one of the integrations to have a different type after newer ones are added
it "returns the first integration of the given type" do
integration_1 = create(:circle_integration)
product = create(:product, active_integrations: [integration_1, create(:circle_integration)])
expect(product.find_integration_by_name(Integration::CIRCLE)).to eq(integration_1)
end
end
context "when called on a Base Variant record" do
# TODO: Change one of the integrations to have a different type after newer ones are added
it "returns the first integration of the given type" do
integration_1 = create(:circle_integration)
category = create(:variant_category, title: "versions", link: create(:product))
variant = create(:variant, variant_category: category, name: "v1", active_integrations: [integration_1, create(:circle_integration)])
expect(variant.find_integration_by_name(Integration::CIRCLE)).to eq(integration_1)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/s3_retrievable_spec.rb | spec/modules/s3_retrievable_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "S3Retrievable" do
let!(:model) do
model = create_mock_model do |t|
t.string :url
end
model.attr_accessor :user
model.include S3Retrievable
model.has_s3_fields :url
model
end
subject(:s3_retrievable_object) do
model.new.tap do |test_class|
test_class.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/nyt.pdf"
end
end
shared_examples "s3 retrievable instance method" do |method_name|
context "when the s3 attribute value is empty" do
before { s3_retrievable_object.url = nil }
it "returns nil" do
expect(s3_retrievable_object.public_send(method_name)).to be nil
end
end
end
describe "#unique_url_identifier" do
it "returns url as an identifier" do
expect(s3_retrievable_object.unique_url_identifier).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/nyt.pdf")
end
context "when it has an s3 guid" do
before do
s3_retrievable_object.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/nyt.pdf"
end
it "returns s3 guid" do
expect(s3_retrievable_object.unique_url_identifier).to eq("23b2d41ac63a40b5afa1a99bf38a0982")
end
end
end
describe "#download_original" do
it "downloads file from s3 into a tempfile" do
s3_object_double = double
expect(s3_object_double).to receive(:download_file)
expect(s3_retrievable_object).to receive(:s3_object).and_return(s3_object_double)
yielded = false
s3_retrievable_object.download_original do |original_file|
yielded = true
expect(original_file).to be_kind_of(Tempfile)
expect(File.extname(original_file)).to eq(".pdf")
end
expect(yielded).to eq(true)
end
it "requires a block" do
expect { s3_retrievable_object.download_original }.to raise_error(ArgumentError, /requires a block/)
end
it "raises a descriptive exception if the S3 object doesn't exist" do
record = model.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/missing.txt")
expect do
record.download_original { }
end.to raise_error(Aws::S3::Errors::NotFound, /Key = attachments\/missing.txt .* #{model.name}.id = #{record.id}/)
end
end
describe "#s3_filename" do
it "returns filename" do
expect(s3_retrievable_object.s3_filename).to eq("nyt.pdf")
end
include_examples "s3 retrievable instance method", "s3_filename"
end
describe "#s3_url" do
it "returns s3 url value" do
expect(s3_retrievable_object.s3_url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/nyt.pdf")
end
include_examples "s3 retrievable instance method", "s3_url"
end
describe "#s3_extension" do
it "returns file extension" do
expect(s3_retrievable_object.s3_extension).to eq(".pdf")
end
include_examples "s3 retrievable instance method", "s3_extension"
end
describe "#s3_display_extension" do
it "returns formatted file extension" do
expect(s3_retrievable_object.s3_display_extension).to eq("PDF")
end
include_examples "s3 retrievable instance method", "s3_display_extension"
end
describe "#s3_display_name" do
it "returns file name without extension" do
expect(s3_retrievable_object.s3_display_name).to eq("nyt")
end
include_examples "s3 retrievable instance method", "s3_display_name"
end
describe "#s3_directory_uri" do
before do
s3_retrievable_object.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/nyt.pdf"
end
it "returns file directory" do
expect(s3_retrievable_object.s3_directory_uri).to eq("attachments/23b2d41ac63a40b5afa1a99bf38a0982/original")
end
include_examples "s3 retrievable instance method", "s3_directory_uri"
end
describe "#restore_deleted_s3_object!" do
context "when the versioned object exists" do
let!(:record) { model.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{SecureRandom.hex}") }
before do
Aws::S3::Resource.new.bucket(S3_BUCKET).object(record.s3_key).upload_file(
File.new(Rails.root.join("spec/support/fixtures/test.pdf")),
content_type: "application/pdf"
)
expect(record.s3_object.exists?).to eq(true)
end
it "returns nil if S3 object is available" do
expect(record.restore_deleted_s3_object!).to eq(nil)
end
it "returns true if S3 object was restored" do
bucket = Aws::S3::Resource.new(
region: AWS_DEFAULT_REGION,
credentials: Aws::Credentials.new(GlobalConfig.get("S3_DELETER_ACCESS_KEY_ID"), GlobalConfig.get("S3_DELETER_SECRET_ACCESS_KEY"))
).bucket(S3_BUCKET)
bucket.object(record.s3_key).delete
expect(record.s3_object.exists?).to eq(false)
expect(record.restore_deleted_s3_object!).to eq(true)
expect(record.s3_object.exists?).to eq(true)
end
end
context "when the versioned object is missing" do
let!(:record) { model.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{SecureRandom.hex}") }
it "retuns false" do
expect(record.restore_deleted_s3_object!).to eq(false)
end
end
end
describe "#confirm_s3_key!" do
it "updates the url if possible" do
s3_directory = "#{SecureRandom.hex}/#{SecureRandom.hex}/original"
Aws::S3::Resource.new.bucket(S3_BUCKET).object("#{s3_directory}/file.pdf").upload_file(
File.new("spec/support/fixtures/test.pdf"),
content_type: "application/pdf"
)
record = model.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{s3_directory}/incorrect-file-name.pdf")
record.confirm_s3_key!
expect(record.s3_key).to eq(s3_directory + "/file.pdf")
end
it "does nothing if the file exists on S3" do
previous_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/sample.mov"
record = model.create!(url: previous_url)
record.confirm_s3_key!
expect(record.s3_key).to eq("specs/sample.mov")
end
end
describe ".s3" do
it "only includes s3 files" do
s3_retrievable_object.save!
model.create!(url: "https://example.com")
expect(model.s3).to match_array(s3_retrievable_object)
end
end
describe ".with_s3_key" do
it "only includes s3 files matching the s3 key" do
foo = model.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/foo.pdf")
foo2 = model.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/foo.pdf")
other = model.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/other.pdf")
model.create!(url: "https://example.com")
expect(model.with_s3_key("attachments/foo.pdf")).to match_array([foo, foo2])
expect(model.with_s3_key("attachments/other.pdf")).to match_array([other])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/subdomain_spec.rb | spec/modules/subdomain_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Subdomain do
before do
@seller1 = create(:user)
@seller1.username = "test_user" # old style username
@seller1.save(validate: false)
@seller2 = create(:user, username: "testuser2") # new style username
@seller3 = create(:user, username: nil)
@root_domain_without_port = URI("#{PROTOCOL}://#{ROOT_DOMAIN}").host
end
describe "#find_seller_by_request" do
def request_obj(username)
username = username.tr("_", "-") # convert underscores to hyphens in usernames
OpenStruct.new({ host: "#{username}.#{@root_domain_without_port}", subdomains: [username] })
end
it "does not match sellers with blank usernames" do
root_domain_request = OpenStruct.new({ host: @root_domain_without_port, subdomains: [] })
expect(Subdomain.find_seller_by_request(root_domain_request)).to eq nil
end
it "finds the sellers using request subdomain" do
expect(Subdomain.find_seller_by_request(request_obj(@seller1.username))).to eq @seller1
expect(Subdomain.find_seller_by_request(request_obj(@seller2.username))).to eq @seller2
expect(Subdomain.find_seller_by_request(request_obj(@seller3.external_id))).to eq @seller3
end
context "when seller is marked as deleted" do
before do
@seller1.mark_deleted!
end
it "does not find the seller" do
expect(Subdomain.find_seller_by_request(request_obj(@seller1.username))).to be_nil
end
end
end
describe "#find_seller_by_hostname" do
def subdomain_url(username)
[username.tr("_", "-"), @root_domain_without_port].join(".")
end
it "does not match sellers with blank usernames" do
expect(Subdomain.find_seller_by_hostname(@root_domain_without_port)).to eq nil
end
it "finds the sellers using request subdomain" do
expect(Subdomain.find_seller_by_hostname(subdomain_url(@seller1.username))).to eq @seller1
expect(Subdomain.find_seller_by_hostname(subdomain_url(@seller2.username))).to eq @seller2
end
context "when seller is marked as deleted" do
before do
@seller1.mark_deleted!
end
it "does not find the seller" do
expect(Subdomain.find_seller_by_hostname(subdomain_url(@seller1.username))).to be_nil
end
end
end
describe "#subdomain_request?" do
it "returns true when it's a valid subdomain request" do
domain = "test.#{@root_domain_without_port}"
expect(Subdomain.send(:subdomain_request?, domain).present?).to eq(true)
end
it "returns false when hostname contains underscore" do
domain = "test_123.#{@root_domain_without_port}"
expect(Subdomain.send(:subdomain_request?, domain).present?).to eq(false)
end
it "returns false when hostname doesn't look like a subdomain request" do
domain = "sample.example.com"
expect(Subdomain.send(:subdomain_request?, domain).present?).to eq(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/cdn_deletable_spec.rb | spec/modules/cdn_deletable_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CdnDeletable do
describe ".alive_in_cdn" do
it "returns only those records which have `deleted_from_cdn_at` set to a NULL value" do
create(:product_file, deleted_from_cdn_at: Time.current)
product_file = create(:product_file)
expect(ProductFile.alive_in_cdn.pluck(:id)).to eq([product_file.id])
end
end
describe ".cdn_deletable" do
it "only includes deleted records, with S3 url, alive in the CDN" do
product_files = [
create(:product_file),
create(:product_file, deleted_at: Time.current),
create(:product_file, deleted_at: Time.current, deleted_from_cdn_at: Time.current),
create(:product_file, deleted_at: Time.current, url: "https://example.com", filetype: "link"),
]
expect(ProductFile.cdn_deletable).to match_array([product_files[1]])
end
end
describe "#deleted_from_cdn?" do
it "returns `true` when `deleted_from_cdn_at` is a non-NULL value" do
product_file = create(:product_file, deleted_from_cdn_at: Time.current)
expect(product_file.deleted_from_cdn?).to eq(true)
end
it "returns `false` when `deleted_from_cdn_at` is a NULL value" do
product_file = create(:product_file)
expect(product_file.deleted_from_cdn?).to eq(false)
end
end
describe "#mark_deleted_from_cdn" do
it "sets the value of `deleted_from_cdn_at` to the current time" do
product_file = create(:product_file)
travel_to(Time.current) do
product_file.mark_deleted_from_cdn
expect(product_file.deleted_from_cdn_at.to_s).to eq(Time.current.utc.to_s)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/stats_spec.rb | spec/modules/product/stats_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::Stats do
include ManageSubscriptionHelpers
describe ".successful_sales_count", :sidekiq_inline, :elasticsearch_wait_for_refresh do
it "does not take into account refunded/disputed purchases" do
@product = create(:product, price_cents: 500)
create(:purchase, link: @product)
create(:purchase, link: @product, stripe_refunded: true)
create(:purchase, link: @product, chargeback_date: Time.current)
create(:purchase, link: @product, chargeback_date: Time.current, chargeback_reversed: true)
@preorder_link = create(:product, price_cents: 500, is_in_preorder_state: true)
create(:purchase, link: @preorder_link, purchase_state: "preorder_authorization_successful")
create(:purchase, link: @preorder_link, purchase_state: "preorder_authorization_successful", stripe_refunded: true)
expect(@product.sales.count).to eq 4
expect(Link.successful_sales_count(products: @product)).to eq 2
expect(@preorder_link.sales.count).to eq 2
expect(Link.successful_sales_count(products: @preorder_link)).to eq 1
end
context "for tiered memberships" do
it "does not double count subscriptions that have been upgraded" do
product = create(:membership_product)
sub = create(:subscription, link: product)
create(:purchase, subscription: sub, link: product, is_original_subscription_purchase: true,
purchase_state: "successful", is_archived_original_subscription_purchase: true)
create(:purchase, subscription: sub, link: product, is_original_subscription_purchase: true,
purchase_state: "not_charged")
sub.reload
create(:purchase, subscription: sub, link: product, is_original_subscription_purchase: false)
expect(Link.successful_sales_count(products: product)).to eq 1
end
end
it "supports multiple products" do
products = create_list(:product, 2)
products.each do |product|
create(:purchase, link: product)
end
expect(Link.successful_sales_count(products: products.map(&:id))).to eq(2)
end
end
describe "#successful_sales_count" do
it "returns value from the class method" do
product = create(:product)
expect(Link).to receive(:successful_sales_count).with(products: product, extra_search_options: nil).and_return(123)
expect(product.successful_sales_count).to eq(123)
end
end
describe "#total_usd_cents", :sidekiq_inline, :elasticsearch_wait_for_refresh do
it "returns net revenue" do
product = create(:product)
expect(product.total_usd_cents).to eq(0)
create_list(:purchase, 2, link: product)
expect(product.reload.total_usd_cents).to eq(200)
end
context "with a created_after option" do
it "returns the sum of matching net revenue" do
product = create(:product)
create(:purchase, link: product, created_at: 5.days.ago)
create(:purchase, link: product, created_at: 3.days.ago)
create(:purchase, link: product, created_at: 1.day.ago)
expect(product.total_usd_cents(created_after: 10.days.ago)).to eq(300)
expect(product.total_usd_cents(created_after: 4.days.ago)).to eq(200)
expect(product.total_usd_cents(created_after: 1.minute.ago)).to eq(0)
end
end
it "does not take into account refunded or not charged purchases", :sidekiq_inline, :elasticsearch_wait_for_refresh do
@product = create(:product, price_cents: 500)
create(:purchase, link: @product)
create(:purchase, link: @product, stripe_refunded: true)
create(:purchase, link: @product, purchase_state: "not_charged")
@preorder_link = create(:product, price_cents: 500, is_in_preorder_state: true)
create(:purchase, link: @preorder_link, purchase_state: "preorder_authorization_successful")
create(:purchase, link: @preorder_link, purchase_state: "preorder_authorization_successful", stripe_refunded: true)
partially_refunded_purchase = create(:purchase, link: @product, stripe_partially_refunded: true)
partially_refunded_purchase.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, 300), partially_refunded_purchase.seller.id)
expect(@product.total_usd_cents).to eq 700
expect(@preorder_link.total_usd_cents).to eq 500
end
end
describe "#total_fee_cents", :sidekiq_inline, :elasticsearch_wait_for_refresh do
it "does not take into account fully refunded, not charged, chargeback not reverted, giftee purchases" do
product = create(:product, price_cents: 500)
create(:purchase, link: product)
create(:purchase, link: product, stripe_refunded: true)
create(:purchase, link: product, stripe_partially_refunded: true)
create(:purchase, link: product, purchase_state: "not_charged")
create(:purchase, link: product, chargeback_date: 1.day.ago)
create(:purchase, link: product, chargeback_date: 1.day.ago, chargeback_reversed: true)
create(:purchase, link: product, created_at: 2.months.ago)
create(:gift, link: product,
gifter_purchase: create(:purchase, link: product, is_gift_sender_purchase: true),
giftee_purchase: create(:purchase, link: product, is_gift_receiver_purchase: true, price_cents: 0, purchase_state: "gift_receiver_purchase_successful"))
preorder_product = create(:product, price_cents: 500, is_in_preorder_state: true)
create(:preorder_authorization_purchase, link: preorder_product)
create(:preorder_authorization_purchase, link: preorder_product, stripe_refunded: true)
create(:preorder_authorization_purchase, link: preorder_product, stripe_partially_refunded: true)
create(:preorder_authorization_purchase, link: preorder_product, chargeback_date: 1.day.ago)
create(:preorder_authorization_purchase, link: preorder_product, chargeback_date: 1.day.ago, chargeback_reversed: true)
create(:gift, link: preorder_product,
gifter_purchase: create(:preorder_authorization_purchase, link: preorder_product, is_gift_sender_purchase: true),
giftee_purchase: create(:preorder_authorization_purchase, link: preorder_product, is_gift_receiver_purchase: true, price_cents: 0, purchase_state: "gift_receiver_purchase_successful"))
# successful + partially refunded + chargeback reversed + gift sender purchases - (4*75)
expect(product.total_fee_cents(created_after: 1.month.ago)).to eq 580
expect(preorder_product.total_fee_cents).to eq 580
end
it "returns net fees" do
product = create(:product)
expect(product.total_fee_cents).to eq(0)
create_list(:purchase, 2, :with_custom_fee, link: product, fee_cents: 15)
expect(product.reload.total_fee_cents).to eq(30)
end
context "with a created_after option" do
it "returns the sum of matching net revenue" do
product = create(:product)
create(:purchase, :with_custom_fee, link: product, created_at: 5.days.ago, fee_cents: 15)
create(:purchase, :with_custom_fee, link: product, created_at: 3.days.ago, fee_cents: 15)
create(:purchase, :with_custom_fee, link: product, created_at: 1.day.ago, fee_cents: 15)
expect(product.total_fee_cents(created_after: 10.days.ago)).to eq(45)
expect(product.total_fee_cents(created_after: 4.days.ago)).to eq(30)
expect(product.total_fee_cents(created_after: 1.minute.ago)).to eq(0)
end
end
end
describe "#pending_balance" do
before do
@product = create(:subscription_product, user: create(:user), duration_in_months: 12)
@sub = create(:subscription, user: create(:user), link: @product, charge_occurrence_count: 12)
@original_purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @sub)
end
it "returns the correct pending balance" do
expect(@product.pending_balance).to eq 1100
end
it "shoud return $0 if there are no pending balances" do
@sub.update_attribute(:cancelled_at, Time.current)
expect(@product.pending_balance).to eq 0
end
context "when a subscription has been updated" do
it "uses the updated purchase price" do
@original_purchase.update!(is_archived_original_subscription_purchase: true)
create(:purchase, link: @product, price_cents: @product.price_cents + 100, is_original_subscription_purchase: true, subscription: @sub, purchase_state: "not_charged")
expect(@product.pending_balance).to eq 2200
end
end
end
describe "#revenue_pending" do
context "when product has a duration set" do
before do
@product = create(:subscription_product, user: create(:user), duration_in_months: 12)
subscription = create(:subscription, link: @product, charge_occurrence_count: 12)
@original_purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription:)
end
it "returns the correct pending revenue" do
expect(@product.revenue_pending).to eq 1100
end
end
context "when product has no duration set" do
before do
@product = create(:product)
end
it "returns 0" do
expect(@product.revenue_pending).to eq 0
end
end
end
describe ".monthly_recurring_revenue", :sidekiq_inline, :elasticsearch_wait_for_refresh do
subject { Link.monthly_recurring_revenue(products: [@product]) }
context "for a non-tiered subscription product" do
before do
@product = create(:subscription_product, user: create(:user))
price_monthly = create(:price, link: @product, price_cents: 10_00, recurrence: BasePrice::Recurrence::MONTHLY)
price_yearly = create(:price, link: @product, price_cents: 100_00, recurrence: BasePrice::Recurrence::YEARLY)
sub_monthly = create(:subscription, user: create(:user), link: @product)
sub_monthly.payment_options.create(price: price_monthly)
create(:purchase, link: @product, price_cents: 10_00, is_original_subscription_purchase: true, subscription: sub_monthly)
@sub_yearly = create(:subscription, user: create(:user), link: @product)
@sub_yearly.payment_options.create(price: price_yearly)
create(:purchase, link: @product, price_cents: 100_00, is_original_subscription_purchase: true, subscription: @sub_yearly)
end
it "returns the monthly recurring revenue" do
is_expected.to eq 1833.3333129882812
end
it "discards inactive subscriptions" do
@sub_yearly.update_attribute(:cancelled_at, Time.current)
is_expected.to eq 1000
end
end
context "for a tiered membership product", :vcr do
before do
# create two subscriptions:
# - monthly @ $3
# - yearly @ $10
shared_setup
@sub_monthly = create_subscription(product_price: @monthly_product_price,
tier: @original_tier,
tier_price: @original_tier_monthly_price)
@sub_yearly = create_subscription(product_price: @yearly_product_price,
tier: @original_tier,
tier_price: @original_tier_yearly_price)
end
it "returns the monthly recurring revenue" do
is_expected.to eq 383.33333587646484
end
it "discards inactive subscriptions" do
@sub_yearly.update_attribute(:cancelled_at, Time.current)
is_expected.to eq 300
end
context "with a subscription that has been upgraded" do
it "uses the new 'original' purchase" do
travel_to(@originally_subscribed_at + 1.year + 1.day) do
params = {
price_id: @yearly_product_price.external_id,
variants: [@original_tier.external_id],
use_existing_card: true,
perceived_price_cents: @original_tier_yearly_price.price_cents,
perceived_upgrade_price_cents: @original_tier_yearly_price.price_cents,
}
result = Subscription::UpdaterService.new(subscription: @sub_monthly,
gumroad_guid: "abc123",
params:,
logged_in_user: @sub_monthly.user,
remote_ip: "1.1.1.1").perform
expect(result[:success]).to eq true
# Two yearly $10 subscriptions
is_expected.to eq 166.6666717529297
end
end
end
shared_examples "common cancelled MRR" do
it "returns only the active subscriptions" do
# One yearly $10 subscription
is_expected.to eq 83.33333587646484
end
end
context "with a subscription cancelled by buyer but still active" do
before do
@sub_monthly.update!(
cancelled_by_buyer: true,
cancelled_at: @sub_monthly.created_at + 1.month
)
end
include_examples "common cancelled MRR"
end
context "with a subscription cancelled by admin but still active" do
before do
@sub_monthly.update!(
cancelled_by_admin: true,
cancelled_at: @sub_monthly.created_at + 1.month
)
end
include_examples "common cancelled MRR"
end
context "with a cancelled subscription" do
before do
@sub_monthly.update!(
cancelled_by_buyer: true,
cancelled_at: 1.day.ago
)
end
include_examples "common cancelled MRR"
end
context "when multiple tiered membership products exist" do
before do
product = create(:membership_product_with_preset_tiered_pricing, user: @user)
create(:membership_purchase,
link: product,
price_cents: 1000,
variant_attributes: [product.default_tier])
end
it "does not count subscriptions from other products" do
is_expected.to eq 383.33333587646484
end
end
end
it "supports multiple products" do
products = create_list(:subscription_product, 2)
products.each do |product|
price_monthly = create(:price, link: product, price_cents: 10_00, recurrence: BasePrice::Recurrence::MONTHLY)
sub_monthly = create(:subscription, link: product)
sub_monthly.payment_options.create(price: price_monthly)
create(:purchase, link: product, price_cents: 10_00, is_original_subscription_purchase: true, subscription: sub_monthly)
end
expect(Link.monthly_recurring_revenue(products: products.map(&:id))).to eq(20_00)
end
end
describe "#monthly_recurring_revenue" do
it "returns monthly recurring revenue from the class method" do
product = create(:product)
expect(Link).to receive(:monthly_recurring_revenue).with(products: product).and_return(123)
expect(product.monthly_recurring_revenue).to eq(123)
end
end
describe "#number_of_views" do
it "returns the views total", :sidekiq_inline, :elasticsearch_wait_for_refresh do
product = create(:product)
2.times { add_page_view(product) }
expect(product.number_of_views).to eq(2)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/preview_spec.rb | spec/modules/product/preview_spec.rb | # frozen_string_literal: true
require "spec_helper"
def uploaded_file(name)
Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", name), MIME::Types.type_for(name).first)
end
describe Product::Preview do
before do
@bad_file = uploaded_file("other.garbage")
@jpg_file = uploaded_file("test-small.jpg")
@mov_file = uploaded_file("thing.mov")
@png_file = uploaded_file("kFDzu.png")
end
describe "Asset Previews", :vcr do
describe "with attached files" do
it "has default attributes if no preview exists" do
link = create(:product)
expect(link.main_preview).to be(nil)
expect(link.preview_image_path?).to be(false)
expect(link.preview_video_path?).to be(false)
expect(link.preview_oembed_url).to be(nil)
expect(link.preview_url).to be(nil)
end
it "saves existing preview image as its main asset preview" do
link = build(:product)
expect { link.preview = @png_file }.to change { AssetPreview.alive.count }.by(1)
expect(link.main_preview.file.filename.to_s).to eq(@png_file.original_filename)
expect(link.preview_width).to eq(670)
expect(link.preview_height).to eq(210)
end
it "saves a new preview image with correct attributes" do
link = create(:product)
expect do
link.preview = @png_file
link.save!
end.to change { link.main_preview }.from(nil)
expect(link.main_preview.file.filename.to_s).to eq(@png_file.original_filename)
expect(HTTParty.head(link.preview_url).code).to eq 200
expect(link.preview_image_path?).to be(true)
expect(link.preview_video_path?).to be(false)
end
it "saves a new preview video with correct attributes" do
link = create(:product)
expect do
link.preview = @mov_file
link.save!
end.to change { link.main_preview }.from(nil)
expect(link.main_preview.file.filename.to_s).to eq(@mov_file.original_filename)
expect(HTTParty.get(link.reload.preview_url).code).to eq 200
expect(link.preview_image_path?).to be(false)
expect(link.preview_video_path?).to be(true)
end
it "does not save an arbitrary filetype" do
link = create(:product)
expect do
expect do
link.preview = @bad_file
link.save!
end.to raise_error(ActiveRecord::RecordInvalid)
end.to_not change { link.main_preview }
end
it "creates a new asset preview when preview is changed" do
link = create(:product, preview: @png_file)
expect(link.display_asset_previews.last.file.filename.to_s).to match(/#{ @png_file.original_filename }$/)
link.preview = @jpg_file
link.save!
expect(link.display_asset_previews.last.file.filename.to_s).to match(/#{ @jpg_file.original_filename }$/)
expect(link.display_asset_previews.last.display_width).to eq(25)
expect(link.display_asset_previews.last.display_height).to eq(25)
end
it "does not create a product preview when an existing product with no asset previews is saved" do
link = create(:product, preview: nil, preview_url: nil)
expect do
link.name = "A link by any other name would preview as sweet"
link.save!
end.to_not change { link.asset_previews.alive.count }.from(0)
end
it "does nothing if a product has an asset preview and its preview is unchanged" do
link = create(:product, preview: @png_file, created_at: 1.day.ago, updated_at: 1.day.ago)
expect do
link.update(name: "This is what happens when we change the name of a product")
end.to_not change { link.main_preview.updated_at }
end
it "deletes an asset preview" do
link = create(:product, preview: @png_file)
expect { link.preview = nil }.to change { link.main_preview }.to(nil)
end
end
describe "with embeddable preview URLs" do
it "creates with correct dimensions from a fully-qualified URL" do
link = create(:product, preview_url: "https://www.youtube.com/watch?v=apiu3pTIwuY")
expect(link.preview_oembed_url).to eq("https://www.youtube.com/embed/apiu3pTIwuY?feature=oembed&showinfo=0&controls=0&rel=0&enablejsapi=1")
expect(link.preview_width).to eq(356)
expect(link.preview_height).to eq(200)
end
it "creates with a relative URL" do
link = create(:product, preview_url: "https://www.youtube.com/watch?v=apiu3pTIwuY")
expect(link.preview_oembed_url).to eq("https://www.youtube.com/embed/apiu3pTIwuY?feature=oembed&showinfo=0&controls=0&rel=0&enablejsapi=1")
end
it "deletes an asset preview URL" do
link = create(:product, preview_url: "https://www.youtube.com/watch?v=apiu3pTIwuY")
expect do
link.preview = ""
link.save!
end.to change { link.main_preview }.to(nil)
end
end
context "preview is from Unsplash" do
let!(:asset_preview) { create(:asset_preview, unsplash_url: "https://images.unsplash.com/example.jpeg", attach: false) }
it "returns the correct URLs" do
product = asset_preview.link
expect(product.main_preview).to eq(asset_preview)
expect(product.preview_image_path?).to eq(true)
expect(product.preview_video_path?).to eq(false)
expect(product.preview_oembed_url).to eq(nil)
expect(product.preview_url).to eq(asset_preview.unsplash_url)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/recommendations_spec.rb | spec/modules/product/recommendations_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::Recommendations, :elasticsearch_wait_for_refresh do
before do
@product = create(:product, user: create(:compliant_user, name: "Some creator person"), taxonomy: create(:taxonomy))
end
it "is true if has recent sale" do
create(:purchase, :with_review, link: @product, created_at: 1.week.ago)
expect(@product.recommendable?).to be(true)
end
it "is true if no recent sale" do
create(:purchase, :with_review, link: @product, created_at: 4.months.ago)
expect(@product.recommendable?).to be(true)
end
it "is true even if the product is rated to be adult" do
create(:purchase, :with_review, link: @product, created_at: 1.week.ago)
@product.update_attribute(:name, "nsfw")
expect(@product.recommendable?).to be(true)
end
it "is true if it displays product reviews" do
create(:purchase, :with_review, link: @product, created_at: 1.month.ago)
expect(@product.recommendable?).to be(true)
end
it "is false if it does not display product reviews" do
create(:purchase, :with_review, link: @product, created_at: 1.month.ago)
@product.update_attribute(:display_product_reviews, false)
expect(@product.recommendable_reasons[:reviews_displayed]).to be(false)
expect(@product.recommendable_reasons.except(:reviews_displayed).values).to all(be true)
expect(@product.recommendable?).to be(false)
end
it "is false if no sale made" do
expect(@product.recommendable_reasons[:sale_made]).to be(false)
expect(@product.recommendable_reasons.except(:sale_made).values).to all(be true)
expect(@product.recommendable?).to be(false)
end
it "is false if there are no non-refunded sales" do
purchase = create(:purchase, :with_review, link: @product, created_at: 1.week.ago)
expect(@product.recommendable_reasons[:sale_made]).to be(true)
expect(@product.recommendable?).to be(true)
purchase.update!(stripe_refunded: true)
expect(@product.reload.recommendable_reasons[:sale_made]).to be(false)
expect(@product.recommendable_reasons.except(:sale_made).values).to all(be true)
expect(@product.recommendable?).to be(false)
end
context "when taxonomy is not set" do
before do
@product.update_attribute(:taxonomy, nil)
create(:purchase, :with_review, link: @product, created_at: 1.week.ago)
end
it "is false" do
expect(@product.recommendable_reasons[:taxonomy_filled]).to be(false)
expect(@product.recommendable_reasons.except(:taxonomy_filled).values).to all(be true)
expect(@product.recommendable?).to be(false)
end
end
it "is true if it has a review" do
create(:purchase, :with_review, link: @product, created_at: 1.week.ago)
expect(@product.recommendable?).to be(true)
end
it "is true if does not have any review" do
create(:purchase, link: @product, created_at: 1.week.ago)
expect(@product.recommendable?).to be(true)
end
it "is false if item is out of stock" do
@product.update_attribute(:max_purchase_count, 1)
create(:purchase, :with_review, link: @product, created_at: 1.week.ago)
expect(@product.recommendable_reasons[:not_sold_out]).to be(false)
expect(@product.recommendable_reasons.except(:not_sold_out).values).to all(be true)
expect(@product.recommendable?).to be(false)
end
it "is false if item is in stock" do
@product.update_attribute(:max_purchase_count, 2)
create(:purchase, :with_review, link: @product, created_at: 1.week.ago)
expect(@product.recommendable_reasons[:not_sold_out]).to be(true)
expect(@product.recommendable?).to be(true)
end
it "is false it is not alive" do
allow(@product).to receive(:alive?).and_return(false)
expect(@product.recommendable_reasons[:alive]).to be(false)
expect(@product.recommendable?).to be(false)
end
it "is false if item is archived" do
allow(@product).to receive(:archived?).and_return(true)
expect(@product.recommendable_reasons[:not_archived]).to be(false)
expect(@product.recommendable?).to be(false)
end
context "when product is recommendable" do
before { @product = create(:product, :recommendable) }
it "returns all recommendable_reason" do
expect(@product.recommendable_reasons.values).to all(be true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/creation_limit_spec.rb | spec/modules/product/creation_limit_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::CreationLimit, :enforce_product_creation_limit do
let(:non_compliant_user) { create(:user, user_risk_state: "not_reviewed") }
let(:compliant_user) { create(:user, user_risk_state: "compliant") }
context "for non-compliant users" do
it "prevents creating more than 10 products in 24 hours" do
create_products_in_bulk(non_compliant_user, 9)
product_10 = build(:product, user: non_compliant_user)
expect(product_10).to be_valid
product_10.save!
product_11 = build(:product, user: non_compliant_user)
expect(product_11).not_to be_valid
expect(product_11.errors.full_messages).to include("Sorry, you can only create 10 products per day.")
travel_to 25.hours.from_now
expect(product_11).to be_valid
end
end
context "for compliant users" do
it "allows creating up to 100 products in 24 hours" do
create_products_in_bulk(compliant_user, 99)
product_100 = build(:product, user: compliant_user)
expect(product_100).to be_valid
product_100.save!
product_101 = build(:product, user: compliant_user)
expect(product_101).not_to be_valid
expect(product_101.errors.full_messages).to include("Sorry, you can only create 100 products per day.")
travel_to 25.hours.from_now
expect(product_101).to be_valid
end
end
context "when user is a team member" do
it "skips the daily product creation limit" do
admin = create(:user, is_team_member: true)
create_products_in_bulk(admin, 100)
product_101 = build(:product, user: admin)
expect(product_101).to be_valid
end
end
describe ".bypass_product_creation_limit" do
it "bypasses the limit within the block and restores it afterwards" do
create_products_in_bulk(non_compliant_user, 10)
Link.bypass_product_creation_limit do
bypassed_product = build(:product, user: non_compliant_user)
expect(bypassed_product).to be_valid
end
blocked_product = build(:product, user: non_compliant_user)
expect(blocked_product).not_to be_valid
expect(blocked_product.errors.full_messages).to include("Sorry, you can only create 10 products per day.")
end
end
private
def create_products_in_bulk(user, count)
unique_permalink_chars = ("a".."z").to_a
rows = Array.new(count) do
FactoryBot.build(
:product,
user: user,
created_at: Time.current,
updated_at: Time.current,
unique_permalink: SecureRandom.alphanumeric(10, chars: unique_permalink_chars),
).attributes
end
Link.insert_all(rows)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/prices_spec.rb | spec/modules/product/prices_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::Prices do
before do
@product = create(:product, price_cents: 2_50)
@subscription_product = create(:subscription_product, price_cents: 4_00)
@subscription_price = @subscription_product.prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY)
create(:price, link: @subscription_product, price_cents: 35_00, recurrence: BasePrice::Recurrence::YEARLY)
end
describe "default_price" do
it "has the correct default price for a subscription product" do
expect(@subscription_product.default_price.price_cents).to eq(4_00)
expect(@subscription_product.default_price.recurrence).to eq(BasePrice::Recurrence::MONTHLY)
end
it "has the correct default price for a non-subscription product" do
expect(@product.default_price.price_cents).to eq(2_50)
expect(@product.default_price.is_rental).to eq(false)
expect(@product.default_price.recurrence).to eq(nil)
end
it "only considers alive prices" do
create(:price, link: @subscription_product, recurrence: BasePrice::Recurrence::MONTHLY, deleted_at: Time.current)
expect(@subscription_product.reload.default_price).to eq @subscription_price
end
it "considers the product currency" do
create(:price, link: @product, price_cents: 2000, currency: "eur")
expect(@product.default_price.currency).to eq("usd")
expect(@product.default_price.price_cents).to eq(2_50)
end
end
describe "#price_cents=" do
it "writes to the price_cents column if product is not persisted" do
product = build(:product)
expect do
product.price_cents = 1234
expect(product.read_attribute(:price_cents)).to eq 1234
end.not_to change { Price.count }
end
it "writes to the price_cents column if product is a tiered membership" do
product = build(:product, is_tiered_membership: true)
expect do
product.price_cents = 1234
expect(product.read_attribute(:price_cents)).to eq 1234
end.not_to change { Price.count }
end
it "creates or updates the price record if the product is persisted" do
product = create(:product)
price = product.default_price
product.price_cents = 1234
expect(product.price_cents).to eq 1234
expect(price.reload.price_cents).to eq 1234
end
it "updates the last price record as that is read when fetching `price_cents`" do
product = create(:product)
product.prices.first.dup.save!
expect(product.prices.alive.size).to eq(2)
second_price = product.prices.alive.second
expect do
expect do
product.price_cents = 200
end.to change { product.reload.price_cents }.from(100).to(200)
end.to change { second_price.reload.price_cents }.from(100).to(200)
end
it "updates the price for the corresponding currency" do
product = create(:product, price_currency_type: "usd", price_cents: 100)
usd_price = product.default_price
expect(usd_price.currency).to eq("usd")
expect(usd_price.price_cents).to eq(100)
product.update!(price_currency_type: "eur", price_cents: 200)
euro_price = product.default_price
expect(euro_price.currency).to eq("eur")
expect(euro_price.price_cents).to eq(200)
usd_price.reload
expect(usd_price.currency).to eq("usd")
expect(usd_price.price_cents).to eq(100)
product.update!(price_currency_type: "usd", price_cents: 300)
usd_price.reload
expect(usd_price.currency).to eq("usd")
expect(usd_price.price_cents).to eq(300)
euro_price.reload
expect(euro_price.currency).to eq("eur")
expect(euro_price.price_cents).to eq(200)
expect(product.alive_prices).to contain_exactly(usd_price, euro_price)
end
end
describe "#set_customizable_price" do
it "sets customizable_price to true if $0" do
@product.price_cents = 0
@product.save!
expect(@product.customizable_price).to be(true)
expect(@product.price_cents).to eq(0)
end
context "tiered memberships" do
it "does not set customizable_price to true" do
product = create(:membership_product, price_cents: 0)
expect(product.customizable_price).to be nil
end
end
context "product with premium versions" do
it "sets customizable_price to true if there are no paid versions" do
product = create(:product, price_cents: 0)
expect(product.customizable_price).to be(true)
expect(product.price_cents).to eq(0)
end
it "does not set customizable_price to true if there are paid versions" do
product = create(:product, price_cents: 0)
create(:variant_category, title: "versions", link: product)
product.variant_categories.first.variants.create!(name: "premium version", price_difference_cents: 1_00)
product.update!(customizable_price: false)
expect(product.customizable_price).to be(false)
expect(product.price_cents).to eq(0)
end
end
end
describe "#rental_price_range=" do
context "when the price is blank" do
it "raises an exception" do
expect do
@product.rental_price_range = ""
end.to raise_error(ActiveRecord::RecordInvalid)
expect(@product.errors[:base].first).to eq("Please enter the rental price.")
end
end
context "when the price is valid" do
it "sets the price correctly" do
@product.rental_price_range = "1.23"
expect(@product.valid?).to be(true)
expect(@product.prices.alive.is_rental.last.price_cents).to be(123)
end
end
end
describe "#display_price_cents" do
it "returns the default_price" do
product = create(:product, price_cents: 5_00)
expect(product.display_price_cents).to eq 5_00
end
context "for tiered membership" do
let(:product) do
recurrence_price_values = [
{ "monthly" => { enabled: true, price: 10 }, "yearly" => { enabled: true, price: 100 } },
{ "monthly" => { enabled: true, price: 2 }, "yearly" => { enabled: true, price: 15 } }
]
create(:membership_product_with_preset_tiered_pricing, recurrence_price_values:, subscription_duration: "yearly")
end
it "returns the lowest price available for any tier" do
expect(product.display_price_cents).to eq 2_00
end
context "when for_default_duration is true" do
it "returns the lowest price available for any tier for the default duration" do
expect(product.display_price_cents(for_default_duration: true)).to eq 15_00
end
end
context "when the tier has no prices" do
it "returns 0" do
product = create(:membership_product)
product.default_tier.prices.destroy_all
expect(product.display_price_cents).to eq 0
end
end
end
context "for a product with live variants" do
let(:product) { create(:product, price_cents: 5_00) }
let(:category) { create(:variant_category, link: product) }
context "with no price differences" do
it "returns the default_price" do
create(:variant, variant_category: category, price_difference_cents: nil)
expect(product.display_price_cents).to eq 5_00
end
end
context "with price differences" do
it "returns the default_price plus the lowest live variant price difference" do
create(:variant, variant_category: category, price_difference_cents: 200)
create(:variant, variant_category: category, price_difference_cents: 99)
create(:variant, variant_category: category, price_difference_cents: 50, deleted_at: 1.hour.ago)
expect(product.display_price_cents).to eq 5_99
end
end
end
context "for a buy-or-rent product" do
let(:product) { create(:product, price_cents: 5_00, rental_price_cents: 1_00, purchase_type: :buy_and_rent) }
it "returns the buy price" do
expect(product.display_price_cents).to eq 5_00
end
end
context "for a rental-only product" do
let(:product) { create(:product, rental_price_cents: 1_00, purchase_type: :rent_only) }
it "returns the rental price" do
expect(product.display_price_cents).to eq 1_00
end
end
end
describe "#available_price_cents" do
context "for simple products" do
let(:product) { create(:product, price_cents: 5_00) }
it "returns the default_price" do
expect(product.available_price_cents).to match_array([5_00])
end
end
context "for simple products with rent prices" do
let(:product) { create(:product, price_cents: 5_00, rental_price_cents: 2_00, purchase_type: :buy_and_rent) }
it "ignores the rent price" do
expect(product.available_price_cents).to match_array([5_00])
end
end
context "for tiered membership" do
context "when product has multiple tiers" do
let(:recurrence_price_values) do
[
{ BasePrice::Recurrence::MONTHLY => { enabled: true, price: 10 } },
{ BasePrice::Recurrence::MONTHLY => { enabled: true, price: 2 } }
]
end
let(:product) { create(:membership_product_with_preset_tiered_pricing, recurrence_price_values:) }
it "returns the price available for all tiers" do
expect(product.available_price_cents).to match_array([10_00, 2_00])
end
end
context "when the tier has no prices" do
let(:product) { create(:membership_product) }
it "returns []" do
product.default_tier.prices.destroy_all
expect(product.available_price_cents).to be_empty
end
end
end
context "for a product with live variants" do
let(:product) { create(:product, price_cents: 5_00) }
let(:category) { create(:variant_category, link: product) }
context "with no price differences" do
let!(:variant) { create(:variant, variant_category: category, price_difference_cents: nil) }
it "returns the default_price" do
expect(product.available_price_cents).to match_array([5_00])
end
end
context "with price differences" do
let!(:variant1) { create(:variant, variant_category: category, price_difference_cents: 200) }
let!(:variant2) { create(:variant, variant_category: category, price_difference_cents: 99) }
let!(:variant3) { create(:variant, variant_category: category, price_difference_cents: 50, deleted_at: 1.hour.ago) }
it "returns the default_price plus the live variant price difference" do
expect(product.available_price_cents).to match_array([7_00, 5_99])
end
end
context "with rent prices" do
let(:product) { create(:product, price_cents: 5_00, rental_price_cents: 2_00, purchase_type: :buy_and_rent) }
let!(:variant) { create(:variant, variant_category: category, price_difference_cents: 99) }
it "ignores the rent price" do
expect(product.available_price_cents).to match_array([5_99])
end
end
end
end
describe "#display_price" do
it "returns formatted display_price" do
digital_product = create(:product, price_cents: 5_00)
recurrence_price_values = [
{ BasePrice::Recurrence::MONTHLY => { enabled: true, price: 10 } },
{ BasePrice::Recurrence::MONTHLY => { enabled: true, price: 2 } }
]
membership_product = create(:membership_product_with_preset_tiered_pricing, recurrence_price_values:)
expect(digital_product.display_price).to eq "$5"
expect(membership_product.display_price).to eq "$2"
end
end
describe "#price_formatted_verbose" do
before :each do
@product = create(:product, price_cents: 2_50)
end
it "returns the formatted price" do
expect(@product.price_formatted_verbose).to eq "$2.50"
end
it "returns the formatted price for a pay-what-you-want product" do
@product.update!(customizable_price: true)
expect(@product.reload.price_formatted_verbose).to eq "$2.50+"
end
context "for a tiered membership" do
before :each do
recurrence_price_values = [
{ BasePrice::Recurrence::MONTHLY => { enabled: true, price: 3 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 30 } },
{ BasePrice::Recurrence::MONTHLY => { enabled: true, price: 5 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 50 } }
]
@product = create(:membership_product_with_preset_tiered_pricing, recurrence_price_values:, subscription_duration: BasePrice::Recurrence::YEARLY)
end
it "returns the formatted price for the minimum tier price" do
expect(@product.price_formatted_verbose).to eq "$3+ a month"
end
it "includes a `+`" do
@product.default_tier.update!(customizable_price: true)
expect(@product.price_formatted_verbose).to eq "$3+ a month"
end
context "that has a single tier" do
before :each do
second_tier = @product.tiers.find_by!(name: "Second Tier")
second_tier.prices.destroy_all
second_tier.destroy
end
context "with multiple prices" do
it "includes a `+`" do
expect(@product.price_formatted_verbose).to eq "$3+ a month"
end
it "excludes rental prices" do
@product.tiers.each do |tier|
tier.prices.each do |price|
price.is_rental = true
price.save!
end
end
@product.tiers.reload
expect(@product.price_formatted_verbose).to eq "$0 a year"
end
end
context "with a single price" do
before :each do
@first_tier = @product.tiers.find_by!(name: "First Tier")
@first_tier.save_recurring_prices!({ BasePrice::Recurrence::YEARLY => { enabled: true, price: 2 } })
expect(@first_tier.prices.alive.count).to eq 1
end
context "and is not pay-what-you-want" do
it "does not include a `+`" do
@product.tiers.reload
expect(@product.price_formatted_verbose).to eq "$2 a year"
end
end
context "and is pay-what-you-want" do
it "includes a `+`" do
@first_tier.update!(customizable_price: true)
expect(@product.price_formatted_verbose).to eq "$2+ a year"
end
end
end
end
context "when the tier has no prices" do
it "returns $0 with the default subscription duration" do
product = create(:membership_product, subscription_duration: BasePrice::Recurrence::YEARLY)
product.default_tier.prices.destroy_all
expect(product.price_formatted_verbose).to eq "$0 a year"
end
end
end
end
describe "#base_price_formatted_without_dollar_sign" do
context "when product is digital" do
it "returns price not including version price" do
category = create(:variant_category, link: @product)
create(:variant, variant_category: category, name: "Version 1", price_difference_cents: 3_00)
create(:variant, variant_category: category, name: "Version 2", price_difference_cents: 2_00)
expect(@product.base_price_formatted_without_dollar_sign).to eq("2.50")
end
end
context "when product is physical" do
it "returns price not including variant price" do
physical_link = create(:physical_product)
category = create(:variant_category, link: physical_link, title: "Size")
create(:variant, variant_category: category, name: "Small", price_difference_cents: 1_50)
create(:variant, variant_category: category, name: "Large", price_difference_cents: 2_50)
expect(physical_link.base_price_formatted_without_dollar_sign).to eq "1"
end
end
context "when product is membership" do
it "returns lowest tier price" do
membership_product = create(:membership_product_with_preset_tiered_pricing)
expect(membership_product.base_price_formatted_without_dollar_sign).to eq("3")
end
end
end
describe "#price_formatted_without_dollar_sign" do
context "when product is digital" do
it "returns price including price of least expensive version" do
category = create(:variant_category, link: @product)
create(:variant, variant_category: category, name: "Version 1", price_difference_cents: 3_00)
create(:variant, variant_category: category, name: "Version 2", price_difference_cents: 2_00)
expect(@product.price_formatted_without_dollar_sign).to eq("4.50")
end
end
context "when product is physical" do
it "returns price not including variant price" do
physical_link = create(:physical_product)
category = create(:variant_category, link: physical_link, title: "Size")
create(:variant, variant_category: category, name: "Small", price_difference_cents: 1_50)
create(:variant, variant_category: category, name: "Large", price_difference_cents: 2_50)
expect(physical_link.price_formatted_without_dollar_sign).to eq "1"
end
end
context "when product is membership" do
it "returns lowest tier price" do
membership_product = create(:membership_product_with_preset_tiered_pricing)
expect(membership_product.price_formatted_without_dollar_sign).to eq("3")
end
end
end
describe "price_cents_for_recurrence" do
it "returns the right price_cents" do
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::MONTHLY)).to eq(4_00)
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::YEARLY)).to eq(35_00)
end
end
describe "price_formatted_without_dollar_sign_for_recurrence" do
before do
monthly_price = @subscription_product.default_price
monthly_price.price_cents = 3_99
monthly_price.save!
end
it "returns the right price_formatted_without_dollar_sign_for_recurrence" do
expect(@subscription_product.price_formatted_without_dollar_sign_for_recurrence(BasePrice::Recurrence::MONTHLY)).to eq("3.99")
expect(@subscription_product.price_formatted_without_dollar_sign_for_recurrence(BasePrice::Recurrence::YEARLY)).to eq("35")
end
end
describe "has_price_for_recurrence?" do
it "returns the right has_price_for_recurrence? value" do
expect(@subscription_product.has_price_for_recurrence?(BasePrice::Recurrence::MONTHLY)).to eq(true)
expect(@subscription_product.has_price_for_recurrence?(BasePrice::Recurrence::QUARTERLY)).to eq(false)
expect(@subscription_product.has_price_for_recurrence?(BasePrice::Recurrence::BIANNUALLY)).to eq(false)
expect(@subscription_product.has_price_for_recurrence?(BasePrice::Recurrence::YEARLY)).to eq(true)
end
end
describe "suggested_price_cents_for_recurrence" do
it "returns the right suggested_price_cents_for_recurrence price for recurrences that don't have prices" do
expect(@subscription_product.send(:suggested_price_cents_for_recurrence, BasePrice::Recurrence::QUARTERLY)).to eq(12_00)
expect(@subscription_product.send(:suggested_price_cents_for_recurrence, BasePrice::Recurrence::BIANNUALLY)).to eq(24_00)
end
it "returns the right suggested_price_cents_for_recurrence price for recurrences that have prices" do
expect(@subscription_product.send(:suggested_price_cents_for_recurrence, BasePrice::Recurrence::MONTHLY)).to eq(4_00)
expect(@subscription_product.send(:suggested_price_cents_for_recurrence, BasePrice::Recurrence::YEARLY)).to eq(35_00)
end
end
describe "save_subscription_prices_and_duration!" do
context "when the passed in subscription_duration is same as the value saved in the DB" do
it "changes the prices of the recurrences properly" do
recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "5"
},
BasePrice::Recurrence::YEARLY => {
enabled: true,
price: "40"
}
}
@subscription_product.save_subscription_prices_and_duration!(recurrence_price_values:,
subscription_duration: @subscription_product.subscription_duration)
expect(@subscription_product.prices.alive.is_buy.count).to eq(2)
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::MONTHLY)).to eq(5_00)
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::YEARLY)).to eq(40_00)
end
it "adds and remove prices properly" do
recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "5"
},
BasePrice::Recurrence::QUARTERLY => {
enabled: true,
price: "12"
}
}
@subscription_product.save_subscription_prices_and_duration!(recurrence_price_values:,
subscription_duration: @subscription_product.subscription_duration)
expect(@subscription_product.prices.alive.is_buy.count).to eq(2)
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::MONTHLY)).to eq(5_00)
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::QUARTERLY)).to eq(12_00)
end
it "does not allow the default recurrence to be removed" do
recurrence_price_values = {
BasePrice::Recurrence::QUARTERLY => {
enabled: true,
price: "12"
}
}
expect do
@subscription_product.save_subscription_prices_and_duration!(recurrence_price_values:,
subscription_duration: @subscription_product.subscription_duration)
end.to raise_error(Link::LinkInvalid)
end
it "does not allow the a price to be created without an amount" do
recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "5"
},
BasePrice::Recurrence::QUARTERLY => {
enabled: true,
price: ""
}
}
expect do
@subscription_product.save_subscription_prices_and_duration!(recurrence_price_values:,
subscription_duration: @subscription_product.subscription_duration)
end.to raise_error(Link::LinkInvalid)
end
end
context "when the passed in subscription_duration is not the same as the value saved in the DB" do
# Current subscription_duration: monthly
it "saves the new subscription prices and duration" do
recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "5"
},
BasePrice::Recurrence::QUARTERLY => {
enabled: true,
price: "12"
}
}
@subscription_product.save_subscription_prices_and_duration!(recurrence_price_values:,
subscription_duration: BasePrice::Recurrence::QUARTERLY)
expect(@subscription_product.reload.subscription_duration.to_s).to eq(BasePrice::Recurrence::QUARTERLY)
expect(@subscription_product.prices.alive.is_buy.count).to eq(2)
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::MONTHLY)).to eq(5_00)
expect(@subscription_product.price_cents_for_recurrence(BasePrice::Recurrence::QUARTERLY)).to eq(12_00)
end
it "does not save the subscription_duration if saving the price fails" do
recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "5"
},
BasePrice::Recurrence::QUARTERLY => {
enabled: true,
price: "" # Invalid
}
}
expect do
expect do
@subscription_product.save_subscription_prices_and_duration!(recurrence_price_values:,
subscription_duration: BasePrice::Recurrence::QUARTERLY)
end.to raise_error(Link::LinkInvalid)
end.to_not change { [Price.count, @subscription_product.reload.subscription_duration] }
end
it "does not save prices if the price for the new subscription duration is missing" do
recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "12"
}
}
expect do
expect do
@subscription_product.save_subscription_prices_and_duration!(recurrence_price_values:,
subscription_duration: BasePrice::Recurrence::BIANNUALLY)
end.to raise_error(Link::LinkInvalid)
end.to_not change { [Price.count, @subscription_product.reload.subscription_duration] }
end
end
end
describe "#save_recurring_prices!" do
before :each do
@product = create(:product)
@recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "20",
suggested_price: "25"
},
BasePrice::Recurrence::YEARLY => {
enabled: true,
price: "99.99",
suggested_price: ""
},
BasePrice::Recurrence::BIANNUALLY => { enabled: false }
}
end
it "saves valid prices" do
@product.save_recurring_prices!(@recurrence_price_values)
prices = @product.reload.prices.alive
monthly_price = prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY)
yearly_price = prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY)
expect(prices.length).to eq 2
expect(monthly_price.price_cents).to eq 2000
expect(monthly_price.suggested_price_cents).to eq 2500
expect(yearly_price.price_cents).to eq 9999
expect(yearly_price.suggested_price_cents).to be_nil
end
it "deletes any old prices" do
biannual_price = create(:price, link: @product, recurrence: BasePrice::Recurrence::BIANNUALLY)
quarterly_price = create(:price, link: @product, recurrence: BasePrice::Recurrence::QUARTERLY)
non_recurring_price = create(:price, link: @product, recurrence: nil)
@product.save_recurring_prices!(@recurrence_price_values)
expect(@product.prices.alive.length).to eq 2
expect(biannual_price.reload).to be_deleted
expect(quarterly_price.reload).to be_deleted
expect(non_recurring_price.reload).to be_deleted
end
context "updating Elasticsearch" do
before :each do
@product.save_recurring_prices!(@recurrence_price_values)
end
it "enqueues Elasticsearch update if a price is new or has changed" do
updated_recurrence_prices = @recurrence_price_values.merge(
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "25",
suggested_price: "30"
},
BasePrice::Recurrence::QUARTERLY => {
enabled: true,
price: "70",
suggested_price: "75"
}
)
expect(@product).to receive(:enqueue_index_update_for).with(["price_cents", "available_price_cents"]).twice
@product.save_recurring_prices!(updated_recurrence_prices)
end
it "does not enqueue Elasticsearch update if prices have not changed" do
expect(@product).not_to receive(:enqueue_index_update_for).with(["price_cents", "available_price_cents"])
@product.save_recurring_prices!(@recurrence_price_values)
end
end
context "missing price" do
it "raises an error" do
invalid_values = @recurrence_price_values
invalid_values[BasePrice::Recurrence::MONTHLY].delete(:price)
expect do
@product.save_recurring_prices!(invalid_values)
end.to raise_error Link::LinkInvalid
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/review_stat_spec.rb | spec/modules/product/review_stat_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::ReviewStat do
before do
@product = create(:product)
end
context "when the product_review_stat record exists" do
before do
purchase_1 = create(:purchase, link: @product)
@review_1 = create(:product_review, purchase: purchase_1, rating: 3)
purchase_2 = create(:purchase, link: @product)
@review_2 = create(:product_review, purchase: purchase_2, rating: 1)
purchase_3 = create(:purchase, link: @product)
@review_3 = create(:product_review, purchase: purchase_3, rating: 1)
@review_stat = @product.reload.product_review_stat
@expected_reviews_count = 3
@expected_average_rating = ((@review_1.rating + @review_2.rating + @review_3.rating).to_f / 3).round(1)
end
describe "#update_review_stat_via_rating_change & #update_review_stat_via_purchase_changes" do
it "computes reviews_count & average_rating for the product correctly" do
expect(@review_stat.reviews_count).to eq(@expected_reviews_count)
expect(@review_stat.average_rating).to eq(@expected_average_rating)
expect(@review_stat.ratings_of_one_count).to eq(2)
expect(@review_stat.ratings_of_three_count).to eq(1)
expect(@review_stat.ratings_of_four_count).to eq(0)
end
it "computes aggregate fields correctly for a new rating added" do
new_purchase = create(:purchase, link: @product)
new_review = create(:product_review, purchase: new_purchase, rating: 5)
expected_average_rating = ((@review_1.rating + @review_2.rating + @review_3.rating + new_review.rating).to_f / 4).round(1)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count + 1)
expect(@review_stat.average_rating).to eq(expected_average_rating)
expect(@review_stat.ratings_of_five_count).to eq(1)
end
it "computes aggregate fields correctly for an existing rating being updated" do
@review_3.update!(rating: 4)
expected_average_rating = ((@review_1.rating + @review_2.rating + @review_3.rating).to_f / 3).round(1)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count)
expect(@review_stat.average_rating).to eq(expected_average_rating)
expect(@review_stat.ratings_of_four_count).to eq(1)
end
it "computes aggregate fields correctly for an existing rating becoming invalid due to a refund" do
purchase = create(:purchase, link: @product)
create(:product_review, purchase:, rating: 1)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count + 1)
expect(@review_stat.average_rating).to eq(((@review_1.rating + @review_2.rating + @review_3.rating + 1).to_f / 4).round(1))
purchase.update!(stripe_refunded: true)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count)
expect(@review_stat.average_rating).to eq(@expected_average_rating)
expect(@review_stat.ratings_of_one_count).to eq(2)
end
it "computes aggregate fields correctly for an existing rating becoming invalid due to purchase state" do
purchase = create(:purchase, link: @product)
create(:product_review, purchase:, rating: 1)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count + 1)
expect(@review_stat.average_rating).to eq(((@review_1.rating + @review_2.rating + @review_3.rating + 1).to_f / 4).round(1))
purchase.update!(purchase_state: "failed")
expect(@review_stat.reviews_count).to eq(@expected_reviews_count)
expect(@review_stat.average_rating).to eq(@expected_average_rating)
expect(@review_stat.ratings_of_one_count).to eq(2)
end
it "computes aggregate fields correctly for an existing rating becoming invalid due to a charge back" do
purchase = create(:purchase, link: @product)
create(:product_review, purchase:, rating: 1)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count + 1)
expect(@review_stat.average_rating).to eq(((@review_1.rating + @review_2.rating + @review_3.rating + 1).to_f / 4).round(1))
purchase.update!(chargeback_date: Date.today)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count)
expect(@review_stat.average_rating).to eq(@expected_average_rating)
expect(@review_stat.ratings_of_one_count).to eq(2)
end
it "computes aggregate fields correctly for an existing rating for a free purchase becoming invalid due to a revoke" do
purchase = create(:free_purchase, link: @product)
create(:product_review, purchase:, rating: 1)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count + 1)
expect(@review_stat.average_rating).to eq(((@review_1.rating + @review_2.rating + @review_3.rating + 1).to_f / 4).round(1))
purchase.update!(is_access_revoked: true)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count)
expect(@review_stat.average_rating).to eq(@expected_average_rating)
expect(@review_stat.ratings_of_one_count).to eq(2)
end
it "computes aggregate fields correctly for an existing rating for a paid purchase NOT becoming invalid due to a revoke" do
purchase = create(:purchase, link: @product)
create(:product_review, purchase:, rating: 1)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count + 1)
expect(@review_stat.average_rating).to eq(((@review_1.rating + @review_2.rating + @review_3.rating + 1).to_f / 4).round(1))
purchase.update!(is_access_revoked: true)
expect(@review_stat.reviews_count).to eq(@expected_reviews_count + 1)
expect(@review_stat.average_rating).to eq(((@review_1.rating + @review_2.rating + @review_3.rating + 1).to_f / 4).round(1))
end
end
describe "#average_rating" do
it "returns the average rating based on all the reviews from successful purchases of the product" do
expect(@product.average_rating).to eq(@expected_average_rating)
end
end
describe "#rating_counts" do
it "returns a list of counts of product reviews by rating" do
expected = { 1 => 2, 2 => 0, 3 => 1, 4 => 0, 5 => 0 }
expect(@product.rating_counts).to eq(expected)
end
end
describe "#reviews_count" do
it "returns the count of reviews from successful purchases" do
expect(@product.reviews_count).to eq(3)
end
end
describe "#sync_review_stat & #generate_review_stat_attributes" do
it "recomputes reviews_count & average_rating for the product correctly" do
@review_stat.update_columns(
reviews_count: 0,
average_rating: 0,
ratings_of_one_count: 0,
ratings_of_three_count: 0,
ratings_of_four_count: 0,
)
expect(@product).to receive(:generate_review_stat_attributes).and_call_original
@product.sync_review_stat
expect(@review_stat.reviews_count).to eq(@expected_reviews_count)
expect(@review_stat.average_rating).to eq(@expected_average_rating)
expect(@review_stat.ratings_of_one_count).to eq(2)
expect(@review_stat.ratings_of_three_count).to eq(1)
expect(@review_stat.ratings_of_four_count).to eq(0)
end
it "creates product_review_stat when there are reviews & no product_review_stat" do
@product.product_review_stat.destroy
@product.reload
@product.sync_review_stat
expect(@product.product_review_stat).to be_present
expect(@product.product_review_stat.reviews_count).to eq(@expected_reviews_count)
end
it "doesn't create product_review_stat when there are no reviews & no product_review_stat" do
product = create(:product)
product.sync_review_stat
expect(product.product_review_stat).to be_nil
end
it "resets product_review_stat when there are no reviews" do
product = create(:product)
product.create_product_review_stat(
reviews_count: 123,
average_rating: 2,
ratings_of_one_count: -1,
)
product.sync_review_stat
expect(product.product_review_stat.reviews_count).to eq(0)
expect(product.product_review_stat.average_rating).to eq(0.0)
expect(product.product_review_stat.ratings_of_one_count).to eq(0)
end
end
end
context "when the product_review_stat record does not exist" do
describe "#average_rating" do
it "returns default value" do
expect(@product.average_rating).to eq(0.0)
end
end
describe "#rating_counts" do
it "returns default value" do
expect(@product.rating_counts).to eq({ 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0 })
end
end
describe "#reviews_count" do
it "returns default value" do
expect(@product.reviews_count).to eq(0)
end
end
end
# There's currently no codepath to uncount (remove) a rating, unrelated to the purchase state changing
it "#update_review_stat_via_rating_change allows to uncount a rating" do
product = create(:product)
purchase = create(:purchase, link: product)
create(:product_review, purchase:, rating: 2)
product.update_review_stat_via_rating_change(2, nil)
expect(product.average_rating).to eq(0)
end
describe "#update_review_stat_via_purchase_changes" do
# There's currently no production codepath to re-count a previously uncounted rating, but we support it anyway
it "allows to count a previously uncounted rating" do
product = create(:product)
purchase = create(:purchase, link: product)
create(:product_review, purchase:, rating: 2)
purchase.update!(stripe_refunded: true)
expect(product.average_rating).to eq(0)
purchase.update!(stripe_refunded: false)
expect(product.average_rating).to eq(2)
end
it "does nothing if there are no purchase changes" do
product = create(:product)
purchase = create(:purchase, link: product)
review = create(:product_review, purchase:, rating: 2)
review_stat_attributes = product.product_review_stat.attributes
product.update_review_stat_via_purchase_changes({}, product_review: review)
expect(product.product_review_stat.reload.attributes).to eq(review_stat_attributes)
end
it "does nothing when updating a subsequent subscription purchase is updated" do
purchase = create(:membership_purchase)
product = purchase.link
create(:product_review, purchase:, rating: 2)
review_stat_attributes = product.product_review_stat.attributes
# test that a subsequent valid purchase doesn't change the product_review_stat
purchase_2 = create(:membership_purchase, link: product, subscription: purchase.reload.subscription)
expect(product.product_review_stat.reload.attributes).to eq(review_stat_attributes)
# test that invalidating a subsequent purchase doesn't change the product_review_stat
purchase_2.update!(stripe_refunded: true)
expect(product.product_review_stat.reload.attributes).to eq(review_stat_attributes)
purchase_2.update!(stripe_refunded: false)
expect(product.product_review_stat.reload.attributes).to eq(review_stat_attributes)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/utils_spec.rb | spec/modules/product/utils_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::Utils do
describe ".f" do
it "fetches product from unique permalink" do
product = create(:product)
expect(Link.f(product.unique_permalink)).to eq(product)
end
it "fetches product from custom permalink" do
product = create(:product, custom_permalink: "FindMeAHex")
expect(Link.f("FindMeAHex")).to eq(product)
end
context "when multiple products with the same custom permalink" do
before do
@product_1 = create(:product, custom_permalink: "custom")
@product_2 = create(:product, custom_permalink: "custom")
end
it "raises an error when custom permalink matches more than one product" do
expect { Link.f("custom") }.to raise_error(ActiveRecord::RecordNotUnique)
end
it "fetches the correct product when scoped to a given user" do
expect(Link.f("custom", @product_2.user_id)).to eq(@product_2)
end
end
it "fetches product from id" do
product = create(:product)
expect(Link.f(product.id)).to eq(product)
end
it "raises error if no product found" do
expect { Link.f(42) }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/caching_spec.rb | spec/modules/product/caching_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::Caching do
describe "#invalidate_cache" do
before do
@product = create(:product)
Rails.cache.write(@product.scoped_cache_key("en"), "<html>hello</html>")
@product.product_cached_values.create!
@other_product = create(:product)
Rails.cache.write(@other_product.scoped_cache_key("en"), "<html>hello</html>")
@other_product.product_cached_values.create!
end
it "clears the correct cache" do
expect(Rails.cache.read(@product.scoped_cache_key("en"))).to be_present
expect(@product.reload.product_cached_values.fresh.size).to eq(1)
expect(Rails.cache.read(@other_product.scoped_cache_key("en"))).to be_present
expect(@other_product.reload.product_cached_values.fresh.size).to eq(1)
@product.invalidate_cache
expect(Rails.cache.read(@product.scoped_cache_key("en"))).to_not be_present
expect(@product.reload.product_cached_values.fresh.size).to eq(0)
expect(Rails.cache.read(@other_product.scoped_cache_key("en"))).to be_present
expect(@other_product.reload.product_cached_values.fresh.size).to eq(1)
end
end
describe ".scoped_cache_key" do
let(:link) { create(:product) }
before do
allow(SecureRandom).to receive(:uuid).and_return("guid")
end
it "returns no test path cache key if ab test is not assigned" do
expect(link.scoped_cache_key("en")).to eq "#{link.id}_guid_en_displayed_switch_ids_"
end
it "returns a fragemented cache key if it is fragmented" do
expect(link.scoped_cache_key("en", true)).to eq "#{link.id}_guid_en_fragmented_displayed_switch_ids_"
end
it "returns dynamic product page switch-aware cache key, with the right ordering" do
expect(link.scoped_cache_key("en", true, [5, 2])).to eq "#{link.id}_guid_en_fragmented_displayed_switch_ids_2_5"
end
it "uses a prefetched_cache_key if given" do
expect(link.scoped_cache_key("en", true, [5, 2], "prefetched")).to eq "prefetched_en_fragmented_displayed_switch_ids_2_5"
end
end
describe "#scoped_cache_keys" do
let(:links) { [create(:product), create(:product)] }
before do
allow(SecureRandom).to receive(:uuid).and_return("guid")
end
it "returns a cache key for each given products" do
keys = Product::Caching.scoped_cache_keys(links, [[], [5, 2]], "en", true)
expect(keys[0]).to eq("#{links[0].id}_guid_en_fragmented_displayed_switch_ids_")
expect(keys[1]).to eq("#{links[1].id}_guid_en_fragmented_displayed_switch_ids_2_5")
end
end
describe ".dashboard_collection_data" do
let(:product) { create(:product, max_purchase_count: 100) }
context "when no block is passed" do
subject(:dashboard_collection_data) { described_class.dashboard_collection_data(collection, cache:) }
context "when cache is true" do
let(:cache) { true }
context "when one product exists" do
let(:collection) { [product] }
context "when the product has no product_cached_value" do
it "schedules a product cache worker and returns the product" do
expect(dashboard_collection_data).to contain_exactly(product)
expect(CacheProductDataWorker).to have_enqueued_sidekiq_job(product.id)
end
end
context "when the product has a product_cached_value" do
before do
product.product_cached_values.create!
end
it "does not schedule a cache worker and returns the product cached value" do
expect do
expect(dashboard_collection_data).to contain_exactly(product.reload.product_cached_values.fresh.first)
end.not_to change { CacheProductDataWorker.jobs.size }
end
end
context "when the product has an expired product_cached_value" do
before do
product.product_cached_values.create!(expired: true)
end
it "schedules a product cache worker and returns the product" do
expect(dashboard_collection_data).to contain_exactly(product)
expect(CacheProductDataWorker).to have_enqueued_sidekiq_job(product.id)
end
end
end
context "when multiple products without cache exist" do
let(:another_product) { create(:product) }
let(:collection) { [product, another_product] }
it "bulk inserts the product cache creation worker" do
expect(CacheProductDataWorker).to receive(:perform_bulk).with([[product.id], [another_product.id]]).and_call_original
dashboard_collection_data
end
context "when one product has a cached value" do
before do
product.product_cached_values.create!
end
it "returns the proper result" do
expect(
dashboard_collection_data
).to contain_exactly(product.reload.product_cached_values.fresh.first, another_product)
end
end
end
end
context "when cache is false" do
let(:cache) { false }
context "when one product exists" do
let(:collection) { [product] }
context "when the product has no product_cached_value" do
it "does not schedule a cache worker and returns the product" do
expect do
expect(dashboard_collection_data).to contain_exactly(product)
end.not_to change { CacheProductDataWorker.jobs.size }
end
end
context "when the product has a product_cached_value" do
before do
product.product_cached_values.create!
end
it "does not schedule a cache worker and returns the product cached value" do
expect do
expect(dashboard_collection_data).to contain_exactly(product.reload.product_cached_values.fresh.first)
end.not_to change { CacheProductDataWorker.jobs.size }
end
end
context "when the product has an expired product_cached_value" do
before do
product.product_cached_values.create!(expired: true)
end
it "does not schedule a cache worker and returns the product" do
expect do
expect(dashboard_collection_data).to contain_exactly(product)
end.not_to change { CacheProductDataWorker.jobs.size }
end
end
end
context "when multiple products without cache exist" do
let(:another_product) { create(:product) }
let(:collection) { [product, another_product] }
it "does not schedule a cache worker and returns the product" do
expect do
expect(dashboard_collection_data).to contain_exactly(product, another_product)
end.not_to change { CacheProductDataWorker.jobs.size }
end
context "when one product has a cached value" do
before do
product.product_cached_values.create!
end
it "returns the proper result" do
expect do
expect(
dashboard_collection_data
).to contain_exactly(product.reload.product_cached_values.fresh.first, another_product)
end.not_to change { CacheProductDataWorker.jobs.size }
end
end
end
end
end
context "when block is passed" do
subject(:dashboard_collection_data) do
described_class.dashboard_collection_data(collection, cache: true) { |product| { "id" => product.id } }
end
context "when one product exists" do
let(:collection) { [product] }
context "when the product has no product_cached_value" do
it "schedules a product cache worker and yields the product metrics" do
expect(dashboard_collection_data).to contain_exactly({
"id" => product.id,
"monthly_recurring_revenue" => 0.0,
"remaining_for_sale_count" => 100,
"revenue_pending" => 0.0,
"successful_sales_count" => 0,
"total_usd_cents" => 0,
})
expect(CacheProductDataWorker).to have_enqueued_sidekiq_job(product.id)
end
end
context "when the product has a product_cached_value" do
before do
product.product_cached_values.create!
end
it "does not schedule a cache worker and returns the product cached value" do
expect do
expect(dashboard_collection_data).to contain_exactly({
"id" => product.id,
"monthly_recurring_revenue" => 0.0,
"remaining_for_sale_count" => 100,
"revenue_pending" => 0.0,
"successful_sales_count" => 0,
"total_usd_cents" => 0,
})
end.not_to change { CacheProductDataWorker.jobs.size }
end
end
context "when the product has an expired product_cached_value" do
before do
product.product_cached_values.create!(expired: true)
end
it "schedules a product cache worker and returns the product" do
expect(dashboard_collection_data).to contain_exactly({
"id" => product.id,
"monthly_recurring_revenue" => 0.0,
"remaining_for_sale_count" => 100,
"revenue_pending" => 0.0,
"successful_sales_count" => 0,
"total_usd_cents" => 0,
})
expect(CacheProductDataWorker).to have_enqueued_sidekiq_job(product.id)
end
end
end
context "when multiple products exist" do
let(:another_product) { create(:product) }
let(:collection) { [product, another_product] }
it "bulk inserts the product cache creation worker" do
expect(CacheProductDataWorker).to receive(:perform_bulk).with([[product.id], [another_product.id]]).and_call_original
dashboard_collection_data
end
it "returns the proper result" do
expect(dashboard_collection_data).to contain_exactly(
{
"id" => product.id,
"monthly_recurring_revenue" => 0.0,
"remaining_for_sale_count" => 100,
"revenue_pending" => 0.0,
"successful_sales_count" => 0,
"total_usd_cents" => 0,
},
{
"id" => another_product.id,
"monthly_recurring_revenue" => 0.0,
"remaining_for_sale_count" => nil,
"revenue_pending" => 0.0,
"successful_sales_count" => 0,
"total_usd_cents" => 0,
}
)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/searchable/search_spec.rb | spec/modules/product/searchable/search_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Product::Searchable - Search scenarios" do
before do
@product = create(:product_with_files)
end
describe "Elasticsearch `search`" do
describe "on indexed products with price values" do
before do
@creator = create(:recommendable_user)
product_ids = []
9.times do |i|
# The products get slightly more expensive
# We choose 99 cents and up so we can filter for price less than and greater than $1
product = create(:product, :recommendable, price_cents: 99 + i, user: @creator)
# People love buying the cheapest products though! The cheapest
# products have the highest sales volume.
(10 - i).times do
create(:purchase, :with_review, link: product)
end
product_ids << product.id
end
free_product = create(:product, :recommendable, price_cents: 0, user: @creator)
product_ids << free_product
decimal_product = create(:product, :recommendable, price_cents: 550, user: @creator)
product_ids << decimal_product
improved_visibility_product = create(:product, :recommendable, discover_fee_per_thousand: 300, price_cents: 200, user: @creator)
product_ids << improved_visibility_product
@product_query = Link.where(id: product_ids)
index_model_records(Purchase)
index_model_records(Link)
end
it "filters by min price" do
# Filtering for products costing 100 cents or more
params = { min_price: 1 }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected_filtered = @product_query.where("price_cents >= ?", 100)
expected = expected_filtered.sort_by(&:total_fee_cents)
.reverse
.first(9)
.map(&:id)
# There are 9 products match, costing 100 - 107 (inclusive) cents
expect(expected).to eq(records.map(&:id))
end
it "filters by max price" do
# Filtering for products costing 100 cents or less
params = { max_price: 1 }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected_filtered = @product_query.where("price_cents <= ?", 100)
expected = expected_filtered.sort_by(&:total_fee_cents)
.reverse
.map(&:id)
# There are 3 products that match, costing 0, 99 and 100 cents
expect(expected).to eq(records.map(&:id))
end
it "filters by min and max price" do
# Filtering for products costing exactly 100 cents
params = { min_price: 1, max_price: 1 }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected = @product_query.where("price_cents = ?", 100).pluck(:id)
# There should just be one record that costs exactly 100 cents
assert_equal 1, records.length
assert_equal expected, records.map(&:id)
end
it "filters when min and max price are 0" do
# Filtering for products are free
params = { min_price: 0, max_price: 0 }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected = @product_query.where("price_cents = ?", 0).pluck(:id)
# There should just be one record that is free
assert_equal 1, records.length
assert_equal expected, records.map(&:id)
end
it "min and max filter include products with a decimal price" do
# Filtering for products costing between $5 and $6
params = { min_price: 5, max_price: 6 }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected = @product_query
.where("price_cents >= ?", 500)
.where("price_cents <= ?", 600)
.pluck(:id)
# There should just be one record in that range that costs $5.50
assert_equal 1, records.length
assert_equal expected, records.map(&:id)
end
describe "is_alive_on_profile" do
let(:seller) { create(:user) }
let!(:product) { create(:product, user: seller) }
let!(:deleted_product) { create(:product, user: seller, deleted_at: Time.current) }
let!(:archived_product) { create(:product, user: seller, archived: true) }
before do
index_model_records(Link)
end
it "filters by is_alive_on_profile" do
records = Link.search(Link.search_options({ is_alive_on_profile: true, user_id: seller.id })).records
expect(records.map(&:id)).to eq([product.id])
records = Link.search(Link.search_options({ is_alive_on_profile: false, user_id: seller.id })).records
expect(records.map(&:id)).to eq([deleted_product.id, archived_product.id])
end
end
it "sorts by price ascending" do
params = { sort: ProductSortKey::PRICE_ASCENDING }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected = @product_query.order(:price_cents).limit(9).pluck(:id)
assert_equal expected, records.map(&:id)
end
it "sorts by price descending" do
params = { sort: ProductSortKey::PRICE_DESCENDING }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected = @product_query.order(price_cents: :desc).limit(9).pluck(:id)
assert_equal expected, records.map(&:id)
end
it "sorts by fee revenue and sales volume" do
search_options = Link.search_options({ sort: ProductSortKey::FEATURED })
records = Link.search(search_options).records
expected = @product_query.sort_by(&:total_fee_cents)
.reverse
.first(9)
.map(&:id)
expect(expected).to eq(records.map(&:id))
end
it "sorts by fee revenue and sales volume when no sort param is present" do
search_options = Link.search_options({})
records = Link.search(search_options).records
expected = @product_query.sort_by(&:total_fee_cents)
.reverse
.first(9)
.map(&:id)
expect(expected).to eq(records.map(&:id))
end
it "filters by ID" do
id = @product_query.first.id
search_options = Link.search_options({ exclude_ids: [id] })
records = Link.search(search_options).records.records
expect(records.map(&:id)).to_not include(id)
end
context "when sorting by curated" do
it "boosts recommended products then sorts by price ascending" do
recommended_product1 = create(:product, :recommendable)
recommended_product2 = create(:product, :recommendable)
recommended_product3 = create(:product, :recommendable)
Link.import(refresh: true, force: true)
search_options = Link.search_options({ sort: ProductSortKey::CURATED, curated_product_ids: [recommended_product1.id, recommended_product2.id, recommended_product3.id] })
records = Link.search(search_options).records
expect(records.map(&:id)).to eq(
[
recommended_product1.id,
recommended_product2.id,
recommended_product3.id,
*@product_query.sort_by(&:total_fee_cents)
.reverse
.first(6)
.map(&:id)
]
)
end
end
end
describe "on indexed products with filetypes" do
before do
@creator = create(:recommendable_user)
non_recommendable_product = create(:product, name: "non-recommendable product", user: @creator)
create(:product_file, link: non_recommendable_product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/nyt.pdf")
create(:product_file, link: non_recommendable_product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3")
@pdf_product = create(:product, :recommendable, name: "PDF product", user: @creator)
create(:product_file, link: @pdf_product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/nyt.pdf")
@mp3_product = create(:product, :recommendable, name: "MP3 product", user: @creator)
create(:product_file, link: @mp3_product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3")
@adult_mp3_product = create(:product, :recommendable, user: @creator, is_adult: true)
create(:product_file, link: @adult_mp3_product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3")
Link.import(refresh: true, force: true)
end
it "filters by one filetype" do
# Filtering for products with a PDF
params = { filetypes: "pdf" }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected = [@pdf_product.id]
# There should just be one record that has a PDF
assert_equal 1, records.length
assert_equal expected, records.map(&:id)
end
it "filters by multiple filetypes" do
# Filtering for products with both a PDF and an MP3
params = { filetypes: ["pdf", "mp3"] }
search_options = Link.search_options(params)
records = Link.search(search_options).records
expected = [@mp3_product.id, @pdf_product.id]
# There should be two records that have both
assert_equal 2, records.length
assert_equal expected.sort, records.map(&:id).sort
end
it "aggregates the filetypes for all params passed, except filetypes" do
params = { taxonomy_id: Taxonomy.find_by(slug: "films").id, filetypes: ["mp3"] }
search_options = Link.filetype_options(params)
aggregations = Link.search(search_options).aggregations["filetypes.keyword"]["buckets"]
expected = [
{ "key": "mp3", "doc_count": 1 },
{ "key": "pdf", "doc_count": 1 }
]
assert_equal expected, aggregations.map { |key| key.to_h.symbolize_keys }
end
end
describe "top creators aggregation" do
let(:taxonomy) { Taxonomy.find_by(slug: "3d") }
let!(:product_1) { create(:product, :recommendable) }
let!(:product_2) { create(:product, :recommendable) }
let!(:product_3) { create(:product, :recommendable, taxonomy:) }
let!(:product_4) { create(:product, :recommendable) }
let!(:product_5) { create(:product, :recommendable, taxonomy:) }
let!(:product_6) { create(:product, :recommendable) }
let!(:product_7) { create(:product, :recommendable) }
before do
3.times { create(:purchase, link: product_7) }
2.times { create(:purchase, link: product_6) }
create(:purchase, link: product_5)
3.times { create(:purchase, link: product_4, created_at: 4.months.ago) }
index_model_records(Purchase)
index_model_records(Link)
end
it "aggregates the top 6 creators by sales volume from the last 3 months" do
options = Link.search_options({ include_top_creators: true })
aggregations = Link.search(options)
.aggregations
.dig("top_creators", "buckets")
expect(aggregations).to eq([
{ doc_count: 1, key: product_7.user_id, sales_volume_sum: { value: 400.0 } },
{ doc_count: 1, key: product_6.user_id, sales_volume_sum: { value: 300.0 } },
{ doc_count: 1, key: product_5.user_id, sales_volume_sum: { value: 200.0 } },
{ doc_count: 1, key: product_1.user_id, sales_volume_sum: { value: 100.0 } },
{ doc_count: 1, key: product_2.user_id, sales_volume_sum: { value: 100.0 } },
{ doc_count: 1, key: product_3.user_id, sales_volume_sum: { value: 100.0 } },
].as_json)
end
it "filters top creators by search options" do
options = Link.search_options({ taxonomy_id: taxonomy.id, include_top_creators: true })
aggregations = Link.search(options)
.aggregations
.dig("top_creators", "buckets")
expect(aggregations).to eq([
{ doc_count: 1, key: product_5.user_id, sales_volume_sum: { value: 200.0 } },
{ doc_count: 1, key: product_3.user_id, sales_volume_sum: { value: 100.0 } },
].as_json)
end
it "does not include top creators if include_top_creators param is not present" do
options = Link.search_options({})
aggregations = Link.search(options).aggregations
expect(aggregations["top_creators"]).to be_nil
end
end
describe "on indexed products with tags" do
before do
creator = create(:compliant_user)
@durian = create(:product, :recommendable, user: creator)
@durian.tag!("fruit")
@celery = create(:product, :recommendable, user: creator)
@celery.tag!("vegetable")
@flf = create(:product, :recommendable, user: creator)
@flf.tag!("house plant")
Link.import(refresh: true, force: true)
end
it "filters by one tag" do
params = { tags: ["fruit"] }
search_options = Link.search_options(params)
records = Link.search(search_options).records
assert_equal 1, records.length
assert_equal [@durian.id], records.map(&:id)
end
it "filters to the union of two tags" do
params = { tags: ["fruit", "vegetable"] }
search_options = Link.search_options(params)
records = Link.search(search_options).records
assert_equal 2, records.length
assert_equal [@celery.id, @durian.id].sort, records.map(&:id).sort
end
end
describe "on indexed products with `created_at` value" do
it "sorts by newest" do
creator = create(:compliant_user, username: "username")
time = Time.current
product_ids = []
18.times do |i|
# Ensure that each created_at is distinct
travel_to(time + i.minutes) do
product = create(:product, :recommendable, user: creator)
product_ids << product.id
end
end
Link.import(refresh: true, force: true)
params = { sort: ProductSortKey::NEWEST }
search_options = Link.search_options(params)
records = Link.search(search_options).records.map(&:id)
expected = Link.where(id: product_ids).order(created_at: :desc).limit(9).pluck(:id)
assert_equal expected, records
end
end
describe "searching by section" do
before do
@creator = create(:user)
product_a = create(:product, :recommendable, user: @creator)
product_b = create(:product, :recommendable, user: @creator)
product_c = create(:product, :recommendable, user: @creator)
product_d = create(:product, :recommendable, user: @creator)
create(:product, :recommendable, user: @creator)
Link.import(refresh: true, force: true)
@products = [product_b, product_a, product_d, product_c]
end
it "returns only the products in the given section, in the correct order" do
section = create(:seller_profile_products_section, seller: @creator, shown_products: @products.map { _1.id })
search_options = Link.search_options({ user_id: @creator.id, section:, sort: "page_layout" })
records = Link.search(search_options).records
expected = @products.map(&:unique_permalink)
assert_equal expected, records.map(&:unique_permalink)
end
end
describe "on indexed products with reviews" do
before do
creator = create(:compliant_user, username: "username")
product_ids = []
time = Time.current
9.times do |i|
travel_to(time + i.seconds) do
product = create(:product, :with_films_taxonomy, user: creator)
# Purchase the product and review it
i.times do
purchase = create(:purchase, link: product)
create(:product_review, purchase:, rating: 1 + (i % 4))
end
product_ids << product.id
end
end
# Add 2 products with the same rating
travel_to(time) do
product = create(:product, :with_films_taxonomy, user: creator,)
2.times do
purchase = create(:purchase, link: product)
create(:product_review, purchase:, rating: 4)
end
product_ids << product.id
product = create(:product, :with_films_taxonomy, user: creator,)
purchase = create(:purchase, link: product)
create(:product_review, purchase:, rating: 4)
product_ids << product.id
end
@products_query = Link.where(id: product_ids)
Link.import(refresh: true, force: true)
end
it "sorts by most reviewed product" do
params = { sort: ProductSortKey::MOST_REVIEWED }
search_options = Link.search_options(params)
records = Link.search(search_options).records
# Sort by review count and created at, but *ascending*
expected_ascending = @products_query.sort_by do |product|
[product.reviews_count, product.created_at]
end
# Reverse to get them descending, and then grab the first 9 results
expected = expected_ascending.reverse[0..8]
assert_equal expected.map(&:id), records.map(&:id)
end
it "sorts and filters by average rating" do
params = { sort: ProductSortKey::HIGHEST_RATED, rating: 2 }
search_options = Link.search_options(params)
records = Link.search(search_options).records
# Filter for sufficient average rating
expected_filtered = @products_query.select { |product| product.average_rating >= 2 }
# Sort by average rating and created at, but *ascending*
expected_ascending = expected_filtered.sort_by do |product|
[product.average_rating, product.reviews_count, product.created_at]
end
# Reverse to get them descending, and then grab the first 9 results
expected = expected_ascending.reverse[0..8]
assert_equal expected.map(&:id), records.map(&:id)
end
end
describe "on all products with reviews_count" do
before do
creator = create(:compliant_user, name: "Gumbot")
@product_1 = create(:product, :with_films_taxonomy, user: creator,)
create(:product_review, purchase: create(:purchase, link: @product_1))
create(:product_review, purchase: create(:purchase, link: @product_1))
@product_2 = create(:product, :with_films_taxonomy, user: creator,)
create(:product_review, purchase: create(:purchase, link: @product_2))
@product_3 = create(:product, :with_films_taxonomy, user: creator,)
Link.import(refresh: true, force: true)
end
it "filters products with reviews_count greater than min_reviews_count" do
search_options_1 = Link.search_options(min_reviews_count: 1)
results_1 = Link.search(search_options_1).records
expect(results_1).to include @product_1
expect(results_1).to include @product_2
expect(results_1).to_not include @product_3
search_options_2 = Link.search_options(min_reviews_count: 2)
results_2 = Link.search(search_options_2).records
expect(results_2).to include @product_1
expect(results_2).to_not include @product_2
expect(results_2).to_not include @product_3
end
end
describe "on indexed products with taxonomy set" do
before do
@films = Taxonomy.find_by(slug: "films")
@comedy = Taxonomy.find_by(slug: "comedy", parent: @films)
@standup = Taxonomy.find_by(slug: "standup", parent: @comedy)
@music = Taxonomy.find_by(slug: "music-and-sound-design")
@product_1 = create(:product, :recommendable, name: "top music", taxonomy: @music)
@product_2 = create(:product, :recommendable, name: "top film", taxonomy: @standup)
Link.import(refresh: true, force: true)
end
it "returns products with matching taxonomy" do
search_options_1 = Link.search_options(taxonomy_id: @music.id)
results_1 = Link.search(search_options_1).records
expect(results_1).to include @product_1
expect(results_1).to_not include @product_2
search_options_2 = Link.search_options(taxonomy_id: @standup.id)
results_2 = Link.search(search_options_2).records
expect(results_2).to include @product_2
expect(results_2).to_not include @product_1
end
it "does not return descendant products" do
search_options_1 = Link.search_options(taxonomy_id: @comedy.id)
results_1 = Link.search(search_options_1).records
expect(results_1.length).to eq(0)
search_options_2 = Link.search_options(taxonomy_id: @films.id)
results_2 = Link.search(search_options_2).records
expect(results_2.length).to eq(0)
end
describe "when include_taxonomy_descendants params is true" do
it "returns products whose taxonomy is a child of the set taxonomy" do
search_options = Link.search_options(
taxonomy_id: @comedy.id,
include_taxonomy_descendants: true
)
results = Link.search(search_options).records
expect(results).to include @product_2
expect(results).to_not include @product_1
end
it "returns products whose taxonomy is the grandchildren of the set taxonomy" do
search_options = Link.search_options(
taxonomy_id: @films.id,
include_taxonomy_descendants: true
)
results = Link.search(search_options).records
expect(results).to include @product_2
expect(results).to_not include @product_1
end
end
end
describe "on indexed products rated as adult" do
before do
@product_sfw = create(:product, :recommendable)
@product_nsfw = create(:product, :recommendable, is_adult: true)
index_model_records(Link)
end
it "excludes adult products when include_rated_as_adult is absent" do
search_options = Link.search_options({})
results = Link.search(search_options).records
expect(results).to include @product_sfw
expect(results).to_not include @product_nsfw
end
it "includes adult products when include_rated_as_adult is present" do
search_options = Link.search_options(include_rated_as_adult: true)
results = Link.search(search_options).records
expect(results).to include @product_sfw
expect(results).to include @product_nsfw
end
end
describe "on indexed products with staff_picked_at" do
let!(:staff_picked_product_one) { create(:product, :recommendable) }
let!(:non_staff_picked_product) { create(:product, :recommendable) }
let!(:staff_picked_product_two) { create(:product, :recommendable) }
before do
staff_picked_product_one.create_staff_picked_product!(updated_at: 1.hour.ago)
staff_picked_product_two.create_staff_picked_product!(updated_at: 2.hour.ago)
index_model_records(Link)
end
it "includes all products when staff_picked is not set" do
search_options = Link.search_options({})
results = Link.search(search_options).records
expect(results).to include staff_picked_product_one
expect(results).to include staff_picked_product_two
expect(results).to include non_staff_picked_product
end
context "with staff_picked filter" do
it "includes only staff_picked products, sorted" do
search_options = Link.search_options({ staff_picked: true, sort: ProductSortKey::STAFF_PICKED })
records = Link.search(search_options).records
assert_equal(
[staff_picked_product_one.id, staff_picked_product_two.id],
records.map(&:id)
)
end
end
end
describe "option 'from'" do
it "is clamped from 0 to a valid max result window" do
expect do
Link.search(Link.search_options(from: -1)).response
end.not_to raise_error
expect do
Link.search(Link.search_options(from: 999_999_999)).response
end.not_to raise_error
end
end
describe "searching by multiple user IDs" do
let!(:product1) { create(:product) }
let!(:product2) { create(:product) }
before do
index_model_records(Link)
end
it "returns products from both users" do
expect(Link.search(Link.search_options(user_id: [product1.user_id, product2.user_id])).records.map(&:id)).to eq([product1.id, product2.id])
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/searchable/filtered_search_spec.rb | spec/modules/product/searchable/filtered_search_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Product::Searchable - Filtered search scenarios" do
describe "filters adult products for recommendable products" do
before do
@creator = create(:recommendable_user, username: "a" + SecureRandom.random_number(1e15).round.to_s, name: "Gumbot")
@adult_creator = create(:recommendable_user, name: "Gumbot", bio: "nsfw stuff")
end
it "does not filter products when user_id is given" do
product_1 = create(:product, :recommendable, is_adult: true, user: @creator)
product_2 = create(:product, :recommendable, is_adult: false, user: @creator)
Link.import(refresh: true, force: true)
# Search by user_id to avoid check on "recommendable" field which
# filters products with is_adult by default
search_options = Link.search_options(user_id: @creator.id)
records = Link.__elasticsearch__.search(search_options).records
expect(records).to include(product_1, product_2)
end
end
it "supports ES query syntax" do
creator = create(:compliant_user, username: "a" + SecureRandom.random_number(1e15).round.to_s)
product_1 = create(:product_with_files, :recommendable, name: "photo presets", user: creator)
product_2 = create(:product_with_files, :recommendable, name: "photo book", user: creator)
Link.import(refresh: true, force: true)
search_options = Link.search_options(query: "photo -presets")
records = Link.__elasticsearch__.search(search_options).records
expect(records).not_to include product_1
expect(records).to include product_2
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/searchable/offer_codes_spec.rb | spec/modules/product/searchable/offer_codes_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Product::Searchable - Offer codes filtering" do
describe "filtering by offer_codes", :elasticsearch_wait_for_refresh do
before do
Link.__elasticsearch__.create_index!(force: true)
Feature.activate(:offer_codes_search)
@creator = create(:recommendable_user)
@offer_code = create(:offer_code, user: @creator, code: "BLACKFRIDAY2025")
@product_with_offer = create(:product, :recommendable, user: @creator, name: "Product with Black Friday")
@product_with_offer.offer_codes << @offer_code
@product_without_offer = create(:product, :recommendable, user: @creator, name: "Product without offer")
@other_offer_code = create(:offer_code, user: @creator, code: "SUMMER2025")
@product_with_other_offer = create(:product, :recommendable, user: @creator, name: "Product with other offer")
@product_with_other_offer.offer_codes << @other_offer_code
index_model_records(Link)
end
after do
Feature.deactivate(:offer_codes_search)
end
it "returns only products with BLACKFRIDAY2025 offer code" do
args = Link.search_options(offer_code: "BLACKFRIDAY2025")
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).to include(@product_with_offer)
expect(records).not_to include(@product_without_offer)
expect(records).not_to include(@product_with_other_offer)
end
it "returns all products when offer_code param is not provided" do
args = Link.search_options({})
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).to include(@product_with_offer)
expect(records).to include(@product_without_offer)
expect(records).to include(@product_with_other_offer)
end
it "returns no products when searching with __no_match__ code" do
# When feature flag is inactive or invalid code is provided,
# SearchProducts concern sets offer_code to "__no_match__"
args = Link.search_options(offer_code: "__no_match__")
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).to be_empty
end
it "returns products when offer code is deleted and reindexed" do
@product_with_offer.offer_codes.delete(@offer_code)
@product_with_offer.enqueue_index_update_for(["offer_codes"])
index_model_records(Link)
args = Link.search_options(offer_code: "BLACKFRIDAY2025")
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).not_to include(@product_with_offer)
end
end
describe "offer codes indexing" do
before do
@creator = create(:recommendable_user)
@product = create(:product, user: @creator)
@offer_code_1 = create(:offer_code, user: @creator, code: "CODE1")
@offer_code_2 = create(:offer_code, user: @creator, code: "CODE2")
@deleted_offer = create(:offer_code, user: @creator, code: "DELETED", deleted_at: Time.current)
end
it "includes all alive offer codes in search property" do
@product.offer_codes << @offer_code_1
@product.offer_codes << @offer_code_2
@product.offer_codes << @deleted_offer
expect(@product.send(:build_search_property, "offer_codes")).to contain_exactly("CODE1", "CODE2")
end
it "returns empty array when product has no offer codes" do
expect(@product.send(:build_search_property, "offer_codes")).to eq([])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/searchable/indexing_spec.rb | spec/modules/product/searchable/indexing_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Product::Searchable - Indexing scenarios" do
before do
@product = create(:product_with_files)
end
describe "#as_indexed_json" do
it "includes all properties" do
taxonomy = create(:taxonomy)
@product.update!(name: "Searching for Robby Fischer", description: "Search search search", taxonomy:, is_adult: true)
@product.tag!("tag")
@product.save_files!([{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/some-url.txt" }])
@product.save_files!([
{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png" },
{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pic.jpg" },
{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/other.jpg" },
])
@product.user.update!(name: "creator name", user_risk_state: "compliant")
purchase = create(:purchase_with_balance, link: @product, seller: @product.user, price_cents: @product.price_cents)
review = create(:product_review, purchase:)
create(:purchase_with_balance, link: @product, seller: @product.user, price_cents: @product.price_cents, created_at: 6.months.ago)
index_model_records(Purchase)
properties = @product.as_indexed_json
# Values for all search properties must be returned by this method
expect(properties.keys).to match_array(Product::Searchable::SEARCH_FIELDS.map(&:as_json))
expect(properties["name"]).to eq("Searching for Robby Fischer")
expect(properties["description"]).to eq("Search search search")
expect(properties["tags"]).to eq(["tag"])
expect(properties["creator_name"]).to eq("creator name")
expect(properties["sales_volume"]).to eq(100)
expect(properties["is_recommendable"]).to eq(true)
expect(properties["rated_as_adult"]).to eq(true)
expect(properties["average_rating"]).to eq(review.rating)
expect(properties["reviews_count"]).to eq(1)
expect(properties["is_physical"]).to eq(false)
expect(properties["is_subscription"]).to eq(false)
expect(properties["is_preorder"]).to eq(false)
expect(properties["filetypes"]).to match_array(["png", "jpg"])
expect(properties["is_alive_on_profile"]).to eq(true)
expect(properties["is_call"]).to eq(false)
expect(properties["is_alive"]).to eq(true)
expect(properties["creator_external_id"]).to eq(@product.user.external_id)
expect(properties["content_updated_at"]).to eq(@product.content_updated_at.iso8601)
expect(properties["taxonomy_id"]).to eq(taxonomy.id)
expect(properties["total_fee_cents"]).to eq(93)
expect(properties["past_year_fee_cents"]).to eq(186)
end
end
describe "#build_search_update" do
it "returns the attributes to update in Elasticsearch" do
product_name = "Some new name"
@product.update!(name: product_name)
update_properties = @product.build_search_update(%w[name])
expect(update_properties.keys).to match_array(%w[name])
expect(update_properties["name"]).to eq(product_name)
end
end
describe "#build_search_property for offer_codes" do
it "returns all codes when total is less than MAX_OFFER_CODES_IN_INDEX" do
stub_const("Product::Searchable::MAX_OFFER_CODES_IN_INDEX", 5)
3.times { |i| @product.offer_codes << create(:offer_code, user: @product.user, code: "CODE#{i}") }
codes = @product.send(:build_search_property, "offer_codes")
expect(codes.size).to eq(3)
end
it "limits to MAX_OFFER_CODES_IN_INDEX most recent codes when total exceeds limit" do
stub_const("Product::Searchable::MAX_OFFER_CODES_IN_INDEX", 5)
# Create older codes
2.times do |i|
create(:offer_code, user: @product.user, code: "OLD#{i}", created_at: 100.days.ago)
end
# Create newer codes
newest_codes = 7.times.map do |i|
create(:offer_code, user: @product.user, code: "NEW#{i}", created_at: 1.day.ago).code
end
@product.offer_codes = OfferCode.where(user: @product.user)
codes = @product.send(:build_search_property, "offer_codes")
expect(codes.size).to eq(5)
expect(codes).to all(start_with("NEW"))
expect(codes).to all(be_in(newest_codes))
end
end
describe "#enqueue_search_index!" do
it "indexes product via ProductIndexingService" do
expect(ProductIndexingService).to receive(:perform).with(product: @product, action: "index", on_failure: :async).and_call_original
@product.enqueue_search_index!
end
end
describe "#enqueue_index_update_for" do
it "updates product document via ProductIndexingService" do
expect(ProductIndexingService).to receive(:perform).with(product: @product, action: "update", attributes_to_update: %w[name filetypes], on_failure: :async).and_call_original
@product.enqueue_index_update_for(%w[name filetypes])
end
end
describe "Indexing the changes through callbacks" do
it "imports all search fields when a product is created" do
product = build(:product)
expect(ProductIndexingService).to receive(:perform).with(product:, action: "index", on_failure: :async).and_call_original
product.save!
end
it "correctly indexes price_cents", :elasticsearch_wait_for_refresh do
document = EsClient.get(index: Link.index_name, id: @product.id)
expect(document["_source"]["price_cents"]).to eq(100)
end
describe "on product update" do
it "requests update of the name & rated_as_adult fields on name change" do
expect_product_update %w[name rated_as_adult]
@product.update!(name: "I have a great idea for a name.")
end
it "requests update of the description & rated_as_adult fields on description change" do
expect_product_update %w[description rated_as_adult]
@product.update!(description: "I have a great idea for a description.")
end
it "sends updated rated_as_adult field on `is_adult` change" do
expect_product_update %w[rated_as_adult]
is_adult = !@product.is_adult
@product.update!(is_adult:)
end
it "sends updated is_recommendable & display_product_reviews fields on `display_product_reviews` change" do
expect_product_update %w[display_product_reviews is_recommendable]
@product.display_product_reviews = !@product.display_product_reviews?
@product.save!
end
it "sends updated is_recommendable and is_alive_on_profile and is_alive fields on `purchase_disabled_at` change" do
expect_product_update %w[is_recommendable is_alive_on_profile is_alive]
@product.purchase_disabled_at = Time.current
@product.save!
end
it "sends updated is_recommendable and is_alive_on_profile and is_alive fields on `banned_at` change" do
expect_product_update %w[is_recommendable is_alive_on_profile is_alive]
@product.update!(banned_at: Time.current)
end
it "sends updated is_recommendable and is_alive_on_profile and is_alive fields on `deleted_at` change" do
expect_product_update %w[is_recommendable is_alive_on_profile is_alive]
@product.update!(deleted_at: Time.current)
end
it "sends updated taxonomy_id field on `taxonomy_id` change" do
expect_product_update %w[taxonomy_id is_recommendable]
@product.update!(taxonomy: create(:taxonomy))
end
it "sends updated is_recommendable & is_alive_on_profile field on `archived` change" do
expect_product_update %w[is_recommendable is_alive_on_profile]
@product.update!(archived: true)
end
it "sends updated price_cents & available_price_cents fields on price_range change" do
expect_product_update %w[price_cents available_price_cents]
new_price = @product.price_cents + 100
@product.update!(price_range: new_price)
end
it "sends updated price_cents & available_price_cents fields on price_cents change" do
expect_product_update %w[price_cents available_price_cents]
new_price = @product.price_cents + 100
@product.update!(price_cents: new_price)
end
it "sends updated is_preorder on preorder state change" do
expect_product_update %w[is_preorder]
@product.is_in_preorder_state = !@product.is_in_preorder_state
@product.save!
end
it "sends updated is_recommendable field on max_purchase_count change" do
expect_product_update %w[is_recommendable]
@product.update!(max_purchase_count: 100)
end
it "sends updated is_call field when native_type changes to call" do
expect_product_update %w[is_call]
@product.native_type = Link::NATIVE_TYPE_CALL
@product.save(validate: false)
end
it "does not index changes when transaction is rolled back" do
expect(ProductIndexingService).not_to receive(:perform)
ActiveRecord::Base.transaction do
@product.update!(name: "new name", price_cents: 234)
raise ActiveRecord::Rollback
end
document = EsClient.get(index: Link.index_name, id: @product.id)
expect(document["_source"]["name"]).to eq("The Works of Edgar Gumstein")
expect(document["_source"]["price_cents"]).to eq(100)
end
end
it "updates review search properties on review save" do
expect_product_update %w[average_rating reviews_count is_recommendable]
purchase = create(:purchase, link: @product)
create(:product_review, purchase:)
end
it "updates the index for the associated product on product file save" do
expect_product_update %w[filetypes]
file_params = [{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png" },
{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf" }]
@product.save_files!(file_params)
end
describe "on user update" do
it "sends updated rated_as_adult & creator_name on name change" do
expect_product_update %w[rated_as_adult creator_name]
user = @product.user
user.update!(name: "New user name")
end
it "sends updated rated_as_adult & creator_name on username change" do
expect_product_update %w[rated_as_adult creator_name]
@product.user.update!(username: "newusername")
end
it "sends updated rated_as_adult field on bio change" do
expect_product_update %w[rated_as_adult]
user = @product.user
user.update!(bio: "New user bio")
end
it "sends updated rated_as_adult field on all_adult_products change" do
expect_product_update %w[rated_as_adult]
user = @product.user
user.update!(all_adult_products: true)
end
it "sends updated is_recommendable flag on payment_address update" do
expect_product_update %w[is_recommendable]
user = @product.user
user.update!(payment_address: nil)
end
it "sends updated is_recommendable flag on creation of active bank_account" do
expect_product_update %w[is_recommendable]
create(:canadian_bank_account, deleted_at: 1.day.ago, user: @product.user)
expect_product_update %w[is_recommendable]
create(:canadian_bank_account, user: @product.user)
end
it "does not index products if user already has an active bank_account" do
create(:canadian_bank_account, user: @product.user)
expect(ProductIndexingService).not_to receive(:perform)
create(:canadian_bank_account, user: @product.user)
end
it "sends updated is_recommendable field when user is marked compliant" do
expect_product_update %w[is_recommendable]
@product.user.mark_compliant!(author_id: create(:user).id)
end
it "sends updated is_recommendable field when compliant user is suspended for fraud" do
admin = create(:user)
@product.user.mark_compliant!(author_id: admin.id)
expect_product_update %w[is_recommendable]
@product.user.update!(user_risk_state: "suspended_for_fraud")
end
it "does nothing if no watched attributes change" do
expect(ProductIndexingService).not_to receive(:perform)
@product.user.update!(kindle_email: "someone@kindle.com")
end
end
it "sends updated tags when a tag is created" do
expect_product_update %w[tags]
@product.tag!("new tag")
end
it "sends updated filetypes when a file is added" do
expect_product_update %w[filetypes]
@product.save_files!([{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pic.jpg" }])
end
it "enqueues the job when a purchase transitions to the successful state" do
expect_product_update %w[is_recommendable]
create(:purchase_with_balance, link: @product, seller: @product.user, price_cents: @product.price_cents)
expect(SendToElasticsearchWorker).to have_enqueued_sidekiq_job(@product.id, "update", ["sales_volume", "total_fee_cents", "past_year_fee_cents"])
end
it "enqueues the job when a purchase transitions to the preorder_authorization_successful state" do
expect_product_update %w[is_recommendable]
purchase = create(:purchase_in_progress, link: @product, seller: @product.user, is_preorder_authorization: true)
purchase.mark_preorder_authorization_successful
expect(SendToElasticsearchWorker).to have_enqueued_sidekiq_job(@product.id, "update", ["sales_volume", "total_fee_cents", "past_year_fee_cents"])
end
end
def expect_product_update(attributes)
expect(ProductIndexingService).to receive(:perform).with(
product: @product,
action: "update",
attributes_to_update: attributes,
on_failure: :async
).and_call_original
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/product/searchable/name_field_search_spec.rb | spec/modules/product/searchable/name_field_search_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Product::Searchable - Name fields search scenarios" do
before do
@product = create(:product_with_files)
end
describe "on name fields for all products", :elasticsearch_wait_for_refresh do
before do
Link.__elasticsearch__.create_index!(force: true)
@product_1 = create(:product, name: "Sample propaganda for antienvironmentalists")
allow(@product_1).to receive(:recommendable?).and_return(true)
create(:product_review, purchase: create(:purchase, link: @product_1))
@product_1.__elasticsearch__.index_document
end
shared_examples_for "includes product" do |query|
it "when query is '#{query}'" do
args = Link.partial_search_options(query:)
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).to include(@product_1)
end
end
shared_examples_for "not includes product" do |query|
it "when query is '#{query}'" do
args = Link.partial_search_options(query:)
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).to_not include(@product_1)
end
end
it_behaves_like "includes product", "propaganda"
it_behaves_like "includes product", "sample propa"
it_behaves_like "includes product", "Sample propaganda for an"
it_behaves_like "includes product", "propaganda sample"
it_behaves_like "includes product", "Sa"
it_behaves_like "includes product", "for"
it_behaves_like "not includes product", "p"
it_behaves_like "not includes product", "b"
it_behaves_like "not includes product", "amp"
it_behaves_like "not includes product", "antienvironmentalistic"
it_behaves_like "not includes product", "anticapitalist"
it_behaves_like "not includes product", "Sample propaganda for envi"
it "supports ES query syntax" do
product_2 = create(:product, name: "Sample photography book")
allow(product_2).to receive(:recommendable?).and_return(true)
create(:product_review, purchase: create(:purchase, link: product_2))
product_2.__elasticsearch__.index_document
args = Link.partial_search_options(query: "sample -propaganda")
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).to_not include(@product_1)
expect(records).to include(product_2)
end
it "sorts products by sales_volume and created_at", :sidekiq_inline do
products = create_list(:product, 3, name: "Sample", price_cents: 200)
products << create(:product, name: "Sample", price_cents: 100, created_at: Time.current + 5.seconds)
products.each_with_index do |product, i|
allow(product).to receive(:recommendable?).and_return(true)
i.times { create(:purchase, link: product) }
create(:product_review, purchase: create(:purchase, link: product))
product.__elasticsearch__.index_document
end
args = Link.partial_search_options(query: "sampl")
records = Link.__elasticsearch__.search(args).records.to_a
expect(records).to start_with(*products.values_at(2, 3, 1, 0))
end
context "filtering" do
before do
@product_not_recommendable = create(:product, name: "sample")
@product_recommendable_sfw = create(:product, :recommendable, name: "sample")
@product_recommendable_nsfw = create(:product, :recommendable, name: "sample", is_adult: true)
end
it "excludes non-recommendable and recommendable-adult products" do
args = Link.partial_search_options(query: "sampl")
records = Link.search(args).records.to_a
expect(records).not_to include(@product_not_recommendable, @product_recommendable_nsfw)
expect(records).to include(@product_recommendable_sfw)
end
it "excludes non-recommendable products, but keeps adult recommendable ones when include_rated_as_adult is true" do
args = Link.partial_search_options(query: "sampl", include_rated_as_adult: true)
records = Link.search(args).records.to_a
expect(records).not_to include(@product_not_recommendable)
expect(records).to include(@product_recommendable_sfw, @product_recommendable_nsfw)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/risk_spec.rb | spec/modules/user/risk_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::Risk do
describe "#disable_refunds!" do
before do
@creator = create(:user)
end
it "disables refunds for the creator" do
@creator.disable_refunds!
expect(@creator.reload.refunds_disabled?).to eq(true)
end
end
describe "#log_suspension_time_to_mongo", :sidekiq_inline do
let(:user) { create(:user) }
let(:collection) { MONGO_DATABASE[MongoCollections::USER_SUSPENSION_TIME] }
it "writes suspension data to mongo collection" do
freeze_time do
user.log_suspension_time_to_mongo
record = collection.find("user_id" => user.id).first
expect(record).to be_present
expect(record["user_id"]).to eq(user.id)
expect(record["suspended_at"]).to eq(Time.current.to_s)
end
end
end
describe ".refund_queue", :sidekiq_inline do
it "returns users suspended for fraud with positive unpaid balances" do
user = create(:user)
create(:balance, user: user, amount_cents: 5000, state: "unpaid")
user.flag_for_fraud!(author_name: "admin")
user.suspend_for_fraud!(author_name: "admin")
result = User.refund_queue
expect(result.to_a).to eq([user])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/stats_spec.rb | spec/modules/user/stats_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::Stats, :vcr do
before do
@user = create(:user, timezone: "London")
end
describe "scopes" do
describe ".by_sales_revenue" do
it "excludes not_charged purchases from revenue total" do
product = create(:product, user: @user)
create(:purchase, link: product, purchase_state: "not_charged")
user_with_sales = create(:user)
product_with_sales = create(:product, user: user_with_sales)
create(:purchase, link: product_with_sales, purchase_state: "successful")
expect(User.by_sales_revenue(limit: 10)).to eq [user_with_sales]
end
end
end
describe "analytics data" do
describe "fees_cents_for_balances" do
before do
@user = create(:user)
link = create(:product, user: @user, price_cents: 20_00)
(0..5).each do |weeks_count|
travel_to(weeks_count.weeks.ago) do
purchase = create(:purchase_in_progress, link:, chargeable: create(:chargeable))
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "calculates the fees for the given balances properly" do
balance_ids = @user.unpaid_balances.map(&:id)
fees_for_balances = @user.fees_cents_for_balances(balance_ids)
expect(fees_for_balances).to eq 2028
end
it "calculates the fees for the given balances that includes a refund" do
purchase = Purchase.last
purchase.refund_and_save!(nil)
balance_ids = @user.unpaid_balances.map(&:id)
fees_for_balances = @user.fees_cents_for_balances(balance_ids)
expect(fees_for_balances).to eq 1760
end
it "calculates the fees correctly for the given balances which include a chargeback" do
purchase = Purchase.last
purchase.stripe_transaction_id = "ch_zitkxbhds3zqlt"
purchase.save!
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt")
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
fees_for_balances = @user.fees_cents_for_balances(balance_ids)
expect(fees_for_balances).to eq (2028 - 338)
end
it "calculates the fees correctly for the given balances which include a chargeback with a partial refund on same purchase" do
purchase = Purchase.last
purchase.refund_partial_purchase!(9_00, @user.id)
purchase.stripe_transaction_id = "ch_zitkxbhds3zqlt"
purchase.save!
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt", flow_of_funds: nil)
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
fees_for_balances = @user.fees_cents_for_balances(balance_ids)
expect(fees_for_balances).to eq (2028 - 238 + 52)
end
it "calculates the fees correctly for the given balances which include a refund and a chargeback" do
purchases = Purchase.last(2)
purchases.first.refund_and_save!(nil)
purchase = purchases.last
purchase.stripe_transaction_id = "ch_zitkxbhds3zqlt"
purchase.save!
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt")
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
fees_for_balances = @user.fees_cents_for_balances(balance_ids)
expect(fees_for_balances).to eq 1422
end
end
describe "refunds_cents_for_balances" do
before do
@user = create(:user)
link = create(:product, user: @user, price_cents: 20_00)
(0..5).each do |weeks_count|
travel_to(weeks_count.weeks.ago) do
purchase = create(:purchase_in_progress, link:, chargeable: create(:chargeable))
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "calculates the refunds when no refunds exist" do
balance_ids = @user.unpaid_balances.map(&:id)
refunds_cents_for_balances = @user.refunds_cents_for_balances(balance_ids)
expect(refunds_cents_for_balances).to eq 0
end
it "calculates the refunds for the given balances that includes a full refund" do
purchase = Purchase.last
purchase.refund_and_save!(nil)
balance_ids = @user.unpaid_balances.map(&:id)
refunds_cents_for_balances = @user.refunds_cents_for_balances(balance_ids)
expect(refunds_cents_for_balances).to eq purchase.price_cents
end
it "calculates the refunds for the given balances that includes a partial refund" do
purchase = Purchase.last
purchase.refund_and_save!(nil, amount_cents: purchase.price_cents - 10)
balance_ids = @user.unpaid_balances.map(&:id)
refunds_cents_for_balances = @user.refunds_cents_for_balances(balance_ids)
expect(refunds_cents_for_balances).to eq(purchase.price_cents - 10)
end
it "calculates the refunds for the given balances that includes a partial refund and a full refund" do
purchase1 = Purchase.where(stripe_refunded: false).last
purchase1.refund_and_save!(nil)
purchase2 = Purchase.where(stripe_refunded: false).last
purchase2.refund_and_save!(nil, amount_cents: purchase2.price_cents - 10)
balance_ids = @user.unpaid_balances.map(&:id)
refunds_cents_for_balances = @user.refunds_cents_for_balances(balance_ids)
expect(refunds_cents_for_balances).to eq(purchase1.price_cents + purchase2.price_cents - 10)
end
end
describe "affiliate_credit_cents_for_balances" do
before do
seller = create(:user)
link = create(:product, user: seller, price_cents: 20_00)
@user = create(:user)
direct_affiliate = create(:direct_affiliate, seller:, affiliate_user: @user, apply_to_all_products: true)
(0..5).each do |weeks_count|
travel_to(weeks_count.weeks.ago) do
purchase = create(:purchase_in_progress, link:, chargeable: create(:chargeable), affiliate: direct_affiliate)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "calculates the affiliate credit cents for the given balances properly" do
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_credits_balances = @user.affiliate_credit_cents_for_balances(balance_ids)
expect(affiliate_credits_balances).to eq 294
end
it "calculates the affiliate fees for the given balances that includes a refund of an old sale" do
purchase = Purchase.last
purchase.balance_transactions.each do |bt|
bt.balance.mark_processing!
bt.balance.mark_paid!
end
purchase.refund_and_save!(nil)
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_credits_balances = @user.affiliate_credit_cents_for_balances(balance_ids)
expect(affiliate_credits_balances).to eq 196
end
it "calculates the affiliate fees correctly for the given balances which include a chargeback of an old sale" do
purchase = Purchase.last
purchase.stripe_transaction_id = "ch_zitkxbhds3zqlt"
purchase.save!
purchase.balance_transactions.each do |bt|
bt.balance.mark_processing!
bt.balance.mark_paid!
end
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt")
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_credits_balances = @user.affiliate_credit_cents_for_balances(balance_ids)
expect(affiliate_credits_balances).to eq 196
end
it "calculates the affiliate fees correctly for the given balances which include a refund and a chargeback of old sales" do
purchases = Purchase.last(2)
purchases.each do |purchase|
purchase.balance_transactions.each do |bt|
bt.balance.mark_processing!
bt.balance.mark_paid!
end
end
purchases.first.refund_and_save!(nil)
purchase = purchases.last
purchase.stripe_transaction_id = "ch_zitkxbhds3zqlt"
purchase.save!
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt")
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_credits_balances = @user.affiliate_credit_cents_for_balances(balance_ids)
expect(affiliate_credits_balances).to eq 98
end
end
describe "affiliate_fee_cents_for_balances" do
before do
@user = create(:user)
link = create(:product, user: @user, price_cents: 20_00)
direct_affiliate = create(:direct_affiliate, seller: @user, affiliate_user: create(:user), apply_to_all_products: true)
(0..5).each do |weeks_count|
travel_to(weeks_count.weeks.ago) do
purchase = create(:purchase_in_progress, link:, chargeable: create(:chargeable), affiliate: direct_affiliate)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "calculates the affiliate fees for the given balances properly" do
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_fees_for_balances = @user.affiliate_fee_cents_for_balances(balance_ids)
expect(affiliate_fees_for_balances).to eq 294
end
it "calculates the affiliate fees for the given balances that includes a refund of an old sale" do
purchase = Purchase.last
purchase.balance_transactions.each do |bt|
bt.balance.mark_processing!
bt.balance.mark_paid!
end
purchase.refund_and_save!(nil)
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_fees_for_balances = @user.affiliate_fee_cents_for_balances(balance_ids)
expect(affiliate_fees_for_balances).to eq 196
end
it "calculates the affiliate fees correctly for the given balances which include a chargeback of an old sale" do
purchase = Purchase.last
purchase.stripe_transaction_id = "ch_zitkxbhds3zqlt"
purchase.save!
purchase.balance_transactions.each do |bt|
bt.balance.mark_processing!
bt.balance.mark_paid!
end
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt")
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_fees_for_balances = @user.affiliate_fee_cents_for_balances(balance_ids)
expect(affiliate_fees_for_balances).to eq 196
end
it "calculates the affiliate fees correctly for the given balances which include a refund and a chargeback of old sales" do
purchases = Purchase.last(2)
purchases.each do |purchase|
purchase.balance_transactions.each do |bt|
bt.balance.mark_processing!
bt.balance.mark_paid!
end
end
purchases.first.refund_and_save!(nil)
purchase = purchases.last
purchase.stripe_transaction_id = "ch_zitkxbhds3zqlt"
purchase.save!
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt")
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
affiliate_fees_for_balances = @user.affiliate_fee_cents_for_balances(balance_ids)
expect(affiliate_fees_for_balances).to eq 98
end
end
describe "#chargebacks_cents_for_balances" do
before do
product = create(:product, user: @user, price_cents: 20_00)
5.times do |weeks_count|
travel_to(weeks_count.weeks.ago) do
create(:purchase_with_balance, link: product, chargeable: create(:chargeable))
end
end
end
it "calculates chargebacks when no chargebacks exist" do
balance_ids = @user.unpaid_balances.map(&:id)
chargebacks_cents_for_balances = @user.chargebacks_cents_for_balances(balance_ids)
expect(balance_ids.count.positive?).to be(true)
expect(chargebacks_cents_for_balances).to eq 0
end
it "calculates chargebacks with full chargeback" do
purchase = Purchase.last
purchase.update!(stripe_transaction_id: "ch_zitkxbhds3zqlt")
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt", flow_of_funds: nil)
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
chargebacks_cents_for_balances = @user.chargebacks_cents_for_balances(balance_ids)
expect(chargebacks_cents_for_balances).to eq 20_00
end
it "calculates chargebacks with partial chargeback" do
purchase = Purchase.last
purchase.refund_partial_purchase!(9_00, @user.id)
purchase.update!(stripe_transaction_id: "ch_zitkxbhds3zqlt")
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt", flow_of_funds: nil)
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
balance_ids = @user.unpaid_balances.map(&:id)
chargebacks_cents_for_balances = @user.chargebacks_cents_for_balances(balance_ids)
expect(chargebacks_cents_for_balances).to eq 11_00
end
it "calculates chargebacks for multiple balance transactions" do
purchases = Purchase.last(2)
event = build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt", flow_of_funds: nil)
purchases.each do |purchase|
purchase.update!(stripe_transaction_id: "ch_zitkxbhds3zqlt")
Purchase.handle_charge_event(event)
expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id)
end
balance_ids = @user.unpaid_balances.map(&:id)
chargebacks_cents_for_balances = @user.chargebacks_cents_for_balances(balance_ids)
expect(chargebacks_cents_for_balances).to eq 20_00 * 2
end
end
describe "#credits_cents_for_balances" do
before do
create(:merchant_account_stripe, user: @user)
5.times do
Credit.create_for_financing_paydown!(purchase: create(:purchase, link: create(:product, user: @user)), amount_cents: -250, merchant_account: @user.stripe_account, stripe_loan_paydown_id: "cptxn_12345")
Credit.create_for_credit!(user: @user, amount_cents: 1000, crediting_user: create(:user))
stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id)
Credit.create_for_manual_paydown_on_stripe_loan!(amount_cents: -2000, merchant_account: @user.stripe_account, stripe_loan_paydown_id: "cptxn_#{SecureRandom.uuid}")
end
end
it "does not include the stripe loan repayment credits" do
balance_ids = @user.unpaid_balances.map(&:id)
loan_repayment_cents = @user.credits_cents_for_balances(balance_ids)
expect(balance_ids.count.positive?).to be(true)
expect(loan_repayment_cents).to eq(5000) # 1000 * 5
end
end
describe "#loan_repayment_cents_for_balances" do
before do
create(:merchant_account_stripe, user: @user)
5.times do
Credit.create_for_financing_paydown!(purchase: create(:purchase, link: create(:product, user: @user)), amount_cents: -250, merchant_account: @user.stripe_account, stripe_loan_paydown_id: "cptxn_#{SecureRandom.uuid}")
Credit.create_for_credit!(user: @user, amount_cents: 1000, crediting_user: create(:user))
end
stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id)
Credit.create_for_manual_paydown_on_stripe_loan!(amount_cents: -2000, merchant_account: @user.stripe_account, stripe_loan_paydown_id: "cptxn_#{SecureRandom.uuid}")
end
it "calculates the total loan repayment deduction made by stripe" do
balance_ids = @user.unpaid_balances.map(&:id)
loan_repayment_cents = @user.loan_repayment_cents_for_balances(balance_ids)
expect(balance_ids.count.positive?).to be(true)
expect(loan_repayment_cents).to eq(-3250) # -250 * 5 - 2000
end
end
describe "PayPal stats" do
before :each do
@creator = create(:user)
create(:user_compliance_info, user: @creator, country: "India")
zip_tax_rate = create(:zip_tax_rate, country: "IN", state: nil, zip_code: nil, combined_rate: 0.2, is_seller_responsible: true)
@creator.zip_tax_rates << zip_tax_rate
@creator.save!
create(:merchant_account_paypal, user: @creator, charge_processor_merchant_id: "CJS32DZ7NDN5L")
@product1 = create(:product, price_cents: 10_00, user: @creator)
@product2 = create(:product, price_cents: 15_00, user: @creator)
@product3 = create(:product, price_cents: 150_00, user: @creator)
direct_affiliate = create(:direct_affiliate, seller: @creator, affiliate_user: create(:affiliate_user), affiliate_basis_points: 2500, products: [@product1, @product2, @product3])
@payout_start_date = 14.days.ago.to_date
@payout_end_date = 7.days.ago.to_date
@old_purchase_to_refund = create(:purchase_in_progress, link: @product1, seller: @creator, chargeable: create(:native_paypal_chargeable),
card_type: CardType::PAYPAL, charge_processor_id: PaypalChargeProcessor.charge_processor_id,
affiliate: direct_affiliate, country: "India")
@old_purchase_to_refund.process!
@old_purchase_to_refund.update_balance_and_mark_successful!
@old_purchase_to_refund.update_attribute(:succeeded_at, @payout_start_date - 1)
@old_purchase_to_chargeback = create(:purchase_in_progress, link: @product3, seller: @creator, chargeable: create(:native_paypal_chargeable),
card_type: CardType::PAYPAL, charge_processor_id: PaypalChargeProcessor.charge_processor_id,
affiliate: direct_affiliate)
@old_purchase_to_chargeback.process!
@old_purchase_to_chargeback.update_balance_and_mark_successful!
@old_purchase_to_chargeback.update_attribute(:succeeded_at, @payout_start_date - 1)
create(:purchase_in_progress, link: @product1, seller: @creator, created_at: 12.days.ago, chargeable: create(:native_paypal_chargeable),
card_type: CardType::PAYPAL, charge_processor_id: PaypalChargeProcessor.charge_processor_id, affiliate: direct_affiliate)
@purchase_to_chargeback = create(:purchase_in_progress, link: @product1, seller: @creator, chargeable: create(:native_paypal_chargeable),
card_type: CardType::PAYPAL, charge_processor_id: PaypalChargeProcessor.charge_processor_id,
affiliate: direct_affiliate)
@purchase_to_chargeback.process!
@purchase_to_chargeback.update_balance_and_mark_successful!
@purchase_to_chargeback.update_attribute(:succeeded_at, @payout_start_date.noon)
@purchase_with_tax = create(:purchase_in_progress, link: @product2, seller: @creator, created_at: 13.days.ago,
chargeable: create(:native_paypal_chargeable), country: "India",
card_type: CardType::PAYPAL, charge_processor_id: PaypalChargeProcessor.charge_processor_id)
@purchase_with_tax.process!
@purchase_with_tax.update_balance_and_mark_successful!
@purchase_with_tax.update_attribute(:succeeded_at, @payout_start_date + 2)
@purchase_with_affiliate = create(:purchase_in_progress, link: @product3, seller: @creator, created_at: 13.days.ago,
chargeable: create(:native_paypal_chargeable),
card_type: CardType::PAYPAL, charge_processor_id: PaypalChargeProcessor.charge_processor_id,
affiliate: direct_affiliate)
@purchase_with_affiliate.process!
@purchase_with_affiliate.update_balance_and_mark_successful!
@purchase_with_affiliate.update_attribute(:succeeded_at, @payout_start_date + 3)
@purchase_to_refund = create(:purchase_in_progress, link: @product3, seller: @creator, created_at: 10.days.ago,
chargeable: create(:native_paypal_chargeable),
card_type: CardType::PAYPAL, charge_processor_id: PaypalChargeProcessor.charge_processor_id)
@purchase_to_refund.process!
@purchase_to_refund.update_balance_and_mark_successful!
@purchase_to_refund.update_attribute(:succeeded_at, @payout_end_date.noon)
create(:purchase, link: @product3, charge_processor_id: StripeChargeProcessor.charge_processor_id, seller: @creator,
chargeable: create(:native_paypal_chargeable), card_type: CardType::VISA, succeeded_at: @payout_start_date + 3)
create(:purchase, link: @product3, charge_processor_id: BraintreeChargeProcessor.charge_processor_id, seller: @creator,
chargeable: create(:native_paypal_chargeable), card_type: CardType::PAYPAL, succeeded_at: @payout_start_date + 2)
allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil)
travel_to(14.days.ago) do
event = OpenStruct.new(created_at: Time.current,
extras: {},
flow_of_funds: FlowOfFunds.build_simple_flow_of_funds(Currency::USD,
@purchase_to_chargeback.total_transaction_cents))
@old_purchase_to_chargeback.handle_event_dispute_formalized!(event)
@old_purchase_to_chargeback.save!
@old_purchase_to_refund.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @old_purchase_to_refund.total_transaction_cents / 4), @creator)
end
travel_to(7.days.ago) do
event = OpenStruct.new(created_at: Time.current,
extras: {},
flow_of_funds: FlowOfFunds.build_simple_flow_of_funds(Currency::USD,
@purchase_to_chargeback.total_transaction_cents))
@purchase_to_chargeback.handle_event_dispute_formalized!(event)
@purchase_to_chargeback.save!
@old_purchase_to_refund.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @old_purchase_to_refund.total_transaction_cents / 4), @creator)
@purchase_to_refund.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @purchase_to_refund.total_transaction_cents), @creator)
end
travel_to(5.days.ago) do
event = OpenStruct.new(created_at: Time.current, extras: {}, flow_of_funds: FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @purchase_to_chargeback.total_transaction_cents))
@purchase_with_affiliate.handle_event_dispute_formalized!(event)
@purchase_with_affiliate.save!
@purchase_with_tax.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @purchase_with_tax.total_transaction_cents), @creator)
end
end
describe "#paypal_sales_in_duration" do
it "returns successful sales from the duration" do
sales = @creator.paypal_sales_in_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(sales).to match_array [@purchase_to_chargeback, @purchase_with_tax, @purchase_with_affiliate, @purchase_to_refund]
end
end
describe "#paypal_refunds_in_duration" do
it "returns refunds from the duration" do
refunds = @creator.paypal_refunds_in_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(refunds).to eq [@old_purchase_to_refund.refunds.to_a, @purchase_to_refund.refunds.to_a].flatten
end
end
describe "#paypal_sales_chargebacked_in_duration" do
it "returns the disputes from the duration" do
disputed_sales = @creator.paypal_sales_chargebacked_in_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(disputed_sales).to eq [@old_purchase_to_chargeback, @purchase_to_chargeback]
end
end
describe "#paypal_sales_cents_for_duration" do
it "returns total paypal direct sales amount from the duration" do
sales_amount = @creator.paypal_sales_cents_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(sales_amount).to eq(325_00)
end
end
describe "#paypal_refunds_cents_for_duration" do
it "returns total paypal direct refunded amount from the duration" do
refunded_amount = @creator.paypal_refunds_cents_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(refunded_amount).to eq(155_00)
end
end
describe "#paypal_chargebacked_cents_for_duration" do
it "returns total paypal direct chargedbacked amount from the duration" do
disputed_amount = @creator.paypal_chargebacked_cents_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(disputed_amount).to eq(160_00)
end
end
describe "#paypal_fees_cents_for_duration" do
it "returns net fees amount from paypal direct sales from the duration" do
fees_amount = @creator.paypal_fees_cents_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(fees_amount).to eq(126)
end
end
describe "#paypal_returned_fees_due_to_refunds_and_chargebacks" do
it "returns fees amount from paypal direct sales that has been returned during the duration" do
fees_amount = @creator.paypal_returned_fees_due_to_refunds_and_chargebacks(start_date: @payout_start_date, end_date: @payout_end_date)
expect(fees_amount).to eq(33_24)
end
end
describe "#paypal_taxes_cents_for_duration" do
it "returns net tax amount from paypal direct sales during the duration" do
tax_amount = @creator.paypal_taxes_cents_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(tax_amount).to eq(0)
end
end
describe "#paypal_returned_taxes_due_to_refunds_and_chargebacks" do
it "returns tax amount from paypal direct sales that has been returned during the duration" do
tax_amount = @creator.paypal_returned_taxes_due_to_refunds_and_chargebacks(start_date: @payout_start_date, end_date: @payout_end_date)
expect(tax_amount).to eq(0)
end
end
describe "#paypal_affiliate_fee_cents_for_duration" do
it "returns net affiliate fee amount from paypal direct sales during the duration" do
affiliate_fee_amount = @creator.paypal_affiliate_fee_cents_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(affiliate_fee_amount).to eq(-1_06)
end
end
describe "#paypal_returned_affiliate_fee_cents_due_to_refunds_and_chargebacks" do
it "returns affiliate fee amount from paypal direct sales that has been returned during the duration" do
affiliate_fee_amount = @creator.paypal_returned_affiliate_fee_cents_due_to_refunds_and_chargebacks(start_date: @payout_start_date, end_date: @payout_end_date)
expect(affiliate_fee_amount).to eq(36_80)
end
end
describe "#paypal_sales_data_for_duration" do
it "returns overall sales stats from paypal direct sales during the duration" do
paypal_sales_data = @creator.paypal_sales_data_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(paypal_sales_data).to eq({
sales_cents: 325_00,
refunds_cents: 155_00,
chargebacks_cents: 160_00,
credits_cents: 0,
fees_cents: 126,
direct_fees_cents: 126,
discover_fees_cents: 0,
direct_sales_count: 4,
discover_sales_count: 0,
taxes_cents: 0,
affiliate_credits_cents: 0,
affiliate_fees_cents: -1_06
})
end
end
describe "#paypal_payout_net_cents" do
it "returns affiliate fee amount from paypal direct sales that has been returned during the duration" do
paypal_sales_data = @creator.paypal_sales_data_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
paypal_payout_net_cents = @creator.paypal_payout_net_cents(paypal_sales_data)
expect(paypal_payout_net_cents).to eq(9_80)
end
end
describe "#paypal_revenue_by_product_for_duration" do
it "returns affiliate fee amount from paypal direct sales that has been returned during the duration" do
revenue_by_product = @creator.paypal_revenue_by_product_for_duration(start_date: @payout_start_date, end_date: @payout_end_date)
expect(revenue_by_product).to eq({
@product1.id => -320,
@product2.id => 1300,
@product3.id => 0,
})
end
end
end
describe "Stripe Connect stats" do
before :each do
@creator = create(:user)
create(:user_compliance_info, user: @creator)
Feature.activate_user(:merchant_migration, @creator)
create(:merchant_account_stripe_connect, user: @creator)
@product1 = create(:product, price_cents: 10_00, user: @creator)
@product2 = create(:product, price_cents: 15_00, user: @creator)
@product3 = create(:product, price_cents: 150_00, user: @creator)
direct_affiliate = create(:direct_affiliate, seller: @creator, affiliate_user: create(:affiliate_user), affiliate_basis_points: 2500, products: [@product1, @product2, @product3])
@payout_start_date = 14.days.ago.to_date
@payout_end_date = 7.days.ago.to_date
create(:zip_tax_rate, country: "DE", state: nil, zip_code: nil, combined_rate: 0.2, is_seller_responsible: false)
@old_purchase_to_refund = create(:purchase_in_progress, link: @product1, seller: @creator, chargeable: create(:chargeable),
affiliate: direct_affiliate, country: "Germany", ip_country: "Germany")
@old_purchase_to_refund.process!
@old_purchase_to_refund.update_balance_and_mark_successful!
@old_purchase_to_refund.update_attribute(:succeeded_at, @payout_start_date - 1)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/async_devise_notification_spec.rb | spec/modules/user/async_devise_notification_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::AsyncDeviseNotification do
include ActiveJob::TestHelper
# The methods in this module are private/protected so they aren't tested.
# Instead, the methods which they affect are tested.
let(:user) { create(:user) }
shared_examples_for "an email sending method" do |devise_email_method, devise_email_name|
describe "##{devise_email_method}" do
it "queues the #{devise_email_name} email in the background" do
expect do
user.public_send(devise_email_method)
end.to(have_enqueued_mail(UserSignupMailer, devise_email_name))
end
it "actually sends the email" do
perform_enqueued_jobs do
expect do
user.public_send(devise_email_method)
end.to change { ActionMailer::Base.deliveries.count }.by(1)
end
end
end
end
include_examples "an email sending method", "send_confirmation_instructions", "confirmation_instructions"
include_examples "an email sending method", "send_reset_password_instructions", "reset_password_instructions"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/australian_backtaxes_spec.rb | spec/modules/user/australian_backtaxes_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::AustralianBacktaxes do
before :each do
@creator = create(:user)
end
describe "#opted_in_to_australia_backtaxes?" do
it "returns false if the creator hasn't opted in" do
expect(@creator.opted_in_to_australia_backtaxes?).to eq(false)
end
it "returns true if the creator has opted in" do
create(:backtax_agreement, user: @creator)
expect(@creator.opted_in_to_australia_backtaxes?).to eq(true)
end
end
describe "#au_backtax_agreement_date" do
it "returns nil if the creator hasn't opted in" do
expect(@creator.au_backtax_agreement_date).to be_nil
end
it "returns the created_at date of the backtax_agreement if the creator has opted in" do
backtax_agreement = create(:backtax_agreement, user: @creator)
expect(@creator.au_backtax_agreement_date).to eq(backtax_agreement.created_at)
end
end
describe "#credit_creation_date" do
it "returns July 1, 2023 as the earliest date" do
travel_to(Time.find_zone("UTC").local(2023, 5, 5)) do
expect(@creator.credit_creation_date).to eq("July 1, 2023")
end
end
it "returns the first of the next month for anything after July 1, 2023" do
travel_to(Time.find_zone("UTC").local(2023, 7, 5)) do
expect(@creator.credit_creation_date).to eq("August 1, 2023")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/recommendations_spec.rb | spec/modules/user/recommendations_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Product::Recommendations, :elasticsearch_wait_for_refresh do
context "when user is recommendable" do
let(:user) { create(:recommendable_user) }
it "is recommendable" do
expect(user.recommendable_reasons.values).to all(be true)
expect(user.recommendable?).to be(true)
end
end
context "when user is not compliant" do
let(:user) { create(:recommendable_user, user_risk_state: "not_reviewed") }
it "is not recommendable" do
expect(user.recommendable_reasons[:compliant]).to be(false)
expect(user.recommendable_reasons.except(:compliant).values).to all(be true)
expect(user.recommendable?).to be(false)
end
end
context "when user is deleted" do
let(:user) { create(:recommendable_user, :deleted) }
it "is not recommendable" do
expect(user.recommendable_reasons[:not_deleted]).to be(false)
expect(user.recommendable_reasons.except(:not_deleted).values).to all(be true)
expect(user.recommendable?).to be(false)
end
end
describe "payout info" do
let(:user) { create(:compliant_user) }
it "is false if user doesn't have payout info" do
user.update!(payment_address: nil)
expect(user.recommendable_reasons[:payout_filled]).to be(false)
expect(user.recommendable_reasons.except(:payout_filled).values).to all(be true)
expect(user.recommendable?).to be(false)
end
it "is true if user has payment_address" do
expect(user.recommendable_reasons[:payout_filled]).to be(true)
expect(user.recommendable?).to be(true)
end
it "is true if user has active bank_account" do
user.update!(payment_address: nil)
create(:canadian_bank_account, user:)
expect(user.recommendable_reasons[:payout_filled]).to be(true)
expect(user.recommendable?).to be(true)
end
it "is true if user has a paypal account connected" do
user.update!(payment_address: nil)
create(:merchant_account_paypal, charge_processor_merchant_id: "CJS32DZ7NDN5L", user:, country: "GB", currency: "gbp")
expect(user.recommendable_reasons[:payout_filled]).to be(true)
expect(user.recommendable?).to be(true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/tier_spec.rb | spec/modules/user/tier_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::Tier do
describe "tier state machine" do
it "upgrades to next tier" do
user = create(:user)
expect(user.tier).to eq(User::TIER_0)
expect(user.upgrade_tier).to eq(true)
expect(user.tier).to eq(User::TIER_1)
end
it "upgrades with tier override" do
user = create(:user)
expect(user.tier).to eq(User::TIER_0)
expect(user.upgrade_tier(User::TIER_2)).to eq(true)
expect(user.tier).to eq(User::TIER_2)
end
it "does not upgrade if tier is 1M" do
user = create(:user, tier_state: User::TIER_4)
expect(user.upgrade_tier).to eq(false)
end
it "rejects upgrade if tier does not change" do
user = create(:user, tier_state: User::TIER_1)
expect { user.upgrade_tier(User::TIER_1) }.to raise_error(ArgumentError)
end
it "rejects invalid tier in transition argument" do
user = create(:user)
expect { user.upgrade_tier(1234) }.to raise_error(ArgumentError)
end
it "rejects invalid upgrade" do
user = create(:user, tier_state: User::TIER_3)
expect { user.upgrade_tier(User::TIER_2) }.to raise_error(ArgumentError)
end
end
describe "#tier" do
it "returns nil if creator does not use new pricing" do
creator = create(:user)
allow(creator).to receive(:tier_pricing_enabled?).and_return(false)
expect(creator.tier).to eq(nil)
end
it "returns 0 if creator has not received any payments" do
creator = create(:user)
expect(creator.tier).to eq(0)
end
it "returns 0 if creator has negative sales" do
creator = create(:user)
sales_cents = -1000
expect(creator.tier(sales_cents)).to eq(0)
end
it "returns value from tier_state column" do
creator = create(:user, tier_state: User::TIER_1)
expect(creator.tier_state).to eq(User::TIER_1)
expect(creator.tier).to eq(User::TIER_1)
end
it "returns correct tier based on revenue" do
creator = create(:user)
# No earning/below $1K = tier 0
allow(creator).to receive(:sales_cents_total).and_return(0)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_0)
allow(creator).to receive(:sales_cents_total).and_return(999_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_0)
# Tier $1K
allow(creator).to receive(:sales_cents_total).and_return(1_000_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_1)
allow(creator).to receive(:sales_cents_total).and_return(9_999_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_1)
# Tier $10K
allow(creator).to receive(:sales_cents_total).and_return(10_000_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_2)
allow(creator).to receive(:sales_cents_total).and_return(99_999_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_2)
# Tier $100K
allow(creator).to receive(:sales_cents_total).and_return(100_000_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_3)
allow(creator).to receive(:sales_cents_total).and_return(999_999_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_3)
# Tier $1M
allow(creator).to receive(:sales_cents_total).and_return(1_000_000_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_4)
allow(creator).to receive(:sales_cents_total).and_return(10_000_000_00)
expect(creator.tier(creator.sales_cents_total)).to eq(User::TIER_4)
end
end
describe "#tier_fee" do
before do
@user = create(:user)
end
it "returns nil if creator does not use new pricing" do
user = create(:user)
allow(user).to receive(:tier_pricing_enabled?).and_return(false)
expect(user.tier_fee).to eq(nil)
expect(user.tier_fee(is_merchant_account: true)).to eq(nil)
expect(user.tier_fee(is_merchant_account: false)).to eq(nil)
end
it "returns correct tier fee for purchases using merchant account" do
expect(@user.tier_fee(is_merchant_account: true)).to eq(0.09)
end
it "returns correct tier fee for purchases using non-merchant account" do
expect(@user.tier_fee).to eq(0.07)
end
end
describe "formatting" do
it "formats tier and tier fee" do
user = create(:user, tier_state: 0)
expect(user.formatted_tier_earning).to eq("$0")
expect(user.formatted_tier_fee_percentage(is_merchant_account: true)).to eq(9.0)
expect(user.formatted_tier_fee_percentage(is_merchant_account: false)).to eq(7.0)
user.update(tier_state: User::TIER_1)
expect(user.formatted_tier_earning).to eq("$1,000")
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: true)).to eq(7.0)
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: false)).to eq(5.0)
user.update(tier_state: User::TIER_2)
expect(user.formatted_tier_earning).to eq("$10,000")
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: true)).to eq(5.0)
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: false)).to eq(3.0)
user.update(tier_state: User::TIER_3)
expect(user.formatted_tier_earning).to eq("$100,000")
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: true)).to eq(3.0)
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: false)).to eq(1.0)
user.update(tier_state: User::TIER_4)
expect(user.formatted_tier_earning).to eq("$1,000,000")
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: true)).to eq(2.9)
expect(user.reload.formatted_tier_fee_percentage(is_merchant_account: false)).to eq(0.9)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/posts_spec.rb | spec/modules/user/posts_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::Posts, :freeze_time do
describe "visible_posts_for", :vcr do
before do
@creator = create(:named_user)
product = create(:product, name: "product name", user: @creator)
product_2 = create(:product, name: "product 2 name", user: @creator)
product_3 = create(:product, name: "product 3 name", user: @creator)
@membership = create(:membership_product, user: @creator)
@dude = create(:user, username: "dude")
create(:purchase, link: product, seller: @creator, purchaser: @dude, created_at: 1.hour.ago, price_cents: 100)
create(:purchase, link: product, seller: @creator, purchaser: @dude, created_at: Time.current, price_cents: 500)
create(:purchase, link: product_2, seller: @creator, purchaser: @dude, created_at: 1.hour.ago, price_cents: 1000)
purchase = create(:membership_purchase, link: @membership, seller: @creator, purchaser: @dude, price_cents: 500, created_at: 1.day.ago)
purchase.subscription.update!(cancelled_at: 1.hour.ago, deactivated_at: 1.hour.ago)
@dude_chargedback = create(:user, username: "chargedbackdude")
create(:disputed_purchase, link: product, seller: @creator, purchaser: @dude_chargedback, created_at: 1.hour.ago, price_cents: 200)
create(:purchase, link: product_2, seller: @creator, purchaser: @dude_chargedback, price_cents: 300)
@follower = create(:user, email: "follower@gum.co")
create(:follower, user: @creator, email: @follower.email, confirmed_at: Time.current)
workflow = create(:workflow, link: product, seller: @creator)
@direct_affiliate = create(:direct_affiliate, seller: @creator)
create(:product_affiliate, product:, affiliate: @direct_affiliate)
@audience_post = create(:audience_installment, name: "audience post shown", seller: @creator, published_at: Time.current, shown_on_profile: true)
create(:audience_installment, name: "hide me because not published", seller: @creator, shown_on_profile: true)
@audience_post_not_on_profile = create(:audience_installment, name: "hide me because shown_on_profile=false", seller: @creator, published_at: Time.current, shown_on_profile: false)
create(:audience_installment, name: "hide me because workflow update", workflow_id: workflow.id, seller: @creator, published_at: Time.current, shown_on_profile: true)
create(:audience_installment, name: "audience post from different seller", seller: create(:user), published_at: Time.current, shown_on_profile: true)
@seller_post = create(:seller_installment, name: "seller post shown", seller: @creator, published_at: 2.hours.ago, shown_on_profile: true)
@seller_post_with_filters = create(:seller_installment, name: "seller post with filters", seller: @creator, published_at: 2.hours.ago, shown_on_profile: true, json_data: { created_after: 1.month.ago, paid_more_than_cents: 100, paid_less_than_cents: 1000, bought_products: [product_2.unique_permalink], not_bought: [product_3.unique_permalink] })
create(:seller_installment, name: "hide seller post because unmet filters", seller: @creator, published_at: 2.hours.ago, shown_on_profile: true, json_data: { paid_more_than_cents: 1100, paid_less_than_cents: 2000 })
create(:seller_installment, name: "hide seller post 2 because unmet filters", seller: @creator, published_at: 2.hours.ago, shown_on_profile: true, json_data: { created_after: 1.month.ago, created_before: 1.week.ago })
create(:seller_installment, name: "hide seller post 3 because unmet filters", seller: @creator, published_at: 2.hours.ago, shown_on_profile: true, json_data: { created_after: 1.month.ago, paid_more_than_cents: 1500 })
create(:seller_installment, name: "hide seller post 4 because unmet filters", seller: @creator, published_at: 2.hours.ago, shown_on_profile: true, json_data: { created_before: 1.month.ago, paid_more_than_cents: 100, paid_less_than_cents: 1000 })
create(:seller_installment, name: "hide seller post 5 because unmet filters", seller: @creator, published_at: 2.hours.ago, shown_on_profile: true, json_data: { created_before: 1.month.ago, paid_more_than_cents: 100, paid_less_than_cents: 1000, bought_products: [product_2.unique_permalink], not_bought: [product_3.unique_permalink] })
create(:seller_installment, seller: @creator, name: "hide me because not published", shown_on_profile: true)
@seller_post_not_on_profile = create(:installment, installment_type: "seller", seller: @creator, name: "hide me because shown_on_profile=false", published_at: Time.current, shown_on_profile: false)
create(:seller_installment, seller: @creator, name: "hide me because workflow update", workflow_id: workflow.id, published_at: Time.current, shown_on_profile: true)
create(:seller_installment, seller: create(:user), name: "seller post from different seller", published_at: Time.current, shown_on_profile: true)
@product_post = create(:installment, link: product, name: "product post shown", published_at: Time.current, shown_on_profile: true)
create(:installment, link: product, name: "hide be because not published", shown_on_profile: true)
create(:installment, link: product, name: "hide me because published before purchase", published_at: 2.hours.ago, shown_on_profile: true)
@product_post_not_on_profile = create(:installment, link: product, name: "hide me because shown_on_profile=false", published_at: Time.current, shown_on_profile: false)
create(:installment, link: product, name: "hide me because workflow update", workflow_id: workflow.id, published_at: Time.current, shown_on_profile: true)
@product_post_2 = create(:installment, link: product_2, name: "product post 2 shown", published_at: Time.current, shown_on_profile: true)
create(:installment, link: create(:product), name: "product post from different seller's product", published_at: Time.current, shown_on_profile: true)
@membership_post = create(:installment, link: @membership, name: "membership post shown", published_at: 2.hours.ago, shown_on_profile: true)
create(:installment, link: @membership, name: "membership hidden because published after cancellation", published_at: 50.minutes.ago, shown_on_profile: true)
@membership_post_not_on_profile = create(:installment, link: @membership, name: "membership post hidden because shown_on_profile=false", published_at: 2.hours.ago, shown_on_profile: false)
create(:installment, link: @membership, name: "membership hidden because published after cancellation", published_at: 50.minutes.ago, shown_on_profile: false)
@follower_post = create(:follower_installment, seller: @creator, name: "follower post shown", published_at: 1.hour.ago, shown_on_profile: true)
@follower_post_with_filters = create(:follower_installment, seller: @creator, name: "follower post with filters shown", published_at: 1.hour.ago, shown_on_profile: true, json_data: { created_after: 1.week.ago })
create(:follower_installment, seller: @creator, name: "hide follower post with unmet filters", published_at: 1.hour.ago, shown_on_profile: true, json_data: { created_after: 1.week.ago, created_before: 1.day.ago })
create(:follower_installment, seller: @creator, name: "hide follower post 2 with unmet filters", published_at: 1.hour.ago, shown_on_profile: true, json_data: { created_before: 1.day.ago })
create(:follower_installment, seller: @creator, name: "hide be because not published", shown_on_profile: true)
@follower_post_not_on_profile = create(:follower_installment, seller: @creator, name: "hide be because shown_on_profile=false", published_at: Time.current, shown_on_profile: false)
create(:follower_installment, seller: @creator, name: "hide me because workflow update", workflow_id: workflow.id, published_at: Time.current, shown_on_profile: true)
create(:follower_installment, seller: create(:user), name: "follower post from different seller", published_at: Time.current, shown_on_profile: true)
@affiliate_post = create(:affiliate_installment, seller: @creator, name: "affiliate post", published_at: Time.current, json_data: { affiliate_products: [product.unique_permalink, product_2.unique_permalink], created_after: 1.week.ago })
create(:affiliate_installment, seller: @creator, name: "hide me affiliate post because unmet filters", published_at: Time.current, json_data: { affiliate_products: [product_2.unique_permalink] })
create(:affiliate_installment, seller: @creator, name: "hide me affiliate post 2 because unmet filters", published_at: Time.current, json_data: { created_before: 1.day.ago })
create(:affiliate_installment, seller: @creator, name: "hide me because not published")
create(:affiliate_installment, seller: @creator, name: "hide me because workflow update", workflow_id: workflow.id, published_at: Time.current)
end
describe "posts with shown_on_profile true" do
it "returns only audience posts that are shown on profile if logged_in_user is not present or is not a customer or follower" do
pundit_user = SellerContext.logged_out
visible_posts = @creator.visible_posts_for(pundit_user:)
expect(visible_posts).to contain_exactly(@audience_post)
user = create(:user)
pundit_user = SellerContext.new(user:, seller: user)
visible_posts = @creator.visible_posts_for(pundit_user:)
expect(visible_posts).to contain_exactly(@audience_post)
end
it "returns audience posts and posts from purchased products that are shown on profile when logged_in_user is a customer" do
pundit_user = SellerContext.new(user: @dude, seller: @dude)
visible_posts = @creator.visible_posts_for(pundit_user:)
expect(visible_posts).to contain_exactly(@audience_post,
@seller_post,
@seller_post_with_filters,
@product_post,
@product_post_2,
@membership_post)
end
it "returns audience posts and follower posts that are shown on profile when logged_in_user is a follower" do
pundit_user = SellerContext.new(user: @follower, seller: @follower)
visible_posts = @creator.visible_posts_for(pundit_user:)
expect(visible_posts).to contain_exactly(@audience_post,
@follower_post,
@follower_post_with_filters)
end
it "returns only audience posts that are shown on profile when logged_in_user is an affiliate" do
affiliate_user = @direct_affiliate.affiliate_user
pundit_user = SellerContext.new(user: affiliate_user, seller: affiliate_user)
visible_posts = @creator.visible_posts_for(pundit_user:)
expect(visible_posts.length).to eq 1
expect(visible_posts).to contain_exactly(@audience_post)
end
it "returns audience posts, seller posts, follower posts, and product/variant posts that are shown on profile from purchased products when logged_in_user is a follower and a customer" do
create(:follower, user: @creator, email: @dude.email, confirmed_at: Time.current)
pundit_user = SellerContext.new(user: @dude, seller: @dude)
visible_posts = @creator.visible_posts_for(pundit_user:)
expect(visible_posts).to contain_exactly(@audience_post,
@seller_post,
@seller_post_with_filters,
@product_post,
@product_post_2,
@follower_post,
@follower_post_with_filters,
@membership_post)
end
it "returns audience posts, seller posts, follower posts, and product/variant posts that are shown on profile from valid purchases when logged_in_user is a customer" do
pundit_user = SellerContext.new(user: @dude_chargedback, seller: @dude_chargedback)
visible_posts = @creator.visible_posts_for(pundit_user:)
expect(visible_posts).to contain_exactly(@audience_post,
@seller_post,
@seller_post_with_filters,
@product_post_2)
end
end
describe "all posts irrespective of shown_on_profile" do
it "returns only audience posts that are shown on profile if logged_in_user is not present or is not a customer or follower" do
pundit_user = SellerContext.logged_out
visible_posts = @creator.visible_posts_for(pundit_user:, shown_on_profile: false)
expect(visible_posts).to contain_exactly(@audience_post)
user = create(:user)
pundit_user = SellerContext.new(user:, seller: user)
visible_posts = @creator.visible_posts_for(pundit_user:, shown_on_profile: false)
expect(visible_posts).to contain_exactly(@audience_post)
end
it "returns all audience posts and posts from purchased products when logged_in_user is a customer" do
pundit_user = SellerContext.new(user: @dude, seller: @dude)
visible_posts = @creator.visible_posts_for(pundit_user:, shown_on_profile: false)
expect(visible_posts).to contain_exactly(@audience_post,
@audience_post_not_on_profile,
@seller_post,
@seller_post_with_filters,
@seller_post_not_on_profile,
@product_post,
@product_post_not_on_profile,
@product_post_2,
@membership_post,
@membership_post_not_on_profile)
end
it "returns audience posts and follower posts when logged_in_user is a follower" do
pundit_user = SellerContext.new(user: @follower, seller: @follower)
visible_posts = @creator.visible_posts_for(pundit_user:, shown_on_profile: false)
expect(visible_posts).to contain_exactly(@audience_post,
@audience_post_not_on_profile,
@follower_post,
@follower_post_with_filters,
@follower_post_not_on_profile)
end
it "returns audience posts and affiliate posts when logged_in_user is an affiliate" do
affiliate_user = @direct_affiliate.affiliate_user
pundit_user = SellerContext.new(user: affiliate_user, seller: affiliate_user)
visible_posts = @creator.visible_posts_for(pundit_user:, shown_on_profile: false)
expect(visible_posts).to contain_exactly(@audience_post,
@audience_post_not_on_profile,
@affiliate_post)
end
it "returns audience posts, seller posts, follower posts, and product/variant posts from purchased products when logged_in_user is a follower and a customer" do
create(:follower, user: @creator, email: @dude.email, confirmed_at: Time.current)
pundit_user = SellerContext.new(user: @dude, seller: @dude)
visible_posts = @creator.visible_posts_for(pundit_user:, shown_on_profile: false)
expect(visible_posts).to contain_exactly(@audience_post,
@audience_post_not_on_profile,
@seller_post,
@seller_post_with_filters,
@seller_post_not_on_profile,
@product_post,
@product_post_not_on_profile,
@product_post_2,
@follower_post,
@follower_post_with_filters,
@follower_post_not_on_profile,
@membership_post,
@membership_post_not_on_profile)
end
end
context "user has stopped and restarted subscription" do
it "does not return posts published while the subscription was stopped" do
membership_buyer = create(:user, username: "membershipbuyer")
membership_purchase = create(:membership_purchase, link: @membership, seller: @creator, purchaser: membership_buyer, price_cents: 500, created_at: 7.months.ago)
subscription = membership_purchase.subscription
membership_post_1 = create(:installment, link: @membership, name: "membership post 1", published_at: 6.months.ago, shown_on_profile: true)
create(:subscription_event, subscription:, event_type: :deactivated, occurred_at: 5.months.ago)
membership_post_2 = create(:installment, link: @membership, name: "membership post 2", published_at: 4.months.ago, shown_on_profile: true)
create(:subscription_event, subscription:, event_type: :restarted, occurred_at: 3.months.ago)
membership_post_3 = create(:installment, link: @membership, name: "membership post 3", published_at: 2.months.ago, shown_on_profile: true)
create(:subscription_event, subscription:, event_type: :deactivated, occurred_at: 1.month.ago)
membership_post_4 = create(:installment, link: @membership, name: "membership post 4", published_at: 2.weeks.ago, shown_on_profile: true)
pundit_user = SellerContext.new(user: membership_buyer, seller: membership_buyer)
visible_posts = @creator.visible_posts_for(pundit_user:, shown_on_profile: false)
expect(visible_posts).to include(membership_post_1, membership_post_3)
expect(visible_posts).not_to include(membership_post_2, membership_post_4)
end
end
end
describe "#last_5_created_posts" do
let(:seller) { create(:named_user) }
let(:product) { create(:product, user: seller) }
let!(:post_1) { create(:installment, link: product, published_at: 1.minute.ago, created_at: 3.hours.ago) }
let!(:post_2) { create(:installment, link: product, published_at: nil, created_at: 2.hours.ago) }
let!(:post_3) { create(:installment, link: product, deleted_at: 1.hour.ago, created_at: 1.hour.ago) }
it "includes deleted and not published posts" do
posts = seller.last_5_created_posts
expect(posts).to eq([post_3, post_2, post_1])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/payment_stats_spec.rb | spec/modules/user/payment_stats_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::Stats do
let(:user) { create(:user) }
let(:link) { create(:product, user:) }
describe "average_transaction_amount_cents" do
describe "no sales" do
it "returns zero" do
expect(user.average_transaction_amount_cents).to eq(0)
end
end
describe "many sales" do
before do
create(:purchase, link:, seller: link.user, price_cents: 1_00)
create(:purchase, link:, seller: link.user, price_cents: 2_00)
create(:purchase, link:, seller: link.user, price_cents: 3_00)
create(:purchase, link:, seller: link.user, price_cents: 4_00)
end
it "averages the transaction values" do
expect(user.average_transaction_amount_cents).to eq(2_50)
end
end
describe "many sales with a fractional average" do
before do
create(:purchase, link:, seller: link.user, price_cents: 1_00)
create(:purchase, link:, seller: link.user, price_cents: 2_00)
create(:purchase, link:, seller: link.user, price_cents: 3_00)
create(:purchase, link:, seller: link.user, price_cents: 4_00)
create(:purchase, link:, seller: link.user, price_cents: 3_00)
create(:purchase, link:, seller: link.user, price_cents: 1_00)
create(:purchase, link:, seller: link.user, price_cents: 1_00)
create(:purchase, link:, seller: link.user, price_cents: 6_00)
end
it "averages the transaction values and return an integer in cents" do
expect(user.average_transaction_amount_cents).to eq(2_62)
end
end
describe "many sales and some free" do
before do
create(:purchase, link:, seller: link.user, price_cents: 1_00)
create(:purchase, link:, seller: link.user, price_cents: 2_00)
create(:purchase, link:, seller: link.user, price_cents: 3_00)
create(:purchase, link:, seller: link.user, price_cents: 4_00)
create(:free_purchase, link:, seller: link.user)
end
it "averages the transaction values" do
expect(user.average_transaction_amount_cents).to eq(2_50)
end
end
describe "long time many sales" do
before do
travel_to(367.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 1_00)
end
create(:purchase, link:, seller: link.user, price_cents: 2_00)
create(:purchase, link:, seller: link.user, price_cents: 3_00)
create(:purchase, link:, seller: link.user, price_cents: 4_00)
create(:purchase, link:, seller: link.user, price_cents: 5_00)
end
it "sums up only the transaction values in the last year" do
expect(user.average_transaction_amount_cents).to eq(3_50)
end
end
end
describe "transaction_volume_in_the_last_year" do
before do
travel_to(367.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 1_00)
end
travel_to(300.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 2_00)
end
travel_to(200.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 3_00)
end
travel_to(100.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 4_00)
end
create(:purchase, link:, seller: link.user, price_cents: 5_00)
end
it "sums up only the transaction values in the last year" do
expect(user.transaction_volume_in_the_last_year).to eq(14_00)
end
end
describe "transaction_volume_since" do
before do
travel_to(367.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 1_00)
end
travel_to(300.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 2_00)
end
travel_to(200.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 3_00)
end
travel_to(100.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 4_00)
end
create(:purchase, link:, seller: link.user, price_cents: 5_00)
end
it "sums up only the transaction values in the period specified (6 months)" do
expect(user.transaction_volume_since(6.months.ago)).to eq(9_00)
end
it "sums up only the transaction values in the period specified (3 months)" do
expect(user.transaction_volume_since(3.months.ago)).to eq(5_00)
end
end
describe "projected_annual_transaction_volume" do
describe "no sales" do
it "returns zero" do
expect(user.projected_annual_transaction_volume).to eq(0)
end
end
describe "long time creator" do
before do
travel_to(367.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 1_00)
end
travel_to(300.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 2_00)
end
travel_to(200.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 3_00)
end
travel_to(100.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 4_00)
end
create(:purchase, link:, seller: link.user, price_cents: 5_00)
end
it "sums up only the transaction values in the period specified" do
expect(user.projected_annual_transaction_volume).to eq(14_00)
end
end
describe "recent creator" do
before do
travel_to(200.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 3_00)
end
travel_to(100.days.ago) do
create(:purchase, link:, seller: link.user, price_cents: 4_00)
end
create(:purchase, link:, seller: link.user, price_cents: 5_00)
end
it "sums up only the transaction values in the period specified" do
expect(user.projected_annual_transaction_volume).to eq(21_91)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/devise_internal_spec.rb | spec/modules/user/devise_internal_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::DeviseInternal do
before do
@user = create(:user, confirmed_at: nil)
end
describe "#confirmation_required?" do
it "returns true if email is required" do
allow(@user).to receive(:email_required?).and_return(true)
allow(@user).to receive(:platform_user?).and_return(false)
expect(@user.confirmation_required?).to be(true)
end
it "returns false if email is not required" do
allow(@user).to receive(:email_required?).and_return(false)
expect(@user.confirmation_required?).to be(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/compliance_spec.rb | spec/modules/user/compliance_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::Compliance do
describe "native_payouts_supported?" do
it "returns true for US, CA, AU, and UK creators" do
%w(US CA AU GB).each do |country_code|
creator = create(:user)
create(:user_compliance_info_empty, user: creator, country: ISO3166::Country[country_code].common_name)
expect(creator.native_payouts_supported?).to be true
end
end
it "returns true for creators from EU, HK, NZ, SG, and CH" do
country_codes = User::Compliance.european_countries.map(&:alpha2) + %w(HK NZ SG CH)
country_codes.each do |country_code|
creator = create(:user)
create(:user_compliance_info_empty, user: creator, country: ISO3166::Country[country_code].common_name)
expect(creator.native_payouts_supported?).to be true
end
end
it "returns true for creators from BG, DK, and HU" do
%w(BG DK HU).each do |country_code|
creator = create(:user)
create(:user_compliance_info_empty, user: creator, country: ISO3166::Country[country_code].common_name)
expect(creator.native_payouts_supported?).to be true
end
end
it "returns false for other countries" do
venezuela_user = create(:user)
create(:user_compliance_info_empty, user: venezuela_user, country: "Venezuela")
expect(venezuela_user.native_payouts_supported?).to be false
end
it "returns false for Kazakhstan (PayPal-only country)" do
kazakhstan_user = create(:user)
create(:user_compliance_info_empty, user: kazakhstan_user, country: "Kazakhstan")
expect(kazakhstan_user.native_payouts_supported?).to be false
end
it "accepts country_code as optional argument" do
jordan_user = create(:user)
create(:user_compliance_info_empty, user: jordan_user, country: "Jordan")
expect(jordan_user.native_payouts_supported?(country_code: "US")).to be true
expect(jordan_user.native_payouts_supported?(country_code: "RU")).to be false
end
end
describe "signed_up_from_united_states?" do
before do
@us_user = create(:user)
@user_compliance_info = create(:user_compliance_info_empty, user: @us_user,
first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca",
zip_code: "94107", country: "United States")
end
it "returns true if from the us" do
expect(@us_user.signed_up_from_united_states?).to be true
expect(@us_user.compliance_country_has_states?).to be true
end
end
describe "signed_up_from_canada?" do
before do
@can_user = create(:user)
@user_compliance_info = create(:user_compliance_info_empty, user: @can_user,
first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca",
zip_code: "94107", country: "Canada")
end
it "returns true if from canada" do
expect(@can_user.signed_up_from_canada?).to be true
expect(@can_user.compliance_country_has_states?).to be true
end
end
describe "signed_up_from_united_kingdom?" do
before do
@uk_user = create(:user)
@user_compliance_info = create(:user_compliance_info_empty, user: @uk_user,
first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca",
zip_code: "94107", country: "United Kingdom")
end
it "returns true if from united_kingdom" do
expect(@uk_user.signed_up_from_united_kingdom?).to be true
expect(@uk_user.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_australia?" do
it "returns true if from australia" do
au_creator = create(:user)
create(:user_compliance_info_empty, user: au_creator, country: "Australia")
expect(au_creator.signed_up_from_australia?).to be true
expect(au_creator.compliance_country_has_states?).to be true
end
end
describe "signed_up_from_hong_kong?" do
it "returns true if from hong kong" do
hk_creator = create(:user)
create(:user_compliance_info_empty, user: hk_creator, country: "Hong Kong")
expect(hk_creator.signed_up_from_hong_kong?).to be true
expect(hk_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_singapore?" do
it "returns true if from singapore" do
sg_creator = create(:user)
create(:user_compliance_info_empty, user: sg_creator, country: "Singapore")
expect(sg_creator.signed_up_from_singapore?).to be true
expect(sg_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_new_zealand?" do
it "returns true if from new zealand" do
nz_creator = create(:user)
create(:user_compliance_info_empty, user: nz_creator, country: "New Zealand")
expect(nz_creator.signed_up_from_new_zealand?).to be true
expect(nz_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_switzerland?" do
it "returns true if from switzerland" do
ch_creator = create(:user)
create(:user_compliance_info_empty, user: ch_creator, country: "Switzerland")
expect(ch_creator.signed_up_from_switzerland?).to be true
expect(ch_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_bulgaria?" do
it "returns true if from bulgaria" do
bg_creator = create(:user)
create(:user_compliance_info_empty, user: bg_creator, country: "Bulgaria")
expect(bg_creator.signed_up_from_bulgaria?).to be true
expect(bg_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_denmark?" do
it "returns true if from denmark" do
dk_creator = create(:user)
create(:user_compliance_info_empty, user: dk_creator, country: "Denmark")
expect(dk_creator.signed_up_from_denmark?).to be true
expect(dk_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_czechia?" do
it "returns true if from Czech Republic" do
cz_creator = create(:user)
create(:user_compliance_info_empty, user: cz_creator, country: "Czech Republic")
expect(cz_creator.signed_up_from_czechia?).to be true
expect(cz_creator.compliance_country_has_states?).to be false
end
it "returns true if from Czechia" do
cz_creator = create(:user)
create(:user_compliance_info_empty, user: cz_creator, country: "Czechia")
expect(cz_creator.signed_up_from_czechia?).to be true
expect(cz_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_bulgaria?" do
it "returns true if from hungary" do
hu_creator = create(:user)
create(:user_compliance_info_empty, user: hu_creator, country: "Hungary")
expect(hu_creator.signed_up_from_hungary?).to be true
expect(hu_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_south_korea?" do
it "returns true if from Korea, Republic of" do
kr_creator = create(:user)
create(:user_compliance_info_empty, user: kr_creator, country: "Korea, Republic of")
expect(kr_creator.signed_up_from_south_korea?).to be true
expect(kr_creator.compliance_country_has_states?).to be false
end
it "returns true if from South Korea" do
kr_creator = create(:user)
create(:user_compliance_info_empty, user: kr_creator, country: "South Korea")
expect(kr_creator.signed_up_from_south_korea?).to be true
expect(kr_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_united_arab_emirates?" do
it "returns true if from uae" do
uae_creator = create(:user)
create(:user_compliance_info_empty, user: uae_creator, country: "United Arab Emirates")
expect(uae_creator.signed_up_from_united_arab_emirates?).to be true
expect(uae_creator.compliance_country_has_states?).to be true
end
end
describe "signed_up_from_israel?" do
it "returns true if from israel" do
il_creator = create(:user)
create(:user_compliance_info_empty, user: il_creator, country: "Israel")
expect(il_creator.signed_up_from_israel?).to be true
expect(il_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_trinidad_and_tobago?" do
it "returns true if from trinidad and tobago" do
tt_creator = create(:user)
create(:user_compliance_info_empty, user: tt_creator, country: "Trinidad and Tobago")
expect(tt_creator.signed_up_from_trinidad_and_tobago?).to be true
expect(tt_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_philippines?" do
it "returns true if from philippines" do
ph_creator = create(:user)
create(:user_compliance_info_empty, user: ph_creator, country: "Philippines")
expect(ph_creator.signed_up_from_philippines?).to be true
expect(ph_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_argentina?" do
it "returns true if from argentina" do
ar_creator = create(:user)
create(:user_compliance_info_empty, user: ar_creator, country: "Argentina")
expect(ar_creator.signed_up_from_argentina?).to be true
expect(ar_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_peru?" do
it "returns true if from peru" do
pe_creator = create(:user)
create(:user_compliance_info_empty, user: pe_creator, country: "Peru")
expect(pe_creator.signed_up_from_peru?).to be true
expect(pe_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_europe?" do
it "returns true if from one of the listed EU countries else false" do
User::Compliance.european_countries.each do |eu_country|
eu_creator = create(:user)
create(:user_compliance_info_empty, user: eu_creator, country: eu_country.common_name)
expect(eu_creator.signed_up_from_europe?).to be true
end
%w(US CA AU GB HK NZ SG CH IN).each do |non_eu_country_code|
non_eu_creator = create(:user)
create(:user_compliance_info_empty, user: non_eu_creator,
country: ISO3166::Country[non_eu_country_code].common_name)
expect(non_eu_creator.signed_up_from_europe?).to be false
end
end
end
describe "signed_up_from_romania?" do
it "returns true if from romania" do
creator = create(:user)
create(:user_compliance_info_empty, user: creator, country: "Romania")
expect(creator.signed_up_from_romania?).to be true
expect(creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_sweden?" do
it "returns true if from sweden" do
creator = create(:user)
create(:user_compliance_info_empty, user: creator, country: "Sweden")
expect(creator.signed_up_from_sweden?).to be true
expect(creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_mexico?" do
it "returns true if from mexico" do
creator = create(:user)
create(:user_compliance_info_empty, user: creator, country: "Mexico")
expect(creator.signed_up_from_mexico?).to be true
expect(creator.compliance_country_has_states?).to be true
end
end
describe "signed_up_from_india?" do
it "returns true if from India" do
in_creator = create(:user)
create(:user_compliance_info_empty, user: in_creator, country: "India")
expect(in_creator.signed_up_from_india?).to be true
expect(in_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_pakistan?" do
it "returns true if from Pakistan" do
pk_creator = create(:user)
create(:user_compliance_info_empty, user: pk_creator, country: "Pakistan")
expect(pk_creator.signed_up_from_pakistan?).to be true
expect(pk_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_turkiye?" do
it "returns true if from Turkey" do
tr_creator = create(:user)
create(:user_compliance_info_empty, user: tr_creator, country: "Türkiye")
expect(tr_creator.signed_up_from_turkiye?).to be true
expect(tr_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_south_africa?" do
it "returns true if from South Africa" do
za_creator = create(:user)
create(:user_compliance_info_empty, user: za_creator, country: "South Africa")
expect(za_creator.signed_up_from_south_africa?).to be true
expect(za_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_kenya?" do
it "returns true if from Kenya" do
ke_creator = create(:user)
create(:user_compliance_info_empty, user: ke_creator, country: "Kenya")
expect(ke_creator.signed_up_from_kenya?).to be true
expect(ke_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_egypt?" do
it "returns true if from Egypt" do
eg_creator = create(:user)
create(:user_compliance_info_empty, user: eg_creator, country: "Egypt")
expect(eg_creator.signed_up_from_egypt?).to be true
expect(eg_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_colombia?" do
it "returns true if from Colombia" do
co_creator = create(:user)
create(:user_compliance_info_empty, user: co_creator, country: "Colombia")
expect(co_creator.signed_up_from_colombia?).to be true
expect(co_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_saudi_arabia?" do
it "returns true if from Saudi Arabia" do
sa_creator = create(:user)
create(:user_compliance_info_empty, user: sa_creator, country: "Saudi Arabia")
expect(sa_creator.signed_up_from_saudi_arabia?).to be true
expect(sa_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_angola?" do
it "returns true if from Angola" do
ao_creator = create(:user)
create(:user_compliance_info_empty, user: ao_creator, country: "Angola")
expect(ao_creator.signed_up_from_angola?).to be true
expect(ao_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_niger?" do
it "returns true if from Niger" do
ne_creator = create(:user)
create(:user_compliance_info_empty, user: ne_creator, country: "Niger")
expect(ne_creator.signed_up_from_niger?).to be true
expect(ne_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_san_marino?" do
it "returns true if from San Marino" do
sm_creator = create(:user)
create(:user_compliance_info_empty, user: sm_creator, country: "San Marino")
expect(sm_creator.signed_up_from_san_marino?).to be true
expect(sm_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_uruguay?" do
it "returns true if from Uruguay" do
uy_creator = create(:user)
create(:user_compliance_info_empty, user: uy_creator, country: "Uruguay")
expect(uy_creator.signed_up_from_uruguay?).to be true
expect(uy_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_botswana?" do
it "returns true if from Botswana" do
bw_creator = create(:user)
create(:user_compliance_info_empty, user: bw_creator, country: "Botswana")
expect(bw_creator.signed_up_from_botswana?).to be true
expect(bw_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_mauritius?" do
it "returns true if from Mauritius" do
mu_creator = create(:user)
create(:user_compliance_info_empty, user: mu_creator, country: "Mauritius")
expect(mu_creator.signed_up_from_mauritius?).to be true
expect(mu_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_jamaica?" do
it "returns true if from Jamaica" do
jm_creator = create(:user)
create(:user_compliance_info_empty, user: jm_creator, country: "Jamaica")
expect(jm_creator.signed_up_from_jamaica?).to be true
expect(jm_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_antigua_and_barbuda?" do
it "returns true if from Antigua and Barbuda" do
ag_creator = create(:user)
create(:user_compliance_info_empty, user: ag_creator, country: "Antigua and Barbuda")
expect(ag_creator.signed_up_from_antigua_and_barbuda?).to be true
expect(ag_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_namibia?" do
it "returns true if from Namibia" do
na_creator = create(:user)
create(:user_compliance_info_empty, user: na_creator, country: "Namibia")
expect(na_creator.signed_up_from_namibia?).to be true
expect(na_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_tanzania?" do
it "returns true if from Tanzania" do
tz_creator = create(:user)
create(:user_compliance_info_empty, user: tz_creator, country: "Tanzania")
expect(tz_creator.signed_up_from_tanzania?).to be true
expect(tz_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_rwanda?" do
it "returns true if from Rwanda" do
rw_creator = create(:user)
create(:user_compliance_info_empty, user: rw_creator, country: "Rwanda")
expect(rw_creator.signed_up_from_rwanda?).to be true
expect(rw_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_bangladesh?" do
it "returns true if from Bangladesh" do
bd_creator = create(:user)
create(:user_compliance_info_empty, user: bd_creator, country: "Bangladesh")
expect(bd_creator.signed_up_from_bangladesh?).to be true
expect(bd_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_bhutan?" do
it "returns true if from Bhutan" do
bt_creator = create(:user)
create(:user_compliance_info_empty, user: bt_creator, country: "Bhutan")
expect(bt_creator.signed_up_from_bhutan?).to be true
expect(bt_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_lao_people_s_democratic_republic?" do
it "returns true if from Lao People's Democratic Republic" do
la_creator = create(:user)
create(:user_compliance_info_empty, user: la_creator, country: "Lao People's Democratic Republic")
expect(la_creator.signed_up_from_lao_people_s_democratic_republic?).to be true
expect(la_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_mozambique?" do
it "returns true if from Mozambique" do
mz_creator = create(:user)
create(:user_compliance_info_empty, user: mz_creator, country: "Mozambique")
expect(mz_creator.signed_up_from_mozambique?).to be true
expect(mz_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_ethiopia?" do
it "returns true if from Ethiopia" do
et_creator = create(:user)
create(:user_compliance_info_empty, user: et_creator, country: "Ethiopia")
expect(et_creator.signed_up_from_ethiopia?).to be true
expect(et_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_brunei_darussalam?" do
it "returns true if from Brunei Darussalam" do
bn_creator = create(:user)
create(:user_compliance_info_empty, user: bn_creator, country: "Brunei Darussalam")
expect(bn_creator.signed_up_from_brunei_darussalam?).to be true
expect(bn_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_guyana?" do
it "returns true if from Guyana" do
gy_creator = create(:user)
create(:user_compliance_info_empty, user: gy_creator, country: "Guyana")
expect(gy_creator.signed_up_from_guyana?).to be true
expect(gy_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_guatemala?" do
it "returns true if from Guatemala" do
gt_creator = create(:user)
create(:user_compliance_info_empty, user: gt_creator, country: "Guatemala")
expect(gt_creator.signed_up_from_guatemala?).to be true
expect(gt_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_ecuador?" do
it "returns true if from Ecuador" do
ec_creator = create(:user)
create(:user_compliance_info_empty, user: ec_creator, country: "Ecuador")
expect(ec_creator.signed_up_from_ecuador?).to be true
expect(ec_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_ghana?" do
it "returns true if from Ghana" do
gh_creator = create(:user)
create(:user_compliance_info_empty, user: gh_creator, country: "Ghana")
expect(gh_creator.signed_up_from_ghana?).to be true
expect(gh_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_oman?" do
it "returns true if from Oman" do
om_creator = create(:user)
create(:user_compliance_info_empty, user: om_creator, country: "Oman")
expect(om_creator.signed_up_from_oman?).to be true
expect(om_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_armenia?" do
it "returns true if from Armenia" do
am_creator = create(:user)
create(:user_compliance_info_empty, user: am_creator, country: "Armenia")
expect(am_creator.signed_up_from_armenia?).to be true
expect(am_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_sri_lanka?" do
it "returns true if from Sri Lanka" do
lk_creator = create(:user)
create(:user_compliance_info_empty, user: lk_creator, country: "Sri Lanka")
expect(lk_creator.signed_up_from_sri_lanka?).to be true
expect(lk_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_kuwait?" do
it "returns true if from Kuwait" do
kw_creator = create(:user)
create(:user_compliance_info_empty, user: kw_creator, country: "Kuwait")
expect(kw_creator.signed_up_from_kuwait?).to be true
expect(kw_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_dominican_republic?" do
it "returns true if from Dominican Republic" do
do_creator = create(:user)
create(:user_compliance_info_empty, user: do_creator, country: "Dominican Republic")
expect(do_creator.signed_up_from_dominican_republic?).to be true
expect(do_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_uzbekistan?" do
it "returns true if from Uzbekistan" do
uz_creator = create(:user)
create(:user_compliance_info_empty, user: uz_creator, country: "Uzbekistan")
expect(uz_creator.signed_up_from_uzbekistan?).to be true
expect(uz_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_bolivia?" do
it "returns true if from Bolivia" do
bo_creator = create(:user)
create(:user_compliance_info_empty, user: bo_creator, country: "Bolivia")
expect(bo_creator.signed_up_from_bolivia?).to be true
expect(bo_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_moldova?" do
it "returns true if from Moldova" do
md_creator = create(:user)
create(:user_compliance_info_empty, user: md_creator, country: "Moldova")
expect(md_creator.signed_up_from_moldova?).to be true
expect(md_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_panama?" do
it "returns true if from Panama" do
pa_creator = create(:user)
create(:user_compliance_info_empty, user: pa_creator, country: "Panama")
expect(pa_creator.signed_up_from_panama?).to be true
expect(pa_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_el_salvador?" do
it "returns true if from El Salvador" do
sv_creator = create(:user)
create(:user_compliance_info_empty, user: sv_creator, country: "El Salvador")
expect(sv_creator.signed_up_from_el_salvador?).to be true
expect(sv_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_paraguay?" do
it "returns true if from Paraguay" do
py_creator = create(:user)
create(:user_compliance_info_empty, user: py_creator, country: "Paraguay")
expect(py_creator.signed_up_from_paraguay?).to be true
expect(py_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_iceland?" do
it "returns true if from Iceland" do
is_creator = create(:user)
create(:user_compliance_info_empty, user: is_creator, country: "Iceland")
expect(is_creator.signed_up_from_iceland?).to be true
expect(is_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_qatar?" do
it "returns true if from Qatar" do
qa_creator = create(:user)
create(:user_compliance_info_empty, user: qa_creator, country: "Qatar")
expect(qa_creator.signed_up_from_qatar?).to be true
expect(qa_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_bahamas?" do
it "returns true if from Bahamas" do
bs_creator = create(:user)
create(:user_compliance_info_empty, user: bs_creator, country: "Bahamas")
expect(bs_creator.signed_up_from_bahamas?).to be true
expect(bs_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_saint_lucia?" do
it "returns true if from Saint Lucia" do
lc_creator = create(:user)
create(:user_compliance_info_empty, user: lc_creator, country: "Saint Lucia")
expect(lc_creator.signed_up_from_saint_lucia?).to be true
expect(lc_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_cambodia?" do
it "returns true if from Cambodia" do
kh_creator = create(:user)
create(:user_compliance_info_empty, user: kh_creator, country: "Cambodia")
expect(kh_creator.signed_up_from_cambodia?).to be true
expect(kh_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_mongolia?" do
it "returns true if from Mongolia" do
mn_creator = create(:user)
create(:user_compliance_info_empty, user: mn_creator, country: "Mongolia")
expect(mn_creator.signed_up_from_mongolia?).to be true
expect(mn_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_algeria?" do
it "returns true if from Algeria" do
al_creator = create(:user)
create(:user_compliance_info_empty, user: al_creator, country: "Algeria")
expect(al_creator.signed_up_from_algeria?).to be true
expect(al_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_macao?" do
it "returns true if from Macao" do
mo_creator = create(:user)
create(:user_compliance_info_empty, user: mo_creator, country: "Macao")
expect(mo_creator.signed_up_from_macao?).to be true
expect(mo_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_benin?" do
it "returns true if from Benin" do
bj_creator = create(:user)
create(:user_compliance_info_empty, user: bj_creator, country: "Benin")
expect(bj_creator.signed_up_from_benin?).to be true
expect(bj_creator.compliance_country_has_states?).to be false
end
end
describe "signed_up_from_cote_d_ivoire?" do
it "returns true if from Cote d'Ivoire" do
ci_creator = create(:user)
create(:user_compliance_info_empty, user: ci_creator, country: "Cote d'Ivoire")
expect(ci_creator.signed_up_from_cote_d_ivoire?).to be true
expect(ci_creator.compliance_country_has_states?).to be false
end
end
describe "compliance_country_code" do
describe "user with an alive compliance info" do
before do
@uk_user = create(:user)
@user_compliance_info = create(:user_compliance_info_empty, user: @uk_user,
first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca",
zip_code: "94107", country: "United Kingdom")
create(:user_compliance_info_empty, user: @uk_user,
first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca",
zip_code: "94107", country: "Ireland", deleted_at: Time.current)
end
it "returns the country code of the currently active user compliance record" do
expect(@uk_user.compliance_country_code).to eq(Compliance::Countries::GBR.alpha2)
end
end
describe "user with no (alive) compliance info" do
before do
@uk_user = create(:user)
@user_compliance_info = create(:user_compliance_info_empty, user: @uk_user,
first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca",
zip_code: "94107", country: "Ireland", deleted_at: Time.current)
end
it "returns the country code of the currently active user compliance record" do
expect(@uk_user.compliance_country_code).to be(nil)
end
end
describe "user with no compliance info" do
before do
@user = create(:user)
end
it "returns nil" do
expect(@user.compliance_country_code).to be(nil)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/social_twitter_spec.rb | spec/modules/user/social_twitter_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::SocialTwitter do
describe "#twitter_picture_url", :vcr do
before do
data = JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/twitter_omniauth.json").read)["extra"]["raw_info"]
@user = create(:user, twitter_user_id: data["id"])
end
it "stores the user's profile picture from twitter to S3 and returns the URL for the saved file" do
twitter_user = double(profile_image_url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/kFDzu.png")
expect($twitter).to receive(:user).and_return(twitter_user)
twitter_picture_url = @user.twitter_picture_url
expect(twitter_picture_url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{@user.avatar_variant.key}")
picture_response = HTTParty.get(twitter_picture_url)
expect(picture_response.content_type).to eq("image/png")
expect(picture_response.success?).to eq(true)
end
end
describe "query_twitter" do
before(:all) do
@data = JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/twitter_omniauth.json").read)["extra"]["raw_info"]
end
describe "already has username" do
it "does not set username", :vcr do
@user = create(:user, username: "squid")
expect { User.query_twitter(@user, @data) }.to_not change { @user.reload.username }
end
end
describe "already has bio" do
it "does not set bio", :vcr do
@user = create(:user, bio: "hi im squid")
expect { User.query_twitter(@user, @data) }.to_not change { @user.reload.bio }
end
end
describe "already has name" do
it "does not set bio", :vcr do
@user = create(:user, name: "sid")
expect { User.query_twitter(@user, @data) }.to_not change { @user.reload.name }
end
end
describe "no existing information" do
before do
@user = create(:user, name: nil, username: nil, bio: nil)
end
it "sets the username", :vcr do
expect { User.query_twitter(@user, @data) }.to change { @user.reload.username }.to(@data["screen_name"])
end
it "sets the bio", :vcr do
expect { User.query_twitter(@user, @data) }.to change { @user.reload.bio }.from(nil).to(
"formerly @columbia, now @gumroad gumroad.com"
)
end
it "sets the name", :vcr do
expect { User.query_twitter(@user, @data) }.to change { @user.reload.name }.from(nil).to(@data["name"])
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/feature_status_spec.rb | spec/modules/user/feature_status_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::FeatureStatus do
describe "#merchant_migration_enabled?" do
it "returns true if either feature flag is enabled of else false" do
creator = create(:user)
create(:user_compliance_info, user: creator)
expect(creator.merchant_migration_enabled?).to eq false
creator.check_merchant_account_is_linked = true
creator.save!
expect(creator.reload.merchant_migration_enabled?).to eq true
creator.check_merchant_account_is_linked = false
creator.save!
expect(creator.merchant_migration_enabled?).to eq false
Feature.activate_user(:merchant_migration, creator)
expect(creator.merchant_migration_enabled?).to eq true
end
it "returns false if user country is not supported by Stripe Connect" do
creator = create(:user)
create(:user_compliance_info, user: creator, country: "India")
expect(creator.merchant_migration_enabled?).to eq false
Feature.activate_user(:merchant_migration, creator)
expect(creator.merchant_migration_enabled?).to eq false
creator.check_merchant_account_is_linked = true
creator.save!
expect(creator.merchant_migration_enabled?).to eq true
end
end
describe "#charge_paypal_payout_fee?" do
let!(:seller) { create(:user) }
before do
create(:user_compliance_info, user: seller)
end
it "returns true if feature flag is set and user is not from Brazil or India and user should be charged fee" do
expect(seller.charge_paypal_payout_fee?).to be true
end
it "returns false if paypal_payout_fee feature flag is disabled" do
expect(seller.charge_paypal_payout_fee?).to be true
Feature.deactivate(:paypal_payout_fee)
expect(seller.charge_paypal_payout_fee?).to be false
end
it "returns false if paypal_payout_fee_waived flag is set of the user" do
expect(seller.reload.charge_paypal_payout_fee?).to be true
seller.update!(paypal_payout_fee_waived: true)
expect(seller.reload.charge_paypal_payout_fee?).to be false
end
it "returns false if user is from Brazil or India" do
expect(seller.charge_paypal_payout_fee?).to be true
seller.alive_user_compliance_info.mark_deleted!
create(:user_compliance_info, user: seller, country: "Brazil")
expect(seller.reload.charge_paypal_payout_fee?).to be false
seller.alive_user_compliance_info.mark_deleted!
create(:user_compliance_info, user: seller, country: "India")
expect(seller.reload.charge_paypal_payout_fee?).to be false
seller.alive_user_compliance_info.mark_deleted!
create(:user_compliance_info, user: seller, country: "Vietnam")
expect(seller.reload.charge_paypal_payout_fee?).to be true
end
end
describe "#has_stripe_account_connected?" do
it "returns true if there is a connected Stripe account and merchant migration flag is enabled" do
creator = create(:user)
create(:user_compliance_info, user: creator)
merchant_account = create(:merchant_account_stripe_connect, user: creator)
creator.check_merchant_account_is_linked = true
creator.save!
expect(creator.reload.merchant_migration_enabled?).to eq true
expect(creator.stripe_connect_account).to eq(merchant_account)
expect(creator.has_stripe_account_connected?).to eq true
end
it "returns false if there is a connected Stripe account but merchant migration flag is not enabled" do
creator = create(:user)
create(:user_compliance_info, user: creator)
merchant_account = create(:merchant_account_stripe_connect, user: creator)
expect(creator.reload.merchant_migration_enabled?).to eq false
expect(creator.stripe_connect_account).to eq(merchant_account)
expect(creator.has_stripe_account_connected?).to eq false
end
it "returns false if there is no connected Stripe account" do
creator = create(:user)
create(:user_compliance_info, user: creator)
Feature.activate_user(:merchant_migration, creator)
expect(creator.reload.merchant_migration_enabled?).to eq true
expect(creator.stripe_connect_account).to be nil
expect(creator.has_stripe_account_connected?).to eq false
end
end
describe "#has_paypal_account_connected?" do
it "returns true if there is a connected PayPal account otherwise returns false" do
creator = create(:user)
create(:user_compliance_info, user: creator)
expect(creator.has_paypal_account_connected?).to eq false
merchant_account = create(:merchant_account_paypal, user: creator)
expect(creator.paypal_connect_account).to eq(merchant_account)
expect(creator.has_paypal_account_connected?).to eq true
end
end
describe "#can_publish_products?" do
let(:seller) { create(:compliant_user, payment_address: nil) }
before do
create(:user_compliance_info, user: seller)
end
it "returns false if no payout method is setup" do
expect(seller.can_publish_products?).to be false
end
it "returns true if a bank account is setup", :vcr do
create(:merchant_account_stripe, user: seller)
expect(seller.can_publish_products?).to be true
end
it "returns true if a PayPal account is connected" do
create(:merchant_account_paypal, user: seller)
expect(seller.can_publish_products?).to be true
end
it "returns true if a Stripe account is connected" do
create(:merchant_account_stripe_connect, user: seller)
expect(seller.can_publish_products?).to be true
end
it "returns true if a PayPal payment address is present" do
seller.update!(payment_address: "payme@example.com")
expect(seller.can_publish_products?).to be true
end
it "returns true if user is admin team member without any payment methods" do
seller.update!(is_team_member: true)
expect(seller.can_publish_products?).to be true
end
end
describe "can_setup_bank_payouts?" do
it "returns true if country is in Stripe supported list" do
User::Compliance.const_get(:SUPPORTED_COUNTRIES).each do |country|
seller = create(:user)
create(:user_compliance_info, user: seller, country: country.common_name)
expect(seller.can_setup_bank_payouts?).to be true
end
end
it "returns true if user has an active bank account" do
seller = create(:user)
create(:ach_account_stripe_succeed, user: seller)
expect(seller.can_setup_bank_payouts?).to be true
end
it "returns false if country is not in Stripe supported list and there's no active bank account" do
seller = create(:user)
create(:user_compliance_info, user: seller, country: "Brazil")
expect(seller.can_setup_bank_payouts?).to be false
end
it "returns true if user is from UAE" do
seller = create(:user)
create(:user_compliance_info, user: seller, country: "United Arab Emirates")
expect(seller.can_setup_bank_payouts?).to be true
end
end
describe "can_setup_paypal_payouts?" do
it "returns true if user already has a payment address set" do
seller = create(:user, payment_address: "paypal@example.com")
create(:user_compliance_info, user: seller, country: "United States")
expect(seller.can_setup_paypal_payouts?).to be true
end
it "returns true if country is not in Stripe supported list" do
seller = create(:user, payment_address: nil)
create(:user_compliance_info, user: seller, country: "Brazil")
expect(seller.can_setup_paypal_payouts?).to be true
end
it "returns true if user is from UAE" do
seller = create(:user, payment_address: nil)
create(:user_compliance_info, user: seller, country: "United Arab Emirates")
expect(seller.can_setup_paypal_payouts?).to be true
end
it "returns true if user is from Egypt" do
seller = create(:user, payment_address: nil)
create(:user_compliance_info, user: seller, country: "Egypt")
expect(seller.can_setup_paypal_payouts?).to be true
end
it "returns false for all Stripe supported countries except UAE and Egypt" do
(User::Compliance.const_get(:SUPPORTED_COUNTRIES) - [Compliance::Countries::ARE, Compliance::Countries::EGY]).each do |country|
seller = create(:user, payment_address: nil)
create(:user_compliance_info, user: seller, country: country.common_name)
expect(seller.can_setup_paypal_payouts?).to be false
end
end
end
describe "#paypal_connect_allowed?" do
let!(:seller) { create(:user) }
before do
seller.mark_compliant!(author_name: "Iffy")
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(100_00)
create(:payment_completed, user: seller)
end
it "returns true if seller is compliant and has more than $100 in sales and a successful payout" do
expect(seller.paypal_connect_allowed?).to eq true
end
it "returns false if seller is not compliant" do
seller.update!(user_risk_state: "not_reviewed")
expect(seller.reload.paypal_connect_allowed?).to eq false
end
it "returns false if seller does not have $100 in sales" do
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(99_00)
expect(seller.reload.paypal_connect_allowed?).to eq false
end
it "returns false if seller does not have a successful payout" do
seller.payments.last.update!(state: "failed")
expect(seller.reload.paypal_connect_allowed?).to eq false
end
it "returns false if seller does not meet any eligibility requirement" do
seller.update!(user_risk_state: "not_reviewed")
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(99_00)
seller.payments.last.update!(state: "failed")
expect(seller.reload.paypal_connect_allowed?).to eq false
end
end
describe "#stripe_disconnect_allowed?" do
it "returns true if there is no connected Stripe account" do
creator = create(:user)
create(:user_compliance_info, user: creator)
expect(creator.merchant_migration_enabled?).to eq false
expect(creator.has_stripe_account_connected?).to eq false
expect(creator.stripe_disconnect_allowed?).to eq true
end
it "returns true if there is a connected Stripe account but no active subscriptions using it" do
creator = create(:user)
create(:user_compliance_info, user: creator)
merchant_account = create(:merchant_account_stripe_connect, user: creator)
creator.check_merchant_account_is_linked = true
creator.save!
expect_any_instance_of(User).to receive(:active_subscribers?).with(charge_processor_id: StripeChargeProcessor.charge_processor_id,
merchant_account:).and_return false
expect(creator.reload.merchant_migration_enabled?).to eq true
expect(creator.has_stripe_account_connected?).to eq true
expect(creator.stripe_disconnect_allowed?).to eq true
end
it "returns false if there is a connected Stripe account and active subscriptions use it" do
creator = create(:user)
create(:user_compliance_info, user: creator)
merchant_account = create(:merchant_account_stripe_connect, user: creator)
creator.check_merchant_account_is_linked = true
creator.save!
expect_any_instance_of(User).to receive(:active_subscribers?).with(charge_processor_id: StripeChargeProcessor.charge_processor_id,
merchant_account:).and_return true
expect(creator.reload.merchant_migration_enabled?).to eq true
expect(creator.has_stripe_account_connected?).to eq true
expect(creator.stripe_disconnect_allowed?).to eq false
end
end
describe "#product_level_support_emails_enabled?" do
let(:user) { create(:user) }
it "returns true if product_level_support_emails feature flag is enabled for user" do
Feature.activate_user(:product_level_support_emails, user)
expect(user.product_level_support_emails_enabled?).to eq true
Feature.deactivate_user(:product_level_support_emails, user)
expect(user.product_level_support_emails_enabled?).to eq false
Feature.activate(:product_level_support_emails)
expect(user.product_level_support_emails_enabled?).to eq true
Feature.deactivate(:product_level_support_emails)
expect(user.product_level_support_emails_enabled?).to eq false
end
end
describe "#waive_gumroad_fee_on_new_sales?" do
it "returns true if waive_gumroad_fee_on_new_sales feature flag is set for seller" do
seller = create(:user)
Feature.activate_user(:waive_gumroad_fee_on_new_sales, seller)
expect($redis.get(RedisKey.gumroad_day_date)).to be nil
expect(seller.waive_gumroad_fee_on_new_sales?).to eq true
end
it "returns true if today is Gumroad day in seller's timezone" do
seller = create(:user)
$redis.set(RedisKey.gumroad_day_date, Time.now.in_time_zone(seller.timezone).to_date.to_s)
expect(Feature.active?(:waive_gumroad_fee_on_new_sales, seller)).to be false
expect(seller.waive_gumroad_fee_on_new_sales?).to be true
end
it "returns false if today is not Gumroad day and feature flag is not set for seller" do
seller = create(:user)
expect($redis.get(RedisKey.gumroad_day_date)).to be nil
expect(Feature.active?(:waive_gumroad_fee_on_new_sales, seller)).to be false
expect(seller.waive_gumroad_fee_on_new_sales?).to be false
end
it "returns false if today is Gumroad day in some other timezone but not in seller's timezone" do
$redis.set(RedisKey.gumroad_day_date, "2024-4-4")
seller_in_act = create(:user, timezone: "Melbourne")
seller_in_utc = create(:user, timezone: "UTC")
seller_in_pst = create(:user, timezone: "Pacific Time (US & Canada)")
gumroad_day = Date.new(2024, 4, 4)
gumroad_day_in_act = gumroad_day.in_time_zone("Melbourne")
gumroad_day_in_utc = gumroad_day.in_time_zone("UTC")
gumroad_day_in_pst = gumroad_day.in_time_zone("Pacific Time (US & Canada)")
travel_to(gumroad_day_in_act.beginning_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_utc.waive_gumroad_fee_on_new_sales?).to be false
expect(seller_in_pst.waive_gumroad_fee_on_new_sales?).to be false
end
travel_to(gumroad_day_in_utc.beginning_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_utc.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_pst.waive_gumroad_fee_on_new_sales?).to be false
end
travel_to(gumroad_day_in_pst.beginning_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_utc.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_pst.waive_gumroad_fee_on_new_sales?).to be true
end
travel_to(gumroad_day_in_act.end_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_utc.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_pst.waive_gumroad_fee_on_new_sales?).to be true
end
travel_to(gumroad_day_in_utc.end_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be false
expect(seller_in_utc.waive_gumroad_fee_on_new_sales?).to be true
expect(seller_in_pst.waive_gumroad_fee_on_new_sales?).to be true
end
travel_to(gumroad_day_in_pst.end_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be false
expect(seller_in_utc.waive_gumroad_fee_on_new_sales?).to be false
expect(seller_in_pst.waive_gumroad_fee_on_new_sales?).to be true
end
end
it "uses seller's gumroad_day_timezone when present to check if it is Gumroad Day" do
$redis.set(RedisKey.gumroad_day_date, "2024-4-4")
gumroad_day = Date.new(2024, 4, 4)
gumroad_day_in_act = gumroad_day.in_time_zone("Melbourne")
gumroad_day_in_pst = gumroad_day.in_time_zone("Pacific Time (US & Canada)")
seller_in_act = create(:user, timezone: "Melbourne")
travel_to(gumroad_day_in_act.beginning_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be true
end
seller_in_act.update!(timezone: "Pacific Time (US & Canada)")
travel_to(gumroad_day_in_pst.end_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be true
end
seller_in_act.update!(gumroad_day_timezone: "Melbourne")
expect(seller_in_act.reload.gumroad_day_timezone).to eq("Melbourne")
travel_to(gumroad_day_in_act.end_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be true
end
travel_to(gumroad_day_in_act.end_of_day + 1) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be false
end
travel_to(gumroad_day_in_pst.end_of_day) do
expect(seller_in_act.waive_gumroad_fee_on_new_sales?).to be false
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/money_balance_spec.rb | spec/modules/user/money_balance_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::MoneyBalance do
before :each do
@user = create(:user)
end
describe "#unpaid_balance_cents" do
context "via SQL" do
it "returns sum of unpaid balance in cents" do
create(:balance, user: @user, amount_cents: 100, state: "unpaid", date: 1.day.ago)
create(:balance, user: @user, amount_cents: 200, state: "unpaid", date: 3.days.ago)
expect(@user.unpaid_balance_cents).to eq 300
end
it "ignores paid balance" do
create(:balance, user: @user, amount_cents: 100, state: "paid")
expect(@user.unpaid_balance_cents).to eq 0
end
it "ignores someone else's balance" do
create(:balance, user: create(:user), amount_cents: 100, state: "paid")
expect(@user.unpaid_balance_cents).to eq 0
end
end
context "via Elasticsearch", :sidekiq_inline, :elasticsearch_wait_for_refresh do
it "returns sum of unpaid balance in cents" do
create(:balance, user: @user, amount_cents: 100, state: "unpaid", date: 1.day.ago)
create(:balance, user: @user, amount_cents: 200, state: "unpaid", date: 3.days.ago)
expect(@user.unpaid_balance_cents(via: :elasticsearch)).to eq 300
end
it "ignores paid balance" do
create(:balance, user: @user, amount_cents: 100, state: "paid")
expect(@user.unpaid_balance_cents(via: :elasticsearch)).to eq 0
end
it "ignores someone else's balance" do
create(:balance, user: create(:user), amount_cents: 100, state: "paid")
expect(@user.unpaid_balance_cents(via: :elasticsearch)).to eq 0
end
it "still returns the correct balance if Elasticsearch call failed and sends error to Bugsnag" do
create(:balance, user: @user, amount_cents: 100, state: "unpaid", date: 1.day.ago)
create(:balance, user: @user, amount_cents: 200, state: "unpaid", date: 3.days.ago)
expect(Balance).to receive(:amount_cents_sum_for).with(@user).and_raise(Net::OpenTimeout)
expect(Bugsnag).to receive(:notify).and_call_original
expect(@user.unpaid_balance_cents(via: :elasticsearch)).to eq 300
end
end
end
describe "#unpaid_balance_cents_up_to_date" do
it "returns sum of unpaid balance in cents with date up to a given date" do
create(:balance, user: @user, amount_cents: 100, state: "unpaid", date: 3.days.ago)
create(:balance, user: @user, amount_cents: 200, state: "unpaid", date: 5.days.ago)
expect(@user.unpaid_balance_cents_up_to_date(1.day.ago)).to eq 300
end
it "ignores paid balance" do
create(:balance, user: @user, amount_cents: 100, state: "paid", date: 3.days.ago)
expect(@user.unpaid_balance_cents_up_to_date(1.day.ago)).to eq 0
end
it "ignores unpaid balance with date after a given date" do
create(:balance, user: @user, amount_cents: 100, state: "paid", date: 1.day.ago)
expect(@user.unpaid_balance_cents_up_to_date(3.days.ago)).to eq 0
end
end
describe "#unpaid_balances_up_to_date" do
it "returns all unpaid balances with date up to a given date" do
b1 = create(:balance, user: @user, amount_cents: 100, state: "unpaid", date: 3.days.ago)
b2 = create(:balance, user: @user, amount_cents: 200, state: "unpaid", date: 5.days.ago)
result = @user.unpaid_balances_up_to_date(1.day.ago)
expect(result.size).to eq 2
expect(result.include?(b1)).to be(true)
expect(result.include?(b2)).to be(true)
end
it "ignores paid balances" do
create(:balance, user: @user, amount_cents: 100, state: "paid", date: 3.days.ago)
expect(@user.unpaid_balances_up_to_date(1.day.ago)).to be_empty
end
it "ignores balances with date after a given date" do
create(:balance, user: @user, amount_cents: 100, state: "unpaid", date: 1.day.ago)
expect(@user.unpaid_balances_up_to_date(3.days.ago)).to be_empty
end
end
describe "#unpaid_balance_cents_up_to_date_held_by_gumroad" do
it "returns unpaid cents that are held by gumroad with date up to the given date" do
create(:balance, user: @user, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id),
amount_cents: 100, state: "unpaid", date: 3.days.ago)
create(:balance, user: @user, merchant_account: MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id),
amount_cents: 200, state: "unpaid", date: 5.days.ago)
expect(@user.unpaid_balance_cents_up_to_date_held_by_gumroad(1.day.ago)).to eq(300)
end
it "does not include balance held in stripe connect account" do
create(:balance, user: @user, merchant_account: create(:merchant_account, user: @user),
amount_cents: 100, state: "unpaid", date: 3.days.ago)
expect(@user.unpaid_balance_cents_up_to_date_held_by_gumroad(1.day.ago)).to eq(0)
end
it "does not include paid balance" do
create(:balance, user: @user, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id),
amount_cents: 100, state: "paid", date: 3.days.ago)
expect(@user.unpaid_balance_cents_up_to_date_held_by_gumroad(1.day.ago)).to eq(0)
end
it "does not include balance with date after the given date" do
create(:balance, user: @user, merchant_account: MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id),
amount_cents: 100, state: "unpaid", date: 1.day.ago)
expect(@user.unpaid_balance_cents_up_to_date_held_by_gumroad(3.days.ago)).to eq(0)
end
end
describe "#unpaid_balance_holding_cents_up_to_date_held_by_stripe" do
let(:stripe_connect_merchant_account) { create(:merchant_account, user: @user, currency: "aud") }
it "returns unpaid holding cents that are held in stripe connect account with date up to the given date" do
create(:balance, user: @user, merchant_account: stripe_connect_merchant_account,
holding_currency: stripe_connect_merchant_account.currency,
amount_cents: 100, holding_amount_cents: 129, state: "unpaid", date: 3.days.ago)
create(:balance, user: @user, merchant_account: stripe_connect_merchant_account,
holding_currency: stripe_connect_merchant_account.currency,
amount_cents: 200, holding_amount_cents: 258, state: "unpaid", date: 5.days.ago)
expect(@user.unpaid_balance_holding_cents_up_to_date_held_by_stripe(1.day.ago)).to eq(387)
end
it "does not include balance held by gumroad" do
create(:balance, user: @user, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id),
amount_cents: 100, state: "unpaid", date: 3.days.ago)
create(:balance, user: @user, merchant_account: MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id),
amount_cents: 200, state: "unpaid", date: 5.days.ago)
expect(@user.unpaid_balance_holding_cents_up_to_date_held_by_stripe(1.day.ago)).to eq(0)
end
it "does not include paid balance" do
create(:balance, user: @user, merchant_account: stripe_connect_merchant_account,
amount_cents: 100, state: "paid", date: 3.days.ago)
expect(@user.unpaid_balance_holding_cents_up_to_date_held_by_stripe(1.day.ago)).to eq(0)
end
it "does not include balance with date after the given date" do
create(:balance, user: @user, merchant_account: stripe_connect_merchant_account,
amount_cents: 100, state: "unpaid", date: 1.day.ago)
expect(@user.unpaid_balance_holding_cents_up_to_date_held_by_stripe(3.days.ago)).to eq(0)
end
end
describe "#paid_payments_cents_for_date" do
let(:payout_date) { Date.today }
before do
create(:payment, payout_period_end_date: payout_date, user: @user, amount_cents: 1_00) # included
create(:payment_completed, payout_period_end_date: payout_date, user: @user, amount_cents: 10_00) # included
create(:payment_unclaimed, payout_period_end_date: payout_date, user: @user, amount_cents: 100_00) # included
create(:payment_returned, payout_period_end_date: payout_date, user: @user, amount_cents: 100_000) # ignored
create(:payment_reversed, payout_period_end_date: payout_date, user: @user, amount_cents: 1_000_000) # ignored
create(:payment_failed, payout_period_end_date: payout_date, user: @user, amount_cents: 10_000_000) # ignored
create(:payment, payout_period_end_date: payout_date - 1, user: @user, amount_cents: 100_000_000) # ignored
end
it "returns the sum of balances that haven't failed or been returned/reversed, and only the ones on the same day" do
expect(@user.paid_payments_cents_for_date(payout_date)).to eq(111_00)
end
end
describe "#formatted_balance_to_forfeit" do
context "country_change" do
let(:merchant_account) { create(:merchant_account, user: @user) }
it "returns formatted balance if there's a positive balance" do
create(:balance, user: @user, merchant_account:, amount_cents: 1322)
expect(@user.formatted_balance_to_forfeit(:country_change)).to eq("$13.22")
end
it "returns nil if there's a zero or negative balance to forfeit" do
expect(@user.formatted_balance_to_forfeit(:country_change)).to eq(nil)
create(:balance, user: @user, state: :unpaid, merchant_account:, amount_cents: -233)
expect(@user.formatted_balance_to_forfeit(:country_change)).to eq(nil)
end
end
context "account_closure" do
it "returns nil when the delete_account_forfeit_balance feature is inactive" do
create(:balance, user: @user, state: :unpaid, amount_cents: 942)
expect(@user.formatted_balance_to_forfeit(:account_closure)).to eq(nil)
end
context "when the delete_account_forfeit_balance feature is active" do
before do
Feature.activate_user(:delete_account_forfeit_balance, @user)
end
it "returns formatted balance if there's a positive balance" do
create(:balance, user: @user, state: :unpaid, amount_cents: 10_00)
expect(@user.formatted_balance_to_forfeit(:account_closure)).to eq("$10")
end
it "returns nil if there's a zero or negative balance to forfeit" do
expect(@user.formatted_balance_to_forfeit(:account_closure)).to eq(nil)
create(:balance, user: @user, state: :unpaid, amount_cents: -233)
expect(@user.formatted_balance_to_forfeit(:account_closure)).to eq(nil)
end
end
end
end
describe "#forfeit_unpaid_balance!" do
before do
stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id) # For negative credits
end
context "country_change" do
let(:merchant_account) { create(:merchant_account, user: @user) }
it "does nothing if there is no balance to forfeit" do
expect(@user.balances.unpaid.sum(:amount_cents)).to eq(0)
expect(@user.forfeit_unpaid_balance!(:country_change)).to eq(nil)
expect(@user.reload.comments.last).to eq(nil)
end
it "marks balances as forfeited and adds a comment" do
balance1 = create(:balance, user: @user, amount_cents: 10_00, merchant_account:, date: Date.yesterday)
balance2 = create(:balance, user: @user, amount_cents: 20_00, merchant_account:, date: Date.today)
balance3 = create(:balance, user: @user, amount_cents: 30_00, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), date: Date.today)
@user.forfeit_unpaid_balance!(:country_change)
expect(balance1.reload.state).to eq("forfeited")
expect(balance2.reload.state).to eq("forfeited")
expect(balance3.reload.state).to eq("unpaid")
expect(@user.comments.last.comment_type).to eq(Comment::COMMENT_TYPE_BALANCE_FORFEITED)
expect(@user.comments.last.content).to eq("Balance of $30 has been forfeited. Reason: Country changed. Balance IDs: #{balance1.id}, #{balance2.id}")
end
end
context "account_closure" do
context "when the delete_account_forfeit_balance feature is not active" do
it "does nothing" do
create(:balance, user: @user, amount_cents: 255)
expect(@user.forfeit_unpaid_balance!(:account_closure)).to eq(nil)
expect(@user.reload.comments.last).to eq(nil)
end
end
context "when the delete_account_forfeit_balance feature is active" do
before do
Feature.activate_user(:delete_account_forfeit_balance, @user)
end
it "does nothing if there is no balance to forfeit" do
expect(@user.forfeit_unpaid_balance!(:account_closure)).to eq(nil)
expect(@user.reload.comments.last).to eq(nil)
end
it "marks balances as forfeited and adds a comment" do
balance1 = create(:balance, user: @user, amount_cents: 255, date: Date.yesterday)
balance2 = create(:balance, user: @user, amount_cents: 635, date: Date.today)
@user.forfeit_unpaid_balance!(:account_closure)
expect(balance1.reload.state).to eq("forfeited")
expect(balance2.reload.state).to eq("forfeited")
expect(@user.comments.last.comment_type).to eq(Comment::COMMENT_TYPE_BALANCE_FORFEITED)
expect(@user.comments.last.content).to eq("Balance of $8.90 has been forfeited. Reason: Account closed. Balance IDs: #{balance1.id}, #{balance2.id}")
end
end
end
end
describe "#validate_account_closure_balances!" do
context "when the delete_account_forfeit_balance feature is not active" do
it "raises UnpaidBalanceError" do
create(:balance, user: @user, state: :unpaid, amount_cents: 942)
expect { @user.validate_account_closure_balances! }.to raise_error(User::UnpaidBalanceError) do |error|
expect(error.amount).to eq("$9.42")
end
end
end
context "when the delete_account_forfeit_balance feature is active" do
before do
Feature.activate_user(:delete_account_forfeit_balance, @user)
end
it "returns nil if there's a zero balance" do
expect(@user.validate_account_closure_balances!).to eq(nil)
end
it "raises User::UnpaidBalanceError if there's non-zero balance to forfeit" do
create(:balance, user: @user, state: :unpaid, amount_cents: 10_00, date: Date.yesterday)
expect { @user.validate_account_closure_balances! }.to raise_error(User::UnpaidBalanceError) do |error|
expect(error.amount).to eq("$10")
end
create(:balance, user: @user, state: :unpaid, amount_cents: -2333)
expect { @user.validate_account_closure_balances! }.to raise_error(User::UnpaidBalanceError) do |error|
expect(error.amount).to eq("$-13.33")
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/social_google_spec.rb | spec/modules/user/social_google_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::SocialGoogle do
before(:all) do
@data = JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/google_omniauth.json").read)
end
describe ".find_or_create_for_google_oauth2" do
before do
@dataCopy1 = @data.deep_dup
@dataCopy1["uid"] = "12345"
@dataCopy1["info"]["email"] = "paulius@example.com"
@dataCopy1["extra"]["raw_info"]["email"] = "paulius@example.com"
@dataCopy2 = @data.deep_dup
@dataCopy2["uid"] = "111111"
@dataCopy2["info"]["email"] = "spongebob@example.com"
@dataCopy2["extra"]["raw_info"]["email"] = "spongebob@example.com"
end
it "creates a new user if one does not exist with the corresponding google uid or email" do
User.find_or_create_for_google_oauth2(@data)
expect(User.find_by(email: @data["info"]["email"])).to_not eq(nil)
expect(User.find_by(google_uid: @data["uid"])).to_not eq(nil)
end
it "finds a user using google's uid payload" do
createdUser = create(:user, google_uid: @dataCopy1["uid"])
foundUser = User.find_or_create_for_google_oauth2(@dataCopy1)
expect(foundUser.id).to eq(createdUser.id)
expect(createdUser.reload.email).to eq(foundUser.email)
expect(createdUser.reload.email).to eq(@dataCopy1["info"]["email"])
end
it "finds a user using email when google's uid is missing and fills in uid" do
createdUser = create(:user, email: @dataCopy2["info"]["email"])
foundUser = User.find_or_create_for_google_oauth2(@dataCopy2)
expect(createdUser.google_uid).to eq(nil)
expect(createdUser.reload.google_uid).to eq(foundUser.google_uid)
expect(createdUser.reload.google_uid).to eq(@dataCopy2["uid"])
end
end
describe ".google_picture_url", :vcr do
before do
@user = create(:user, google_uid: @data["uid"])
end
it "stores the user's profile picture from Google to S3 and returns the URL for the saved file" do
google_picture_url = @user.google_picture_url(@data)
expect(google_picture_url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{@user.avatar_variant.key}")
picture_response = HTTParty.get(google_picture_url)
expect(picture_response.content_type).to eq("image/jpeg")
expect(picture_response.success?).to eq(true)
end
end
describe ".query_google" do
describe "email change" do
it "sets email if the email coming from google is different" do
@user = create(:user, email: "spongebob@example.com")
expect { User.query_google(@user, @data) }.to change { @user.reload.email }.from("spongebob@example.com").to(@data["info"]["email"])
end
context "when the email already exists in a different case" do
before do
@user = create(:user, email: @data["info"]["email"].upcase)
end
it "doesn't update email" do
expect { User.query_google(@user, @data) }.not_to change { @user.reload.email }
end
it "doesn't raise error" do
expect { User.query_google(@user, @data) }.not_to raise_error(ActiveRecord::RecordInvalid)
end
end
end
describe "already has name" do
it "does not not set a name if one already exists" do
@user = create(:user, name: "Spongebob")
expect { User.query_google(@user, @data) }.to_not change { @user.reload.name }
end
end
describe "no existing information" do
before do
@user = create(:user)
end
it "sets the google uid if one does not exist upon creation" do
expect { User.query_google(@user, @data) }.to change { @user.reload.google_uid }.from(nil).to(@data["uid"])
end
it "sets the name if one does not exist upon creation" do
expect { User.query_google(@user, @data) }.to change { @user.reload.name }.from(nil).to(@data["info"]["name"])
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/payout_schedule_spec.rb | spec/modules/user/payout_schedule_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::PayoutSchedule do
describe "#next_payout_date" do
let(:user) { create(:user, payment_address: "bob1@example.com") }
context "when payout frequency is weekly" do
it "returns the correct next payout date" do
travel_to(Date.new(2012, 12, 26)) do
create(:balance, user:, amount_cents: 100, date: Date.new(2012, 12, 20))
expect(user.next_payout_date).to eq nil
balance = create(:balance, user:, amount_cents: 2000, date: Date.new(2012, 12, 21))
expect(user.next_payout_date).to eq Date.new(2012, 12, 28)
balance.update_attribute(:state, "paid")
create(:balance, user:, amount_cents: 2000, date: Date.new(2012, 12, 22))
expect(user.next_payout_date).to eq Date.new(2013, 1, 4)
end
travel_to(Date.new(2013, 1, 25)) do
expect(user.next_payout_date).to eq Date.new(2013, 1, 25)
create(:payment, user:)
expect(user.next_payout_date).to eq Date.new(2013, 2, 1)
end
end
end
context "when payout frequency is monthly" do
before { user.update!(payout_frequency: "monthly") }
it "returns the correct next payout date" do
travel_to(Date.new(2013, 1, 15)) do
create(:balance, user:, amount_cents: 100, date: Date.new(2013, 1, 14))
expect(user.next_payout_date).to eq nil
balance = create(:balance, user:, amount_cents: 2000, date: Date.new(2013, 1, 15))
expect(user.next_payout_date).to eq Date.new(2013, 1, 25)
balance.update_attribute(:state, "paid")
create(:balance, user:, amount_cents: 2000, date: Date.new(2013, 1, 19))
expect(user.next_payout_date).to eq Date.new(2013, 2, 22)
end
travel_to(Date.new(2013, 2, 22)) do
expect(user.next_payout_date).to eq Date.new(2013, 2, 22)
create(:payment, user:)
expect(user.next_payout_date).to eq Date.new(2013, 3, 29)
end
end
end
context "when payout frequency is quarterly" do
before { user.update!(payout_frequency: "quarterly") }
it "returns the correct next payout date" do
travel_to(Date.new(2013, 3, 15)) do
create(:balance, user:, amount_cents: 100, date: Date.new(2013, 3, 14))
expect(user.next_payout_date).to eq nil
balance = create(:balance, user:, amount_cents: 2000, date: Date.new(2013, 3, 15))
expect(user.next_payout_date).to eq Date.new(2013, 3, 29)
balance.update_attribute(:state, "paid")
create(:balance, user:, amount_cents: 2000, date: Date.new(2013, 3, 23))
expect(user.next_payout_date).to eq Date.new(2013, 6, 28)
end
travel_to(Date.new(2013, 6, 28)) do
expect(user.next_payout_date).to eq Date.new(2013, 6, 28)
create(:payment, user:)
expect(user.next_payout_date).to eq Date.new(2013, 9, 27)
end
end
end
end
describe "#upcoming_payout_amounts" do
let(:user) { create(:user, payment_address: "bob1@example.com") }
around do |example|
travel_to(Date.new(2025, 9, 22)) do
example.run
end
end
context "when payout frequency is weekly" do
it "returns nothing if the user has no unpaid balance" do
expect(user.upcoming_payout_amounts).to eq({})
end
it "returns the correct upcoming payout amounts" do
create(:balance, user:, amount_cents: 100, date: Date.new(2025, 9, 17))
create(:balance, user:, amount_cents: 2000, date: Date.new(2025, 9, 18))
expect(user.upcoming_payout_amounts).to eq({ Date.new(2025, 9, 26) => 2100 })
create(:balance, user:, amount_cents: 2000, date: Date.new(2025, 9, 22))
expect(user.upcoming_payout_amounts).to eq({ Date.new(2025, 9, 26) => 2100, Date.new(2025, 10, 3) => 2000 })
end
end
end
describe "#payout_amount_for_payout_date" do
let(:user) { create(:user, payment_address: "bob1@example.com") }
context "when payout frequency is weekly" do
it "calculates the correct payout amount" do
travel_to(Date.new(2013, 1, 25)) do
create(:balance, user:, amount_cents: 100, date: Date.new(2012, 12, 20))
create(:balance, user:, amount_cents: 2000, date: Date.new(2012, 12, 21))
create(:payment, user:)
expect(user.payout_amount_for_payout_date(user.next_payout_date)).to eq 2100
create(:balance, user:, amount_cents: 2000, date: Date.new(2013, 2, 1))
expect(user.payout_amount_for_payout_date(user.next_payout_date)).to eq 2100
end
end
end
end
describe ".manual_payout_end_date" do
it "returns the date upto which creators are expected to have been automatically paid out till now" do
today = Date.today
last_weeks_friday = today.beginning_of_week - 3
(today.beginning_of_week..today.end_of_week).each do |date|
travel_to(date) do
if Date.today.wday == 1
expect(described_class.manual_payout_end_date).to eq last_weeks_friday - 7
else
expect(described_class.manual_payout_end_date).to eq last_weeks_friday
end
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/user/ping_notification_spec.rb | spec/modules/user/ping_notification_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::PingNotification do
describe "#send_test_ping" do
before do
@user = create(:user)
@purchase = create(:purchase, seller: @user, link: create(:product, user: @user))
@ping_params = @purchase.payload_for_ping_notification.merge(test: true)
end
context "when notification_content_type if application/json" do
before do
@user.update_attribute(:notification_content_type, Mime[:json])
end
it "sends JSON payload in test ping" do
expect(HTTParty).to receive(:post).with("https://example.com", timeout: 5, body: @ping_params.to_json, headers: { "Content-Type" => "application/json" })
expect do
@user.send_test_ping("https://example.com")
end.to_not raise_error
end
end
context "when notification_content_type is application/x-www-form-urlencoded" do
before do
@user.update_attribute(:notification_content_type, Mime[:url_encoded_form])
end
it "sends form-encoded payload in test ping" do
expect(HTTParty).to receive(:post).with("https://example.com", timeout: 5, body: @ping_params.deep_stringify_keys, headers: { "Content-Type" => "application/x-www-form-urlencoded" })
expect do
@user.send_test_ping("https://example.com")
end.to_not raise_error
end
it "encodes brackets in the payload keys" do
@purchase.purchase_custom_fields << build(:purchase_custom_field, name: "name [for field] [[]]!@#$%^&", value: "John")
expect(HTTParty).to receive(:post) do |url, options|
expect(url).to eq("https://example.com")
expect(options[:timeout]).to eq(5)
expect(options[:headers]).to include("Content-Type" => "application/x-www-form-urlencoded")
expect(options[:body]).not_to include("name [for field] [[]]!@#$%^&" => "John")
expect(options[:body]).not_to include("custom_fields" => { "name [for field] [[]]!@#$%^&" => "John" })
expect(options[:body]).to include("name %5Bfor field%5D %5B%5B%5D%5D!@#$%^&" => "John")
expect(options[:body]).to include("custom_fields" => { "name %5Bfor field%5D %5B%5B%5D%5D!@#$%^&" => "John" })
end
expect do
@user.send_test_ping("https://example.com")
end.to_not raise_error
end
end
end
describe "#urls_for_ping_notification" do
it "contains notification_endpoint and notification_content_type for 'sale' resource if present" do
user = create(:user)
post_urls = user.urls_for_ping_notification(ResourceSubscription::SALE_RESOURCE_NAME)
expect(post_urls).to match_array([])
user.update_attribute(:notification_endpoint, "http://notification.com")
post_urls = user.urls_for_ping_notification(ResourceSubscription::SALE_RESOURCE_NAME)
expect(post_urls).to match_array([[user.notification_endpoint, user.notification_content_type]])
end
it "contains the post_urls and content_type for the respective resources based on input parameter" do
user = create(:user, notification_endpoint: "http://notification.com")
oauth_app = create(:oauth_application, owner: user)
create("doorkeeper/access_token", application: oauth_app, resource_owner_id: user.id, scopes: "view_sales")
sale_resource_subscription = create(:resource_subscription, oauth_application: oauth_app, user:,
post_url: "http://notification.com/sale")
refunded_resource_subscription = create(:resource_subscription, oauth_application: oauth_app, user:,
resource_name: ResourceSubscription::REFUNDED_RESOURCE_NAME,
post_url: "http://notification.com/refund")
cancelled_resource_subscription = create(:resource_subscription, oauth_application: oauth_app, user:,
resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME,
post_url: "http://notification.com/cancellation")
sale_post_urls = user.urls_for_ping_notification(ResourceSubscription::SALE_RESOURCE_NAME)
expect(sale_post_urls).to match_array([[sale_resource_subscription.post_url, sale_resource_subscription.content_type],
[user.notification_endpoint, user.notification_content_type]])
refunded_post_urls = user.urls_for_ping_notification(ResourceSubscription::REFUNDED_RESOURCE_NAME)
expect(refunded_post_urls).to match_array([[refunded_resource_subscription.post_url, refunded_resource_subscription.content_type]])
cancelled_post_urls = user.urls_for_ping_notification(ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(cancelled_post_urls).to match_array([[cancelled_resource_subscription.post_url, cancelled_resource_subscription.content_type]])
end
it "does not contain URLs for resource subscriptions if the user revoked access to the application" do
user = create(:user)
oauth_app = create(:oauth_application, owner: user)
token = create("doorkeeper/access_token", application: oauth_app, resource_owner_id: user.id, scopes: "view_sales")
sale_resource_subscription = create(:resource_subscription, oauth_application: oauth_app, user:)
sale_post_urls = user.urls_for_ping_notification(ResourceSubscription::SALE_RESOURCE_NAME)
expect(sale_post_urls).to match_array([[sale_resource_subscription.post_url, sale_resource_subscription.content_type]])
token.update!(revoked_at: Time.current)
sale_post_urls = user.urls_for_ping_notification(ResourceSubscription::SALE_RESOURCE_NAME)
expect(sale_post_urls).to match_array([])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/shipping_destination/destinations_spec.rb | spec/modules/shipping_destination/destinations_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ShippingDestination::Destinations do
describe ".shipping_countries" do
it "returns the expected shipping countries" do
expect(ShippingDestination::Destinations.shipping_countries).to eq(shipping_countries_expected)
end
end
describe ".europe_shipping_countries" do
it "returns the expected Europe countries mapping" do
expect(ShippingDestination::Destinations.europe_shipping_countries).to eq(europe_shipping_countries_expected)
end
end
describe ".asia_shipping_countries" do
it "returns the expected Asia countries mapping" do
expect(ShippingDestination::Destinations.asia_shipping_countries).to eq(asia_shipping_countries_expected)
end
end
describe ".north_america_shipping_countries" do
it "returns the expected North America countries mapping" do
expect(ShippingDestination::Destinations.north_america_shipping_countries).to eq(north_america_shipping_countries_expected)
end
end
def shipping_countries_expected
{
"US" => "United States",
"ASIA" => "Asia",
"EUROPE" => "Europe",
"NORTH AMERICA" => "North America",
"ELSEWHERE" => "Elsewhere",
"AX" => "Åland Islands",
"AL" => "Albania",
"DZ" => "Algeria",
"AS" => "American Samoa",
"AD" => "Andorra",
"AO" => "Angola",
"AI" => "Anguilla",
"AQ" => "Antarctica",
"AG" => "Antigua and Barbuda",
"AR" => "Argentina",
"AM" => "Armenia",
"AW" => "Aruba",
"AU" => "Australia",
"AT" => "Austria",
"AZ" => "Azerbaijan",
"BS" => "Bahamas",
"BH" => "Bahrain",
"BD" => "Bangladesh",
"BB" => "Barbados",
"BY" => "Belarus",
"BE" => "Belgium",
"BZ" => "Belize",
"BJ" => "Benin",
"BM" => "Bermuda",
"BT" => "Bhutan",
"BO" => "Bolivia",
"BQ" => "Bonaire, Sint Eustatius and Saba",
"BA" => "Bosnia and Herzegovina",
"BW" => "Botswana",
"BV" => "Bouvet Island",
"BR" => "Brazil",
"IO" => "British Indian Ocean Territory",
"BN" => "Brunei Darussalam",
"BG" => "Bulgaria",
"BF" => "Burkina Faso",
"BI" => "Burundi",
"KH" => "Cambodia",
"CM" => "Cameroon",
"CA" => "Canada",
"CV" => "Cabo Verde",
"KY" => "Cayman Islands",
"CF" => "Central African Republic",
"TD" => "Chad",
"CL" => "Chile",
"CN" => "China",
"CX" => "Christmas Island",
"CC" => "Cocos (Keeling) Islands",
"CO" => "Colombia",
"KM" => "Comoros",
"CG" => "Congo",
"CK" => "Cook Islands",
"CR" => "Costa Rica",
"HR" => "Croatia",
"CW" => "Curaçao",
"CY" => "Cyprus",
"CZ" => "Czechia",
"DK" => "Denmark",
"DJ" => "Djibouti",
"DM" => "Dominica",
"DO" => "Dominican Republic",
"EC" => "Ecuador",
"EG" => "Egypt",
"SV" => "El Salvador",
"GQ" => "Equatorial Guinea",
"ER" => "Eritrea",
"EE" => "Estonia",
"ET" => "Ethiopia",
"FK" => "Falkland Islands (Malvinas)",
"FO" => "Faroe Islands",
"FJ" => "Fiji",
"FI" => "Finland",
"FR" => "France",
"GF" => "French Guiana",
"PF" => "French Polynesia",
"TF" => "French Southern Territories",
"GA" => "Gabon",
"GM" => "Gambia",
"DE" => "Germany",
"GH" => "Ghana",
"GI" => "Gibraltar",
"GR" => "Greece",
"GL" => "Greenland",
"GD" => "Grenada",
"GE" => "Georgia",
"GP" => "Guadeloupe",
"GU" => "Guam",
"GT" => "Guatemala",
"GG" => "Guernsey",
"GN" => "Guinea",
"GW" => "Guinea-Bissau",
"GY" => "Guyana",
"HT" => "Haiti",
"HM" => "Heard Island and McDonald Islands",
"VA" => "Holy See (Vatican City State)",
"HN" => "Honduras",
"HK" => "Hong Kong",
"HU" => "Hungary",
"IS" => "Iceland",
"IN" => "India",
"ID" => "Indonesia",
"IE" => "Ireland",
"IM" => "Isle of Man",
"IL" => "Israel",
"IT" => "Italy",
"JM" => "Jamaica",
"JP" => "Japan",
"JE" => "Jersey",
"JO" => "Jordan",
"KZ" => "Kazakhstan",
"KE" => "Kenya",
"KI" => "Kiribati",
"KR" => "South Korea",
"XK" => "Kosovo",
"KW" => "Kuwait",
"KG" => "Kyrgyzstan",
"LA" => "Lao People's Democratic Republic",
"LV" => "Latvia",
"LS" => "Lesotho",
"LI" => "Liechtenstein",
"LT" => "Lithuania",
"LU" => "Luxembourg",
"MO" => "Macao",
"MK" => "North Macedonia",
"MG" => "Madagascar",
"MW" => "Malawi",
"MY" => "Malaysia",
"MV" => "Maldives",
"ML" => "Mali",
"MT" => "Malta",
"MH" => "Marshall Islands",
"MQ" => "Martinique",
"MR" => "Mauritania",
"MU" => "Mauritius",
"YT" => "Mayotte",
"MX" => "Mexico",
"FM" => "Micronesia, Federated States of",
"MD" => "Moldova",
"MC" => "Monaco",
"MN" => "Mongolia",
"ME" => "Montenegro",
"MS" => "Montserrat",
"MA" => "Morocco",
"MZ" => "Mozambique",
"NA" => "Namibia",
"NR" => "Nauru",
"NP" => "Nepal",
"NL" => "Netherlands",
"NC" => "New Caledonia",
"NZ" => "New Zealand",
"NI" => "Nicaragua",
"NE" => "Niger",
"NG" => "Nigeria",
"NU" => "Niue",
"NF" => "Norfolk Island",
"MP" => "Northern Mariana Islands",
"NO" => "Norway",
"OM" => "Oman",
"PK" => "Pakistan",
"PW" => "Palau",
"PS" => "Palestine, State of",
"PA" => "Panama",
"PG" => "Papua New Guinea",
"PY" => "Paraguay",
"PE" => "Peru",
"PH" => "Philippines",
"PN" => "Pitcairn",
"PL" => "Poland",
"PT" => "Portugal",
"PR" => "Puerto Rico",
"QA" => "Qatar",
"RE" => "Réunion",
"RO" => "Romania",
"RU" => "Russian Federation",
"RW" => "Rwanda",
"BL" => "Saint Barthélemy",
"SH" => "Saint Helena, Ascension and Tristan da Cunha",
"KN" => "Saint Kitts and Nevis",
"LC" => "Saint Lucia",
"MF" => "Saint Martin (French part)",
"PM" => "Saint Pierre and Miquelon",
"VC" => "Saint Vincent and the Grenadines",
"WS" => "Samoa",
"SM" => "San Marino",
"ST" => "Sao Tome and Principe",
"SA" => "Saudi Arabia",
"SN" => "Senegal",
"RS" => "Serbia",
"SC" => "Seychelles",
"SL" => "Sierra Leone",
"SG" => "Singapore",
"SX" => "Sint Maarten (Dutch part)",
"SK" => "Slovakia",
"SI" => "Slovenia",
"SB" => "Solomon Islands",
"ZA" => "South Africa",
"GS" => "South Georgia and the South Sandwich Islands",
"SS" => "South Sudan",
"ES" => "Spain",
"LK" => "Sri Lanka",
"SR" => "Suriname",
"SJ" => "Svalbard and Jan Mayen",
"SZ" => "Eswatini",
"SE" => "Sweden",
"CH" => "Switzerland",
"TW" => "Taiwan",
"TJ" => "Tajikistan",
"TZ" => "Tanzania",
"TH" => "Thailand",
"TL" => "Timor-Leste",
"TG" => "Togo",
"TK" => "Tokelau",
"TO" => "Tonga",
"TT" => "Trinidad and Tobago",
"TN" => "Tunisia",
"TR" => "Türkiye",
"TM" => "Turkmenistan",
"TC" => "Turks and Caicos Islands",
"TV" => "Tuvalu",
"UG" => "Uganda",
"UA" => "Ukraine",
"AE" => "United Arab Emirates",
"GB" => "United Kingdom",
"UM" => "United States Minor Outlying Islands",
"UY" => "Uruguay",
"UZ" => "Uzbekistan",
"VU" => "Vanuatu",
"VE" => "Venezuela",
"VN" => "Vietnam",
"VG" => "Virgin Islands, British",
"VI" => "Virgin Islands, U.S.",
"WF" => "Wallis and Futuna",
"EH" => "Western Sahara",
"ZM" => "Zambia"
}
end
def europe_shipping_countries_expected
{
"AD" => "Andorra",
"AT" => "Austria",
"BY" => "Belarus",
"BE" => "Belgium",
"BA" => "Bosnia and Herzegovina",
"BG" => "Bulgaria",
"HR" => "Croatia",
"CZ" => "Czechia",
"DK" => "Denmark",
"EE" => "Estonia",
"FO" => "Faroe Islands",
"FI" => "Finland",
"FR" => "France",
"DE" => "Germany",
"GI" => "Gibraltar",
"GR" => "Greece",
"GG" => "Guernsey",
"VA" => "Holy See (Vatican City State)",
"HU" => "Hungary",
"IS" => "Iceland",
"IE" => "Ireland",
"IM" => "Isle of Man",
"IT" => "Italy",
"JE" => "Jersey",
"XK" => "Kosovo",
"LV" => "Latvia",
"LI" => "Liechtenstein",
"LU" => "Luxembourg",
"MT" => "Malta",
"MD" => "Moldova",
"MC" => "Monaco",
"ME" => "Montenegro",
"NL" => "Netherlands",
"MK" => "North Macedonia",
"NO" => "Norway",
"PL" => "Poland",
"PT" => "Portugal",
"RO" => "Romania",
"RU" => "Russian Federation",
"SM" => "San Marino",
"RS" => "Serbia",
"SK" => "Slovakia",
"SI" => "Slovenia",
"ES" => "Spain",
"SJ" => "Svalbard and Jan Mayen",
"SE" => "Sweden",
"CH" => "Switzerland",
"TR" => "Türkiye",
"UA" => "Ukraine",
"GB" => "United Kingdom",
"AX" => "Åland Islands"
}
end
def asia_shipping_countries_expected
{
"AM" => "Armenia",
"AZ" => "Azerbaijan",
"BH" => "Bahrain",
"BT" => "Bhutan",
"IO" => "British Indian Ocean Territory",
"BN" => "Brunei Darussalam",
"KH" => "Cambodia",
"CN" => "China",
"CX" => "Christmas Island",
"CC" => "Cocos (Keeling) Islands",
"CY" => "Cyprus",
"GE" => "Georgia",
"HK" => "Hong Kong",
"IN" => "India",
"IL" => "Israel",
"JP" => "Japan",
"JO" => "Jordan",
"KZ" => "Kazakhstan",
"KW" => "Kuwait",
"KG" => "Kyrgyzstan",
"LA" => "Lao People's Democratic Republic",
"MO" => "Macao",
"MY" => "Malaysia",
"MV" => "Maldives",
"MN" => "Mongolia",
"NP" => "Nepal",
"OM" => "Oman",
"PK" => "Pakistan",
"PS" => "Palestine, State of",
"PH" => "Philippines",
"QA" => "Qatar",
"SA" => "Saudi Arabia",
"SG" => "Singapore",
"KR" => "South Korea",
"LK" => "Sri Lanka",
"TW" => "Taiwan",
"TJ" => "Tajikistan",
"TH" => "Thailand",
"TL" => "Timor-Leste",
"TM" => "Turkmenistan",
"AE" => "United Arab Emirates",
"UZ" => "Uzbekistan"
}
end
def north_america_shipping_countries_expected
{
"AI" => "Anguilla",
"AG" => "Antigua and Barbuda",
"AW" => "Aruba",
"BS" => "Bahamas",
"BB" => "Barbados",
"BZ" => "Belize",
"BM" => "Bermuda",
"BQ" => "Bonaire, Sint Eustatius and Saba",
"CA" => "Canada",
"KY" => "Cayman Islands",
"CR" => "Costa Rica",
"CW" => "Curaçao",
"DM" => "Dominica",
"DO" => "Dominican Republic",
"SV" => "El Salvador",
"GL" => "Greenland",
"GD" => "Grenada",
"GP" => "Guadeloupe",
"GT" => "Guatemala",
"HT" => "Haiti",
"HN" => "Honduras",
"JM" => "Jamaica",
"MQ" => "Martinique",
"MX" => "Mexico",
"MS" => "Montserrat",
"NI" => "Nicaragua",
"PR" => "Puerto Rico",
"BL" => "Saint Barthélemy",
"KN" => "Saint Kitts and Nevis",
"LC" => "Saint Lucia",
"MF" => "Saint Martin (French part)",
"PM" => "Saint Pierre and Miquelon",
"VC" => "Saint Vincent and the Grenadines",
"SX" => "Sint Maarten (Dutch part)",
"TT" => "Trinidad and Tobago",
"TC" => "Turks and Caicos Islands",
"US" => "United States",
"VG" => "Virgin Islands, British",
"VI" => "Virgin Islands, U.S."
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/subscription/ping_notification_spec.rb | spec/modules/subscription/ping_notification_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Subscription::PingNotification do
describe "#payload_for_ping_notification" do
let(:purchase) { create(:membership_purchase) }
let(:subscription) { purchase.subscription }
it "contains subscription details" do
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params.keys).to match_array [:subscription_id, :product_id, :product_name,
:user_id, :user_email, :purchase_ids, :created_at,
:charge_occurrence_count, :recurrence,
:free_trial_ends_at, :resource_name]
end
it "contains custom fields if present in original purchase" do
create(:purchase_custom_field, purchase:, name: "foo", value: "bar")
payload = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(payload[:resource_name]).to eq ResourceSubscription::SALE_RESOURCE_NAME
expect(payload[:custom_fields]["foo"]).to eq "bar"
end
it "contains license_key if product has licensing enabled" do
product = create(:membership_product, is_licensed: true)
subscription = create(:subscription, link: product)
purchase = create(:membership_purchase, subscription:, link: product)
license = create(:license, link: product, purchase:)
payload = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(payload[:license_key]).to eq license.serial
end
context "cancellation event" do
it "contains the subscription cancellation details if the input resource_name is 'cancellation'" do
cancelled_at_ts = Time.current
subscription = create(:subscription, cancelled_at: cancelled_at_ts)
subscription.purchases << create(:membership_purchase, subscription:) << create(:purchase)
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:resource_name]).to eq(ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:cancelled]).to be(true)
expect(params[:cancelled_at]).to eq(cancelled_at_ts.as_json)
end
it "contains the details of who cancelled the subscription - admin/buyer/seller/payment failures" do
cancellation_requested_at = 1.hour.ago
cancelled_at_ts = Time.current
subscription = create(:subscription, cancelled_at: cancelled_at_ts, user_requested_cancellation_at: cancellation_requested_at)
subscription.purchases << create(:membership_purchase, subscription:) << create(:purchase)
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:cancelled]).to be(true)
expect(params[:cancelled_at]).to eq(cancelled_at_ts.as_json)
expect(params[:cancelled_by_seller]).to eq(true)
expect(params).not_to have_key(:cancelled_by_buyer)
expect(params).not_to have_key(:cancelled_by_admin)
subscription.cancelled_by_buyer = true
subscription.save!
params = subscription.reload.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:cancelled_by_buyer]).to eq(true)
expect(params).not_to have_key(:cancelled_by_admin)
expect(params).not_to have_key(:cancelled_by_seller)
subscription.cancelled_by_admin = true
subscription.save!
params = subscription.reload.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:cancelled_by_admin]).to eq(true)
expect(params).not_to have_key(:cancelled_by_seller)
expect(params).not_to have_key(:cancelled_by_buyer)
subscription.cancelled_at = nil
subscription.failed_at = Time.current
subscription.save!
params = subscription.reload.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:cancelled_due_to_payment_failures]).to eq(true)
expect(params).not_to have_key(:cancelled_by_seller)
expect(params).not_to have_key(:cancelled_by_buyer)
expect(params).not_to have_key(:cancelled_by_admin)
end
it "contains subscribing user's id and email when user is present, else contains subscribing email for logged out purchases" do
subscription = create(:subscription, cancelled_at: Time.current)
original_purchase_email = "orig@gum.co"
subscription.purchases << create(:purchase, is_original_subscription_purchase: true, email: original_purchase_email) << create(:purchase)
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:resource_name]).to eq(ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:user_id]).to eq(subscription.user.external_id)
expect(params[:user_email]).to eq(subscription.user.form_email)
subscription.user = nil
subscription.save!
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:resource_name]).to eq(ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:user_id]).to be(nil)
expect(params[:user_email]).to eq(original_purchase_email)
end
end
context "ended event" do
it "contains the subscription ending details if the subscription ended after a fixed subscription length" do
ended_at = 1.minute.ago
subscription = create(:subscription, ended_at:, deactivated_at: ended_at)
create(:membership_purchase, subscription:)
payload = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
expect(payload[:resource_name]).to eq ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME
expect(payload[:ended_at]).to eq ended_at.as_json
expect(payload[:ended_reason]).to eq "fixed_subscription_period_ended"
end
it "contains the subscription ending details if the subscription was cancelled" do
ended_at = 1.minute.ago
subscription = create(:subscription, cancelled_at: ended_at, deactivated_at: ended_at)
create(:membership_purchase, subscription:)
payload = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
expect(payload[:resource_name]).to eq ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME
expect(payload[:ended_at]).to eq ended_at.as_json
expect(payload[:ended_reason]).to eq "cancelled"
end
it "contains the subscription ending details if the subscription was terminated due to failed payments" do
ended_at = 1.minute.ago
subscription = create(:subscription, failed_at: ended_at, deactivated_at: ended_at)
create(:membership_purchase, subscription:)
payload = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
expect(payload[:resource_name]).to eq ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME
expect(payload[:ended_at]).to eq ended_at.as_json
expect(payload[:ended_reason]).to eq "failed_payment"
end
it "contains empty subscription ending details if the subscription has not ended" do
subscription = create(:subscription)
create(:membership_purchase, subscription:)
payload = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
expect(payload[:resource_name]).to eq ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME
expect(payload[:ended_at]).to be_nil
expect(payload[:ended_reason]).to be_nil
end
end
context "passing additional parameters" do
it "includes those parameters in the payload" do
subscription = create(:subscription)
create(:membership_purchase, subscription:)
payload = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_UPDATED_RESOURCE_NAME, additional_params: { foo: "bar" })
expect(payload[:resource_name]).to eq ResourceSubscription::SUBSCRIPTION_UPDATED_RESOURCE_NAME
expect(payload[:foo]).to eq "bar"
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/payment/stats_spec.rb | spec/modules/payment/stats_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Payment::Stats, :vcr do
describe "revenue_by_link" do
before do
@user = create(:singaporean_user_with_compliance_info, user_risk_state: "compliant", payment_address: "bob@cat.com")
@json = JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/stripe.json").read)
@product_1 = create(:product, user: @user, price_cents: 1000)
@product_2 = create(:product, user: @user, price_cents: 2000)
@product_3 = create(:product, user: @user, price_cents: 3000)
@affiliate = create(:direct_affiliate, seller: @user, affiliate_basis_points: 1500, apply_to_all_products: true)
WebMock.stub_request(:post, PAYPAL_ENDPOINT)
.to_return(body: "TIMESTAMP=2012%2d10%2d26T20%3a29%3a14Z&CORRELATIONID=c51c5e0cecbce&ACK=Success&VERSION=90%2e0&BUILD=4072860")
allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil)
allow_any_instance_of(User).to receive(:unpaid_balance_cents).and_return(100_00)
end
it "calculates the revenue per link based on all purchases during the payout period, even with affiliate_credits" do
travel_to(Date.today - 10) do
p1 = create(:purchase, link: @product_1, price_cents: @product_1.price_cents, purchase_state: "in_progress")
p1.update_balance_and_mark_successful!
p2 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p2.update_balance_and_mark_successful!
end
travel_to(Date.today - 9) do
p3 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p3.update_balance_and_mark_successful!
@p4 = create(:purchase, link: @product_3, price_cents: @product_3.price_cents, affiliate: @affiliate, purchase_state: "in_progress")
@p4.process!
@p4.update_balance_and_mark_successful!
end
travel_to(Date.today - 3) do
# This one shouldn't be included in the stats since it's only 3 days ago
p5 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p5.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 7, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
revenue_by_link = Payment.last.revenue_by_link
expect(revenue_by_link.count).to eq 3
expect(revenue_by_link[@product_1.id]).to eq 791
expect(revenue_by_link[@product_2.id]).to eq 3324
expect(revenue_by_link[@product_3.id]).to eq 2154 # @p4.price_cents (3000) - @p4.fee_cents (467) - @p4.affiliate_credit_cents (379)
expect(Payment.last.amount_cents + Payment.last.gumroad_fee_cents).to eq revenue_by_link.values.sum
expect(Payment.last.gumroad_fee_cents).to eq (revenue_by_link.values.sum * PaypalPayoutProcessor::PAYPAL_PAYOUT_FEE_PERCENT / 100.0).ceil
end
describe "chargeback", :vcr do
it "deducts the chargeback and refund fees from the link's revenue if we didn't waive our fee" do
travel_to(Date.today - 10) do
p1 = create(:purchase_in_progress, link: @product_1, chargeable: create(:chargeable))
p1.process!
p1.update_balance_and_mark_successful!
p1.reload.refund_and_save!(@product_1.user.id)
p1.is_refund_chargeback_fee_waived = false
p1.save!
p2 = create(:purchase_in_progress, link: @product_2, chargeable: create(:chargeable))
p2.process!
p2.update_balance_and_mark_successful!
allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil)
Purchase.handle_charge_event(build(:charge_event_dispute_formalized, charge_reference: p2.external_id))
p2.reload.is_refund_chargeback_fee_waived = false
p2.save!
p3 = create(:purchase_in_progress, link: @product_2, chargeable: create(:chargeable))
p3.process!
p3.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 7, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
revenue_by_link = Payment.last.revenue_by_link
expect(revenue_by_link.count).to eq(2)
expect(revenue_by_link[@product_1.id]).to eq(-50)
expect(revenue_by_link[@product_2.id]).to eq(1662) # 20_00 (price) - 2_88 (12.9% + 50c + 30c fee)
end
it "deducts the full purchase amount if the chargeback or refund happened in this period but the original purchase did not (fees waived)" do
refunded_purchase = nil
chargedback_purchase = nil
travel_to(Date.today - 20) do
refunded_purchase = create(:purchase_in_progress, link: @product_1, chargeable: create(:chargeable), affiliate: @affiliate)
refunded_purchase.process!
refunded_purchase.update_balance_and_mark_successful!
chargedback_purchase = create(:purchase_in_progress, link: @product_2, chargeable: create(:chargeable))
chargedback_purchase.process!
chargedback_purchase.update_balance_and_mark_successful!
p3 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p3.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 14, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
payment = Payment.last
PaypalPayoutProcessor.handle_paypal_event("payment_date" => payment.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => payment.user.payment_address,
"masspay_txn_id_0" => "sometxn1",
"status_0" => "Completed",
"unique_id_0" => payment.id,
"mc_fee_0" => "2.99 ")
travel_to(Date.today - 10) do
refunded_purchase.reload.refund_and_save!(refunded_purchase.seller.id)
allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil)
Purchase.handle_charge_event(build(:charge_event_dispute_formalized, charge_reference: chargedback_purchase.external_id))
# A few purchases so that the user's balance goes over $10 and is therefore payable
p4 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p4.update_balance_and_mark_successful!
p5 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p5.update_balance_and_mark_successful!
p6 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p6.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
revenue_by_link = Payment.last.revenue_by_link
expect(revenue_by_link.count).to eq(2)
expect(revenue_by_link[@product_1.id]).to eq(-723) # - $10 (price cents) + $1.5 (affiliate cents) + $0.77 (returned fee) for the refunded purchase
expect(revenue_by_link[@product_2.id]).to eq(3324) # 3 new sales, one chargeback: 3 * (20 - (20 * 0.129 + 50 + 30)) - (20 - 2.88)
expect(Payment.last.amount_cents + Payment.last.gumroad_fee_cents).to eq revenue_by_link.values.sum
expect(Payment.last.gumroad_fee_cents).to eq (revenue_by_link.values.sum * PaypalPayoutProcessor::PAYPAL_PAYOUT_FEE_PERCENT / 100.0).ceil
end
it "deducts the full purchase amount if the chargeback or refund happened in this period but the original purchase did not (fees not waived)" do
refunded_purchase = nil
chargedback_purchase = nil
travel_to(Date.today - 20) do
refunded_purchase = create(:purchase_in_progress, link: @product_1, chargeable: create(:chargeable), affiliate: @affiliate)
refunded_purchase.process!
refunded_purchase.update_balance_and_mark_successful!
chargedback_purchase = create(:purchase_in_progress, link: @product_2, chargeable: create(:chargeable))
chargedback_purchase.process!
chargedback_purchase.update_balance_and_mark_successful!
p3 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p3.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 14, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
payment = Payment.last
PaypalPayoutProcessor.handle_paypal_event("payment_date" => payment.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => payment.user.payment_address,
"masspay_txn_id_0" => "sometxn1",
"status_0" => "Completed",
"unique_id_0" => payment.id,
"mc_fee_0" => "2.99 ")
travel_to(Date.today - 10) do
refunded_purchase.reload.refund_and_save!(refunded_purchase.seller.id)
refunded_purchase.is_refund_chargeback_fee_waived = false
refunded_purchase.save!
allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil)
Purchase.handle_charge_event(build(:charge_event_dispute_formalized, charge_reference: chargedback_purchase.external_id))
chargedback_purchase.reload.is_refund_chargeback_fee_waived = false
chargedback_purchase.save!
# A few purchases so that the user's balance goes over $10 and is therefore payable
p4 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p4.update_balance_and_mark_successful!
p5 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p5.update_balance_and_mark_successful!
p6 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p6.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
revenue_by_link = Payment.last.revenue_by_link
expect(revenue_by_link.count).to eq 2
expect(revenue_by_link[@product_1.id]).to eq(-723) # - $10 (purchase price) + $1.5 (affiliate commission) + $1.27 (returned fee)
expect(revenue_by_link[@product_2.id]).to eq(3324) # 3 new sales, one chargeback: 3 * (20 - (20 * 0.129 + 50 + 30)) - (20 - 2.88)
end
end
describe "partial refund" do
it "deducts the refund amount if the refund happened in this period but the original purchase did not (fees not waived)" do
refunded_purchase = nil
travel_to(Date.today - 20) do
refunded_purchase = create(:purchase_in_progress, link: @product_3, chargeable: create(:chargeable), affiliate: @affiliate)
refunded_purchase.process!
refunded_purchase.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 14, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
payment = Payment.last
PaypalPayoutProcessor.handle_paypal_event("payment_date" => payment.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => payment.user.payment_address,
"masspay_txn_id_0" => "sometxn1",
"status_0" => "Completed",
"unique_id_0" => payment.id,
"mc_fee_0" => "2.99 ")
travel_to(Date.today - 10) do
refunded_purchase.reload.refund_and_save!(refunded_purchase.seller.id, amount_cents: 1500)
refunded_purchase.is_refund_chargeback_fee_waived = false
refunded_purchase.save!
# A few purchases so that the user's balance goes over $10 and is therefore payable
p4 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p4.update_balance_and_mark_successful!
p5 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p5.update_balance_and_mark_successful!
p6 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p6.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
revenue_by_link = Payment.last.revenue_by_link
expect(revenue_by_link.count).to eq 2
expect(revenue_by_link[@product_3.id]).to eq(-1123) # -$15 (refunded amount) + $2.25 (affiliate commission) + $1.77 (returned fee)
expect(revenue_by_link[@product_2.id]).to eq(4986) # 3 new sales: 3 * (20 - (20 * 0.129 + 50 + 30))
end
it "deducts the refund amount - fee amount if the refund happened in this period but the original purchase did not (fees waived)" do
refunded_purchase = nil
travel_to(Date.today - 20) do
refunded_purchase = create(:purchase_in_progress, link: @product_3, chargeable: create(:chargeable), affiliate: @affiliate)
refunded_purchase.process!
refunded_purchase.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 14, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
payment = Payment.last
PaypalPayoutProcessor.handle_paypal_event("payment_date" => payment.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => payment.user.payment_address,
"masspay_txn_id_0" => "sometxn1",
"status_0" => "Completed",
"unique_id_0" => payment.id,
"mc_fee_0" => "2.99 ")
travel_to(Date.today - 10) do
refunded_purchase.reload.refund_and_save!(refunded_purchase.seller.id, amount_cents: 1500)
# A few purchases so that the user's balance goes over $10 and is therefore payable
p4 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p4.update_balance_and_mark_successful!
p5 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p5.update_balance_and_mark_successful!
p6 = create(:purchase, link: @product_2, price_cents: @product_2.price_cents, purchase_state: "in_progress")
p6.update_balance_and_mark_successful!
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
revenue_by_link = Payment.last.revenue_by_link
expect(revenue_by_link.count).to eq 2
expect(revenue_by_link[@product_3.id]).to eq(-1123) # -$15 (refunded amount) + $2.25 (affiliate commission) + $1.77 (returned fee)
expect(revenue_by_link[@product_2.id]).to eq(4986) # # 3 new sales: 3 * (20 - (20 * 0.129 + 50 + 30))
end
it "deducts the refund amount - refunded fee amount - refunded affiliate amount if the partial refunds and the original purchase both happened in this period (fees waived)" do
travel_to(Date.today - 2) do
partially_refunded_purchase = create(:purchase_in_progress, link: @product_3, chargeable: create(:chargeable), affiliate: @affiliate)
partially_refunded_purchase.process!
partially_refunded_purchase.update_balance_and_mark_successful!
partially_refunded_purchase.reload.refund_and_save!(partially_refunded_purchase.seller.id, amount_cents: 1000)
partially_refunded_purchase.reload.refund_and_save!(partially_refunded_purchase.seller.id, amount_cents: 200)
end
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [@user], from_admin: true)
revenue_by_link = Payment.last.revenue_by_link
expect(revenue_by_link.count).to eq 1
expect(revenue_by_link[@product_3.id]).to eq(1255) # $30 (purchase price) - $12 (refunded amount) - $2.14 (fees) - $2.7 (affiliate commission on remaining $18)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/balance/searchable_spec.rb | spec/modules/balance/searchable_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Balance::Searchable do
it "includes ElasticsearchModelAsyncCallbacks" do
expect(Balance).to include(ElasticsearchModelAsyncCallbacks)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/purchase/risk_spec.rb | spec/modules/purchase/risk_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Purchase::Risk do
before do
Feature.activate(:purchase_check_for_fraudulent_ips)
end
describe "check purchase for previous chargebacks" do
it "returns errors if the email has charged-back" do
product = create(:product)
product_2 = create(:product)
create(:purchase, link: product, email: "tuhins@gmail.com", chargeback_date: Time.current)
new_purchase = build(:purchase, link: product_2, email: "tuhins@gmail.com", created_at: Time.current)
new_purchase.send(:check_for_fraud)
expect(new_purchase.errors.empty?).to be(false)
expect(new_purchase.errors.full_messages).to eq ["There's an active chargeback on one of your past Gumroad purchases. Please withdraw it by contacting your charge processor and try again later."]
end
it "returns errors if the guid has charged-back" do
product = create(:product)
product_2 = create(:product)
create(:purchase, link: product, browser_guid: "blahbluebleh", chargeback_date: Time.current)
new_purchase = build(:purchase, link: product_2, browser_guid: "blahbluebleh", created_at: Time.current)
new_purchase.send(:check_for_fraud)
expect(new_purchase.errors.empty?).to be(false)
expect(new_purchase.errors.full_messages).to eq ["There's an active chargeback on one of your past Gumroad purchases. Please withdraw it by contacting your charge processor and try again later."]
end
it "returns errors if the email is associated with suspended for fraud creator" do
product = create(:product)
create(:user, email: "test@test.test", user_risk_state: "suspended_for_fraud")
create(:purchase, link: product, email: "test@test.test")
new_purchase = build(:purchase, link: product, email: "test@test.test")
new_purchase.send(:check_for_fraud)
expect(new_purchase.errors.empty?).to be(false)
end
it "doesn't return error when buyer user doesn't exist" do
product = create(:product)
purchase = build(:purchase, link: product, email: "nonexistent@example.com")
purchase.send(:check_for_past_fraudulent_buyers)
expect(purchase.errors).to be_empty
end
it "doesn't return error if the chargeback has been won" do
product = create(:product)
product_2 = create(:product)
chargeback_purchase = create(:purchase, link: product, browser_guid: "blahbluebleh", chargeback_date: Time.current)
chargeback_purchase.chargeback_reversed = true
chargeback_purchase.save!
new_purchase = build(:purchase, link: product_2, browser_guid: "blahbluebleh", created_at: Time.current)
new_purchase.send(:check_for_fraud)
expect(new_purchase.errors.empty?).to be(true)
end
end
describe "#check_for_past_chargebacks" do
let(:product) { create(:product) }
let(:new_purchase) { build(:purchase, link: product, email: "test@example.com", browser_guid: "test-guid-123") }
context "when there are no past chargebacks" do
it "does not add errors" do
expect { new_purchase.send(:check_for_past_chargebacks) }.not_to change { new_purchase.errors.count }
expect(new_purchase.error_code).to be_nil
end
end
context "when there is a past chargeback by email" do
before do
create(:purchase, link: product, email: "test@example.com", chargeback_date: Time.current)
end
it "adds chargeback error" do
expect { new_purchase.send(:check_for_past_chargebacks) }
.to change { new_purchase.error_code }.from(nil).to(PurchaseErrorCode::BUYER_CHARGED_BACK)
.and change { new_purchase.errors.count }.by(1)
end
it "sets the correct error message" do
new_purchase.send(:check_for_past_chargebacks)
expect(new_purchase.errors.full_messages).to include("There's an active chargeback on one of your past Gumroad purchases. Please withdraw it by contacting your charge processor and try again later.")
end
end
context "when there is a past chargeback by browser_guid" do
before do
create(:purchase, link: product, browser_guid: "test-guid-123", chargeback_date: Time.current)
end
it "adds chargeback error" do
expect { new_purchase.send(:check_for_past_chargebacks) }
.to change { new_purchase.error_code }.from(nil).to(PurchaseErrorCode::BUYER_CHARGED_BACK)
.and change { new_purchase.errors.count }.by(1)
end
end
context "when there are chargebacks by both email and browser_guid" do
before do
create(:purchase, link: product, email: "test@example.com", chargeback_date: Time.current)
create(:purchase, link: product, browser_guid: "test-guid-123", chargeback_date: Time.current)
end
it "adds chargeback error" do
expect { new_purchase.send(:check_for_past_chargebacks) }
.to change { new_purchase.error_code }.from(nil).to(PurchaseErrorCode::BUYER_CHARGED_BACK)
.and change { new_purchase.errors.count }.by(1)
end
end
context "when chargeback has been reversed" do
before do
chargeback_purchase = create(:purchase, link: product, email: "test@example.com", chargeback_date: Time.current)
chargeback_purchase.chargeback_reversed = true
chargeback_purchase.save!
end
it "does not add errors" do
expect { new_purchase.send(:check_for_past_chargebacks) }.not_to change { new_purchase.errors.count }
expect(new_purchase.error_code).to be_nil
end
end
context "when purchase has no email" do
let(:new_purchase) { build(:purchase, link: product, email: nil, browser_guid: "test-guid-123") }
it "only checks browser_guid" do
create(:purchase, link: product, browser_guid: "test-guid-123", chargeback_date: Time.current)
expect { new_purchase.send(:check_for_past_chargebacks) }
.to change { new_purchase.error_code }.from(nil).to(PurchaseErrorCode::BUYER_CHARGED_BACK)
end
end
context "when purchase has no browser_guid" do
let(:new_purchase) { build(:purchase, link: product, email: "test@example.com", browser_guid: nil) }
it "only checks email" do
create(:purchase, link: product, email: "test@example.com", chargeback_date: Time.current)
expect { new_purchase.send(:check_for_past_chargebacks) }
.to change { new_purchase.error_code }.from(nil).to(PurchaseErrorCode::BUYER_CHARGED_BACK)
end
end
context "when purchase has neither email nor browser_guid" do
let(:new_purchase) { build(:purchase, link: product, email: nil, browser_guid: nil) }
it "does not add errors" do
expect { new_purchase.send(:check_for_past_chargebacks) }.not_to change { new_purchase.errors.count }
expect(new_purchase.error_code).to be_nil
end
end
end
describe "#check_for_fraud" do
before do
@user = create(:user, account_created_ip: "123.121.11.1")
@product = create(:product, user: @user)
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "192.378.12.1", nil, expires_in: 1.hour)
end
it "handles timeout and returns nil" do
purchase = build(:purchase, link: @product)
allow(purchase).to receive(:check_for_past_blocked_emails).and_raise(Timeout::Error.new("timeout"))
allow(purchase).to receive(:logger).and_return(double(info: nil))
result = purchase.send(:check_for_fraud)
expect(result).to be_nil
end
it "returns errors if the buyer ip_address has been blocked" do
good_purchase = build(:purchase, link: @product, ip_address: "128.12.11.11")
good_purchase.send(:check_for_fraud)
expect(good_purchase.errors.empty?).to be(true)
bad_purchase = build(:purchase, link: @product, ip_address: "192.378.12.1")
bad_purchase.send(:check_for_fraud)
expect(bad_purchase.errors.empty?).to be(false)
expect(bad_purchase.errors.full_messages).to eq ["Your card was not charged. Please try again on a different browser and/or internet connection."]
end
it "returns errors if the buyer browser_guid has been blocked" do
browser_guid = "abc123"
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:browser_guid], browser_guid, nil, expires_in: 1.hour)
bad_purchase = build(:purchase, link: @product, browser_guid:)
bad_purchase.send(:check_for_fraud)
expect(bad_purchase.errors.empty?).to be(false)
expect(bad_purchase.errors.full_messages).to eq ["Your card was not charged. Please try again on a different browser and/or internet connection."]
end
it "returns errors if the seller ip_address has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "123.121.11.1", nil, expires_in: 1.hour)
bad_purchase = build(:purchase, link: @product, seller: @user)
bad_purchase.send(:check_for_fraud)
expect(bad_purchase.errors.empty?).to be(false)
end
describe "ip_address check" do
let(:blocked_ip_address) { "192.1.2.3" }
before do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], blocked_ip_address, nil, expires_in: 1.hour)
end
it "returns error if the purchaser's ip_address has been blocked" do
purchaser = create(:user, current_sign_in_ip: blocked_ip_address)
purchase = build(:purchase, purchaser:)
expect do
purchase.check_for_fraud
end.to change { purchase.error_code }
.from(nil).to(PurchaseErrorCode::BLOCKED_IP_ADDRESS)
.and change { purchase.errors.empty? }.from(true).to(false)
.and change { purchase.errors.full_messages }.from([]).to(["Your card was not charged. Please try again on a different browser and/or internet connection."])
end
describe "subscription purchase" do
let(:subscription) { create(:subscription) }
context "when it is an original subscription purchase" do
it "returns error if the ip_address is blocked" do
purchase = build(:membership_purchase, is_original_subscription_purchase: true, ip_address: blocked_ip_address, subscription:)
purchase.send(:check_for_fraud)
expect(purchase.errors.empty?).to be(false)
expect(purchase.errors.full_messages).to eq ["Your card was not charged. Please try again on a different browser and/or internet connection."]
end
end
context "when it is a subscription recurring charge" do
it "doesn't block the purchase when ip_address is blocked" do
create(:membership_purchase, is_original_subscription_purchase: true, subscription:)
purchase = build(:membership_purchase, is_original_subscription_purchase: false, ip_address: blocked_ip_address, subscription:)
purchase.send(:check_for_fraud)
expect(purchase.errors).to be_empty
expect(purchase).to be_valid
end
end
context "when it's a free purchase" do
it "doesn't block the purchase when ip_address is blocked" do
purchase = build(:free_purchase, ip_address: blocked_ip_address)
purchase.send(:check_for_fraud)
expect(purchase.errors).to be_empty
expect(purchase).to be_valid
end
end
end
end
context "when the creator's ip_address has been blocked but the seller is compliant" do
let(:seller) { @product.user }
before do
seller.update!(account_created_ip: "123.121.11.1", user_risk_state: "compliant")
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "123.121.11.1", nil, expires_in: 1.hour)
end
it "doesn't return errors" do
purchase = build(:purchase, link: @product, seller:)
purchase.send(:check_for_fraud)
expect(purchase.errors.empty?).to be(true)
end
end
describe "#check_for_past_blocked_email_domains" do
let!(:purchaser) { create(:user) }
let!(:purchase) { build(:purchase, purchaser:, email: "john@example.com") }
context "when it is a paid product" do
vague_purchase_error_notice = "Your card was not charged."
it "returns error if the specified email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], "example.com", nil)
expect do
purchase.check_for_fraud
end.to change { purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice)
end
it "returns error if the purchaser's email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], Mail::Address.new(purchaser.email).domain, nil)
expect do
purchase.check_for_fraud
end.to change { purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice)
end
context "when it is a gift purchase" do
let!(:product) { create(:product, price_cents: 100) }
let(:gift) { create(:gift, gifter_email: "gifter@gifter.com", giftee_email: "giftee@giftee.com", link: product) }
let(:gifter_purchase) do build(:purchase, link: product,
seller: product.user,
price_cents: product.price_cents,
email: gift.gifter_email,
is_gift_sender_purchase: true,
gift_given: gift,
purchase_state: "in_progress") end
let(:giftee_purchase) do build(:purchase, link: product,
seller: product.user,
email: gift.giftee_email,
price_cents: 0,
is_gift_receiver_purchase: true,
gift_received: gift,
purchase_state: "in_progress") end
before do
gift.gifter_purchase = gifter_purchase
gift.giftee_purchase = giftee_purchase
end
it "returns error if the gift recipient's email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], "giftee.com", nil)
expect(giftee_purchase.price_cents).to eq 0
expect(gifter_purchase.price_cents).to eq 100
expect do
giftee_purchase.check_for_fraud
end.to change { giftee_purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { giftee_purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice)
end
it "returns error if the gift sender's email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], "gifter.com", nil)
expect do
gifter_purchase.check_for_fraud
end.to change { gifter_purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { gifter_purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice)
end
end
end
context "when it is a free product" do
let!(:free_purchase) { build(:purchase, purchaser:, email: "john@example.com", price_cents: 0) }
vague_purchase_error_notice_for_free_products = "The transaction could not complete."
it "returns error if the specified email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], "example.com", nil)
expect do
free_purchase.check_for_fraud
end.to change { free_purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { free_purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice_for_free_products)
end
it "returns error if the purchaser's email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], Mail::Address.new(purchaser.email).domain, nil)
expect do
free_purchase.check_for_fraud
end.to change { free_purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { free_purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice_for_free_products)
end
context "when it is a gift purchase" do
let!(:product) { create(:product, price_cents: 0) }
let(:gift) { create(:gift, gifter_email: "gifter@gifter.com", giftee_email: "giftee@giftee.com", link: product) }
let(:gifter_purchase) do build(:purchase, link: product,
seller: product.user,
price_cents: product.price_cents,
email: gift.gifter_email,
is_gift_sender_purchase: true,
gift_given: gift,
purchase_state: "in_progress") end
let(:giftee_purchase) do build(:purchase, link: product,
seller: product.user,
email: gift.giftee_email,
price_cents: 0,
is_gift_receiver_purchase: true,
gift_received: gift,
purchase_state: "in_progress") end
before do
gift.gifter_purchase = gifter_purchase
gift.giftee_purchase = giftee_purchase
end
it "returns error if the gift recipient's email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], "giftee.com", nil)
expect(giftee_purchase.price_cents).to eq 0
expect(gifter_purchase.price_cents).to eq 0
expect do
giftee_purchase.check_for_fraud
end.to change { giftee_purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { giftee_purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice_for_free_products)
end
it "returns error if the gift sender's email domain has been blocked" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], "gifter.com", nil)
expect do
gifter_purchase.check_for_fraud
end.to change { gifter_purchase.error_code }.from(nil).to(PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN)
.and change { gifter_purchase.errors.full_messages.to_sentence }.from("").to(vague_purchase_error_notice_for_free_products)
end
end
end
it "doesn't return an error if neither the purchaser email's domain nor the specified email's domain has been blocked" do
expect do
purchase.check_for_fraud
end.to_not change { purchase.error_code }
expect(purchase.errors.any?).to be(false)
end
context "when purchaser has blank email" do
let(:purchaser) { create(:user, email: "", provider: "twitter") }
it "doesn't return an error" do
expect do
purchase.check_for_fraud
end.to_not change { purchase.error_code }
expect(purchase.errors.any?).to be(false)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/purchase/reviews_spec.rb | spec/modules/purchase/reviews_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Purchase::Reviews do
describe "#post_review" do
context "non-recurring purchase" do
let!(:purchase) { create(:purchase) }
context "when there is an existing product_review" do
let!(:existing_product_review) { create(:product_review, purchase:, rating: 1, message: "Original message") }
it "updates the existing product_review with the provided rating" do
result = purchase.post_review(rating: 1, message: "Updated message")
expect(result).to eq(existing_product_review)
expect(result.rating).to eq(1)
expect(result.message).to eq("Updated message")
end
it "does not update the rating if the purchase does not allow reviews to be counted" do
purchase.update!(stripe_refunded: true)
expect { purchase.post_review(rating: 5, message: "Updated message") }.to raise_error(ProductReview::RestrictedOperationError)
expect(existing_product_review.reload.rating).to eq(1)
expect(existing_product_review.message).to eq("Original message")
end
end
context "when there is no existing product_review" do
it "creates a new product review for a purchase that allows reviews to be counted" do
expect(purchase.product_review).to be(nil)
result = purchase.post_review(rating: 1, message: "Updated message")
expect(result).to be_a(ProductReview)
expect(result.rating).to eq(1)
expect(result.message).to eq("Updated message")
expect(result.purchase).to eq(purchase)
end
it "creates a product review and enqueues an email notification" do
expect(purchase.product_review).to be(nil)
expect do
purchase.post_review(rating: 1, message: "Updated message")
end.to have_enqueued_mail(ContactingCreatorMailer, :review_submitted).with { purchase.reload.product_review.id }
expect(purchase.reload.product_review).not_to be(nil)
expect(purchase.product_review.rating).to eq(1)
expect(purchase.product_review.message).to eq("Updated message")
end
it "does not enqueue an email when review notifications are disabled" do
purchase.seller.update(disable_reviews_email: true)
expect do
purchase.post_review(rating: 1, message: "Updated message")
end.to_not have_enqueued_mail(ContactingCreatorMailer, :review_submitted)
end
it "does not add review when the purchase does not allow reviews to be counted" do
allow(purchase).to receive(:allows_review_to_be_counted?).and_return(false)
expect { purchase.post_review(rating: 1, message: "Updated message") }.to raise_error(ProductReview::RestrictedOperationError)
expect(purchase.reload.product_review).to be_blank
end
it "saves the link_id associated with the purchase on the product review" do
review = purchase.post_review(rating: 1, message: "Updated message")
expect(review.link_id).to eq(purchase.link_id)
end
end
end
context "recurring purchase" do
let!(:subscription_product) { create(:subscription_product) }
let!(:subscription) { create(:subscription, link: subscription_product) }
let!(:original_purchase) { create(:purchase, link: subscription_product, is_original_subscription_purchase: true, subscription:) }
let!(:recurring_purchase) { create(:purchase, link: subscription_product, subscription:) }
before { recurring_purchase.reload }
context "when there is an existing product_review" do
let!(:product_review) { create(:product_review, rating: 1, purchase: original_purchase) }
it "updates the product review of the original purchase in case of recurring purchase of a subscription" do
result = recurring_purchase.post_review(rating: 1)
expect(result).to eq(product_review)
original_purchase.reload
expect(original_purchase.product_review.rating).to eq(1)
expect(original_purchase.product_review.message).to be_nil
end
end
context "when there is no existing product_review" do
it "adds product review to the original purchase in case of recurring purchase of a subscription" do
review = recurring_purchase.post_review(rating: 1)
expect(review.purchase).to eq(original_purchase)
expect(original_purchase.reload.product_review.rating).to eq(1)
end
end
end
end
describe "#update_product_review_stat" do
it "does not update the product_review_stat after update if no product review exists" do
purchase = create(:purchase)
expect(purchase.link).not_to receive(:update_review_stat_via_purchase_changes)
purchase.stripe_refunded = true
purchase.save!
end
it "does not update the product_review_stat after update if no changes have been saved" do
purchase = create(:purchase)
expect(purchase.link).not_to receive(:update_review_stat_via_purchase_changes)
purchase.save(id: purchase.id)
purchase.save!
end
it "updates the product_review_stat after update" do
purchase = create(:purchase)
purchase.post_review(rating: 3)
expect(purchase.link).to receive(:update_review_stat_via_purchase_changes).with(
hash_including("stripe_refunded" => [nil, true]),
product_review: purchase.product_review
)
purchase.stripe_refunded = true
purchase.save!
end
end
describe "#refund_purchase! effect on reviews" do
it "updates product_review_stat" do
purchase = create(:purchase)
product = purchase.link
expect(product.average_rating).to eq(0)
purchase.post_review(rating: 3)
expect(product.average_rating).to eq(3)
purchase.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, purchase.total_transaction_cents), purchase.seller.id)
expect(product.average_rating).to eq(0)
expect(purchase.product_review).to be_deleted
end
end
describe "revoking/unrevoking access" do
it "updates the product review" do
purchase = create(:purchase, price_cents: 0)
product = purchase.link
expect(product.average_rating).to eq(0)
purchase.post_review(rating: 3)
expect(product.average_rating).to eq(3)
purchase.update!(is_access_revoked: true)
expect(product.average_rating).to eq(0)
expect(purchase.product_review).to be_deleted
purchase.update!(is_access_revoked: false)
expect(product.average_rating).to eq(3)
expect(purchase.product_review).to be_alive
end
end
describe "#allows_review_to_be_counted? & .allowing_reviews_to_be_counted & #allows_review?", :vcr do
before do
@non_matching_purchases = [
create(:test_purchase),
create(:preorder_authorization_purchase),
create(:failed_purchase),
create(:refunded_purchase),
create(:free_purchase, is_access_revoked: true),
create(:disputed_purchase),
create(:purchase_in_progress),
create(:disputed_purchase),
create(:purchase, is_gift_sender_purchase: true),
create(:purchase, should_exclude_product_review: true),
create(:purchase, is_bundle_purchase: true),
create(:purchase, is_commission_completion_purchase: true)
]
@matching_purchases = [
create(:purchase),
create(:purchase, purchase_state: "gift_receiver_purchase_successful", is_gift_receiver_purchase: true),
create(:free_trial_membership_purchase, should_exclude_product_review: false),
create(:purchase_2, is_access_revoked: true),
]
true_original_purchase = create(:membership_purchase, is_original_subscription_purchase: true, is_archived_original_subscription_purchase: true)
@matching_purchases << true_original_purchase
new_original_purchase = create(:purchase, link: true_original_purchase.link, subscription: true_original_purchase.subscription.reload, is_original_subscription_purchase: true, purchase_state: "not_charged")
@non_matching_purchases << new_original_purchase
upgrade_purchase = create(:purchase, link: true_original_purchase.link, subscription: true_original_purchase.subscription, is_upgrade_purchase: true)
@non_matching_purchases << upgrade_purchase
@recurring_purchase = create(:purchase, subscription: new_original_purchase.subscription)
end
it "is only valid for matching successful or free trial purchases" do
@non_matching_purchases << @recurring_purchase
expect(@matching_purchases.all?(&:allows_review_to_be_counted?)).to eq(true)
expect(@non_matching_purchases.none?(&:allows_review_to_be_counted?)).to eq(true)
expect(Purchase.allowing_reviews_to_be_counted.load).to match_array(@matching_purchases)
end
it "returns true for recurring subscription purchases" do
@matching_purchases << @recurring_purchase
expect(@matching_purchases.all?(&:allows_review?)).to eq(true)
end
end
describe "#original_product_review" do
context "when purchase is for a subscription" do
let!(:original_purchase) { create(:membership_purchase, is_original_subscription_purchase: true) }
let!(:recurring_purchase) { original_purchase.subscription.charge! }
let!(:product_review) { create(:product_review, purchase: original_purchase) }
it "returns the product review of the original purchase for all purchases in the subscription" do
expect(original_purchase.reload.original_product_review).to eq(product_review)
expect(recurring_purchase.reload.original_product_review).to eq(product_review)
end
end
context "when purchase is a gift" do
let!(:product) { create(:product) }
let!(:gift) { create(:gift, link: product) }
let!(:gifter_purchase) { create(:purchase, :gift_sender, link: product, gift_given: gift) }
let!(:giftee_purchase) { create(:purchase, :gift_receiver, link: product, is_gift_receiver_purchase: true, gift_received: gift) }
let!(:product_review) { create(:product_review, purchase: giftee_purchase) }
it "returns giftee's product review for either purchases" do
expect(giftee_purchase.original_product_review).to eq(product_review)
expect(gifter_purchase.original_product_review).to eq(product_review)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/purchase/accounting_spec.rb | spec/modules/purchase/accounting_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Purchase::Accounting do
describe "#price_dollars" do
it "returns price_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:price_cents).and_return(1234)
expect(purchase.price_dollars).to eq(12.34)
end
end
describe "#variant_extra_cost_dollars" do
it "returns variant_extra_cost in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:variant_extra_cost).and_return(1234)
expect(purchase.variant_extra_cost_dollars).to eq(12.34)
end
end
describe "#tax_dollars" do
it "returns tax_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:gumroad_tax_cents).and_return(0)
allow(purchase).to receive(:tax_cents).and_return(1234)
expect(purchase.tax_dollars).to eq(12.34)
end
it "returns gumroad_tax_cents in dollars if present" do
purchase = create(:purchase)
allow(purchase).to receive(:gumroad_tax_cents).and_return(5678)
allow(purchase).to receive(:tax_cents).and_return(0)
expect(purchase.tax_dollars).to eq(56.78)
end
end
describe "#variant_extra_cost_dollars" do
it "returns variant_extra_cost in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:variant_extra_cost).and_return(1234)
expect(purchase.variant_extra_cost_dollars).to eq(12.34)
end
end
describe "#shipping_dollars" do
it "returns shipping_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:shipping_cents).and_return(1234)
expect(purchase.shipping_dollars).to eq(12.34)
end
end
describe "#fee_dollars" do
it "returns fee_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:fee_cents).and_return(1234)
expect(purchase.fee_dollars).to eq(12.34)
end
end
describe "#processor_fee_dollars" do
it "returns processor_fee_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:processor_fee_cents).and_return(1234)
expect(purchase.processor_fee_dollars).to eq(12.34)
end
end
describe "#affiliate_credit_dollars" do
it "returns affiliate_credit_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:affiliate_credit_cents).and_return(1234)
expect(purchase.affiliate_credit_dollars).to eq(12.34)
end
end
describe "#net_total" do
it "returns price_cents - fee_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:price_cents).and_return(1234)
allow(purchase).to receive(:fee_cents).and_return(1126)
expect(purchase.net_total).to eq(1.08)
end
end
describe "#sub_total" do
it "returns price_cents - tax_cents - shipping_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:price_cents).and_return(1234)
allow(purchase).to receive(:tax_cents).and_return(78)
allow(purchase).to receive(:shipping_cents).and_return(399)
expect(purchase.sub_total).to eq(7.57)
end
end
describe "#amount_refunded_dollars" do
it "returns amount_refunded_cents in dollars" do
purchase = create(:purchase)
allow(purchase).to receive(:amount_refunded_cents).and_return(1234)
expect(purchase.amount_refunded_dollars).to eq(12.34)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/purchase/targeting_spec.rb | spec/modules/purchase/targeting_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Purchase::Targeting do
before do
@seller = create(:user)
@product = create(:product, user: @seller)
@product2 = create(:product, user: @seller)
@product3 = create(:product, user: @seller)
@purchase1 = create(:purchase, price_cents: 500, link: @product, created_at: 1.week.ago)
@purchase2 = create(:purchase, price_cents: 100, link: @product, email: "anish@gumroad.com", created_at: 2.weeks.ago)
@purchase3 = create(:purchase, price_cents: 1000, link: @product2, created_at: 1.week.ago)
@purchase4 = create(:purchase, price_cents: 900, link: @product2, email: "anish@gumroad.com", created_at: 2.weeks.ago)
@purchase5 = create(:purchase, price_cents: 800, link: @product2, email: "anish2@gumroad.com", created_at: 3.weeks.ago)
@purchase6 = create(:purchase, price_cents: 2500, link: @product3, created_at: 1.week.ago)
@purchase7 = create(:purchase, price_cents: 2000, link: @product3, email: "anish@gumroad.com", created_at: 2.weeks.ago)
@purchase8 = create(:purchase, link: @product3, email: "anish3@gumroad.com", created_at: 3.weeks.ago)
end
describe "#by_variant" do
before do
category = create(:variant_category, title: "title", link: @product)
@variant1 = create(:variant, variant_category: category, name: "V1")
@variant2 = create(:variant, variant_category: category, name: "V2")
@purchase1.variant_attributes << @variant1
@purchase2.variant_attributes << @variant2
end
it "does nothing if no variant_id is passed" do
expect(Purchase.by_variant(nil).count).to eq 8
end
it "filters by variant if variant_id is passed" do
expect(Purchase.by_variant(@variant1.id).count).to eq 1
expect(Purchase.by_variant(@variant1.id).first).to eq @purchase1
expect(Purchase.by_variant(@variant2.id).count).to eq 1
expect(Purchase.by_variant(@variant2.id).first).to eq @purchase2
end
end
describe "#for_products" do
it "does nothing if no bought products are passed" do
expect(Purchase.for_products(nil).count).to eq 8
end
it "filters by product if only one bought product is passed" do
expect(Purchase.for_products([@product.id]).count).to eq 2
expect(Purchase.for_products([@product2.id]).count).to eq 3
end
it "filters by multiple products if more than one bought product is passed" do
expect(Purchase.for_products([@product.id, @product2.id]).count).to eq 5
expect(Purchase.for_products([@product3.id, @product2.id]).count).to eq 6
expect(Purchase.for_products([@product.id, @product3.id, @product2.id]).count).to eq 8
end
end
describe "#email_not" do
it "excludes the purchases made with specific emails" do
link = create(:product)
purchase1 = create(:purchase, link:, email: "gum1@gr.co")
create(:purchase, link: create(:product), email: "gum2@gr.co")
purchase3 = create(:purchase, link:, email: "gum3@gr.co")
create(:purchase, link: create(:product), email: "gum4@gr.co")
result = Purchase.for_products([link.id])
expect(result.map(&:id)).to match_array([purchase1.id, purchase3.id])
result = Purchase.for_products([link.id]).email_not(["gum2@gr.co", "gum3@gr.co"])
expect(result.map(&:id)).to eq([purchase1.id])
end
end
describe "paid" do
before do
@purchase8.update_attribute(:price_cents, 0)
end
describe "#paid_more_than" do
it "does nothing if no paid_more_than is passed" do
expect(Purchase.paid_more_than(nil).count).to eq 8
end
it "filters by paid if paid_more_than is passed" do
expect(Purchase.paid_more_than(100).count).to eq 6
expect(Purchase.paid_more_than(500).count).to eq 5
expect(Purchase.paid_more_than(1500).count).to eq 2
expect(Purchase.paid_more_than(2000).count).to eq 1
expect(Purchase.paid_more_than(5000).count).to eq 0
end
end
describe "#paid_less_than" do
it "does nothing if no paid_less_than is passed" do
expect(Purchase.paid_less_than(nil).count).to eq 8
end
it "filters by paid if paid_less_than is passed" do
expect(Purchase.paid_less_than(100).count).to eq 1
expect(Purchase.paid_less_than(500).count).to eq 2
expect(Purchase.paid_less_than(1500).count).to eq 6
expect(Purchase.paid_less_than(2200).count).to eq 7
expect(Purchase.paid_less_than(5000).count).to eq 8
end
end
describe "paid between" do
it "does nothing if no paid_more_than or paid_less_than are passed" do
expect(Purchase.paid_less_than(nil).paid_more_than(nil).count).to eq 8
end
it "filters by paid between if both scopes are applied" do
expect(Purchase.paid_more_than(0).paid_less_than(100).count).to eq 0
expect(Purchase.paid_more_than(99).paid_less_than(500).count).to eq 1
expect(Purchase.paid_more_than(400).paid_less_than(1500).count).to eq 4
expect(Purchase.paid_more_than(600).paid_less_than(2200).count).to eq 4
expect(Purchase.paid_more_than(2000).paid_less_than(5000).count).to eq 1
expect(Purchase.paid_more_than(4000).paid_less_than(5000).count).to eq 0
end
end
end
describe "created" do
describe "#created_after" do
it "does nothing if no date passed" do
expect(Purchase.created_after(nil).count).to eq 8
end
it "filters by created at if date is passed" do
expect(Purchase.created_after(Date.today - 1.day).count).to eq 0
expect(Purchase.created_after(Date.today - 8.days).count).to eq 3
expect(Purchase.created_after(Date.today - 15.days).count).to eq 6
expect(Purchase.created_after(Date.today - 22.days).count).to eq 8
end
end
describe "#created_before" do
it "does nothing if no date is passed" do
expect(Purchase.created_before(nil).count).to eq 8
end
it "filters by created at if date is passed" do
expect(Purchase.created_before(Date.today - 1.day).count).to eq 8
expect(Purchase.created_before(Date.today - 8.days).count).to eq 5
expect(Purchase.created_before(Date.today - 15.days).count).to eq 2
expect(Purchase.created_before(Date.today - 22.days).count).to eq 0
end
end
describe "created between" do
it "does nothing if no after date or before date are passed" do
expect(Purchase.created_after(nil).created_before(nil).count).to eq 8
end
it "filters by paid between if both scopes are applied" do
expect(Purchase.created_after(Date.today - 22.days).created_before(Date.today - 1.day).count).to eq 8
expect(Purchase.created_after(Date.today - 15.days).created_before(Date.today - 8.days).count).to eq 3
expect(Purchase.created_after(Date.today - 8.days).created_before(Date.today).count).to eq 3
expect(Purchase.created_after(Date.today - 18.days).created_before(Date.today - 5.days).count).to eq 6
expect(Purchase.created_after(Date.today - 1.day).created_before(Date.today).count).to eq 0
end
end
end
describe "#filter_by_country_bought_from" do
before do
@purchase1.update_attribute(:country, "United States")
@purchase2.update_attribute(:country, "Canada")
@purchase3.update_attribute(:country, "Canada")
@purchase4.update_attribute(:country, "United States")
@purchase3.update_attribute(:ip_country, "United States")
@purchase4.update_attribute(:ip_country, "Canada")
@purchase5.update_attribute(:country, "Korea, Republic of")
@purchase6.update_attribute(:country, "South Korea")
end
it "does nothing if no bought_from is passed" do
expect(Purchase.country_bought_from(nil).count).to eq 8
end
it "filters by country or ip country if bought_from is passed" do
expect(Purchase.country_bought_from("United States").count).to eq 2
expect(Purchase.country_bought_from("United States").include?(@purchase3)).to eq false
expect(Purchase.country_bought_from("Canada").count).to eq 2
expect(Purchase.country_bought_from("Canada").include?(@purchase4)).to eq false
end
it "filters by country for a country whose name is different for `countries` gem and `iso_country_codes` gem" do
expect(Purchase.country_bought_from("Korea, Republic of").count).to eq 2
expect(Purchase.country_bought_from("South Korea").count).to eq 2
end
end
describe "#by_external_variant_ids_or_products" do
before do
category = create(:variant_category, link: @product)
@variant1 = create(:variant, variant_category: category, name: "V1")
@variant2 = create(:variant, variant_category: category, name: "V2")
@purchase1.variant_attributes << @variant1
@purchase2.variant_attributes << @variant2
end
it "returns purchases for both products and variants" do
result = Purchase.by_external_variant_ids_or_products(@variant1.external_id, [@product2.id, @product3.id])
expect(result).to include(@purchase1, @purchase3, @purchase4, @purchase5, @purchase6, @purchase7, @purchase8)
expect(result.length).to eq 7
end
it "returns purchases for variants if product_ids are blank" do
result = Purchase.by_external_variant_ids_or_products(@variant2.external_id, nil)
expect(result).to include(@purchase2)
expect(result.length).to eq 1
end
it "returns purchase for products if external_variant_ids are nil" do
result = Purchase.by_external_variant_ids_or_products(nil, @product)
expect(result).to include(@purchase1, @purchase2)
expect(result.length).to eq 2
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/modules/purchase/ping_notification_spec.rb | spec/modules/purchase/ping_notification_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Purchase::PingNotification, :vcr do
describe "#payload_for_ping_notification" do
it "contains the correct resource_name" do
purchase = create(:purchase, stripe_refunded: true)
[ResourceSubscription::SALE_RESOURCE_NAME, ResourceSubscription::REFUNDED_RESOURCE_NAME].each do |resource_name|
params = purchase.payload_for_ping_notification(resource_name:)
expect(params[:resource_name]).to eq(resource_name)
end
end
it "contains the 'refunded' key if the input resource_name is 'refunded'" do
purchase = create(:purchase, stripe_refunded: true)
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::REFUNDED_RESOURCE_NAME)
expect(params[:refunded]).to be(true)
end
it "contains the 'disputed' key set to true if purchase is chargebacked, else false" do
purchase = create(:purchase)
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::DISPUTE_RESOURCE_NAME)
expect(params[:disputed]).to be(false)
purchase.chargeback_date = Date.today
purchase.save!
params = purchase.reload.payload_for_ping_notification(resource_name: ResourceSubscription::DISPUTE_RESOURCE_NAME)
expect(params[:disputed]).to be(true)
end
it "contains the 'dispute_won' key set to true if purchase is chargeback_reversed, else false" do
purchase = create(:purchase, chargeback_date: Date.today)
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::DISPUTE_WON_RESOURCE_NAME)
expect(params[:dispute_won]).to be(false)
purchase.chargeback_reversed = true
purchase.save!
params = purchase.reload.payload_for_ping_notification(resource_name: ResourceSubscription::DISPUTE_WON_RESOURCE_NAME)
expect(params[:dispute_won]).to be(true)
end
it "has the correct value for 'discover_fee_charged'" do
purchase = create(:purchase, was_discover_fee_charged: true)
params = purchase.reload.payload_for_ping_notification
expect(params[:discover_fee_charged]).to be(true)
end
it "has the correct value for 'can_contact'" do
purchase = create(:purchase, can_contact: nil)
params = purchase.reload.payload_for_ping_notification
expect(params[:can_contact]).to be(false)
end
it "has the correct value for 'referrer'" do
referrer = "https://myreferrer.com"
purchase = create(:purchase, referrer:)
params = purchase.reload.payload_for_ping_notification
expect(params[:referrer]).to eq(referrer)
end
it "has the correct value for 'gumroad_fee'" do
purchase = create(:purchase, price_cents: 500)
params = purchase.reload.payload_for_ping_notification
expect(params[:gumroad_fee]).to be(145) # 500 * 0.129 + 50c + 30c
end
it "has the correct value for 'card'" do
purchaser = create(:user, credit_card: create(:credit_card))
purchase = create(:purchase, price_cents: 500, purchaser:)
params = purchase.reload.payload_for_ping_notification
expect(params[:card]).to eq({
bin: nil,
expiry_month: nil,
expiry_year: nil,
type: "visa",
visual: "**** **** **** 4062"
})
end
it "has the correct link information" do
purchase = create(:purchase)
product = purchase.link
unique_permalink = product.unique_permalink
custom_permalink = "GreatestProductEver"
product.update!(custom_permalink:)
payload = purchase.reload.payload_for_ping_notification
expect(payload[:permalink]).to eq(custom_permalink)
expect(payload[:product_permalink]).to eq(product.long_url)
expect(payload[:short_product_id]).to eq(unique_permalink)
end
it "doesn't set the card expiry month and year fields" do
purchase = create(:purchase, card_expiry_month: 11, card_expiry_year: 2022)
payload = purchase.reload.payload_for_ping_notification
expect(payload[:card][:expiry_month]).to be_nil
expect(payload[:card][:expiry_year]).to be_nil
end
describe "custom fields" do
let(:purchase) { create(:purchase) }
context "when purchase has custom fields set" do
before do
purchase.purchase_custom_fields << build(:purchase_custom_field, name: "name", value: "Amy")
end
it "includes the purchase's custom fields" do
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params[:custom_fields].keys).to eq ["name"]
expect(params[:custom_fields]["name"]).to eq "Amy"
end
end
context "when the purchase does not have custom fields set" do
context "and is not a subscription purchase" do
it "does not include the 'custom_fields' key" do
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params.has_key?(:custom_fields)).to eq false
end
end
context "and is a subscription purchase" do
let(:sub) { create(:subscription) }
let(:original_purchase) { create(:membership_purchase, subscription: sub) }
let(:purchase) { create(:membership_purchase, subscription: sub, is_original_subscription_purchase: false) }
it "includes the subscription's 'custom_fields'" do
original_purchase.purchase_custom_fields << build(:purchase_custom_field, name: "name", value: "Amy")
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params[:custom_fields].keys).to eq ["name"]
expect(params[:custom_fields]["name"]).to eq "Amy"
original_purchase.purchase_custom_fields.destroy_all
sub.reload
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params.has_key?(:custom_fields)).to eq false
end
end
end
end
describe "is_multiseat_license" do
context "when the purchased product is licensed" do
it "includes the 'is_multiseat_license' key" do
product = create(:membership_product, is_licensed: true, is_multiseat_license: true)
purchase = create(:membership_purchase, link: product, license: create(:license))
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params.has_key?(:is_multiseat_license)).to eq true
expect(params[:is_multiseat_license]).to eq true
product = create(:membership_product, is_licensed: true, is_multiseat_license: false)
purchase = create(:membership_purchase, link: product, license: create(:license))
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params.has_key?(:is_multiseat_license)).to eq true
expect(params[:is_multiseat_license]).to eq false
end
end
context "when the purchased product is not licensed" do
it "does not include the 'is_multiseat_license' key" do
product = create(:membership_product, is_licensed: false)
purchase = create(:membership_purchase, link: product)
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::SALE_RESOURCE_NAME)
expect(params.has_key?(:is_multiseat_license)).to eq false
end
end
end
end
context "when the product is physical with variants" do
let(:variant) { create(:variant) }
let(:purchase) { create(:purchase, variant_attributes: [variant]) }
before do
purchase.link.is_physical = true
end
it "includes sku_id in the payload" do
params = purchase.payload_for_ping_notification
expect(params[:sku_id]).to eq(variant.external_id)
expect(params[:original_sku_id]).to be_nil
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/payouts/payout_estimates_spec.rb | spec/business/payments/payouts/payout_estimates_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PayoutEstimates do
describe "estimate_held_amount_cents" do
let(:payout_date) { Date.today - 1 }
let(:payout_processor_type) { PayoutProcessorType::STRIPE }
# user who has some balances in the payout period and out of it
let(:u0) { create(:user_with_compliance_info) }
let(:u0m1) { create(:merchant_account, user: u0, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:u0a1) { create(:ach_account, user: u0, stripe_bank_account_id: "ba_1234") }
let(:u0b1) { create(:balance, user: u0, date: payout_date - 3, amount_cents: 1_00, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) }
let(:u0b2) { create(:balance, user: u0, date: payout_date - 2, amount_cents: 10_00, merchant_account: u0m1) }
let(:u0b3) { create(:balance, user: u0, date: payout_date + 1, amount_cents: 100_00, merchant_account: u0m1) }
before { u0 && u0m1 && u0a1 && u0b1 && u0b2 && u0b3 }
# user who has some balances in the payout period and out of it
let(:u1) { create(:user_with_compliance_info) }
let(:u1m1) { create(:merchant_account, user: u1, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:u1a1) { create(:ach_account, user: u1, stripe_bank_account_id: "ba_1234") }
let(:u1b1) { create(:balance, user: u1, date: payout_date - 3, amount_cents: 1_00, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) }
let(:u1b2) { create(:balance, user: u1, date: payout_date - 2, amount_cents: 10_00, merchant_account: u1m1) }
let(:u1b3) { create(:balance, user: u1, date: payout_date + 1, amount_cents: 100_00, merchant_account: u1m1) }
before { u1 && u1m1 && u1a1 && u1b1 && u1b2 && u1b3 }
# user who doesn't have enough in balances to be paid out, but has a payment already made for the same period which makes it enough
let(:u2) { create(:user_with_compliance_info) }
let(:u2m1) { create(:merchant_account, user: u2, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:u2a1) { create(:ach_account, user: u2, stripe_bank_account_id: "ba_1235") }
let(:u2p1) { create(:payment_completed, user: u2, payout_period_end_date: payout_date, amount_cents: 10_00) }
let(:u2b1) { create(:balance, user: u2, date: payout_date - 2, amount_cents: 1_00, merchant_account: u2m1) }
let(:u2b2) { create(:balance, user: u2, date: payout_date - 1, amount_cents: 5_00, merchant_account: u2m1) }
before { u2 && u2m1 && u2a1 && u2p1 && u2b1 && u2b2 }
# user who doesn't have enough in balances to be paid out
let(:u3) { create(:user_with_compliance_info) }
let(:u3m1) { create(:merchant_account, user: u3, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:u3a1) { create(:ach_account, user: u3, stripe_bank_account_id: "ba_1236") }
let(:u3b1) { create(:balance, user: u3, date: payout_date - 2, amount_cents: 1_00, merchant_account: u3m1) }
before { u3 && u3m1 && u3a1 && u3b1 }
let(:estimate_held_amount_cents) do
subject.estimate_held_amount_cents(payout_date, payout_processor_type)
end
it "returns the aggregate of the amount being held at each holder of funds" do
User.holding_balance.update_all(user_risk_state: "compliant")
holder_of_funds_amount_cents = estimate_held_amount_cents
expect(holder_of_funds_amount_cents[HolderOfFunds::STRIPE]).to eq(26_00)
expect(holder_of_funds_amount_cents[HolderOfFunds::GUMROAD]).to eq(2_00)
end
end
describe "estimate_payments_for_balances_up_to_date_for_users" do
describe "common payment cases (ACH via Stripe)" do
let(:payout_date) { Date.today - 1 }
let(:payout_processor_type) { PayoutProcessorType::STRIPE }
# user who has some balances in the payout period and out of it
let(:u1) { create(:user_with_compliance_info) }
let(:u1m1) { create(:merchant_account, user: u1, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:u1a1) { create(:ach_account, user: u1, stripe_bank_account_id: "ba_123") }
let(:u1b1) { create(:balance, user: u1, date: payout_date - 3, amount_cents: 1_00) }
let(:u1b2) { create(:balance, user: u1, date: payout_date - 2, amount_cents: 10_00) }
let(:u1b3) { create(:balance, user: u1, date: payout_date + 1, amount_cents: 100_00) }
before { u1 && u1m1 && u1a1 && u1b1 && u1b2 && u1b3 }
# user who doesn't have enough in balances to be paid out, but has a payment already made for the same period which makes it enough
let(:u2) { create(:user_with_compliance_info) }
let(:u2m1) { create(:merchant_account, user: u2, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:u2a1) { create(:ach_account, user: u2, stripe_bank_account_id: "ba_1234") }
let(:u2p1) { create(:payment_completed, user: u2, payout_period_end_date: payout_date, amount_cents: 10_00) }
let(:u2b1) { create(:balance, user: u2, date: payout_date - 2, amount_cents: 1_00) }
let(:u2b2) { create(:balance, user: u2, date: payout_date - 1, amount_cents: 5_00) }
before { u2 && u2m1 && u2a1 && u2p1 && u2b1 && u2b2 }
# user who doesn't have enough in balances to be paid out
let(:u3) { create(:user_with_compliance_info) }
let(:u3m1) { create(:merchant_account, user: u3, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:u3a1) { create(:ach_account, user: u3, stripe_bank_account_id: "ba_12345") }
let(:u3b1) { create(:balance, user: u3, date: payout_date - 2, amount_cents: 1_00) }
before { u3 && u3m1 && u3a1 && u3b1 }
let(:users) { [u1, u2, u3] }
let(:estimate_payments_for_balances_up_to_date_for_users) do
subject.estimate_payments_for_balances_up_to_date_for_users(payout_date, payout_processor_type, users)
end
it "does not mark the balances that will be paid as processing" do
estimate_payments_for_balances_up_to_date_for_users
expect(u1b1.reload.state).to eq("unpaid")
expect(u1b2.reload.state).to eq("unpaid")
expect(u2b1.reload.state).to eq("unpaid")
expect(u2b2.reload.state).to eq("unpaid")
end
it "does not mark the balances not being paid as processing" do
estimate_payments_for_balances_up_to_date_for_users
expect(u1b3.reload.state).to eq("unpaid")
expect(u3b1.reload.state).to eq("unpaid")
end
it "does not deduct the balance from the user" do
estimate_payments_for_balances_up_to_date_for_users
expect(u1.unpaid_balance_cents).to eq(111_00)
expect(u2.unpaid_balance_cents).to eq(6_00)
expect(u3.unpaid_balance_cents).to eq(1_00)
end
it "does not create payments for the payable users, up to the date" do
expect { estimate_payments_for_balances_up_to_date_for_users }.not_to change { [u1.payments, u2.payments, u3.payments] }
end
it "generates payment estimates containing info about where funds are held" do
expect(estimate_payments_for_balances_up_to_date_for_users).to eq(
[
{
user: u1,
amount_cents: 11_00,
holder_of_funds_amount_cents: { "gumroad" => 11_00 }
},
{
user: u2,
amount_cents: 6_00,
holder_of_funds_amount_cents: { "gumroad" => 6_00 }
}
]
)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/payouts/payouts_spec.rb | spec/business/payments/payouts/payouts_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Payouts do
describe "is_user_payable" do
let(:payout_date) { Date.today - 1 }
it "returns false for creators with paused payouts" do
creator = create(:user, payment_address: "payme@example.com", payouts_paused_internally: true)
create(:balance, user: creator, amount_cents: 100_001, date: 3.days.ago)
expect(described_class.is_user_payable(creator, payout_date)).to be(false)
end
describe "risk state" do
def expect_processors_not_called
PayoutProcessorType.all.each do |payout_processor_type|
expect(PayoutProcessorType.get(payout_processor_type)).not_to receive(:is_user_payable)
end
end
it "returns false for creators suspended for TOS violation" do
expect_processors_not_called
creator = create(:user, payment_address: "payme@example.com", user_risk_state: "suspended_for_tos_violation")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(false)
end
it "returns false for creators suspended for fraud" do
expect_processors_not_called
creator = create(:user, payment_address: "payme@example.com", user_risk_state: "suspended_for_fraud")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(false)
end
it "returns true for creators that are compliant" do
creator = create(:singaporean_user_with_compliance_info, payment_address: "payme@example.com", user_risk_state: "compliant")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(true)
end
it "returns true for compliant creators who have a PayPal account connected", :vcr do
creator = create(:singaporean_user_with_compliance_info, payment_address: "", user_risk_state: "compliant")
create(:merchant_account_paypal, user: creator, charge_processor_merchant_id: "B66YJBBNCRW6L")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(true)
end
it "returns false for accounts not reviewed" do
expect_processors_not_called
creator = create(:user, payment_address: "payme@example.com", user_risk_state: "not_reviewed")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(false)
end
it "returns false for accounts on probation" do
expect_processors_not_called
creator = create(:user, payment_address: "payme@example.com", user_risk_state: "on_probation")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(false)
end
it "returns false for accounts flagged for terms violation" do
expect_processors_not_called
creator = create(:user, payment_address: "payme@example.com", user_risk_state: "flagged_for_tos_violation")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(false)
end
it "returns false for accounts flagged for fraud" do
expect_processors_not_called
creator = create(:user, payment_address: "payme@example.com", user_risk_state: "flagged_for_fraud")
create(:balance, user: creator, amount_cents: 100_001, date: Date.today - 3)
expect(described_class.is_user_payable(creator, payout_date)).to be(false)
end
describe "non-compliant user from admin" do
let(:payout_date) { Date.today }
let(:user) { create(:tos_user, payment_address: "bob1@example.com") }
before do
create(:balance, user: user, amount_cents: 1001, date: payout_date - 3)
create(:user_compliance_info, user:)
end
it "returns true" do
expect(described_class.is_user_payable(user, payout_date, from_admin: true)).to eq(true)
end
end
end
describe "unpaid balance" do
let(:payout_date) { Date.today }
let(:u1) { create(:singaporean_user_with_compliance_info, user_risk_state: "compliant", payment_address: "bob1@example.com") }
let(:u1b1) { create(:balance, user: u1, amount_cents: 499, date: payout_date - 3) }
let(:u1b2) { create(:balance, user: u1, amount_cents: 501, date: payout_date - 2) }
describe "enough money in balance to meet minimum" do
before { u1b1 && u1b2 }
it "considers the user payable" do
expect(described_class.is_user_payable(u1, payout_date)).to eq(true)
end
end
describe "not enough money in balance to meet minimum" do
before { u1b1 }
describe "no other paid balances for the same payout date" do
it "considers the user NOT payable" do
expect(described_class.is_user_payable(u1, payout_date)).to eq(false)
end
end
describe "paid balances for the same payout date" do
let(:u1p1) { create(:payment_completed, user: u1, payout_period_end_date: payout_date, amount_cents: 501) }
before { u1b1 && u1p1 }
it "considers the user payable" do
expect(described_class.is_user_payable(u1, payout_date)).to eq(true)
end
end
describe "returned balances for the same payout date" do
let(:u1p1) { create(:payment_returned, user: u1, payout_period_end_date: payout_date, amount_cents: 501) }
before { u1p1 }
it "considers the user NOT payable" do
expect(described_class.is_user_payable(u1, payout_date)).to eq(false)
end
end
end
end
describe "instant payouts" do
let(:seller) { create(:compliant_user) }
before do
allow(StripePayoutProcessor).to receive(:is_user_payable).and_return(true)
create(:balance, user: seller, amount_cents: 50_00, date: payout_date - 3)
end
it "returns true when instant payouts are supported and the user has an eligible balance" do
allow_any_instance_of(User).to receive(:instant_payouts_supported?).and_return(true)
expect(described_class.is_user_payable(seller, payout_date, payout_type: Payouts::PAYOUT_TYPE_INSTANT)).to be(true)
end
it "returns false when instant payouts are not supported" do
allow_any_instance_of(User).to receive(:instant_payouts_supported?).and_return(false)
expect(described_class.is_user_payable(seller, payout_date, payout_type: Payouts::PAYOUT_TYPE_INSTANT)).to be(false)
end
it "calls the stripe payout processor with only the instantly payable balance amount" do
allow_any_instance_of(User).to receive(:instant_payouts_supported?).and_return(true)
allow_any_instance_of(User).to receive(:instantly_payable_unpaid_balance_cents_up_to_date).and_return(100_00)
allow_any_instance_of(User).to receive(:unpaid_balance_cents_up_to_date).and_return(200_00)
expect(StripePayoutProcessor).to receive(:is_user_payable).with(seller, 100_00, add_comment: false, from_admin: false, payout_type: anything)
described_class.is_user_payable(seller, payout_date, payout_type: Payouts::PAYOUT_TYPE_INSTANT)
end
end
describe "payout processor logic" do
let(:u1) { create(:compliant_user) }
before do
create(:balance, user: u1, amount_cents: 49_99, date: payout_date - 2)
create(:balance, user: u1, amount_cents: 50_01, date: payout_date - 1)
end
describe "no payout processor type specified" do
it "asks all payout processors" do
expect(PaypalPayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything)
expect(StripePayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything)
described_class.is_user_payable(u1, payout_date)
end
describe "all processors say no" do
before do
allow(PaypalPayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(false)
allow(StripePayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(false)
end
it "considers the user NOT payable" do
expect(described_class.is_user_payable(u1, payout_date)).to eq(false)
end
end
describe "one processor says yes, rest say no" do
before do
allow(PaypalPayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(false)
allow(StripePayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(true)
end
it "considers the user payable" do
expect(described_class.is_user_payable(u1, payout_date)).to eq(true)
end
end
describe "all processors say yes" do
before do
allow(PaypalPayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(true)
allow(StripePayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(true)
end
it "considers the user payable" do
expect(described_class.is_user_payable(u1, payout_date)).to eq(true)
end
end
end
describe "a payout processor type specified" do
let(:payout_processor_type) { PayoutProcessorType::STRIPE }
it "asks only that payout processors" do
expect(PaypalPayoutProcessor).to_not receive(:is_user_payable).with(u1, 100_00, add_comment: anything, payout_type: anything)
expect(StripePayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything)
described_class.is_user_payable(u1, payout_date, processor_type: payout_processor_type)
end
describe "processor says no" do
before do
allow(StripePayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(false)
end
it "considers the user NOT payable" do
expect(described_class.is_user_payable(u1, payout_date, processor_type: payout_processor_type)).to eq(false)
end
end
describe "processor says yes" do
before do
allow(StripePayoutProcessor).to receive(:is_user_payable).with(u1, 100_00, add_comment: false, from_admin: false, payout_type: anything).and_return(true)
end
it "considers the user payable" do
expect(described_class.is_user_payable(u1, payout_date, processor_type: payout_processor_type)).to eq(true)
end
end
end
end
end
describe "create_payments_for_balances_up_to_date" do
let(:payout_date) { Date.yesterday }
let(:payout_processor_type) { PayoutProcessorType::PAYPAL }
it "calls on create_payments_for_balances_up_to_date_for_users with all users holding balance" do
create(:user, unpaid_balance_cents: 0)
u2 = create(:user, unpaid_balance_cents: 1)
u3 = create(:user, unpaid_balance_cents: 10)
u4 = create(:user, unpaid_balance_cents: 1000)
expect(described_class).to receive(:create_payments_for_balances_up_to_date_for_users).with(payout_date, payout_processor_type, [u2, u3, u4], perform_async: true)
described_class.create_payments_for_balances_up_to_date(payout_date, payout_processor_type)
end
it "calls create_payments_for_balances_up_to_date_for_users with all users holding balance who have an active Stripe Connect account" do
u1 = create(:user, unpaid_balance_cents: 0) # Has an active Stripe Connect account but no balance
u2 = create(:user, unpaid_balance_cents: 200) # Has balance and a Stripe account but no Stripe Connect account
u3 = create(:user, unpaid_balance_cents: 100) # Has balance and an active Stripe Connect account
u4 = create(:user, unpaid_balance_cents: 1000) # Has balance and an inactive Stripe Connect account
create(:user, unpaid_balance_cents: 1000) # Has balance but no Stripe or Stripe Connect account
create(:merchant_account_stripe_connect, charge_processor_merchant_id: "stripe_connect_u1", user: u1)
create(:merchant_account, charge_processor_merchant_id: "stripe_u2", user: u2)
create(:merchant_account_stripe_connect, charge_processor_merchant_id: "stripe_connect_u3", user: u3)
create(:merchant_account_stripe_connect, charge_processor_merchant_id: "stripe_connect_u4", user: u4, deleted_at: Time.current)
expect(described_class).to receive(:create_payments_for_balances_up_to_date_for_users).with(payout_date, PayoutProcessorType::STRIPE, [u3], perform_async: true)
described_class.create_payments_for_balances_up_to_date(payout_date, PayoutProcessorType::STRIPE)
end
end
describe "create_instant_payouts_for_balances_up_to_date" do
let(:payout_date) { Date.yesterday }
it "calls create_instant_payouts_for_balances_up_to_date_for_users with all users holding balance with a payout frequency of daily" do
create(:user, unpaid_balance_cents: 0, payout_frequency: User::PayoutSchedule::WEEKLY)
create(:user, unpaid_balance_cents: 100, payout_frequency: User::PayoutSchedule::WEEKLY)
create(:user, unpaid_balance_cents: 0, payout_frequency: User::PayoutSchedule::DAILY)
u4 = create(:user, unpaid_balance_cents: 100, payout_frequency: User::PayoutSchedule::DAILY)
expect(described_class).to receive(:create_instant_payouts_for_balances_up_to_date_for_users).with(payout_date, [u4], perform_async: true, add_comment: true)
described_class.create_instant_payouts_for_balances_up_to_date(payout_date)
end
end
describe "create_instant_payouts_for_balances_up_to_date_for_users" do
let(:payout_date) { Date.yesterday }
context "when the seller does not support instant payouts" do
it "does not create payments" do
creator = create(:user_with_compliance_info)
allow_any_instance_of(User).to receive(:instant_payouts_supported?).and_return(false)
expect do
described_class.create_instant_payouts_for_balances_up_to_date_for_users(payout_date, [creator])
end.to_not change { Payment.count }
end
end
end
describe ".create_payments_for_balances_up_to_date_for_bank_account_types" do
let(:payout_date) { Date.today - 1 }
let(:payout_processor_type) { PayoutProcessorType::STRIPE }
let(:u0_0) do
create(:user, unpaid_balance_cents: 0)
end
let(:u0_1) do
user = create(:user, unpaid_balance_cents: 0)
create(:ach_account, user:)
user
end
let(:u0_2) do
user = create(:user, unpaid_balance_cents: 0)
create(:australian_bank_account, user:)
user
end
before { u0_0 && u0_1 && u0_2 }
let(:u1_0) do
create(:user, unpaid_balance_cents: 10_00)
end
let(:u1_1) do
user = create(:user, unpaid_balance_cents: 10_00)
create(:ach_account, user:)
user
end
let(:u1_2) do
user = create(:user, unpaid_balance_cents: 10_00)
create(:australian_bank_account, user:)
user
end
before { u1_0 && u1_1 && u1_2 }
let(:u2_0) do
create(:user, unpaid_balance_cents: 100_00)
end
let(:u2_1) do
user = create(:user, unpaid_balance_cents: 100_00)
create(:ach_account, user:)
user
end
let(:u2_2) do
user = create(:user, unpaid_balance_cents: 100_00)
create(:australian_bank_account, user:).mark_deleted!
create(:australian_bank_account, user:)
user
end
before { u2_0 && u2_1 && u2_2 }
let(:u3_0) do
user = create(:user, unpaid_balance_cents: 100_00)
create(:canadian_bank_account, user:)
user
end
before { u3_0 }
it "calls create_payments_for_balances_up_to_date_for_users for users holding balance once for every bank account type" do
allow(Payouts).to receive(:is_user_payable).exactly(3).times.and_return(true)
expect(described_class).to receive(:create_payments_for_balances_up_to_date_for_users).with(payout_date, payout_processor_type, [u1_2, u2_2], perform_async: true, bank_account_type: "AustralianBankAccount").and_call_original
expect(described_class).to receive(:create_payments_for_balances_up_to_date_for_users).with(payout_date, payout_processor_type, [u3_0], perform_async: true, bank_account_type: "CanadianBankAccount").and_call_original
described_class.create_payments_for_balances_up_to_date_for_bank_account_types(payout_date, payout_processor_type, [AustralianBankAccount.name, CanadianBankAccount.name])
end
end
describe "create_payments_for_balances_up_to_date_for_users" do
context "when payouts are paused for the seller" do
it "does not create payments" do
creator = create(:user_with_compliance_info, payouts_paused_internally: true)
create(:merchant_account, user: creator)
create(:ach_account, user: creator, stripe_bank_account_id: "ba_bankaccountid")
create(:balance, user: creator, amount_cents: 100_001, date: 20.days.ago)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(10.days.ago, PayoutProcessorType::STRIPE, [creator])
end.to_not change { Payment.count }
end
end
describe "attempting to payout for today" do
it "raises an argument error" do
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today, PayoutProcessorType::PAYPAL, [])
end.to raise_error(ArgumentError)
end
end
describe "attempting to payout for a future date" do
it "raises an argument error" do
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today + 10, PayoutProcessorType::PAYPAL, [])
end.to raise_error(ArgumentError)
end
end
describe "payout schedule" do
let(:seller) { create(:compliant_user, payment_address: "seller@example.com") }
let(:payout_date) { Date.today - 1 }
before do
create(:balance, user: seller, date: payout_date - 3, amount_cents: 1000_00)
end
it "does not create payments if next_payout_date does not match payout date" do
allow(seller).to receive(:next_payout_date).and_return(payout_date + 1.week)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(payout_date, PayoutProcessorType::PAYPAL, [seller])
end.not_to change { Payment.count }
end
end
describe "payout skipped notes" do
it "adds a comment if payout is skipped due to low balance", :vcr do
payout_time = Date.today.in_time_zone("UTC").beginning_of_week(:friday).change(hour: 10)
travel_to payout_time + 1.day
seller = create(:compliant_user, payment_address: "seller@gr.co")
create(:user_compliance_info, user: seller)
create(:balance, user: seller, date: Date.today - 3, amount_cents: 900)
seller2 = create(:compliant_user, payment_address: "seller@gr.co")
create(:user_compliance_info, user: seller2)
create(:balance, user: seller2, date: Date.today - 3, amount_cents: 1000)
seller3 = create(:compliant_user, payment_address: "seller@gr.co")
create(:user_compliance_info, user: seller3)
expect(seller3.unpaid_balance_cents).to eq(0)
expect do
expect do
expect do
described_class.create_payments_for_balances_up_to_date_for_users(payout_time.to_date, PayoutProcessorType::PAYPAL, [seller, seller2])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
end.not_to change { seller2.comments.count }
end.not_to change { seller3.comments.count }
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because the account balance $9 USD was less than the minimum payout amount of $10 USD."
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
end
it "adds a comment if payout is skipped because the account is under review" do
seller = create(:user, payment_address: "seller@example.com")
create(:user_compliance_info, user: seller)
create(:balance, user: seller, date: Date.today - 3, amount_cents: 1000)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [seller])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because the account was under review."
expect(seller.comments.with_type_payout_note.count).to eq 1
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
end
it "adds a comment if payout is skipped because the account is suspended" do
seller = create(:user, user_risk_state: "suspended_for_fraud", payment_address: "seller@example.com")
create(:user_compliance_info, user: seller)
create(:balance, user: seller, date: Date.today - 3, amount_cents: 1000)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [seller])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because the account was not compliant."
expect(seller.comments.with_type_payout_note.count).to eq 1
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
seller.update!(user_risk_state: "suspended_for_tos_violation")
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [seller])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
expect(seller.comments.with_type_payout_note.count).to eq 2
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
end
it "adds a comment if payout is skipped because payouts are paused by admin" do
seller = create(:compliant_user, payment_address: "seller@gr.co")
create(:user_compliance_info, user: seller)
create(:balance, user: seller, date: Date.today - 3, amount_cents: 1000)
seller.update!(payouts_paused_internally: true)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [seller])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because payouts on the account were paused by the admin."
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
end
it "adds a comment if payout is skipped because payouts are paused by stripe" do
seller = create(:compliant_user)
create(:ach_account, user: seller)
create(:user_compliance_info, user: seller)
create(:balance, user: seller, date: Date.today - 3, amount_cents: 1000)
seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_STRIPE)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because payouts on the account were paused by the payout processor."
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
end
it "adds a comment if payout is skipped because payouts are paused by the system" do
seller = create(:compliant_user)
create(:ach_account, user: seller)
create(:user_compliance_info, user: seller)
create(:balance, user: seller, date: Date.today - 3, amount_cents: 1000)
seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_SYSTEM)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because payouts on the account were paused by the system."
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
end
it "adds a comment if payout is skipped because payouts are paused by the seller" do
seller = create(:compliant_user)
create(:ach_account, user: seller)
create(:user_compliance_info, user: seller)
create(:balance, user: seller, date: Date.today - 3, amount_cents: 1000)
seller.update!(payouts_paused_by_user: true)
expect do
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller])
end.to change { seller.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because payouts on the account were paused by the user."
expect(seller.comments.with_type_payout_note.last.content).to eq(content)
end
end
describe "slack notification" do
before do
@seller = create(:compliant_user, payment_address: "seller@gr.co")
create(:balance, user: @seller, date: Date.today - 3, amount_cents: 900)
@seller2 = create(:compliant_user, payment_address: "seller@gr.co")
create(:balance, user: @seller2, date: Date.today - 3, amount_cents: 1000)
end
it "sends a started scheduling payouts message when scheduling payouts" do
allow(Payouts).to receive(:is_user_payable).twice.and_return(true)
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [@seller, @seller2], perform_async: true)
end
it "sends a retrying message when retrying failed payouts" do
allow(Payouts).to receive(:is_user_payable).twice.and_return(true)
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, [@seller, @seller2], perform_async: true, retrying: true)
end
it "includes the country info if payouts are for creators of a specific country" do
seller = create(:user, unpaid_balance_cents: 100_00)
create(:canadian_bank_account, user: seller)
seller2 = create(:user, unpaid_balance_cents: 50_00)
create(:canadian_bank_account, user: seller2)
seller3 = create(:user, unpaid_balance_cents: 20_00)
create(:korea_bank_account, user: seller3)
seller4 = create(:user, unpaid_balance_cents: 220_00)
create(:korea_bank_account, user: seller4)
seller5 = create(:user, unpaid_balance_cents: 120_00)
create(:korea_bank_account, user: seller5)
seller6 = create(:user, unpaid_balance_cents: 120_00)
create(:european_bank_account, user: seller6)
seller7 = create(:user, unpaid_balance_cents: 120_00)
create(:european_bank_account, user: seller7)
allow(Payouts).to receive(:is_user_payable).exactly(7).times.and_return(true)
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller, seller2], perform_async: true, bank_account_type: "CanadianBankAccount")
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller3, seller4, seller5], perform_async: true, bank_account_type: "KoreaBankAccount")
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller6, seller7], perform_async: true, bank_account_type: "EuropeanBankAccount")
end
it "includes the bank or debit card info if payouts are for creators from US", :vcr do
seller = create(:user, unpaid_balance_cents: 100_00)
create(:ach_account, user: seller)
seller2 = create(:user, unpaid_balance_cents: 100_00)
create(:ach_account, user: seller2)
seller3 = create(:user, unpaid_balance_cents: 100_00)
create(:ach_account, user: seller3)
seller4 = create(:user, unpaid_balance_cents: 50_00)
create(:card_bank_account, user: seller4)
seller5 = create(:user, unpaid_balance_cents: 50_00)
create(:card_bank_account, user: seller5)
seller6 = create(:user, unpaid_balance_cents: 50_00)
create(:card_bank_account, user: seller6)
seller7 = create(:user, unpaid_balance_cents: 50_00)
create(:card_bank_account, user: seller7)
allow(Payouts).to receive(:is_user_payable).exactly(7).times.and_return(true)
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller, seller2, seller3], perform_async: true, bank_account_type: "AchAccount")
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller4, seller5, seller6, seller7], perform_async: true, bank_account_type: "CardBankAccount")
end
it "includes the Stripe Connect info for Stripe payouts without a bank account type" do
seller = create(:user, unpaid_balance_cents: 100_00)
create(:merchant_account_stripe_connect, user: seller)
seller2 = create(:user, unpaid_balance_cents: 100_00)
create(:merchant_account_stripe_connect, user: seller2)
allow(Payouts).to receive(:is_user_payable).exactly(2).times.and_return(true)
described_class.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::STRIPE, [seller, seller2], perform_async: true)
end
end
describe "a user is payable but balances are changed (e.g. by a chargeback) and will make for a negative payment" do
let(:payout_date) { Date.today - 1 }
let(:payout_processor_type) { PayoutProcessorType::PAYPAL }
let(:u1) { create(:user) }
let(:u1a1) { create(:ach_account, user: u1) }
let(:u1b1) { create(:balance, user: u1, date: payout_date - 3, amount_cents: 1_00) }
let(:u1b2) { create(:balance, user: u1, date: payout_date - 2, amount_cents: -15_00) }
before do
u1 && u1a1 && u1b1 && u1b2
expect(described_class).to receive(:is_user_payable).and_return(true) # let the user be thought to be payable on the initial check
end
let(:create_payments_for_balances_up_to_date_for_users) do
described_class.create_payments_for_balances_up_to_date_for_users(payout_date, payout_processor_type, [u1])
end
it "remarks the balances as unpaid" do
create_payments_for_balances_up_to_date_for_users
expect(u1b1.reload.state).to eq("unpaid")
expect(u1b2.reload.state).to eq("unpaid")
end
it "does not alter the user's balance" do
create_payments_for_balances_up_to_date_for_users
expect(u1.reload.unpaid_balance_cents).to eq(-14_00)
end
it "does not create a payment" do
expect { create_payments_for_balances_up_to_date_for_users }.to_not change { Payment.count }
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/payouts/processor/stripe/stripe_payout_processor_spec.rb | spec/business/payments/payouts/processor/stripe/stripe_payout_processor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripePayoutProcessor, :vcr do
include CurrencyHelper
include StripeChargesHelper
describe "is_user_payable" do
before do
# sufficient balance for US USD payout
@u1 = create(:compliant_user, unpaid_balance_cents: 10_01)
@m1 = create(:merchant_account, user: @u1)
@b1 = create(:ach_account, user: @u1, stripe_bank_account_id: "ba_bankaccountid")
create(:user_compliance_info, user: @u1)
# insufficient balance for KOR KRW payout
@u2 = create(:compliant_user, unpaid_balance_cents: 10_01)
@m2 = create(:merchant_account_stripe_korea, user: @u2)
@b2 = create(:korea_bank_account, user: @u2, stripe_bank_account_id: "ba_korbankaccountid")
# balance too high for instant payout
@u3 = create(:compliant_user, unpaid_balance_cents: 10_000_01)
@m3 = create(:merchant_account, user: @u3)
@n3 = create(:ach_account, user: @u3, stripe_bank_account_id: "ba_bankaccountid")
create(:user_compliance_info, user: @u3)
end
describe "creator no longer has an ach account" do
before do
@b1.mark_deleted!
end
it "returns false" do
expect(described_class.is_user_payable(@u1, 10_01)).to eq(false)
end
it "adds a payout skipped note if the flag is set" do
expect do
described_class.is_user_payable(@u1, 10_01)
end.not_to change { @u1.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(@u1, 10_01, add_comment: true)
end.to change { @u1.comments.with_type_payout_note.count }.by(1)
content = "Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because a bank account wasn't added at the time."
expect(@u1.comments.with_type_payout_note.last.content).to eq(content)
end
end
describe "creator has a ach account without a corresponding stripe id" do
before do
@b1.stripe_bank_account_id = nil
@b1.save!
end
it "returns false" do
expect(described_class.is_user_payable(@u1, 10_01)).to eq(false)
end
it "adds a payout skipped note if the flag is set" do
expect do
described_class.is_user_payable(@u1, 10_01)
end.not_to change { @u1.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(@u1, 10_01, add_comment: true)
end.to change { @u1.comments.with_type_payout_note.count }.by(1)
content = "Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because the payout bank account was not correctly set up."
expect(@u1.comments.with_type_payout_note.last.content).to eq(content)
end
end
describe "creator does not have a merchant account" do
before do
@m1.mark_deleted!
@u1.reload
end
it "returns false" do
expect(described_class.is_user_payable(@u1, 10_01)).to eq(false)
end
it "adds a payout skipped note if the flag is set" do
expect do
described_class.is_user_payable(@u1, 10_01)
end.not_to change { @u1.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(@u1, 10_01, add_comment: true)
end.to change { @u1.comments.with_type_payout_note.count }.by(1)
content = "Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because the payout bank account was not correctly set up."
expect(@u1.comments.with_type_payout_note.last.content).to eq(content)
end
end
it "returns true when the user is marked as compliant" do
expect(described_class.is_user_payable(@u1, 10_01)).to eq(true)
end
describe "instant payouts" do
it "returns true when the user has an eligible balance" do
expect(described_class.is_user_payable(@u1, 10_01, payout_type: Payouts::PAYOUT_TYPE_INSTANT)).to eq(true)
end
it "returns false when the user has a balance above the maximum instant payout amount" do
expect(described_class.is_user_payable(@u3, 10_000_01, payout_type: Payouts::PAYOUT_TYPE_INSTANT)).to eq(false)
end
it "returns false when the user has a balance below the minimum instant payout amount" do
expect(described_class.is_user_payable(@u1, 9_99, payout_type: Payouts::PAYOUT_TYPE_INSTANT)).to eq(false)
end
end
describe "when the user has a previous payout in processing state" do
before do
@payout1 = create(:payment, user: @u1, processor: "STRIPE", processor_fee_cents: 10,
stripe_transfer_id: "tr_1234", stripe_connect_account_id: "acct_1234")
@payout2 = create(:payment, user: @u1, processor: "STRIPE", processor_fee_cents: 20,
stripe_transfer_id: "tr_5678", stripe_connect_account_id: "acct_1234")
end
it "returns false" do
expect(described_class.is_user_payable(@u1, 10_01)).to eq(false)
@u1.payments.processing.each { |payment| payment.mark_completed! }
expect(described_class.is_user_payable(@u1, 10_01)).to eq(true)
end
it "adds a payout skipped note if the flag is set" do
expect do
described_class.is_user_payable(@u1, 10_01)
end.not_to change { @u1.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(@u1, 10_01, add_comment: true)
end.to change { @u1.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout on #{date} was skipped because there was already a payout in processing."
expect(@u1.comments.with_type_payout_note.last.content).to eq(content)
end
end
describe "creator has a Stripe Connect account" do
before do
@m1.mark_deleted!
@b1.mark_deleted!
@u1.update_columns(user_risk_state: "compliant")
expect_any_instance_of(User).to receive(:merchant_migration_enabled?).and_return true
create(:merchant_account_stripe_connect, user: @u1)
@u1.reload
end
it "returns true" do
expect(described_class.is_user_payable(@u1, 10_01)).to eq(true)
end
it "returns false if Stripe Connect account is from Brazil" do
@u1.stripe_connect_account.mark_deleted!
create(:merchant_account_stripe_connect, user: @u1, country: "BR", currency: "brl")
expect(described_class.is_user_payable(@u1, 10_01)).to eq(false)
end
end
end
describe "has_valid_payout_info?" do
let(:user) { create(:compliant_user) }
before do
create(:merchant_account, user:)
create(:ach_account, user:, stripe_bank_account_id: "ba_bankaccountid")
end
it "returns true if the user otherwise has valid payout info" do
expect(user.has_valid_payout_info?).to eq true
end
it "returns false if the user does not have an active bank account" do
user.active_bank_account.destroy!
expect(user.has_valid_payout_info?).to eq false
end
it "returns false if the user's bank account is not linked to Stripe" do
user.active_bank_account.update!(stripe_bank_account_id: "")
expect(user.has_valid_payout_info?).to eq false
end
it "returns false if the user does not have a Stripe account" do
user.stripe_account.destroy!
expect(user.has_valid_payout_info?).to eq false
end
it "returns true if the user has a connected Stripe account regardless of other checks" do
allow(user).to receive(:has_stripe_account_connected?).and_return(true)
user.active_bank_account.destroy!
expect(user.has_valid_payout_info?).to eq true
end
end
describe "is_balance_payable" do
describe "balance is associated with a Gumroad merchant account" do
let(:balance) { create(:balance) }
it "returns true" do
expect(described_class.is_balance_payable(balance)).to eq(true)
end
end
describe "balance is associated with a Creators' merchant account" do
let(:merchant_account) { create(:merchant_account) }
let(:balance) { create(:balance, merchant_account:) }
it "returns false" do
expect(described_class.is_balance_payable(balance)).to eq(true)
end
end
describe "balance is associated with a Creators' merchant account but in the wrong currency for some reason" do
let(:merchant_account) { create(:merchant_account, currency: Currency::USD) }
let(:balance) { create(:balance, merchant_account:, currency: Currency::CAD) }
it "returns false" do
expect(described_class.is_balance_payable(balance)).to eq(false)
end
end
end
describe "prepare_payment_and_set_amount" do
let(:user) { create(:user) }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:merchant_account) { create(:merchant_account_stripe_canada, user:) }
before do
user
bank_account
merchant_account
bank_account.reload
user.reload
end
let(:balance_1) { create(:balance, user:, date: Date.today - 1, currency: Currency::USD, amount_cents: 10_00, holding_currency: Currency::USD, holding_amount_cents: 10_00) }
let(:balance_2) { create(:balance, user:, date: Date.today - 2, currency: Currency::USD, amount_cents: 20_00, holding_currency: Currency::CAD, holding_amount_cents: 20_00) }
let(:payment) do
payment = create(:payment, user:, currency: nil, amount_cents: nil)
payment.balances << balance_1
payment.balances << balance_2
payment
end
before do
described_class.prepare_payment_and_set_amount(payment, [balance_1, balance_2])
end
it "sets the currency" do
expect(payment.currency).to eq(Currency::CAD)
end
it "sets the amount as the sum of the balances" do
expect(payment.amount_cents).to eq(30_00)
end
end
describe "prepare_payment_and_set_amount for Korean bank account" do
let(:user) { create(:user) }
let(:bank_account) { create(:korea_bank_account, user:) }
let(:merchant_account) { create(:merchant_account_stripe_korea, user:) }
before do
user
bank_account
merchant_account
bank_account.reload
user.reload
end
let(:balance_1) { create(:balance, user:, date: Date.today - 1, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::USD, holding_amount_cents: 100_00) }
let(:balance_2) { create(:balance, user:, date: Date.today - 2, currency: Currency::USD, amount_cents: 200_00, holding_currency: Currency::USD, holding_amount_cents: 200_00) }
let(:payment) do
payment = create(:payment, user:, currency: nil, amount_cents: nil)
payment.balances << balance_1
payment.balances << balance_2
payment
end
before do
described_class.prepare_payment_and_set_amount(payment, [balance_1, balance_2])
end
it "sets the currency" do
expect(payment.currency).to eq(Currency::KRW)
end
it "sets the amount as the sum of the balances, converted to match the database for KRW" do
expect(payment.amount_cents).to eq(39640900)
end
end
describe ".enqueue_payments" do
let!(:yesterday) { Date.yesterday.to_s }
let!(:user_ids) { [1, 2, 3, 4] }
it "enqueues PayoutUsersWorker jobs for the supplied payments" do
described_class.enqueue_payments(user_ids, yesterday)
expect(PayoutUsersWorker.jobs.size).to eq(user_ids.size)
sidekiq_job_args = user_ids.each_with_object([]) do |user_id, accumulator|
accumulator << [yesterday, PayoutProcessorType::STRIPE, user_id, Payouts::PAYOUT_TYPE_STANDARD]
end
expect(PayoutUsersWorker.jobs.map { _1["args"] }).to match_array(sidekiq_job_args)
end
end
describe ".process_payments" do
let(:payment1) { create(:payment) }
let(:payment2) { create(:payment) }
let(:payment3) { create(:payment) }
let(:payments) { [payment1, payment2, payment3] }
it "calls `perform_payment` for every payment" do
allow(described_class).to receive(:perform_payment).with(anything)
expect(described_class).to receive(:perform_payment).with(payment1)
expect(described_class).to receive(:perform_payment).with(payment2)
expect(described_class).to receive(:perform_payment).with(payment3)
described_class.process_payments(payments)
end
end
describe "perform_payment" do
let(:user) { create(:user) }
let(:tos_agreement) { create(:tos_agreement, user:) }
let(:user_compliance_info) { create(:user_compliance_info, user:) }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
before do
tos_agreement
user_compliance_info
bank_account
end
let(:merchant_account) { create(:merchant_account_stripe, user: user.reload) }
before do
merchant_account
bank_account.reload
user.reload
end
let(:payment_amount_cents) { 600_00 }
let(:balances) do
[
create(:balance, state: "processing", merchant_account:, amount_cents: 100_00),
create(:balance, state: "processing", merchant_account:, amount_cents: 200_00),
create(:balance, state: "processing", merchant_account:, amount_cents: 300_00)
]
end
let(:payment) do
create(:payment,
user:, bank_account: bank_account.reload, state: "processing", processor: PayoutProcessorType::STRIPE,
amount_cents: payment_amount_cents, payout_period_end_date: Date.today - 1, correlation_id: nil,
balances:, payout_type: Payouts::PAYOUT_TYPE_STANDARD)
end
before do
payment_intent = create_stripe_payment_intent(StripePaymentMethodHelper.success_available_balance.to_stripejs_payment_method_id,
amount: 600_00,
currency: "usd",
transfer_data: { destination: merchant_account.charge_processor_merchant_id })
payment_intent.confirm
Stripe::Charge.retrieve(id: payment_intent.latest_charge)
end
it "creates a transfer at stripe" do
expect(Stripe::Payout).to receive(:create).with(
{
amount: payment_amount_cents,
currency: "usd",
destination: bank_account.stripe_bank_account_id,
description: payment.external_id,
statement_descriptor: "Gumroad",
method: Payouts::PAYOUT_TYPE_STANDARD,
metadata: {
payment: payment.external_id,
"balances{0}" => balances.map(&:external_id).join(","),
bank_account: bank_account.external_id
}
},
{ stripe_account: merchant_account.charge_processor_merchant_id }
).and_call_original
described_class.prepare_payment_and_set_amount(payment, balances)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
end
it "marks the payment as processing" do
described_class.prepare_payment_and_set_amount(payment, balances)
described_class.perform_payment(payment)
expect(payment.state).to eq("processing")
end
it "stores the stripe account identifier of the account the transfer was created on, on the payment" do
described_class.prepare_payment_and_set_amount(payment, balances)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "stores the stripe transfer's identifier on the payment" do
described_class.prepare_payment_and_set_amount(payment, balances)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_transfer_id).to match(/po_[a-zA-Z0-9]+/)
end
it "does not store an internal stripe transfer's identifier on the payment" do
described_class.prepare_payment_and_set_amount(payment, balances)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_internal_transfer_id).to eq(nil)
end
describe "the payment includes funds not held by stripe, which don't sum to a positive amount" do
let(:balances_held_by_gumroad) do
[
create(:balance, state: "processing", merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), amount_cents: -5_00),
create(:balance, state: "processing", merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), amount_cents: -5_00)
]
end
before do
payment.balances += balances_held_by_gumroad
end
it "creates a normal transfer" do
expect(Stripe::Payout).to receive(:create).with(
{
amount: payment_amount_cents,
currency: "usd",
destination: bank_account.stripe_bank_account_id,
description: payment.external_id,
statement_descriptor: "Gumroad",
method: Payouts::PAYOUT_TYPE_STANDARD,
metadata: {
payment: payment.external_id,
"balances{0}" => payment.balances.map(&:external_id).join(","),
bank_account: bank_account.external_id
}
},
{ stripe_account: merchant_account.charge_processor_merchant_id }
).and_call_original
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
end
it "marks the payment as processing" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
expect(payment.state).to eq("processing")
end
it "stores the stripe account identifier of the account the transfer was created on, on the payment" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "stores the stripe transfer's identifier on the payment" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_transfer_id).to match(/po_[a-zA-Z0-9]+/)
end
it "stores the internal stripe transfer's identifier on the payment" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_internal_transfer_id).to eq(nil)
end
describe "the external transfer fails" do
before do
allow(Stripe::Payout).to receive(:create).and_raise(Stripe::InvalidRequestError.new("Invalid request", "amount_cents"))
end
it "notifies bugsnag" do
expect(Bugsnag).to receive(:notify)
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
end
it "returns the errors" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_present
end
it "marks the payment as failed" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
payment.reload
expect(payment.state).to eq("failed")
end
end
describe "the external transfer fails because the account cannot be paid" do
before do
allow(Stripe::Payout).to receive(:create).and_raise(Stripe::InvalidRequestError.new("Cannot create live transfers: The account has fields needed.", "amount_cents"))
end
it "returns the errors" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_present
end
it "marks the payment as failed" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
payment.reload
expect(payment.state).to eq("failed")
end
it "marks the payment with a failure reason of cannot pay" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
payment.reload
expect(payment.failure_reason).to eq(Payment::FailureReason::CANNOT_PAY)
end
end
describe "the external transfer fails because of an unsupported reason" do
before do
allow(Stripe::Payout).to receive(:create).and_raise(Stripe::InvalidRequestError.new("Food was not tasty.", "food_bad"))
end
it "notifies bugsnag" do
expect(Bugsnag).to receive(:notify)
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
end
end
end
describe "the payment includes funds not held by stripe, which sum to a positive amount" do
let(:balances_held_by_gumroad) do
[
create(:balance, state: "processing", merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), amount_cents: 1_00),
create(:balance, state: "processing", merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), amount_cents: 1_00)
]
end
before do
payment.balances += balances_held_by_gumroad
end
it "creates an internal transfer and a normal transfer" do
expect(Stripe::Transfer).to receive(:create).once.with(
hash_including(
amount: balances_held_by_gumroad.sum(&:amount_cents),
currency: "usd",
destination: merchant_account.charge_processor_merchant_id,
description: "Funds held by Gumroad for Payment #{payment.external_id}.",
metadata: {
payment: payment.external_id,
"balances{0}" => balances_held_by_gumroad.map(&:external_id).join(",")
}
)
).and_call_original
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
expect(Stripe::Payout).to receive(:create).once.with(
hash_including(
amount: payment.amount_cents,
currency: payment.currency,
destination: bank_account.stripe_bank_account_id,
description: payment.external_id,
statement_descriptor: "Gumroad",
method: Payouts::PAYOUT_TYPE_STANDARD,
metadata: {
payment: payment.external_id,
"balances{0}" => payment.balances.map(&:external_id).join(","),
bank_account: bank_account.external_id
}
),
{ stripe_account: merchant_account.charge_processor_merchant_id }
).and_call_original
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
end
it "marks the payment as processing" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
expect(payment.state).to eq("processing")
end
it "stores the stripe account identifier of the account the transfer was created on, on the payment" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "stores the stripe transfer's identifier on the payment" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_transfer_id).to match(/po_[a-zA-Z0-9]+/)
end
it "stores the internal stripe transfer's identifier on the payment" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_internal_transfer_id).to match(/tr_[a-zA-Z0-9]+/)
end
describe "the internal transfer fails" do
before do
allow(Stripe::Transfer).to receive(:create).once.and_raise(Stripe::InvalidRequestError.new("Invalid request", "amount_cents"))
end
it "notifies bugsnag" do
expect(Bugsnag).to receive(:notify)
errors = described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
expect(errors).to be_present
end
it "returns the errors" do
errors = described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
expect(errors).to be_present
end
it "marks the payment as failed" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
payment.reload
expect(payment.state).to eq("failed")
end
end
describe "the external transfer fails" do
describe "mocked" do
let(:internal_transfer) do
transfer = double
allow(transfer).to receive(:id).and_return("tr_1234")
allow(transfer).to receive(:destination_payment).and_return("py_1234")
transfer
end
let(:destination_payment) do
destination_payment_balance_transaction = double
allow(destination_payment_balance_transaction).to receive(:amount).and_return(50_00)
destination_payment = double
allow(destination_payment).to receive(:balance_transaction).and_return(destination_payment_balance_transaction)
destination_payment
end
before do
expect(Stripe::Transfer).to(receive(:create).once.and_return(internal_transfer))
expect(Stripe::Charge).to(receive(:retrieve).and_return(destination_payment))
expect(Stripe::Payout).to(receive(:create).once.and_raise(Stripe::InvalidRequestError.new("Invalid request", "amount_cents")))
expect(Stripe::Transfer).to(receive(:retrieve).with(internal_transfer.id).and_return(internal_transfer))
expect(described_class).to receive(:create_credit_for_difference_from_reversed_internal_transfer)
end
it "creates a reversal for the internal transfer" do
expect(internal_transfer).to receive_message_chain(:reversals, :create)
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
end
end
describe "hitting stripe" do
before do
expect(Stripe::Transfer).to(receive(:create).once.and_call_original)
expect(Stripe::Payout).to(receive(:create).once.and_raise(Stripe::InvalidRequestError.new("Invalid request", "amount_cents")))
end
it "notifies bugsnag" do
expect(Bugsnag).to receive(:notify)
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
end
it "returns the errors" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
errors = described_class.perform_payment(payment)
expect(errors).to be_present
end
it "marks the payment as failed" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
described_class.perform_payment(payment)
payment.reload
expect(payment.state).to eq("failed")
end
end
end
end
describe "transfer fails due to an invalid request (amount over balance of creator)" do
it "returns an error" do
described_class.prepare_payment_and_set_amount(payment, payment.balances.to_a)
payment.amount_cents = 500_000 # adjust payment amount to be over what's in the account
errors = described_class.perform_payment(payment)
expect(errors).to be_present
expect(errors.first).to match(/You have insufficient funds in your Stripe account for this transfer/)
end
end
end
describe "perform_payment for a US account with instant payout method type" do
let(:user) { create(:user) }
let(:tos_agreement) { create(:tos_agreement, user:) }
let(:user_compliance_info) { create(:user_compliance_info, user:) }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
before do
tos_agreement
user_compliance_info
bank_account
end
let(:merchant_account) { create(:merchant_account_stripe, user: user.reload) }
before do
merchant_account
bank_account.reload
user.reload
end
let(:payment_amount_cents) { 600_00 }
let(:balances) do
[
create(:balance, state: "processing", merchant_account:, amount_cents: 100_00),
create(:balance, state: "processing", merchant_account:, amount_cents: 200_00),
create(:balance, state: "processing", merchant_account:, amount_cents: 300_00)
]
end
let(:payment) do
create(:payment,
user:, bank_account: bank_account.reload, state: "processing", processor: PayoutProcessorType::STRIPE,
amount_cents: payment_amount_cents, payout_period_end_date: Date.today - 1, correlation_id: nil,
balances:, payout_type: Payouts::PAYOUT_TYPE_INSTANT)
end
before do
payment_intent = create_stripe_payment_intent(StripePaymentMethodHelper.success_available_balance.to_stripejs_payment_method_id,
amount: 600_00,
currency: "usd",
transfer_data: { destination: merchant_account.charge_processor_merchant_id })
payment_intent.confirm
Stripe::Charge.retrieve(id: payment_intent.latest_charge)
end
it "creates a transfer at stripe" do
expect(Stripe::Payout).to receive(:create).with(
{
amount: (payment_amount_cents * 100 / (100 + StripePayoutProcessor::INSTANT_PAYOUT_FEE_PERCENT)).floor,
currency: "usd",
destination: bank_account.stripe_bank_account_id,
description: payment.external_id,
statement_descriptor: "Gumroad",
method: Payouts::PAYOUT_TYPE_INSTANT,
metadata: {
payment: payment.external_id,
"balances{0}" => balances.map(&:external_id).join(","),
bank_account: bank_account.external_id
}
},
{ stripe_account: merchant_account.charge_processor_merchant_id }
).and_call_original
described_class.prepare_payment_and_set_amount(payment, balances)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
end
it "marks the payment as processing" do
described_class.prepare_payment_and_set_amount(payment, balances)
described_class.perform_payment(payment)
expect(payment.state).to eq("processing")
end
it "stores the stripe account identifier of the account the transfer was created on, on the payment" do
described_class.prepare_payment_and_set_amount(payment, balances)
errors = described_class.perform_payment(payment)
expect(errors).to be_empty
expect(payment.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "stores the stripe transfer's identifier on the payment" do
described_class.prepare_payment_and_set_amount(payment, balances)
errors = described_class.perform_payment(payment)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/payouts/processor/paypal/paypal_payout_processor_spec.rb | spec/business/payments/payouts/processor/paypal/paypal_payout_processor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalPayoutProcessor do
describe "is_user_payable" do
let(:user) { create(:singaporean_user_with_compliance_info, payment_address: "seller@gr.co") }
describe "creator has not set a payment address" do
before do
user.update!(payment_address: "")
end
it "returns false" do
expect(described_class.is_user_payable(user, 10_01)).to eq(false)
end
it "adds a payout skipped note if the flag is set" do
expect do
described_class.is_user_payable(user, 10_01)
end.not_to change { user.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(user, 10_01, add_comment: true)
end.to change { user.comments.with_type_payout_note.count }.by(1)
content = "Payout via PayPal on #{Time.current.to_fs(:formatted_date_full_month)} skipped because the account does not have a valid PayPal payment address"
expect(user.comments.with_type_payout_note.last.content).to eq(content)
end
it "returns true if creator has a paypal account connected", :vcr do
create(:merchant_account_paypal, user:, charge_processor_merchant_id: "B66YJBBNCRW6L")
expect(described_class.is_user_payable(user, 10_01)).to eq(true)
end
end
describe "creator has set a payment address" do
it "returns true" do
expect(described_class.is_user_payable(user, 10_01)).to eq(true)
end
describe "when the user has a previous payout in processing state" do
before do
@payout1 = create(:payment, user:, txn_id: "dummy", processor_fee_cents: 10)
@payout2 = create(:payment, user:, txn_id: "dummy2", processor_fee_cents: 20)
end
it "returns false " do
expect(described_class.is_user_payable(user, 10_01)).to eq(false)
user.payments.processing.each { |payment| payment.mark_completed! }
expect(described_class.is_user_payable(user, 10_01)).to eq(true)
end
it "adds a payout skipped note if the flag is set" do
expect do
described_class.is_user_payable(user, 10_01)
end.not_to change { user.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(user, 10_01, add_comment: true)
end.to change { user.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout via PayPal on #{date} skipped because there are already payouts (ID #{@payout1.id}, #{@payout2.id}) in processing"
expect(user.comments.with_type_payout_note.last.content).to eq(content)
end
end
describe "payment address contains non-ascii characters" do
before do
user.payment_address = "sebastian.ripenås@example.com"
end
it "returns false" do
expect(described_class.is_user_payable(user, 10_01)).to eq(false)
end
it "adds a payout skipped note if the flag is set" do
expect do
described_class.is_user_payable(user, 10_01)
end.not_to change { user.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(user, 10_01, add_comment: true)
end.to change { user.comments.with_type_payout_note.count }.by(1)
date = Time.current.to_fs(:formatted_date_full_month)
content = "Payout via PayPal on #{date} skipped because the PayPal payment address contains invalid characters"
expect(user.comments.with_type_payout_note.last.content).to eq(content)
end
end
describe "creator has an active bank account" do
before do
create(:ach_account, user:)
end
it "returns false" do
expect(described_class.is_user_payable(user, 10_01)).to eq(false)
end
it "does not add a payout skipped note" do
expect do
described_class.is_user_payable(user, 10_01)
end.not_to change { user.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(user, 10_01, add_comment: true)
end.not_to change { user.comments.with_type_payout_note.count }
end
end
describe "creator is payable via Stripe" do
before do
allow(StripePayoutProcessor).to receive(:is_user_payable).and_return true
end
it "returns false" do
expect(described_class.is_user_payable(user, 10_01)).to eq(false)
end
it "does not add a payout skipped note" do
expect do
described_class.is_user_payable(user, 10_01)
end.not_to change { user.comments.with_type_payout_note.count }
expect do
described_class.is_user_payable(user, 10_01, add_comment: true)
end.not_to change { user.comments.with_type_payout_note.count }
end
end
end
describe "instant payouts" do
it "returns false" do
expect(described_class.is_user_payable(user, 10_01, payout_type: Payouts::PAYOUT_TYPE_INSTANT)).to be(false)
end
end
end
describe "has_valid_payout_info?" do
let(:user) { create(:user_with_compliance_info, payment_address: "user@example.com") }
it "returns true if the user has valid payout info" do
expect(user.has_valid_payout_info?).to eq true
end
it "returns false if the user is missing a payment address" do
user.payment_address = ""
expect(user.has_valid_payout_info?).to eq false
end
it "returns false if the user has an invalid payment address" do
user.payment_address = "foo"
expect(user.has_valid_payout_info?).to eq false
user.payment_address = "user @example.co,m"
expect(user.has_valid_payout_info?).to eq false
end
it "returns false if the user hasn't provided their compliance info" do
user.alive_user_compliance_info.destroy!
expect(user.has_valid_payout_info?).to eq false
end
it "returns true if the user has a PayPal account connected", :vcr do
user.update!(payment_address: "")
expect(user.reload.has_valid_payout_info?).to eq false
create(:merchant_account_paypal, user:, charge_processor_merchant_id: "B66YJBBNCRW6L")
expect(user.reload.has_valid_payout_info?).to eq true
end
end
describe "is_balance_payable" do
describe "balance is associated with a Gumroad merchant account" do
let(:balance) { create(:balance) }
it "returns true" do
expect(described_class.is_balance_payable(balance)).to eq(true)
end
end
describe "balance is associated with a Creators' merchant account" do
let(:merchant_account) { create(:merchant_account) }
let(:balance) { create(:balance, merchant_account:) }
it "returns false" do
expect(described_class.is_balance_payable(balance)).to eq(false)
end
end
end
describe "prepare_payment_and_set_amount" do
let(:user) { create(:singaporean_user_with_compliance_info) }
let(:balance_1) { create(:balance, user:, date: Date.today - 1, currency: Currency::USD, amount_cents: 10_00) }
let(:balance_2) { create(:balance, user:, date: Date.today - 2, currency: Currency::USD, amount_cents: 20_00) }
let(:payment) do
payment = create(:payment, user:, currency: nil, amount_cents: nil)
payment.balances << balance_1
payment.balances << balance_2
payment
end
before do
described_class.prepare_payment_and_set_amount(payment, [balance_1, balance_2])
end
it "sets the currency" do
expect(payment.currency).to eq(Currency::USD)
end
it "sets the amount as the sum of the balances" do
expect(payment.amount_cents).to eq(29_40)
expect(payment.gumroad_fee_cents).to eq(60)
end
end
describe ".enqueue_payments" do
let!(:yesterday) { Date.yesterday.to_s }
let!(:user_ids) { (1..5000).to_a }
it "enqueues PayoutUsersWorker jobs for the supplied payments" do
# Assert that a fake delay is supplied to get around rate-limits
user_ids.each_slice(240).with_index do |ids, index|
expect(PayoutUsersWorker).to receive(:perform_in)
.with(index.minutes, yesterday, PayoutProcessorType::PAYPAL, ids)
.once.and_call_original
end
described_class.enqueue_payments(user_ids, yesterday)
# Assert that the jobs are enqueued
expect(PayoutUsersWorker.jobs.size).to eq(user_ids.size / 240 + 1)
sidekiq_job_args = user_ids.each_slice(240).each_with_object([]) do |ids, accumulator|
accumulator << [yesterday, PayoutProcessorType::PAYPAL, ids]
end
expect(PayoutUsersWorker.jobs.map { _1["args"] }).to match_array(sidekiq_job_args)
end
end
describe ".process_payments" do
# Will not be split because the user does not have the `should_paypal_payout_be_split` flag set
let(:payment1) { create(:payment, amount_cents: described_class::MAX_SPLIT_PAYMENT_BY_CENTS + 1) }
# Will be split
let(:payment2) do create(:payment, user: create(:user, should_paypal_payout_be_split: true),
amount_cents: described_class::MAX_SPLIT_PAYMENT_BY_CENTS + 1) end
# Will be split
let(:payment3) do create(:payment, user: create(:user, should_paypal_payout_be_split: true),
amount_cents: described_class::MAX_SPLIT_PAYMENT_BY_CENTS * 2) end
# Will not be split because the amount can be sent in 1 request
let(:payment4) do create(:payment, user: create(:user, should_paypal_payout_be_split: true),
amount_cents: described_class::MAX_SPLIT_PAYMENT_BY_CENTS) end
# Regular payments
let(:payment5) { create(:payment) }
let(:payment6) { create(:payment) }
# US creator payments
let(:payment7) do
user = create(:user)
create(:user_compliance_info, user:)
expect(user.signed_up_from_united_states?).to eq(true)
create(:payment, user:)
end
let(:payment8) do
user = create(:user)
create(:user_compliance_info, user:)
expect(user.signed_up_from_united_states?).to eq(true)
create(:payment, user:)
end
# Will be split because the amount is greater than the split payout size set for the user
let(:payment9) do
create(:payment, amount_cents: 19_000_00,
user: create(:user, should_paypal_payout_be_split: true, split_payment_by_cents: 10_000_00))
end
# Will be split because the payout amount is greater than the maximum split payout size
let(:payment10) do
create(:payment, amount_cents: 21_000_00,
user: create(:user, should_paypal_payout_be_split: true, split_payment_by_cents: 30_000_00))
end
let(:payments) { [payment1, payment2, payment3, payment4, payment5, payment6, payment7, payment8, payment9, payment10] }
it "calls payout methods with the correct payments" do
allow(described_class).to receive(:perform_payments).with(anything)
allow(described_class).to receive(:perform_split_payment).with(anything)
expect(described_class).to receive(:perform_split_payment).with(payment2)
expect(described_class).to receive(:perform_split_payment).with(payment3)
expect(described_class).to receive(:perform_split_payment).with(payment9)
expect(described_class).to receive(:perform_split_payment).with(payment10)
expect(described_class).to receive(:perform_payments).with([payment1, payment4, payment5, payment6, payment7, payment8])
described_class.process_payments(payments)
end
it "calls the correct methods for every payment even if exceptions are raised" do
allow(described_class).to receive(:perform_payments).with(anything)
allow(described_class).to receive(:perform_split_payment).with(payment3)
# Make processing the first split payment raise an error
allow(described_class).to receive(:perform_split_payment).with(payment2).and_raise(StandardError)
# Assert that all methods are called as expected
expect(described_class).to receive(:perform_split_payment).with(payment2)
expect(described_class).to receive(:perform_split_payment).with(payment3)
expect(described_class).to receive(:perform_split_payment).with(payment9)
expect(described_class).to receive(:perform_split_payment).with(payment10)
expect(described_class).to receive(:perform_payments).with([payment1, payment4, payment5, payment6, payment7, payment8])
described_class.process_payments(payments)
# Assert that processing the US payouts worked
expect(payment7.reload.state).to eq("processing")
expect(payment8.reload.state).to eq("processing")
end
end
describe ".note_for_paypal_payment" do
let(:user) { create(:user, name: "Test User", username: "testuser") }
let(:payment) { create(:payment, user:) }
context "when user has compliance info with a legal entity name" do
let!(:compliance_info) { create(:user_compliance_info, user:, is_business: true, business_name: "Test Legal Entity") }
it "returns the note with the legal entity name" do
expected_note = "Test Legal Entity, selling digital products / memberships"
expect(described_class.note_for_paypal_payment(payment)).to eq(expected_note)
end
end
context "when user has compliance info but legal entity name is blank" do
let!(:compliance_info) { create(:user_compliance_info, user:, first_name: "", last_name: "") }
it "returns the note with the user's name" do
expected_note = "Test User, selling digital products / memberships"
expect(described_class.note_for_paypal_payment(payment)).to eq(expected_note)
end
end
context "when user does not have compliance info" do
it "returns the note with the user's name" do
user.update!(name: nil) # Use username in this case
expected_note = "testuser, selling digital products / memberships"
expect(described_class.note_for_paypal_payment(payment)).to eq(expected_note)
end
end
end
describe "pay via paypal and handle IPNs", :vcr do
before do
@u1 = create(:singaporean_user_with_compliance_info, payment_address: "amir_1351103838_biz@gumroad.com")
@balance1_1 = create(:balance, user: @u1, amount_cents: 501, date: Date.today - 8)
@balance1_2 = create(:balance, user: @u1, amount_cents: 500, date: Date.today - 9)
@u2 = create(:singaporean_user_with_compliance_info, payment_address: "amir2_1351103838_biz@gumroad.com")
@balance2 = create(:balance, user: @u2, amount_cents: 1002, date: Date.today - 8)
@u3 = create(:singaporean_user_with_compliance_info, payment_address: "")
create(:merchant_account_paypal, user: @u3, charge_processor_merchant_id: "B66YJBBNCRW6L")
@balance3 = create(:balance, user: @u3, amount_cents: 1003, date: Date.today - 8)
@u4 = create(:singaporean_user_with_compliance_info, payment_address: "amir4_1351103838_biz@gumroad.com")
create(:merchant_account_paypal, user: @u4, charge_processor_merchant_id: "B66YJBBNCRW6L")
@balance4 = create(:balance, user: @u4, amount_cents: 1004, date: Date.today - 8)
WebMock.stub_request(:post, PAYPAL_ENDPOINT)
.to_return(body: "TIMESTAMP=2012%2d10%2d26T20%3a29%3a14Z&CORRELATIONID=c51c5e0cecbce&ACK=Success&VERSION=90%2e0&BUILD=4072860")
end
it "creates the correct payment objects and update them once the IPN comes in" do
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, User.holding_balance)
p1 = @u1.payments.last
p2 = @u2.payments.last
p3 = @u3.payments.last
p4 = @u4.payments.last
expect(p1.state).to eq "processing"
expect(p2.state).to eq "processing"
expect(p3.state).to eq "processing"
expect(p4.state).to eq "processing"
expect(@balance1_1.reload.state).to eq "processing"
expect(@balance1_2.reload.state).to eq "processing"
expect(@balance2.reload.state).to eq "processing"
expect(@balance3.reload.state).to eq "processing"
expect(@balance4.reload.state).to eq "processing"
expect(p1.balances.size).to eq 2
expect(p1.balances).to include(@balance1_1)
expect(p1.balances).to include(@balance1_2)
expect(p2.balances).to eq [@balance2]
expect(p3.balances).to eq [@balance3]
expect(p4.balances).to eq [@balance4]
expect(p1.gumroad_fee_cents).to eq (@u1.balances.processing.sum(:amount_cents) * PaypalPayoutProcessor::PAYPAL_PAYOUT_FEE_PERCENT / 100.0).ceil
expect(p1.amount_cents).to eq @u1.balances.processing.sum(:amount_cents) - p1.gumroad_fee_cents
expect(p2.gumroad_fee_cents).to eq (@u2.balances.processing.sum(:amount_cents) * PaypalPayoutProcessor::PAYPAL_PAYOUT_FEE_PERCENT / 100.0).ceil
expect(p2.amount_cents).to eq @u2.balances.processing.sum(:amount_cents) - p2.gumroad_fee_cents
expect(p3.gumroad_fee_cents).to eq (@u3.balances.processing.sum(:amount_cents) * PaypalPayoutProcessor::PAYPAL_PAYOUT_FEE_PERCENT / 100.0).ceil
expect(p3.amount_cents).to eq @u3.balances.processing.sum(:amount_cents) - p3.gumroad_fee_cents
expect(p4.gumroad_fee_cents).to eq (@u4.balances.processing.sum(:amount_cents) * PaypalPayoutProcessor::PAYPAL_PAYOUT_FEE_PERCENT / 100.0).ceil
expect(p4.amount_cents).to eq @u4.balances.processing.sum(:amount_cents) - p4.gumroad_fee_cents
expect(p1.payment_address).to eq @u1.payment_address
expect(p2.payment_address).to eq @u2.payment_address
expect(p3.payment_address).to eq @u3.paypal_connect_account.paypal_account_details["primary_email"]
expect(p4.payment_address).to eq @u4.payment_address
described_class.handle_paypal_event("payment_date" => p1.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => p1.user.payment_address,
"masspay_txn_id_0" => "sometxn1",
"status_0" => "Completed",
"unique_id_0" => p1.id,
"mc_fee_0" => "2.99",
"receiver_email_1" => p2.user.payment_address,
"masspay_txn_id_1" => "sometxn2",
"status_1" => "Failed",
"reason_code_1" => "1002",
"unique_id_1" => p2.id,
"mc_fee_1" => "3.99",
"receiver_email_2" => p3.user.paypal_connect_account.paypal_account_details["primary_email"],
"masspay_txn_id_2" => "sometxn3",
"status_2" => "Unclaimed",
"unique_id_2" => p3.id,
"mc_fee_2" => "3.59",
"receiver_email_3" => p4.user.payment_address,
"masspay_txn_id_3" => "sometxn3",
"status_3" => "Unclaimed",
"unique_id_3" => p4.id,
"mc_fee_3" => "3.59")
expect(p1.reload.state).to eq "completed"
expect(p2.reload.state).to eq "failed"
expect(p3.reload.state).to eq "unclaimed"
expect(p4.reload.state).to eq "unclaimed"
expect(@balance1_1.reload.state).to eq "paid"
expect(@balance1_2.reload.state).to eq "paid"
expect(@balance2.reload.state).to eq "unpaid"
expect(@balance3.reload.state).to eq "processing"
expect(@balance4.reload.state).to eq "processing"
expect(p1.txn_id).to eq "sometxn1"
expect(p2.txn_id).to eq "sometxn2"
expect(p3.txn_id).to eq "sometxn3"
expect(p1.processor_fee_cents).to eq 299
expect(p2.processor_fee_cents).to eq 399
expect(p3.processor_fee_cents).to eq 359
expect(@u1.reload.unpaid_balance_cents).to eq 0
expect(@u2.reload.unpaid_balance_cents).to eq 1002
expect(@u3.reload.unpaid_balance_cents).to eq 0
expect(@u4.reload.unpaid_balance_cents).to eq 0
expect(p2.failure_reason).to eq("PAYPAL 1002")
described_class.handle_paypal_event("payment_date" => p3.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => p3.user.paypal_connect_account.paypal_account_details["primary_email"],
"masspay_txn_id_0" => "sometxn3",
"status_0" => "Completed",
"unique_id_0" => p3.id,
"mc_fee_0" => "3.59",
"receiver_email_1" => p4.user.payment_address,
"masspay_txn_id_1" => "sometxn3",
"status_1" => "Returned",
"unique_id_1" => p4.id,
"mc_fee_1" => "3.59")
p3 = p3.reload
p4 = p4.reload
expect(p3.state).to eq "completed"
expect(p4.state).to eq "returned"
expect(@balance3.reload.state).to eq "paid"
expect(@balance4.reload.state).to eq "unpaid"
expect(@u3.reload.unpaid_balance_cents).to eq 0
expect(@u4.reload.unpaid_balance_cents).to eq 1004
end
it "decreases the user's balance by the amount of the payment and not down to 0" do
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, User.holding_balance)
@u1.reload
create(:balance, user: @u1, amount_cents: 99)
p1 = @u1.payments.last
p2 = @u2.payments.last
described_class.handle_paypal_event("payment_date" => p1.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_10" => p1.user.payment_address,
"masspay_txn_id_10" => "sometxn1",
"status_10" => "Completed",
"unique_id_10" => p1.id,
"mc_fee_10" => "2.99",
"receiver_email_11" => p2.user.payment_address,
"masspay_txn_id_11" => "sometxn2",
"status_11" => "Failed",
"unique_id_11" => p2.id,
"mc_fee_11" => "3.99")
@u1.reload
p2.reload
expect(@u1.unpaid_balance_cents).to eq 99
expect(p2.state).to eq "failed"
expect(p2.failure_reason).to be_nil
end
it "behaves idempotently" do
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, User.holding_balance)
@u1.reload
create(:balance, user: @u1, amount_cents: 99)
p1 = @u1.payments.last
p2 = @u2.payments.last
described_class.handle_paypal_event("payment_date" => p1.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_10" => p1.user.payment_address,
"masspay_txn_id_10" => "sometxn1",
"status_10" => "Completed",
"unique_id_10" => p1.id,
"mc_fee_10" => "2.99",
"receiver_email_11" => p2.user.payment_address,
"masspay_txn_id_11" => "sometxn2",
"status_11" => "Failed",
"unique_id_11" => p2.id,
"mc_fee_11" => "3.99")
@u1.reload
expect(@u1.unpaid_balance_cents).to eq 99
described_class.handle_paypal_event("payment_date" => p1.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_10" => p1.user.payment_address,
"masspay_txn_id_10" => "sometxn1",
"status_10" => "Completed",
"unique_id_10" => p1.id,
"mc_fee_10" => "2.99",
"receiver_email_11" => p2.user.payment_address,
"masspay_txn_id_11" => "sometxn2",
"status_11" => "Failed",
"unique_id_11" => p2.id,
"mc_fee_11" => "3.99")
@u1.reload
expect(@u1.unpaid_balance_cents).to eq 99
end
describe "more" do
before do
@u1 = create(:singaporean_user_with_compliance_info, payment_address: "bob1@example.com")
@balance1_1 = create(:balance, user: @u1, amount_cents: 1_000, date: Date.today - 10)
@balance1_2 = create(:balance, user: @u1, amount_cents: 2_000, date: Date.today - 9)
@balance1_3 = create(:balance, user: @u1, amount_cents: 3_000, date: Date.today - 8)
@balance1_4 = create(:balance, user: @u1, amount_cents: 4_000, date: Date.today)
@u2 = create(:singaporean_user_with_compliance_info, payment_address: "bob1@example.com")
@balance2_1 = create(:balance, user: @u2, amount_cents: 10_000, date: Date.today - 10)
@balance2_2 = create(:balance, user: @u2, amount_cents: 20_000, date: Date.today - 9)
@balance2_3 = create(:balance, user: @u2, amount_cents: 30_000, date: Date.today - 8)
@balance2_4 = create(:balance, user: @u2, amount_cents: 40_000, date: Date.today)
@u3 = create(:singaporean_user_with_compliance_info)
@balance3 = create(:balance, user: @u3, amount_cents: 4_000)
end
it "creates the proper payments and mark the balances and make the association between those" do
WebMock.stub_request(:post, PAYPAL_ENDPOINT)
.to_return(body: "TIMESTAMP=2012%2d10%2d26T20%3a29%3a14Z&CORRELATIONID=c51c5e0cecbce&ACK=Success&VERSION=90%2e0&BUILD=4072860")
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, User.holding_balance)
expect(@balance1_1.reload.state).to eq "processing"
expect(@balance1_2.reload.state).to eq "processing"
expect(@balance1_3.reload.state).to eq "processing"
expect(@balance1_4.reload.state).to eq "unpaid"
expect(@balance2_1.reload.state).to eq "processing"
expect(@balance2_2.reload.state).to eq "processing"
expect(@balance2_3.reload.state).to eq "processing"
expect(@balance2_4.reload.state).to eq "unpaid"
expect(@balance3.reload.state).to eq "unpaid"
expect(@u1.reload.unpaid_balance_cents).to eq 4_000
expect(@u2.reload.unpaid_balance_cents).to eq 40_000
expect(@u3.reload.unpaid_balance_cents).to eq 4_000
p1 = @u1.payments.last
p2 = @u2.payments.last
expect(@balance1_1.payments).to eq [p1]
expect(@balance1_2.payments).to eq [p1]
expect(@balance1_3.payments).to eq [p1]
expect(@balance1_4.payments).to eq []
expect(@balance2_1.payments).to eq [p2]
expect(@balance2_2.payments).to eq [p2]
expect(@balance2_3.payments).to eq [p2]
expect(@balance2_4.payments).to eq []
expect(@balance3.payments).to eq []
described_class.handle_paypal_event("payment_date" => p1.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => p1.user.payment_address,
"masspay_txn_id_0" => "sometxn1",
"status_0" => "Completed",
"unique_id_0" => p1.id,
"mc_fee_0" => "2.99",
"receiver_email_1" => p2.user.payment_address,
"masspay_txn_id_1" => "sometxn2",
"status_1" => "Failed",
"unique_id_1" => p2.id,
"mc_fee_1" => "3.99 ")
expect(@u1.reload.unpaid_balance_cents).to eq 4000
expect(@u2.reload.unpaid_balance_cents).to eq 100_000
expect(@balance1_1.reload.state).to eq "paid"
expect(@balance1_2.reload.state).to eq "paid"
expect(@balance1_3.reload.state).to eq "paid"
expect(@balance1_4.reload.state).to eq "unpaid"
expect(@balance2_1.reload.state).to eq "unpaid"
expect(@balance2_2.reload.state).to eq "unpaid"
expect(@balance2_3.reload.state).to eq "unpaid"
expect(@balance2_4.reload.state).to eq "unpaid"
expect(@balance3.reload.state).to eq "unpaid"
end
it "marks the balances as unpaid if the paypal call fails" do
WebMock.stub_request(:post, PAYPAL_ENDPOINT)
.to_return(body: "TIMESTAMP=2012%2d10%2d26T20%3a29%3a14Z&CORRELATIONID=c51c5e0cecbce&ACK=Fail&VERSION=90%2e0&BUILD=4072860")
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, User.holding_balance)
expect(@balance1_1.reload.state).to eq "unpaid"
expect(@balance1_2.reload.state).to eq "unpaid"
expect(@balance1_3.reload.state).to eq "unpaid"
expect(@balance1_4.reload.state).to eq "unpaid"
expect(@balance2_1.reload.state).to eq "unpaid"
expect(@balance2_2.reload.state).to eq "unpaid"
expect(@balance2_3.reload.state).to eq "unpaid"
expect(@balance2_4.reload.state).to eq "unpaid"
expect(@balance3.reload.state).to eq "unpaid"
expect(@u1.unpaid_balance_cents).to eq 10_000
expect(@u2.unpaid_balance_cents).to eq 100_000
expect(@u3.unpaid_balance_cents).to eq 4000
p1 = @u1.payments.last
p2 = @u2.payments.last
expect(p1.state).to eq "failed"
expect(p2.state).to eq "failed"
end
it "handles unclaimed payments properly" do
WebMock.stub_request(:post, PAYPAL_ENDPOINT)
.to_return(body: "TIMESTAMP=2012%2d10%2d26T20%3a29%3a14Z&CORRELATIONID=c51c5e0cecbce&ACK=Success&VERSION=90%2e0&BUILD=4072860")
Payouts.create_payments_for_balances_up_to_date_for_users(Date.today - 1, PayoutProcessorType::PAYPAL, User.holding_balance)
p1 = @u1.payments.last
p2 = @u2.payments.last
described_class.handle_paypal_event("payment_date" => p1.created_at.strftime("%T+%b+%d,+%Y+%Z"),
"receiver_email_0" => p1.user.payment_address,
"masspay_txn_id_0" => "sometxn1",
"status_0" => "Unclaimed",
"unique_id_0" => p1.id,
"mc_fee_0" => "2.99",
"receiver_email_1" => p2.user.payment_address,
"masspay_txn_id_1" => "sometxn2",
"status_1" => "Unclaimed",
"unique_id_1" => p2.id,
"mc_fee_1" => "3.99 ")
expect(@balance1_1.reload.state).to eq "processing"
expect(@balance1_2.reload.state).to eq "processing"
expect(@balance1_3.reload.state).to eq "processing"
expect(@balance1_4.reload.state).to eq "unpaid"
expect(@balance2_1.reload.state).to eq "processing"
expect(@balance2_2.reload.state).to eq "processing"
expect(@balance2_3.reload.state).to eq "processing"
expect(@balance2_4.reload.state).to eq "unpaid"
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/integrations/paypal_integration_rest_api_spec.rb | spec/business/payments/integrations/paypal_integration_rest_api_spec.rb | # frozen_string_literal: true
describe PaypalIntegrationRestApi, :vcr do
before do
@creator = create(:user, email: "sb-oy4cl2265599@business.example.com")
end
describe "create_partner_referral" do
context "valid inputs" do
before do
authorization_header = PaypalPartnerRestCredentials.new.auth_token
api_object = PaypalIntegrationRestApi.new(@creator, authorization_header:)
@response = api_object.create_partner_referral("http://example.com")
end
it "succeeds and returns links in the response" do
expect(@response.success?).to eq(true)
expect(@response.parsed_response["links"].count).to eq(2)
end
end
context "invalid inputs" do
before do
api_object = PaypalIntegrationRestApi.new(@creator, authorization_header: "invalid header")
@response = api_object.create_partner_referral("http://example.com")
end
it "fails and returns unauthorized as error" do
expect(@response.success?).to eq(false)
expect(@response.code).to eq(401)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.