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/services/product/variants_updater_service_spec.rb
spec/services/product/variants_updater_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::VariantsUpdaterService do describe ".perform" do context "for products with variants" do before :each do @product = create(:product) @size_category = create(:variant_category, link: @product, title: "Size") @small = create(:variant, variant_category: @size_category, name: "Small") @large = create(:variant, variant_category: @size_category, name: "Large") @variants_params = { "0" => { name: "SIZE", id: @size_category.external_id, options: { "0" => { name: @small.name, id: @small.external_id, }, "1" => { name: "LARGE", id: @large.external_id } } }, "1" => { name: "Color", id: nil, options: { "0" => { name: "Red", id: nil }, "1" => { name: "Blue", id: nil } } } } end it "updates the variants and variant categories" do Product::VariantsUpdaterService.new( product: @product, variants_params: @variants_params ).perform new_category = @product.variant_categories.last expect(new_category.title).to eq "Color" expect(new_category.variants.pluck(:name)).to match_array ["Red", "Blue"] expect(@size_category.reload.title).to eq "SIZE" expect(@large.reload.name).to eq "LARGE" end context "missing category name" do it "sets the category title to nil" do @variants_params["0"].delete(:name) Product::VariantsUpdaterService.new( product: @product, variants_params: @variants_params ).perform expect(@size_category.reload.title).to be_nil end end context "with empty categories" do it "deletes all categories" do Product::VariantsUpdaterService.new( product: @product, variants_params: {} ).perform expect(@product.reload.variant_categories_alive).to be_empty end end end context "for tiered memberships" do it "updates the tiers" do product = create(:membership_product) tier_category = product.variant_categories.first effective_date = 7.days.from_now.to_date variant_categories = { "0" => { name: tier_category.title, id: tier_category.external_id, options: { "0" => { name: "First Tier", settings: { apply_price_changes_to_existing_memberships: { enabled: "1", effective_date: effective_date.strftime("%Y-%m-%d"), custom_message: "hello" }, }, }, "1" => { name: "Second Tier" } } } } Product::VariantsUpdaterService.new( product:, variants_params: variant_categories ).perform tiers = tier_category.reload.variants.alive tier = tiers.find_by(name: "First Tier") expect(tiers.pluck(:name)).to match_array ["First Tier", "Second Tier"] expect(tier.apply_price_changes_to_existing_memberships).to eq true expect(tier.subscription_price_change_effective_date).to eq effective_date expect(tier.subscription_price_change_message).to eq "hello" end end context "for SKUs" do before :each do @product = create(:physical_product) @default_sku = @product.skus.first category = create(:variant_category, link: @product, title: "Size") @large_sku = create(:sku, link: @product, name: "Large") @medium_sku = create(:sku, link: @product, name: "Medium") @small_sku = create(:sku, link: @product, name: "Small") @xs_sku = create(:sku, link: @product, name: "X-Small") large_variant = create(:variant, variant_category: category, skus: [@large_sku], name: "Large") medium_variant = create(:variant, variant_category: category, skus: [@medium_sku], name: "Medium") small_variant = create(:variant, variant_category: category, skus: [@small_sku], name: "Small") create(:variant, variant_category: category, skus: [@xs_sku], name: "Small") @variants_params = { "0" => { id: category.external_id, title: category.title, options: { "0" => { id: large_variant.external_id, name: large_variant.name, }, "1" => { id: medium_variant.external_id, name: medium_variant.name, }, "2" => { id: small_variant.external_id, name: small_variant.name, } } } } @skus_params = { "0" => { id: @large_sku.external_id, price_difference: 0 }, "1" => { id: @medium_sku.external_id, price_difference: 10 }, "2" => { id: @small_sku.external_id, custom_sku: "small-sku", price_difference: 0 } } end it "updates new SKUs and deletes old ones" do Product::VariantsUpdaterService.new( product: @product, variants_params: @variants_params, skus_params: @skus_params ).perform updated_skus = [@default_sku, @large_sku, @medium_sku, @small_sku].map(&:reload) expect(@product.reload.skus.alive).to match_array updated_skus expect(@small_sku.custom_sku).to eq "small-sku" expect(@medium_sku.price_difference_cents).to eq 1000 expect(@xs_sku.reload).to be_deleted end context "missing SKU id" do it "raises an error" do params = @skus_params params["0"].delete(:id) expect do Product::VariantsUpdaterService.new( product: @product, variants_params: @variants_params, skus_params: params ).perform end.to raise_error Link::LinkInvalid end end end describe "deleting categories" do before :each do @product = create(:product) @size_category = create(:variant_category, link: @product, title: "Size") @color_category = create(:variant_category, link: @product, title: "Color") @variant_categories = { "0" => { name: @color_category.title, id: @color_category.external_id, options: { "0" => { id: nil, name: "green" } } } } end it "marks a category deleted if not included in variant_category_params" do Product::VariantsUpdaterService.new( product: @product, variants_params: @variant_categories ).perform expect(@color_category.reload).to be_alive expect(@size_category.reload).not_to be_alive end it "does not mark a category deleted if it has purchases and files" do small_variant = create(:variant, :with_product_file, variant_category: @size_category, name: "Small") create(:purchase, link: @product, variant_attributes: [small_variant]) Product::VariantsUpdaterService.new( product: @product, variants_params: @variant_categories ).perform expect(@color_category.reload).to be_alive expect(@size_category.reload).to be_alive end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/ssl_certificates/generate_spec.rb
spec/services/ssl_certificates/generate_spec.rb
# frozen_string_literal: true require "spec_helper" describe SslCertificates::Generate do before do stub_const("SslCertificates::Base::CONFIG_FILE", File.join(Rails.root, "spec", "support", "fixtures", "ssl_certificates.yml.erb")) @custom_domain = create(:custom_domain, domain: "www.example.com") @obj = SslCertificates::Generate.new(@custom_domain) end it "inherits from SslCertificates::Base" do expect(described_class).to be < SslCertificates::Base end describe "#hourly_rate_limit_reached?" do before do allow_any_instance_of(described_class).to receive(:rate_limit).and_return(1) create(:custom_domain, domain: "www.example-1.com").set_ssl_certificate_issued_at! end context "when hourly limit is not reached" do it "returns false" do expect(@obj.send(:hourly_rate_limit_reached?)).to eq false end end context "when hourly limit is reached" do context "when there are no deleted domains" do before do create(:custom_domain, domain: "www.example-2.com").set_ssl_certificate_issued_at! end it "returns true" do expect(@obj.send(:hourly_rate_limit_reached?)).to eq true end end context "when there are deleted domains" do before do create(:custom_domain, domain: "www.example-2.com").set_ssl_certificate_issued_at! custom_domain_3 = create(:custom_domain, domain: "www.example-3.com") custom_domain_3.set_ssl_certificate_issued_at! custom_domain_3.mark_deleted! end it "returns true" do expect(@obj.send(:hourly_rate_limit_reached?)).to eq true end end end end describe "#can_order_certificates?" do context "with a valid certificate" do it "returns false when the domain already has a valid certificate" do @custom_domain.set_ssl_certificate_issued_at! expect(@obj.send(:can_order_certificates?)).to eq [false, "Has valid certificate"] end end context "when the domain is invalid" do before do @custom_domain.domain = "test_store.example.com" @custom_domain.save(validate: false) end it "returns false with an error message" do expect(@obj.send(:can_order_certificates?)).to eq [false, "Invalid domain"] end end context "when the hourly limit is reached" do it "returns false when the hourly rate limit is reached" do custom_domains_double = double("custom_domains collection") allow(CustomDomain).to receive(:certificates_younger_than).with(@obj.send(:rate_limit_hours)).and_return(custom_domains_double) allow(custom_domains_double).to receive(:count).and_return(@obj.send(:rate_limit) + 1) expect(@obj.send(:can_order_certificates?)).to eq [false, "Hourly limit reached"] end end describe "CNAME/ALIAS check" do before do allow_any_instance_of(CustomDomain).to receive(:cname_is_setup_correctly?).and_return(false) allow_any_instance_of(CustomDomain).to receive(:alias_is_setup_correctly?).and_return(false) end it "returns false when no domains are pointed to Gumroad" do expect(@obj.send(:can_order_certificates?)).to eq [false, "No domains pointed to Gumroad"] end end end describe "#domain_check_cache_key" do it "returns domin check cache key" do expect(@obj.send(:domain_check_cache_key)).to eq "domain_check_www.example.com" end end describe "#generate_certificate" do before do @letsencrypt_double = double("letsencrypt") allow(SslCertificates::LetsEncrypt).to receive(:new).with("test-domain").and_return(@letsencrypt_double) end it "invokes process method of LetsEncrypt service" do expect(@letsencrypt_double).to receive(:process) @obj.send(:generate_certificate, "test-domain") end end describe "#process" do context "when `can_order_certificates?` returns false" do before do allow_any_instance_of(described_class).to receive(:can_order_certificates?).and_return([false, "sample error message"]) end it "logs a message" do expect(@obj).to receive(:log_message).with(@custom_domain.domain, "sample error message") @obj.process end end context "when the certificate is successfully created" do before do @domains_pointed_to_gumroad = ["example.com", "www.example.com"] allow(@obj).to receive(:can_order_certificates?).and_return(true) allow_any_instance_of(CustomDomainVerificationService).to receive(:domains_pointed_to_gumroad).and_return(@domains_pointed_to_gumroad) @domains_pointed_to_gumroad.each do |domain| allow(@obj).to receive(:generate_certificate).with(domain).and_return(true) end end it "set ssl_certificate_issued_at and logs a message" do @domains_pointed_to_gumroad.each do |domain| expect(@obj).to receive(:generate_certificate).with(domain) expect(@obj).to receive(:log_message).with(domain, "Issued SSL certificate.") end time = Time.current travel_to(time) do @obj.process end expect(@custom_domain.reload.ssl_certificate_issued_at.to_i).to eq time.to_i end end context "when the certificate generation fails" do before do allow_any_instance_of(described_class).to receive(:can_order_certificates?).and_return(true) allow_any_instance_of(described_class).to receive(:generate_certificate).and_return(false) allow_any_instance_of(CustomDomainVerificationService).to receive(:domains_pointed_to_gumroad).and_return([@custom_domain.domain]) @custom_domain.set_ssl_certificate_issued_at! end it "writes the information to cache and resets custom_domain's ssl_certificate_issued_at attribute" do cache_double = double(".cache") allow(Rails).to receive(:cache).and_return(cache_double) expect(cache_double).to receive(:write).with("domain_check_#{@custom_domain.domain}", false, expires_in: @obj.send(:invalid_domain_cache_expires_in)) expect(@obj).to receive(:log_message).with(@custom_domain.domain, "LetsEncrypt order failed. Next retry in about 8 hours.") @obj.process expect(@custom_domain.reload.ssl_certificate_issued_at).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/services/ssl_certificates/letsencrypt_spec.rb
spec/services/ssl_certificates/letsencrypt_spec.rb
# frozen_string_literal: true require "spec_helper" describe SslCertificates::LetsEncrypt do before do stub_const("SslCertificates::Base::CONFIG_FILE", File.join(Rails.root, "spec", "support", "fixtures", "ssl_certificates.yml.erb")) @custom_domain = create(:custom_domain, domain: "www.example.com") @obj = SslCertificates::LetsEncrypt.new(@custom_domain.domain) end it "inherits from SslCertificates::Base" do expect(described_class).to be < SslCertificates::Base end describe "#initialize" do it "initializes custom_domain" do expect(@obj.send(:domain)).to eq @custom_domain.domain end describe "certificate_private_key" do context "when initialized" do it { expect(@obj.send(:certificate_private_key).class).to eq OpenSSL::PKey::RSA } end context "when the key size is 2048" do it { expect(@obj.certificate_private_key.n.num_bits).to eq 2048 } end end end describe "#upload_certificate_to_s3" do it "invokes write_to_s3 twice to upload key and cert" do sample_path = "/sample/path" allow_any_instance_of(described_class).to receive(:ssl_file_path).and_return(sample_path) certificate = "cert 123" key = "key 123" expect(@obj).to receive(:write_to_s3).with(sample_path, certificate) expect(@obj).to receive(:write_to_s3).with(sample_path, key) @obj.send(:upload_certificate_to_s3, certificate, key) end end describe "#finalize_with_csr" do it "finalizes order and return certificate" do order_double = double("order") certificate_double = double("certificate") allow(order_double).to receive(:status).and_return("processed") allow(order_double).to receive(:certificate).and_return(certificate_double) csr_double = double("csr_double") allow(Acme::Client::CertificateRequest).to receive(:new).and_return(csr_double) http_challenge_double = double("http_challenge") expect(order_double).to receive(:finalize).with(csr: csr_double) expect(order_double).to receive(:certificate) returned_object = @obj.send(:finalize_with_csr, order_double, http_challenge_double) expect(returned_object).to eq certificate_double end end describe "#poll_validation_status" do before do @http_challenge_double = double("http_challenge") allow(@http_challenge_double).to receive(:status).and_return("pending") allow(@http_challenge_double).to receive(:reload) allow_any_instance_of(Object).to receive(:sleep) @max_tries = @obj.send(:max_retries) end it "polls for validation status 'max_tries' times" do expect(@http_challenge_double).to receive(:status).exactly(@max_tries).times expect_any_instance_of(Object).to receive(:sleep).exactly(@max_tries).times expect(@http_challenge_double).to receive(:reload).exactly(@max_tries).times @obj.send(:poll_validation_status, @http_challenge_double) end end describe "#request_validation" do before do @http_challenge_double = double("http_challenge") allow(@http_challenge_double).to receive(:request_validation) end it "requests for HTTP validation" do expect(@http_challenge_double).to receive(:request_validation) @obj.send(:request_validation, @http_challenge_double) end end describe "#prepare_http_challenge" do before do @sample_token = "sample_token" @sample_file_content = "sample content" @http_challenge_double = double("http_challenge") allow(@http_challenge_double).to receive(:token).and_return(@sample_token) allow(@http_challenge_double).to receive(:file_content).and_return(@sample_file_content) end it "stores validation content in Redis" do expect($redis).to receive(:setex).with(RedisKey.acme_challenge(@sample_token), described_class::CHALLENGE_TTL, @sample_file_content) @obj.send(:prepare_http_challenge, @http_challenge_double) end end describe "#delete_http_challenge" do before do @sample_token = "sample_token" @http_challenge_double = double("http_challenge") allow(@http_challenge_double).to receive(:token).and_return(@sample_token) end it "deletes validation content from Redis" do expect($redis).to receive(:del).with(RedisKey.acme_challenge(@sample_token)) @obj.send(:delete_http_challenge, @http_challenge_double) end end describe "#order_certificate" do before do client_double = double("client_double") @order_double = double("order_double") allow_any_instance_of(described_class).to receive(:client).and_return(client_double) allow(client_double).to receive(:new_order).and_return(@order_double) @authorization_double = double("authorization_double") allow(@order_double).to receive(:authorizations).and_return([@authorization_double]) @http_challenge_double = double("http_challenge_double") allow(@authorization_double).to receive(:http).and_return(@http_challenge_double) end it "orders the certificate" do expect(@order_double).to receive(:authorizations) returned_objects = @obj.send(:order_certificate) expect(returned_objects).to eq [@order_double, @http_challenge_double] end end describe "#client" do before do account_private_key_double = double("account_private_key_double") allow_any_instance_of(described_class).to receive(:account_private_key) .and_return(account_private_key_double) @client_double = double("client_double") allow(Acme::Client).to receive(:new).and_return(@client_double) allow(@client_double).to receive(:new_account) end context "when ACME account doesn't exist" do before do allow(@client_double).to receive(:account).and_raise(Acme::Client::Error::AccountDoesNotExist) end it "creates the ACME account" do expect(@client_double).to receive(:new_account) client = @obj.send(:client) expect(client).to eq @client_double end end context "when ACME account exists" do before do account_double = double("account") allow(@client_double).to receive(:account).and_return(account_double) end it "doesn't create the ACME account" do expect(@client_double).not_to receive(:new_account) client = @obj.send(:client) expect(client).to eq @client_double end it "caches the account status" do allow(@client_double).to receive(:account).once 2.times do @obj.send(:client) end end end end describe "#account_private_key" do before do @pkey_double = double("pkey_double") @private_key = "private_key" allow(OpenSSL::PKey::RSA).to receive(:new).and_return(@pkey_double) ENV["LETS_ENCRYPT_ACCOUNT_PRIVATE_KEY"] = @private_key end after do ENV["LETS_ENCRYPT_ACCOUNT_PRIVATE_KEY"] = nil end it "returns account private key" do expect(OpenSSL::PKey::RSA).to receive(:new).with(@private_key).and_return(@pkey_double) expect(@obj.send(:account_private_key)).to eq @pkey_double end end describe "#process" do before do @order_double = double("order_double") @http_challenge_double = double("http_challenge_double") @certificate_double = double("certificate_double") @sample_token = "challenge-token" allow_any_instance_of(described_class).to receive(:order_certificate) .and_return([@order_double, @http_challenge_double]) allow_any_instance_of(described_class).to receive(:prepare_http_challenge).with(@http_challenge_double) allow_any_instance_of(Object).to receive(:sleep) allow_any_instance_of(described_class).to receive(:request_validation).with(@http_challenge_double) allow_any_instance_of(described_class).to receive(:poll_validation_status).with(@http_challenge_double) allow_any_instance_of(described_class).to receive(:upload_certificate_to_s3) .with(@certificate_double, @obj.send(:certificate_private_key)) allow_any_instance_of(described_class).to receive(:finalize_with_csr) .with(@order_double, @http_challenge_double).and_return(@certificate_double) allow(@http_challenge_double).to receive(:token).and_return(@sample_token) allow($redis).to receive(:del) end context "when the order is successful" do it "processes the LetsEncrypt order" do expect(@obj).to receive(:order_certificate).and_return([@order_double, @http_challenge_double]) expect(@obj).to receive(:prepare_http_challenge).with(@http_challenge_double) expect(@obj).to receive(:request_validation).with(@http_challenge_double) expect(@obj).to receive(:poll_validation_status).with(@http_challenge_double) expect(@obj).to receive(:finalize_with_csr).with(@order_double, @http_challenge_double) .and_return(@certificate_double) expect(@obj).to receive(:upload_certificate_to_s3).with(@certificate_double, @obj.send(:certificate_private_key)) @obj.process end it "deletes the http challenge from Redis" do expect($redis).to receive(:del).with(RedisKey.acme_challenge(@sample_token)) @obj.process end end context "when the order fails" do it "logs message and returns false" do allow_any_instance_of(described_class).to receive(:finalize_with_csr) .with(@order_double, @http_challenge_double).and_raise("sample error message") expect(@obj).to receive(:order_certificate).and_return([@order_double, @http_challenge_double]) expect(@obj).to receive(:prepare_http_challenge).with(@http_challenge_double) expect(@obj).to receive(:request_validation).with(@http_challenge_double) expect(@obj).to receive(:poll_validation_status).with(@http_challenge_double) expect(@obj).to receive(:log_message).with(@custom_domain.domain, "SSL Certificate cannot be issued. Error: sample error message") expect(@obj.process).to be false expect(@custom_domain.ssl_certificate_issued_at).to be_nil end it "deletes the http challenge from Redis" do expect($redis).to receive(:del).with(RedisKey.acme_challenge(@sample_token)) @obj.process end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/ssl_certificates/base_spec.rb
spec/services/ssl_certificates/base_spec.rb
# frozen_string_literal: true require "spec_helper" describe SslCertificates::Base do before do stub_const("SslCertificates::Base::CONFIG_FILE", Rails.root.join("spec", "support", "fixtures", "ssl_certificates.yml.erb")) @obj = SslCertificates::Base.new end describe "self.supported_environment?" do context "when the environment is production or staging" do before do allow(Rails.env).to receive(:production?).and_return(true) end it "returns true" do expect(SslCertificates::Base.supported_environment?).to be true end end context "when the environment is not production or staging" do it "returns false" do expect(SslCertificates::Base.supported_environment?).to be false end end end describe "#initialize" do it "sets the required config variables as methods" do expect(@obj.send(:account_email)).to eq "test-service-letsencrypt@gumroad.com" expect(@obj.send(:acme_url)).to eq "https://test.api.letsencrypt.org/directory" expect(@obj.send(:invalid_domain_cache_expires_in)).to eq 8.hours.seconds expect(@obj.send(:max_retries)).to eq 10 expect(@obj.send(:rate_limit)).to eq 300 expect(@obj.send(:rate_limit_hours)).to eq 3.hours.seconds expect(@obj.send(:renew_in)).to eq 60.days.seconds expect(@obj.send(:sleep_duration)).to eq 2.seconds expect(@obj.send(:ssl_env)).to eq "test" end end describe "#certificate_authority" do it "returns the certificate authority" do expect(@obj.send(:certificate_authority)).to eq SslCertificates::LetsEncrypt end end describe "#ssl_file_path" do it "returns the S3 SSL file path" do file_path = @obj.ssl_file_path("sample.com", "sample") expect(file_path).to eq "custom-domains-ssl/test/sample.com/ssl/sample" end end describe "#delete_from_s3" do before do s3_client = double("s3_client") @s3_bucket = double("s3_bucket") @s3_object = double("s3_object") allow(Aws::S3::Resource).to receive(:new).and_return(s3_client) allow(s3_client).to receive(:bucket).and_return(@s3_bucket) @s3_key = "custom-domains-ssl/test/www.example.com/public/sample_challenge_file" allow(@s3_bucket).to receive(:object).with(@s3_key).and_return(@s3_object) allow(@s3_object).to receive(:delete) end it "deletes the file from S3" do expect(@s3_bucket).to receive(:object).with(@s3_key).and_return(@s3_object) expect(@s3_object).to receive(:delete) @obj.send(:delete_from_s3, @s3_key) end end describe "#write_to_s3" do it "writes the content to S3" do test_key = "test_key" test_content = "test_content" test_bucket = "test-bucket" stub_const("SslCertificates::Base::SECRETS_S3_BUCKET", test_bucket) s3_double = double("aws_s3") aws_instance_profile_double = double("aws_instance_profile_double") allow(Aws::InstanceProfileCredentials).to receive(:new).and_return(aws_instance_profile_double) allow(Aws::S3::Resource).to receive(:new).with(credentials: aws_instance_profile_double).and_return(s3_double) bucket_double = double("s3_bucket") allow(s3_double).to receive(:bucket).with(test_bucket).and_return(bucket_double) obj_double = double("s3_obj") allow(bucket_double).to receive(:object).with(test_key).and_return(obj_double) expect(obj_double).to receive(:put).with(body: test_content) @obj.send(:write_to_s3, test_key, test_content) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/ssl_certificates/renew_spec.rb
spec/services/ssl_certificates/renew_spec.rb
# frozen_string_literal: true require "spec_helper" describe SslCertificates::Renew do before do stub_const("SslCertificates::Base::CONFIG_FILE", File.join(Rails.root, "spec", "support", "fixtures", "ssl_certificates.yml.erb")) @obj = SslCertificates::Renew.new end it "inherits from SslCertificates::Base" do expect(described_class).to be < SslCertificates::Base end describe "#process" do before do @custom_domain = create(:custom_domain, domain: "www.example.com") allow(CustomDomain).to receive(:certificate_absent_or_older_than) .with(@obj.send(:renew_in)).and_return([@custom_domain]) end it "enques job for generating SSL certificate" do expect(CustomDomain).to receive(:certificate_absent_or_older_than).with(@obj.send(:renew_in)) expect(@custom_domain).to receive(:generate_ssl_certificate) @obj.process end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/follower/create_service_spec.rb
spec/services/follower/create_service_spec.rb
# frozen_string_literal: false describe Follower::CreateService do let(:user) { create(:user) } let(:follower_user) { create(:user) } let(:follower) { create(:follower, user:) } let(:active_follower) { create(:active_follower, user:) } let(:deleted_follower) { create(:deleted_follower, user:) } context "when follower is present" do it "updates the source of the follow and follower_user_id" do Follower::CreateService.perform( followed_user: user, follower_email: deleted_follower.email, follower_attributes: { source: "welcome-greeter", follower_user_id: follower_user.id } ) deleted_follower.reload expect(deleted_follower.source).to eq("welcome-greeter") expect(deleted_follower.follower_user_id).to eq(follower_user.id) end context "when follower is cancelled" do it "uncancels the follower" do Follower::CreateService.perform( followed_user: user, follower_email: deleted_follower.email ) deleted_follower.reload expect(deleted_follower.deleted?).to be_falsey expect(deleted_follower.confirmed?).to be_falsey end end context "when follower exists in master DB but not in replica" do it "reactivates the existing follower" do deleted_follower # Mock a situation when an existing follower is at first not found because # changes have not propagated to replica DB allow(user.followers).to receive(:find_by) .with(email: deleted_follower.email) .and_return(nil, deleted_follower) # At first attempt to save the follower, fail with ActiveRecord::RecordNotUnique behaviour = [:raise_once, :then_call_original] allow_any_instance_of(Follower).to receive(:save!).and_wrap_original do |m, *args| raise(ActiveRecord::RecordNotUnique) if behaviour.shift == :raise_once m.call(*args) end Follower::CreateService.perform( followed_user: user, follower_email: deleted_follower.email ) deleted_follower.reload expect(deleted_follower.deleted?).to be_falsey end end describe "confirmation" do context "when follower not confirmed nor cancelled" do it "sends the confirmation email again" do expect do Follower::CreateService.perform( followed_user: user, follower_email: follower.email, ) end.to have_enqueued_mail(FollowerMailer, :confirm_follower).with(user.id, follower.id) end end context "when imported from CSV" do it "auto-confirms and does not send the confirmation email" do expect do follower = Follower::CreateService.perform( followed_user: user, follower_email: "imported@email.com", follower_attributes: { source: Follower::From::CSV_IMPORT } ) expect(follower.confirmed?).to be_truthy end.to_not have_enqueued_mail(FollowerMailer, :confirm_follower) # Re-importing existing followers should not trigger an email either expect do follower = Follower::CreateService.perform( followed_user: user, follower_email: "imported@email.com", follower_attributes: { source: Follower::From::CSV_IMPORT } ) expect(follower.confirmed?).to be_truthy end.to_not have_enqueued_mail(FollowerMailer, :confirm_follower) end end context "when follower is not logged in" do it "does not auto-confirm and sends the confirmation email" do expect do follower = Follower::CreateService.perform( followed_user: user, follower_email: deleted_follower.email ) expect(follower.confirmed?).to be_falsey end.to have_enqueued_mail(FollowerMailer, :confirm_follower).with(user.id, deleted_follower.id) end it "sends the confirmation email even if follower is confirmed" do expect do Follower::CreateService.perform( followed_user: user, follower_email: active_follower.email ) end.to have_enqueued_mail(FollowerMailer, :confirm_follower).with(user.id, active_follower.id) end it "does not send the confirmation email if the new email is invalid" do expect do follower = Follower::CreateService.perform( followed_user: user, follower_email: active_follower.email, follower_attributes: { email: "invalid email" } ) expect(follower.valid?).to eq(false) end.not_to have_enqueued_mail(FollowerMailer, :confirm_follower).with(user.id, active_follower.id) end end context "when follower is logged in" do it "auto-confirms if logged-in user has confirmed email" do confirmed_user = create(:user) expect do follower = Follower::CreateService.perform( followed_user: user, follower_email: confirmed_user.email, logged_in_user: confirmed_user ) expect(follower.confirmed?).to be_truthy end.to_not have_enqueued_mail(FollowerMailer, :confirm_follower) end it "sends the confirmation email if-logged in user has unconfirmed email" do unconfirmed_user = create(:unconfirmed_user) expect do follower = Follower::CreateService.perform( followed_user: user, follower_email: unconfirmed_user.email, logged_in_user: unconfirmed_user ) expect(follower.confirmed?).to be_falsey end.to have_enqueued_mail(FollowerMailer, :confirm_follower).with(user.id, anything) end end end end context "when follower is not present" do it do expect do Follower::CreateService.perform( followed_user: user, follower_email: "new@email.com", follower_attributes: { source: "welcome-greeter" } ) end.to have_enqueued_mail(FollowerMailer, :confirm_follower) follower = Follower.find_by(email: "new@email.com") expect(follower.source).to eq("welcome-greeter") expect(follower.confirmed?).to be_falsey end it "does not send the confirmation email if the email is invalid" do expect do follower = Follower::CreateService.perform( followed_user: user, follower_email: "invalid email", follower_attributes: { source: "welcome-greeter" } ) expect(follower.persisted?).to eq(false) expect(follower.valid?).to eq(false) end.not_to have_enqueued_mail(FollowerMailer, :confirm_follower) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/dispute_evidence/generate_uncategorized_text_service_spec.rb
spec/services/dispute_evidence/generate_uncategorized_text_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe DisputeEvidence::GenerateUncategorizedTextService, :vcr do let(:product) do create( :physical_product, name: "Sample product title at purchase time" ) end let(:disputed_purchase) do create( :disputed_purchase, email: "customer@example.com", full_name: "Joe Doe", ip_state: "California", ip_country: "United States", credit_card_zipcode: "12345", stripe_fingerprint: "sample_fingerprint", ) end let!(:other_undisputed_purchase) do create( :purchase, created_at: Date.parse("2023-12-31"), total_transaction_cents: 1299, email: "other_email@example.com", full_name: "John Doe", ip_state: "Oregon", ip_country: "United States", credit_card_zipcode: "99999", ip_address: "1.1.1.1", stripe_fingerprint: "sample_fingerprint", ) end let(:uncategorized_text) { described_class.perform(disputed_purchase) } describe ".perform" do it "returns customer location, billing postal code, and previous purchases information" do expected_uncategorized_text = <<~TEXT.strip_heredoc.rstrip Device location: California, United States Billing postal code: 12345 Previous undisputed purchase on Gumroad: 2023-12-31 00:00:00 UTC, $12.99, John Doe, other_email@example.com, Billing postal code: 99999, Device location: 1.1.1.1, Oregon, United States TEXT expect(uncategorized_text).to eq(expected_uncategorized_text) end context "when the other purchase has a different fingerprint" do before do other_undisputed_purchase.update!(stripe_fingerprint: "other_fintgerprint") end it "does not include previous purchases information" do expected_uncategorized_text = <<~TEXT.strip_heredoc.rstrip Device location: California, United States Billing postal code: 12345 TEXT expect(uncategorized_text).to eq(expected_uncategorized_text) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/dispute_evidence/create_from_dispute_service_spec.rb
spec/services/dispute_evidence/create_from_dispute_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe DisputeEvidence::CreateFromDisputeService, :vcr, :versioning do let(:product) do travel_to 1.hour.ago do create( :physical_product, name: "Sample product title at purchase time" ) end end let(:variant) { create(:variant, name: "Platinum", variant_category: create(:variant_category, link: product)) } let!(:disputed_purchase) do create( :disputed_purchase, email: "customer@example.com", full_name: "John Example", street_address: "123 Sample St", city: "San Francisco", state: "CA", country: "United States", zip_code: "12343", ip_state: "California", ip_country: "United States", credit_card_zipcode: "1234", link: product, url_redirect: create(:url_redirect), quantity: 2, variant_attributes: [variant] ) end let!(:shipment) do create( :shipment, carrier: "UPS", tracking_number: "123456", purchase: disputed_purchase, ship_state: "shipped", shipped_at: DateTime.parse("2023-02-10 14:55:32") ) end let!(:sample_image) { File.read(Rails.root.join("spec", "support", "fixtures", "test-small.jpg")) } before do create(:dispute_formalized, purchase: disputed_purchase) travel_to 1.hour.from_now do product.update!( name: "New product title", description: "New product description" ) end end it "creates a dispute evidence" do allow(DisputeEvidence::GenerateReceiptImageService).to receive(:perform).with(disputed_purchase).and_return(sample_image) allow(DisputeEvidence::GenerateUncategorizedTextService).to( receive(:perform).with(disputed_purchase).and_return("Sample uncategorized text") ) allow(DisputeEvidence::GenerateAccessActivityLogsService).to( receive(:perform).with(disputed_purchase).and_return("Sample activity logs") ) dispute_evidence = DisputeEvidence.create_from_dispute!(disputed_purchase.dispute) expect(dispute_evidence.dispute).to eq(disputed_purchase.dispute) expect(dispute_evidence.purchased_at).to eq(disputed_purchase.created_at) expect(dispute_evidence.customer_purchase_ip).to eq(disputed_purchase.ip_address) expect(dispute_evidence.customer_email).to eq(disputed_purchase.email) expect(dispute_evidence.customer_name).to eq(disputed_purchase.full_name) expect(dispute_evidence.billing_address).to eq("123 Sample St, San Francisco, CA, 12343, United States") expect(dispute_evidence.shipping_address).to eq("123 Sample St, San Francisco, CA, 12343, United States") expect(dispute_evidence.shipped_at).to eq(shipment.shipped_at) expect(dispute_evidence.shipping_carrier).to eq("UPS") expect(dispute_evidence.shipping_tracking_number).to eq(shipment.tracking_number) expected_product_description = \ "Product name: Sample product title at purchase time\n" + "Product as seen when purchased: #{Rails.application.routes.url_helpers.purchase_product_url(disputed_purchase.external_id, host: DOMAIN, protocol: PROTOCOL)}\n" + "Product type: physical product\n" + "Product variant: Platinum\n" + "Quantity purchased: 2\n" + "Receipt: #{Rails.application.routes.url_helpers.receipt_purchase_url(disputed_purchase.external_id, email: disputed_purchase.email, host: DOMAIN, protocol: PROTOCOL)}\n" + "Live product: #{disputed_purchase.link.long_url}" expect(dispute_evidence.product_description).to eq(expected_product_description) expect(dispute_evidence.uncategorized_text).to eq("Sample uncategorized text") expect(dispute_evidence.receipt_image).to be_attached expect(dispute_evidence.refund_policy_image).not_to be_attached expect(dispute_evidence.refund_policy_disclosure).to be_nil expect(dispute_evidence.cancellation_policy_image).not_to be_attached expect(dispute_evidence.cancellation_policy_disclosure).to be_nil expect(dispute_evidence.access_activity_log).to eq("Sample activity logs") end context "when dispute is on a combined charge" do let(:purchase) do create( :purchase, total_transaction_cents: 20_00, chargeback_date: Date.today, email: "customer@example.com", full_name: "John Example", street_address: "123 Sample St", city: "San Francisco", state: "CA", country: "United States", zip_code: "12343", ip_state: "California", ip_country: "United States", credit_card_zipcode: "1234", link: product, url_redirect: create(:url_redirect), quantity: 2, variant_attributes: [variant] ) end let(:charge) do charge = create(:charge) charge.purchases << create(:purchase, total_transaction_cents: 10_00, email: "customer@example.com") charge.purchases << purchase charge.purchases << create(:purchase, total_transaction_cents: 5_00, email: "customer@example.com") charge end let(:shipment) do create( :shipment, carrier: "UPS", tracking_number: "123456", purchase:, ship_state: "shipped", shipped_at: DateTime.parse("2023-02-10 14:55:32") ) end let(:dispute) { create(:dispute_on_charge, charge:) } before do expect(charge.purchase_for_dispute_evidence).to eq purchase allow(DisputeEvidence::GenerateUncategorizedTextService).to( receive(:perform).with(purchase).and_return("Sample uncategorized text") ) allow(DisputeEvidence::GenerateAccessActivityLogsService).to( receive(:perform).with(purchase).and_return("Sample activity logs") ) allow(DisputeEvidence::GenerateReceiptImageService).to receive(:perform).with(purchase).and_return(sample_image) end it "creates a dispute evidence" do dispute_evidence = DisputeEvidence.create_from_dispute!(dispute) expect(dispute_evidence.dispute).to eq(charge.dispute) expect(dispute_evidence.purchased_at).to eq(purchase.created_at) expect(dispute_evidence.customer_purchase_ip).to eq(purchase.ip_address) expect(dispute_evidence.customer_email).to eq(purchase.email) expect(dispute_evidence.customer_name).to eq(purchase.full_name) expect(dispute_evidence.billing_address).to eq("123 Sample St, San Francisco, CA, 12343, United States") expect(dispute_evidence.shipping_address).to eq("123 Sample St, San Francisco, CA, 12343, United States") expect(dispute_evidence.shipped_at).to eq(shipment.shipped_at) expect(dispute_evidence.shipping_carrier).to eq("UPS") expect(dispute_evidence.shipping_tracking_number).to eq(shipment.tracking_number) product_description = \ "Product name: Sample product title at purchase time\n" + "Product as seen when purchased: #{Rails.application.routes.url_helpers.purchase_product_url(purchase.external_id, host: DOMAIN, protocol: PROTOCOL)}\n" + "Product type: physical product\n" + "Product variant: Platinum\n" + "Quantity purchased: 2\n" + "Receipt: #{Rails.application.routes.url_helpers.receipt_purchase_url(purchase.external_id, email: purchase.email, host: DOMAIN, protocol: PROTOCOL)}\n" + "Live product: #{purchase.link.long_url}" expect(dispute_evidence.product_description).to eq(product_description) expect(dispute_evidence.uncategorized_text).to eq("Sample uncategorized text") expect(dispute_evidence.receipt_image).to be_attached expect(dispute_evidence.refund_policy_image).not_to be_attached expect(dispute_evidence.refund_policy_disclosure).to be_nil expect(dispute_evidence.cancellation_policy_image).not_to be_attached expect(dispute_evidence.cancellation_policy_disclosure).to be_nil expect(dispute_evidence.access_activity_log).to eq("Sample activity logs") end end context "when the purchase has a refund policy" do let(:url) do Rails.application.routes.url_helpers.purchase_product_url( disputed_purchase.external_id, host: DOMAIN, protocol: PROTOCOL, anchor: nil, ) end let(:sample_image) { File.read(Rails.root.join("spec", "support", "fixtures", "test-small.jpg")) } before do disputed_purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "This is the fine print." ) allow(DisputeEvidence::GenerateRefundPolicyImageService) .to receive(:perform).with(url:, mobile_purchase: false, open_fine_print_modal: false, max_size_allowed: anything) .and_return sample_image allow(DisputeEvidence::GenerateUncategorizedTextService).to( receive(:perform).with(disputed_purchase).and_return("Sample uncategorized text") ) allow(DisputeEvidence::GenerateReceiptImageService).to receive(:perform).with(disputed_purchase).and_return(sample_image) end it "attaches refund policy image" do dispute_evidence = DisputeEvidence.create_from_dispute!(disputed_purchase.dispute) expect(dispute_evidence.refund_policy_image).to be_attached end context "when the refund policy image is too big" do before do allow(DisputeEvidence::GenerateRefundPolicyImageService).to receive(:perform).and_raise(DisputeEvidence::GenerateRefundPolicyImageService::ImageTooLargeError) end it "doesn't attach refund policy image" do dispute_evidence = DisputeEvidence.create_from_dispute!(disputed_purchase.dispute) expect(dispute_evidence.refund_policy_image).not_to be_attached end end context "when there is a view event before the purchase" do let!(:event) do disputed_purchase.events.create!( event_name: Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW, link_id: disputed_purchase.link_id, browser_guid: disputed_purchase.browser_guid, created_at: disputed_purchase.created_at - 1.second ) end let(:url) do Rails.application.routes.url_helpers.purchase_product_url( disputed_purchase.external_id, host: DOMAIN, protocol: PROTOCOL, anchor: "refund-policy" ) end let(:open_fine_print_modal) { true } before do allow(DisputeEvidence::GenerateRefundPolicyImageService) .to receive(:perform).with(url:, mobile_purchase: false, open_fine_print_modal:, max_size_allowed: anything) .and_return sample_image end it "generates refund policy disclosure" do dispute_evidence = DisputeEvidence.create_from_dispute!(disputed_purchase.dispute) expect(dispute_evidence.refund_policy_disclosure).to eq( "The refund policy modal has been viewed by the customer 1 time before the purchase was made at #{disputed_purchase.created_at}.\n" \ "Timestamp information of the view: #{event.created_at}\n\n" \ "Internal browser GUID for reference: #{disputed_purchase.browser_guid}" ) end end end context "#find_refund_policy_fine_print_view_events" do let(:service_instance) { described_class.new(disputed_purchase.dispute) } let(:events) { service_instance.send(:find_refund_policy_fine_print_view_events, disputed_purchase) } before do allow(DisputeEvidence::GenerateUncategorizedTextService).to( receive(:perform).with(disputed_purchase).and_return("Sample uncategorized text") ) allow(DisputeEvidence::GenerateReceiptImageService).to receive(:perform).with(disputed_purchase).and_return(sample_image) end context "when there are no events" do it "returns empty array" do expect(events.count).to eq(0) end end context "when there is one eligible event" do let!(:event) do disputed_purchase.events.create!( event_name: Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW, link_id: disputed_purchase.link_id, browser_guid: disputed_purchase.browser_guid, created_at: disputed_purchase.created_at - 1.second ) end it "returns an array with the event" do expect(events).to eq([event]) end end context "when the event belongs to a different product" do let(:another_purchase) { create(:purchase) } let!(:event) do another_purchase.events.create!( event_name: Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW, link_id: another_purchase.link_id, browser_guid: another_purchase.browser_guid, created_at: another_purchase.created_at + 1.second ) end it "doesn't include the event" do expect(events.count).to eq(0) end end context "when the event has a different browser guid" do let!(:event) do disputed_purchase.events.create!( event_name: Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW, link_id: disputed_purchase.link_id, browser_guid: "other_guid", created_at: disputed_purchase.created_at - 1.second ) end it "doesn't include the event" do expect(events.count).to eq(0) end end context "when the view event is done after the purchase" do let!(:event) do disputed_purchase.events.create!( event_name: Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW, link_id: disputed_purchase.link_id, browser_guid: disputed_purchase.browser_guid, created_at: disputed_purchase.created_at + 1.second ) end it "doesn't include the event" do expect(events.count).to eq(0) end end end describe "#mobile_purchase?" do let(:service_instance) { described_class.new(disputed_purchase.dispute) } context "when purchase.is_mobile is false" do before { disputed_purchase.update!(is_mobile: false) } it "returns false" do expect(service_instance.send(:mobile_purchase?)).to eq(false) end end context "when purchase.is_mobile is empty" do before { disputed_purchase.update!(is_mobile: "") } it "returns false" do expect(service_instance.send(:mobile_purchase?)).to eq(false) end end context "when purchase.is_mobile is 1" do before { disputed_purchase.update!(is_mobile: 1) } it "returns true" do expect(service_instance.send(:mobile_purchase?)).to eq(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/services/dispute_evidence/generate_access_activity_logs_service_spec.rb
spec/services/dispute_evidence/generate_access_activity_logs_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe DisputeEvidence::GenerateAccessActivityLogsService do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) { create(:purchase, link: product) } describe ".perform" do let(:activity_logs_content) { described_class.perform(purchase) } let(:sent_at) { DateTime.parse("2024-05-07") } let(:rental_first_viewed_at) { DateTime.parse("2024-05-08") } let(:consumed_at) { DateTime.parse("2024-05-08") } before do purchase.create_url_redirect! create( :customer_email_info_opened, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, purchase: purchase, sent_at:, delivered_at: sent_at + 1.hour, opened_at: sent_at + 2.hours ) purchase.url_redirect.update!(rental_first_viewed_at:) create(:consumption_event, purchase:, consumed_at:, ip_address: "0.0.0.0") end it "returns combined rental_activity, usage_activity, and email_activity" do expect(activity_logs_content).to eq( <<~TEXT.strip_heredoc.rstrip The receipt email was sent at 2024-05-07 00:00:00 UTC, delivered at 2024-05-07 01:00:00 UTC, opened at 2024-05-07 02:00:00 UTC. The rented content was first viewed at 2024-05-08 00:00:00 UTC. The customer accessed the product 1 time. consumed_at,event_type,platform,ip_address 2024-05-08 00:00:00 UTC,watch,web,0.0.0.0 TEXT ) end end describe "#rental_activity" do let(:rental_activity) { described_class.new(purchase).send(:rental_activity) } context "without url_redirect" do it "returns nil" do expect(rental_activity).to be_nil end end context "with url_redirect" do before do purchase.create_url_redirect! end context "when rental hasn't been viewed" do it "returns nil" do expect(rental_activity).to be_nil end end context "when rental has been viewed" do let(:rental_first_viewed_at) { DateTime.parse("2024-05-07") } before do purchase.url_redirect.update!(rental_first_viewed_at:) end it "returns appropriate content" do expect(rental_activity).to eq("The rented content was first viewed at 2024-05-07 00:00:00 UTC.") end end end end describe "#usage_activity" do let(:usage_activity) { described_class.new(purchase).send(:usage_activity) } context "without consumption events" do context "without url_redirect" do it "returns nil" do expect(usage_activity).to be_nil end end context "with url_redirect" do before do purchase.create_url_redirect! end context "without usage" do it "returns nil" do expect(usage_activity).to be_nil end end context "when there is usage" do before do purchase.url_redirect.update!(uses: 2) end it "returns usage from url_redirect" do expect(usage_activity).to eq("The customer accessed the product 2 times.") end end end end context "with consumption events" do let(:consumed_at) { DateTime.parse("2024-05-07") } before do create(:consumption_event, purchase:, consumed_at:, ip_address: "0.0.0.0") end it "returns consumption events content" do expect(usage_activity).to eq( <<~TEXT.strip_heredoc.rstrip The customer accessed the product 1 time. consumed_at,event_type,platform,ip_address 2024-05-07 00:00:00 UTC,watch,web,0.0.0.0 TEXT ) end context "with multiple events" do before do create( :consumption_event, purchase:, consumed_at: (consumed_at - 15.hours), event_type: ConsumptionEvent::EVENT_TYPE_DOWNLOAD, ip_address: "0.0.0.0" ) end it "sorts events chronologically" do expect(usage_activity).to eq( <<~TEXT.strip_heredoc.rstrip The customer accessed the product 2 times. consumed_at,event_type,platform,ip_address 2024-05-06 09:00:00 UTC,download,web,0.0.0.0 2024-05-07 00:00:00 UTC,watch,web,0.0.0.0 TEXT ) end context "with more records than the limit" do before do DisputeEvidence::GenerateAccessActivityLogsService::LOG_RECORDS_LIMIT.times do |i| create( :consumption_event, purchase:, consumed_at: (consumed_at - i.hour), platform: Platform::IPHONE, ip_address: "0.0.0.0" ) end end it "limits content to the last 10 events" do expect(usage_activity).to eq( <<~TEXT.strip_heredoc.rstrip The customer accessed the product 12 times. Most recent 10 log records: consumed_at,event_type,platform,ip_address 2024-05-06 09:00:00 UTC,download,web,0.0.0.0 2024-05-06 15:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 16:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 17:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 18:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 19:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 20:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 21:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 22:00:00 UTC,watch,iphone,0.0.0.0 2024-05-06 23:00:00 UTC,watch,iphone,0.0.0.0 TEXT ) end end end end end describe "#email_activity" do let(:email_activity) { described_class.new(purchase).send(:email_activity) } context "without customer_email_infos" do it "returns nil" do expect(email_activity).to be_nil end end context "with customer_email_infos" do let(:sent_at) { DateTime.parse("2024-05-07") } context "when the email infos is associated with a purchase" do context "when the email info is not delivered" do before do create( :customer_email_info_sent, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, purchase: purchase, sent_at:, ) end it "returns appropriate content" do expect(email_activity).to eq( "The receipt email was sent at 2024-05-07 00:00:00 UTC." ) end end context "when the email info is delivered" do before do create( :customer_email_info_delivered, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, purchase: purchase, sent_at:, delivered_at: sent_at + 1.hour, ) end it "returns appropriate content" do expect(email_activity).to eq( "The receipt email was sent at 2024-05-07 00:00:00 UTC, delivered at 2024-05-07 01:00:00 UTC." ) end end context "when the email info is opened" do before do create( :customer_email_info_opened, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, purchase: purchase, sent_at:, delivered_at: sent_at + 1.hour, opened_at: sent_at + 2.hours ) end it "returns appropriate content" do expect(email_activity).to eq( "The receipt email was sent at 2024-05-07 00:00:00 UTC, delivered at 2024-05-07 01:00:00 UTC, opened at 2024-05-07 02:00:00 UTC." ) end end end context "when the email info is associated with a charge" do let(:charge) { create(:charge, purchases: [purchase], seller:) } let(:order) { charge.order } before do order.purchases << purchase create( :customer_email_info_opened, purchase_id: nil, state: :opened, sent_at:, delivered_at: sent_at + 1.hour, opened_at: sent_at + 2.hours, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, email_info_charge_attributes: { charge_id: charge.id } ) end it "returns appropriate content" do expect(email_activity).to eq( "The receipt email was sent at 2024-05-07 00:00:00 UTC, delivered at 2024-05-07 01:00:00 UTC, opened at 2024-05-07 02:00:00 UTC." ) 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/services/dispute_evidence/generate_receipt_image_service_spec.rb
spec/services/dispute_evidence/generate_receipt_image_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe DisputeEvidence::GenerateReceiptImageService, type: :system, js: true do let(:purchase) { create(:purchase) } describe ".perform" do it "generates a JPG receipt image" do expect_any_instance_of(Selenium::WebDriver::Driver).to receive(:quit) binary_data = described_class.perform(purchase) expect(binary_data).to start_with("\xFF\xD8".b) expect(binary_data).to end_with("\xFF\xD9".b) end end describe "#generate_html" do before do mailer_double = double( body: double(raw_source: "<html><body><p>receipt</p></body></html>"), from: ["support@example.com"], to: ["customer@example.com"], subject: "You bought #{purchase.link.name}" ) expect(CustomerMailer).to receive(:receipt).with(purchase.id).and_return(mailer_double) end it "generates the HTML for the receipt" do expected_html = <<~HTML <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body> <div style="padding: 20px 20px"> <p><strong>Email receipt sent at:</strong> #{purchase.created_at}</p> <p><strong>From:</strong> support@example.com</p> <p><strong>To:</strong> customer@example.com</p> <p><strong>Subject:</strong> You bought #{purchase.link.name}</p> </div> <hr> <p>receipt</p> </body></html> HTML html = described_class.new(purchase).send(:generate_html, purchase) expect(html).to eq(expected_html) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/dispute_evidence/generate_refund_policy_image_service_spec.rb
spec/services/dispute_evidence/generate_refund_policy_image_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe DisputeEvidence::GenerateRefundPolicyImageService, type: :system, js: true do let(:purchase) { create(:purchase) } let(:url) do Rails.application.routes.url_helpers.purchase_product_url( purchase.external_id, host: DOMAIN, protocol: PROTOCOL, anchor: nil, ) end before do visit receipt_purchase_path(purchase.external_id, email: purchase.email) # Needed to boot the server end describe ".perform" do it "generates a JPG image" do expect_any_instance_of(Selenium::WebDriver::Driver).to receive(:quit) binary_data = described_class.perform(url:, mobile_purchase: false, open_fine_print_modal: false, max_size_allowed: 3_000_000.bytes) expect(binary_data).to start_with("\xFF\xD8".b) expect(binary_data).to end_with("\xFF\xD9".b) end context "when the image is too large" do it "raises an error" do expect_any_instance_of(Selenium::WebDriver::Driver).to receive(:quit) expect do described_class.perform(url:, mobile_purchase: false, open_fine_print_modal: false, max_size_allowed: 1_000.bytes) end.to raise_error(DisputeEvidence::GenerateRefundPolicyImageService::ImageTooLargeError) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/pdf_stamping_service/stamp_for_purchase_spec.rb
spec/services/pdf_stamping_service/stamp_for_purchase_spec.rb
# frozen_string_literal: true require "spec_helper" describe PdfStampingService::StampForPurchase do describe ".perform!" do let(:product) { create(:product) } let(:purchase) { create(:purchase, link: product) } before do purchase.create_url_redirect! end context "with stampable PDFs" do let!(:product_file_one) { create(:readable_document, pdf_stamp_enabled: true) } before do product.product_files << product_file_one end it "creates stamp_pdf and updates url_redirect" do url_redirect = purchase.url_redirect expect do expect(described_class.perform!(purchase)).to be(true) end.to change { url_redirect.reload.stamped_pdfs.count }.by(1) stamped_pdf = url_redirect.stamped_pdfs.first expect(stamped_pdf.product_file).to eq(product_file_one) expect(stamped_pdf.url).to match(/#{AWS_S3_ENDPOINT}/o) expect(url_redirect.reload.is_done_pdf_stamping?).to eq(true) end context "with encrypted stampable PDFs" do let!(:product_file_two) { create(:readable_document, pdf_stamp_enabled: true, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/encrypted_pdf.pdf") } let!(:product_file_three) { create(:readable_document, pdf_stamp_enabled: true) } let!(:product_file_four) { create(:readable_document, pdf_stamp_enabled: false, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/encrypted_pdf.pdf") } before do product.product_files << product_file_one product.product_files << product_file_two product.product_files << product_file_three product.product_files << product_file_four end it "stamps all files and raises" do url_redirect = purchase.url_redirect error_message = \ "Failed to stamp 1 file(s) for purchase #{purchase.id} - " \ "File #{product_file_two.id}: PdfStampingService::Stamp::Error: Error generating stamped PDF: PDF is encrypted." expect do expect do expect(described_class.perform!(purchase)).to be(true) end.to change { url_redirect.reload.stamped_pdfs.count }.by(2) end.to raise_error(PdfStampingService::Error).with_message(error_message) expect_stamped_pdf(url_redirect.stamped_pdfs.first, product_file_one) expect_stamped_pdf(url_redirect.stamped_pdfs.second, product_file_three) expect(url_redirect.reload.is_done_pdf_stamping?).to eq(false) end def expect_stamped_pdf(stamped_pdf, product_file) expect(stamped_pdf.product_file).to eq(product_file) expect(stamped_pdf.url).to match(/#{AWS_S3_ENDPOINT}/o) end end end context "when the product doesn't have stampable PDFs" do it "does nothing" do expect(described_class.perform!(purchase)).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/services/pdf_stamping_service/stamp_spec.rb
spec/services/pdf_stamping_service/stamp_spec.rb
# frozen_string_literal: true require "spec_helper" describe PdfStampingService::Stamp do describe ".can_stamp_file?" do context "with readable PDF" do let(:pdf) { create(:readable_document, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/billion-dollar-company-chapter-0.pdf") } it "returns true" do result = described_class.can_stamp_file?(product_file: pdf) expect(result).to eq(true) end end context "with encrypted PDF" do let(:pdf) { create(:readable_document, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/encrypted_pdf.pdf") } it "logs and returns false" do expect(Rails.logger).to receive(:error).with( /\[PdfStampingService::Stamp.apply_watermark!\] Failed to execute command: pdftk/ ) expect(Rails.logger).to receive(:error).with(/\[PdfStampingService::Stamp.apply_watermark!\] STDOUT: /) expect(Rails.logger).to receive(:error).with(/\[PdfStampingService::Stamp.apply_watermark!\] STDERR: /) result = described_class.can_stamp_file?(product_file: pdf) expect(result).to eq(false) end end end describe ".perform!" do let(:pdf_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/billion-dollar-company-chapter-0.pdf" } let(:product_file) { create(:readable_document, url: pdf_url) } let(:watermark_text) { "customer@example.com" } let(:created_file_paths) { [] } before do allow(described_class).to receive(:perform!).and_wrap_original do |method, **args| created_file_paths << method.call(**args) end end after(:each) do created_file_paths.each { FileUtils.rm_f(_1) } created_file_paths.clear end it "stamps the PDF without errors" do expect(Rails.logger).not_to receive(:error) expect do described_class.perform!(product_file:, watermark_text:) end.not_to raise_error end context "when applying the watermark fails" do context "when the PDF is encrypted" do let(:pdf_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/encrypted_pdf.pdf" } it "logs and raises PdfStampingService::Stamp::Error" do expect(Rails.logger).to receive(:error).with( /\[PdfStampingService::Stamp.apply_watermark!\] Failed to execute command: pdftk/ ) expect(Rails.logger).to receive(:error).with(/\[PdfStampingService::Stamp.apply_watermark!\] STDOUT: /) expect(Rails.logger).to receive(:error).with(/\[PdfStampingService::Stamp.apply_watermark!\] STDERR: /) expect do described_class.perform!(product_file:, watermark_text:) end.to raise_error(PdfStampingService::Stamp::Error).with_message("Error generating stamped PDF: PDF is encrypted.") end end context "when pdftk command fails" do before do allow(Open3).to receive(:capture3).and_return( ["stdout message", "stderr line1\nstderr line2", OpenStruct.new(success?: false)] ) allow(Rails.logger).to receive(:error) end it "logs and raises PdfStampingService::Stamp::Error" do expect(Rails.logger).to receive(:error).with( /\[PdfStampingService::Stamp.apply_watermark!\] Failed to execute command: pdftk/ ) expect(Rails.logger).to receive(:error).with( "[PdfStampingService::Stamp.apply_watermark!] STDOUT: stdout message" ) expect(Rails.logger).to receive(:error).with( "[PdfStampingService::Stamp.apply_watermark!] STDERR: stderr line1\nstderr line2" ) expect do described_class.perform!(product_file:, watermark_text: "customer@example.com") end.to raise_error(PdfStampingService::Stamp::Error).with_message("Error generating stamped PDF: stderr line1") 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/services/admin/unreviewed_users_service_spec.rb
spec/services/admin/unreviewed_users_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::UnreviewedUsersService do describe "#count" do it "returns the total count of unreviewed users with unpaid balance" do 2.times do user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user:, amount_cents: 5000) end expect(described_class.new.count).to eq(2) end it "excludes users with balance <= $10" do user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user:, amount_cents: 500) expect(described_class.new.count).to eq(0) end end describe "#users_with_unpaid_balance" do it "returns users ordered by total balance descending" do low_balance_user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user: low_balance_user, amount_cents: 2000) high_balance_user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user: high_balance_user, amount_cents: 10000) users = described_class.new.users_with_unpaid_balance expect(users.first.id).to eq(high_balance_user.id) expect(users.last.id).to eq(low_balance_user.id) end it "includes total_balance_cents attribute" do user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user:, amount_cents: 5000) result = described_class.new.users_with_unpaid_balance.first expect(result.total_balance_cents).to eq(5000) end it "excludes users with balance <= $10" do user_with_low_balance = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user: user_with_low_balance, amount_cents: 500) expect(described_class.new.users_with_unpaid_balance).to be_empty end it "excludes compliant users" do compliant_user = create(:user, user_risk_state: "compliant", created_at: 1.year.ago) create(:balance, user: compliant_user, amount_cents: 5000) expect(described_class.new.users_with_unpaid_balance).to be_empty end it "excludes users created before cutoff date" do old_user = create(:user, user_risk_state: "not_reviewed", created_at: 3.years.ago) create(:balance, user: old_user, amount_cents: 5000) expect(described_class.new.users_with_unpaid_balance).to be_empty end it "includes old users when cutoff_date is set in Redis" do old_user = create(:user, user_risk_state: "not_reviewed", created_at: Date.new(2023, 6, 1)) create(:balance, user: old_user, amount_cents: 5000) $redis.set(RedisKey.unreviewed_users_cutoff_date, "2023-01-01") users = described_class.new.users_with_unpaid_balance expect(users.map(&:id)).to include(old_user.id) end it "respects the limit parameter" do 3.times do user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user:, amount_cents: 5000) end users = described_class.new.users_with_unpaid_balance(limit: 2) expect(users.to_a.size).to eq(2) end end describe ".cached_users_data" do it "returns nil when no cached data exists" do $redis.del(RedisKey.unreviewed_users_data) expect(described_class.cached_users_data).to be_nil end it "returns parsed data from Redis" do cache_payload = { users: [{ id: 1, email: "test@example.com" }], total_count: 1, cutoff_date: "2023-01-01", cached_at: "2024-01-01T00:00:00Z" } $redis.set(RedisKey.unreviewed_users_data, cache_payload.to_json) result = described_class.cached_users_data expect(result[:users].first[:email]).to eq("test@example.com") expect(result[:total_count]).to eq(1) end end describe ".cache_users_data!" do it "caches user data in Redis" do user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user:, amount_cents: 5000) result = described_class.cache_users_data! expect(result[:users].size).to eq(1) expect(result[:users].first[:id]).to eq(user.id) expect(result[:total_count]).to eq(1) expect(result[:cutoff_date]).to eq("2024-01-01") expect(result[:cached_at]).to be_present end it "stores data in Redis" do user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user:, amount_cents: 5000) described_class.cache_users_data! cached = described_class.cached_users_data expect(cached[:users].first[:id]).to eq(user.id) end it "limits cached users to MAX_CACHED_USERS but total_count reflects true total" do stub_const("Admin::UnreviewedUsersService::MAX_CACHED_USERS", 2) 3.times do |i| user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) create(:balance, user:, amount_cents: 5000 + (i * 1000)) end result = described_class.cache_users_data! expect(result[:users].size).to eq(2) expect(result[:total_count]).to eq(3) end end describe ".cutoff_date" do it "defaults to 2024-01-01 when not set in Redis" do $redis.del(RedisKey.unreviewed_users_cutoff_date) expect(described_class.cutoff_date).to eq(Date.new(2024, 1, 1)) end it "reads from Redis when set" do $redis.set(RedisKey.unreviewed_users_cutoff_date, "2023-06-15") expect(described_class.cutoff_date).to eq(Date.new(2023, 6, 15)) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/creator_analytics/product_page_views_spec.rb
spec/services/creator_analytics/product_page_views_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::ProductPageViews do let(:user_timezone) { "UTC" } before do @user = create(:user, timezone: user_timezone) @products = create_list(:product, 2, user: @user) @service = described_class.new( user: @user, products: @products, dates: (Date.new(2021, 1, 1) .. Date.new(2021, 1, 3)).to_a ) end describe "#by_product_and_date" do before do add_page_view(@products[0], Time.utc(2021, 1, 1)) add_page_view(@products[0], Time.utc(2021, 1, 1, 1)) add_page_view(@products[1], Time.utc(2021, 1, 1, 2)) add_page_view(@products[0], Time.utc(2021, 1, 3, 23, 30)) add_page_view(@products[0], Time.utc(2021, 1, 4)) ProductPageView.__elasticsearch__.refresh_index! end it "returns expected data" do result = @service.by_product_and_date expected_result = { [@products[0].id, "2021-01-01"] => 2, [@products[0].id, "2021-01-03"] => 1, [@products[1].id, "2021-01-01"] => 1, } expect(result).to eq(expected_result) end context "when user time zone is Pacific Time" do let(:user_timezone) { "Pacific Time (US & Canada)" } it "returns expected data" do result = @service.by_product_and_date expected_result = { [@products[0].id, "2021-01-03"] => 2, } expect(result).to eq(expected_result) end end context "when user time zone is Central European Time" do let(:user_timezone) { "Paris" } it "returns expected data" do result = @service.by_product_and_date expected_result = { [@products[0].id, "2021-01-01"] => 2, [@products[1].id, "2021-01-01"] => 1, } expect(result).to eq(expected_result) end end end describe "#by_product_and_country_and_state" do before do add_page_view(@products[0], Time.utc(2021, 1, 1), country: "United States", state: "CA") add_page_view(@products[0], Time.utc(2021, 1, 1, 1), country: "Japan", state: nil) add_page_view(@products[1], Time.utc(2021, 1, 1, 2), country: "United States", state: "NY") add_page_view(@products[0], Time.utc(2021, 1, 3), country: "United States", state: "CA") add_page_view(@products[0], Time.utc(2021, 1, 4), country: "United States", state: "WA") ProductPageView.__elasticsearch__.refresh_index! end let(:expected_result) do { [@products[0].id, "United States", "CA"] => 2, [@products[0].id, "Japan", nil] => 1, [@products[1].id, "United States", "NY"] => 1 } end it "returns expected data with one query" do expect(ProductPageView).to receive(:search).once.and_call_original result = @service.by_product_and_country_and_state expect(result).to eq(expected_result) end it "returns expected data when paginating" do stub_const("#{described_class}::ES_MAX_BUCKET_SIZE", 2) expect(ProductPageView).to receive(:search).exactly(2).times.and_call_original result = @service.by_product_and_country_and_state expect(result).to eq(expected_result) end end describe "#by_product_and_referrer_and_date" do before do add_page_view(@products[0], Time.utc(2021, 1, 1), referrer_domain: "google.com") add_page_view(@products[0], Time.utc(2021, 1, 1), referrer_domain: "direct") add_page_view(@products[1], Time.utc(2021, 1, 3), referrer_domain: "google.com") add_page_view(@products[0], Time.utc(2021, 1, 3), referrer_domain: "direct") add_page_view(@products[0], Time.utc(2021, 1, 3), referrer_domain: "direct") add_page_view(@products[0], Time.utc(2021, 1, 3, 23, 30), referrer_domain: "t.co") add_page_view(@products[0], Time.utc(2021, 1, 4), referrer_domain: "medium.com") ProductPageView.__elasticsearch__.refresh_index! end let(:expected_result) do { [@products[0].id, "google.com", "2021-01-01"] => 1, [@products[0].id, "direct", "2021-01-01"] => 1, [@products[1].id, "google.com", "2021-01-03"] => 1, [@products[0].id, "direct", "2021-01-03"] => 2, [@products[0].id, "t.co", "2021-01-03"] => 1, } end it "returns expected data with one query" do expect(ProductPageView).to receive(:search).once.and_call_original result = @service.by_product_and_referrer_and_date expect(result).to eq(expected_result) end it "returns expected data when paginating" do stub_const("#{described_class}::ES_MAX_BUCKET_SIZE", 4) expect(ProductPageView).to receive(:search).exactly(2).times.and_call_original result = @service.by_product_and_referrer_and_date expect(result).to eq(expected_result) end context "when user time zone is Pacific Time" do let(:user_timezone) { "Pacific Time (US & Canada)" } it "returns expected data" do result = @service.by_product_and_referrer_and_date expected_result = { [@products[0].id, "direct", "2021-01-02"] => 2, [@products[0].id, "medium.com", "2021-01-03"] => 1, [@products[0].id, "t.co", "2021-01-03"] => 1, [@products[1].id, "google.com", "2021-01-02"] => 1, } expect(result).to eq(expected_result) end end context "when user time zone is Central European Time" do let(:user_timezone) { "Paris" } it "returns expected data" do result = @service.by_product_and_referrer_and_date expected_result = { [@products[0].id, "google.com", "2021-01-01"] => 1, [@products[0].id, "direct", "2021-01-01"] => 1, [@products[1].id, "google.com", "2021-01-03"] => 1, [@products[0].id, "direct", "2021-01-03"] => 2, } expect(result).to eq(expected_result) end end end describe "DST handling" do context "when page view occurs near midnight during DST" do let(:user_timezone) { "Pacific Time (US & Canada)" } it "correctly attributes page view to the right day" do user = create(:user, timezone: user_timezone) product = create(:product, user: user) # Page view at July 15, 00:30 PDT = July 15, 07:30 UTC add_page_view(product, Time.utc(2025, 7, 15, 7, 30)) ProductPageView.__elasticsearch__.refresh_index! service = described_class.new( user: user, products: [product], dates: [Date.new(2025, 7, 14), Date.new(2025, 7, 15)] ) result = service.by_product_and_date expect(result[[product.id, "2025-07-15"]]).to eq(1) expect(result[[product.id, "2025-07-14"]]).to be_nil end end context "when query spans DST transition" do let(:user_timezone) { "Pacific Time (US & Canada)" } it "correctly buckets page views across DST boundary" do user = create(:user, timezone: user_timezone) product = create(:product, user: user) # Page view on March 8 at 11:00 PM PST = March 9, 07:00 UTC (before DST starts) add_page_view(product, Time.utc(2025, 3, 9, 7, 0)) # Page view on March 10 at 01:00 AM PDT = March 10, 08:00 UTC (after DST starts) add_page_view(product, Time.utc(2025, 3, 10, 8, 0)) ProductPageView.__elasticsearch__.refresh_index! service = described_class.new( user: user, products: [product], dates: (Date.new(2025, 3, 8)..Date.new(2025, 3, 10)).to_a ) result = service.by_product_and_date expect(result[[product.id, "2025-03-08"]]).to eq(1) expect(result[[product.id, "2025-03-10"]]).to eq(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/services/creator_analytics/sales_spec.rb
spec/services/creator_analytics/sales_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::Sales do let(:user_timezone) { "UTC" } before do @user = create(:user, timezone: user_timezone) @products = create_list(:product, 2, user: @user) @service = described_class.new( user: @user, products: @products, dates: (Date.new(2021, 1, 1) .. Date.new(2021, 1, 3)).to_a ) create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 1), ip_country: "United States", ip_state: "CA", referrer: "https://google.com") create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 1, 1), ip_country: "Japan", referrer: "https://google.com") create(:purchase, link: @products[1], created_at: Time.utc(2021, 1, 1, 2)) create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), ip_country: "United States", ip_state: "NY", referrer: "https://t.co") create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3, 23, 30), is_gift_sender_purchase: true, ip_country: "United States", ip_state: "NY") preorder = create(:preorder) purchase = create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), purchase_state: "preorder_concluded_successfully", ip_country: "France") purchase.update!(preorder:) create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), preorder:, ip_country: "France", referrer: "https://t.co") purchase = create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), is_gift_sender_purchase: true, ip_country: "France") purchase.refund_partial_purchase!(1, purchase.seller) purchase.refund_partial_purchase!(2, purchase.seller) create(:refund, purchase: create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), stripe_refunded: true)) create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), chargeback_date: Time.current, chargeback_reversed: true) # invalid states create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), is_gift_receiver_purchase: true, purchase_state: "gift_receiver_purchase_successful") create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), purchase_state: "failed") create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), chargeback_date: Time.current) # outside of date range create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 4)) index_model_records(Purchase) end describe "#by_product_and_date" do let(:expected_result) do { [@products[0].id, "2021-01-01"] => { count: 2, total: 200 }, [@products[0].id, "2021-01-03"] => { count: 7, total: 497 }, [@products[1].id, "2021-01-01"] => { count: 1, total: 100 }, } end it "returns expected data" do expect(Purchase).to receive(:search).once.and_call_original result = @service.by_product_and_date expect(result).to eq(expected_result) end it "returns expected data when paginating" do stub_const("#{described_class}::ES_MAX_BUCKET_SIZE", 2) expect(Purchase).to receive(:search).exactly(2).times.and_call_original result = @service.by_product_and_date expect(result).to eq(expected_result) end context "when user time zone is Pacific Time" do let(:user_timezone) { "Pacific Time (US & Canada)" } it "returns expected data" do result = @service.by_product_and_date expected_result = { [@products[0].id, "2021-01-02"] => { count: 6, total: 397 }, [@products[0].id, "2021-01-03"] => { count: 2, total: 200 }, } expect(result).to eq(expected_result) end end context "when user time zone is Central European Time" do let(:user_timezone) { "Paris" } it "returns expected data" do result = @service.by_product_and_date expected_result = { [@products[0].id, "2021-01-01"] => { count: 2, total: 200 }, [@products[0].id, "2021-01-03"] => { count: 3, total: 297 }, [@products[0].id, "2021-01-03"] => { count: 6, total: 397 }, [@products[1].id, "2021-01-01"] => { count: 1, total: 100 }, } expect(result).to eq(expected_result) end end end describe "#by_product_and_country_and_state" do let(:expected_result) do { [@products[0].id, "France", nil] => { count: 2, total: 197 }, [@products[0].id, "Japan", nil] => { count: 1, total: 100 }, [@products[0].id, "United States", "CA"] => { count: 1, total: 100 }, [@products[0].id, "United States", "NY"] => { count: 2, total: 200 }, [@products[0].id, nil, nil] => { count: 3, total: 100 }, [@products[1].id, nil, nil] => { count: 1, total: 100 }, } end it "returns expected data with one query" do expect(Purchase).to receive(:search).once.and_call_original result = @service.by_product_and_country_and_state expect(result).to eq(expected_result) end it "returns expected data when paginating" do stub_const("#{described_class}::ES_MAX_BUCKET_SIZE", 2) expect(Purchase).to receive(:search).exactly(4).times.and_call_original result = @service.by_product_and_country_and_state expect(result).to eq(expected_result) end end describe "#by_product_and_referrer_and_date" do let(:expected_result) do { [@products[0].id, "direct", "2021-01-03"] => { count: 6, total: 397 }, [@products[0].id, "google.com", "2021-01-01"] => { count: 2, total: 200 }, [@products[0].id, "t.co", "2021-01-03"] => { count: 1, total: 100 }, [@products[1].id, "direct", "2021-01-01"] => { count: 1, total: 100 }, } end it "returns expected data with one query" do expect(Purchase).to receive(:search).once.and_call_original result = @service.by_product_and_referrer_and_date expect(result).to eq(expected_result) end it "returns expected data when paginating" do stub_const("#{described_class}::ES_MAX_BUCKET_SIZE", 2) expect(Purchase).to receive(:search).exactly(3).times.and_call_original result = @service.by_product_and_referrer_and_date expect(result).to eq(expected_result) end context "when user time zone is Pacific Time" do let(:user_timezone) { "Pacific Time (US & Canada)" } it "returns expected data" do result = @service.by_product_and_referrer_and_date expected_result = { [@products[0].id, "direct", "2021-01-02"] => { count: 5, total: 297 }, [@products[0].id, "direct", "2021-01-03"] => { count: 2, total: 200 }, [@products[0].id, "t.co", "2021-01-02"] => { count: 1, total: 100 }, } expect(result).to eq(expected_result) end end context "when user time zone is Central European Time" do let(:user_timezone) { "Paris" } it "returns expected data" do result = @service.by_product_and_referrer_and_date expected_result = { [@products[0].id, "direct", "2021-01-03"] => { count: 5, total: 297 }, [@products[0].id, "google.com", "2021-01-01"] => { count: 2, total: 200 }, [@products[0].id, "t.co", "2021-01-03"] => { count: 1, total: 100 }, [@products[1].id, "direct", "2021-01-01"] => { count: 1, total: 100 }, } expect(result).to eq(expected_result) end end end end describe CreatorAnalytics::Sales, "DST handling" do context "when sale occurs near midnight during DST" do it "correctly attributes sale to the right day" do user = create(:user, timezone: "Pacific Time (US & Canada)") product = create(:product, user: user) # July 15, 00:30 PDT = July 15, 07:30 UTC create(:free_purchase, link: product, created_at: Time.utc(2025, 7, 15, 7, 30)) index_model_records(Purchase) service = described_class.new( user: user, products: [product], dates: [Date.new(2025, 7, 14), Date.new(2025, 7, 15)] ) result = service.by_product_and_date expect(result[[product.id, "2025-07-15"]]).to be_present expect(result[[product.id, "2025-07-14"]]).to be_nil end end context "when query spans DST transition" do it "correctly buckets sales across DST boundary" do user = create(:user, timezone: "Pacific Time (US & Canada)") product = create(:product, user: user) # March 8, 11:00 PM PST = March 9, 07:00 UTC create(:free_purchase, link: product, created_at: Time.utc(2025, 3, 9, 7, 0)) # March 10, 01:00 AM PDT = March 10, 08:00 UTC create(:free_purchase, link: product, created_at: Time.utc(2025, 3, 10, 8, 0)) index_model_records(Purchase) service = described_class.new( user: user, products: [product], dates: (Date.new(2025, 3, 8)..Date.new(2025, 3, 10)).to_a ) result = service.by_product_and_date expect(result[[product.id, "2025-03-08"]]).to be_present expect(result[[product.id, "2025-03-10"]]).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/services/creator_analytics/web_spec.rb
spec/services/creator_analytics/web_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::Web do before do @user = create(:user, timezone: "UTC") @products = create_list(:product, 2, user: @user) @service = described_class.new( user: @user, dates: (Date.new(2021, 1, 1) .. Date.new(2021, 1, 3)).to_a ) add_page_view(@products[0], Time.utc(2021, 1, 1)) add_page_view(@products[0], Time.utc(2021, 1, 3), country: "France") add_page_view(@products[0], Time.utc(2021, 1, 3), referrer_domain: "google.com", country: "France", state: "75") add_page_view(@products[0], Time.utc(2021, 1, 3), referrer_domain: "google.com", country: "United States", state: "NY") add_page_view(@products[1], Time.utc(2021, 1, 3), referrer_domain: "google.com", country: "United States", state: "NY") ProductPageView.__elasticsearch__.refresh_index! create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 1)) create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), ip_country: "France") create(:purchase, link: @products[0], created_at: Time.utc(2021, 1, 3), ip_country: "United States", ip_state: "NY", referrer: "https://google.com") create(:purchase, link: @products[1], created_at: Time.utc(2021, 1, 3), ip_country: "United States", ip_state: "NY", referrer: "https://google.com") index_model_records(Purchase) end describe "#by_date" do it "returns expected data" do expected_result = { dates_and_months: [ { date: "Friday, January 1st", month: "January 2021", month_index: 0 }, { date: "Saturday, January 2nd", month: "January 2021", month_index: 0 }, { date: "Sunday, January 3rd", month: "January 2021", month_index: 0 } ], start_date: "Jan 1, 2021", end_date: "Jan 3, 2021", first_sale_date: "Jan 1, 2021", by_date: { views: { @products[0].unique_permalink => [1, 0, 3], @products[1].unique_permalink => [0, 0, 1] }, sales: { @products[0].unique_permalink => [1, 0, 2], @products[1].unique_permalink => [0, 0, 1] }, totals: { @products[0].unique_permalink => [100, 0, 200], @products[1].unique_permalink => [0, 0, 100] } } } expect(@service.by_date).to eq(expected_result) end end describe "#by_state" do it "returns expected data" do expected_result = { by_state: { views: { @products[0].unique_permalink => { "United States" => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], nil => 1, "France" => 2 }, @products[1].unique_permalink => { "United States" => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } }, sales: { @products[0].unique_permalink => { "United States" => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], nil => 1, "France" => 1 }, @products[1].unique_permalink => { "United States" => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } }, totals: { @products[0].unique_permalink => { "United States" => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], nil => 100, "France" => 100 }, @products[1].unique_permalink => { "United States" => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } } } } expect(@service.by_state).to eq(expected_result) end end describe "#by_referral" do it "returns expected data" do expected_result = { dates_and_months: [ { date: "Friday, January 1st", month: "January 2021", month_index: 0 }, { date: "Saturday, January 2nd", month: "January 2021", month_index: 0 }, { date: "Sunday, January 3rd", month: "January 2021", month_index: 0 } ], start_date: "Jan 1, 2021", end_date: "Jan 3, 2021", first_sale_date: "Jan 1, 2021", by_referral: { views: { @products[0].unique_permalink => { "Google" => [0, 0, 2], "direct" => [1, 0, 1] }, @products[1].unique_permalink => { "Google" => [0, 0, 1] } }, sales: { @products[0].unique_permalink => { "Google" => [0, 0, 1], "direct" => [1, 0, 1] }, @products[1].unique_permalink => { "Google" => [0, 0, 1] } }, totals: { @products[0].unique_permalink => { "Google" => [0, 0, 100], "direct" => [100, 0, 100] }, @products[1].unique_permalink => { "Google" => [0, 0, 100] } } } } expect(@service.by_referral).to eq(expected_result) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/creator_analytics/caching_proxy_spec.rb
spec/services/creator_analytics/caching_proxy_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::CachingProxy do describe "#data_for_dates" do before do @user = create(:user, timezone: "London", created_at: Time.utc(2019, 1, 1)) travel_to Time.utc(2020, 1, 1) @product = create(:product, user: @user) @dates = (Date.new(2019, 1, 30) .. Date.new(2019, 2, 5)).to_a @service = described_class.new(@user) recreate_model_index(ProductPageView) recreate_model_index(Purchase) end def web_data(by, start_date, end_date) CreatorAnalytics::Web.new(user: @user, dates: (start_date .. end_date).to_a).public_send("by_#{by}") end it "returns merged mix of cached and generated data" do allow(@service).to receive(:use_cache?).and_return(true) [:date, :state, :referral].each do |by| # create data for some days, not others @dates.values_at(0, 3, 6).each do |date| create(:computed_sales_analytics_day, key: @service.send(:cache_key_for_data, date, by:), data: web_data(by, date, date).to_json ) end # check that the two missing date ranges are generated dynamically expect(@service).to receive(:analytics_data).with(@dates[1], @dates[2], by:).and_call_original expect(@service).to receive(:analytics_data).with(@dates[4], @dates[5], by:).and_call_original if by == :date expect(@service).to receive(:rebuild_month_index_values!).and_call_original end expect(@service).to receive("merge_data_by_#{by}").and_call_original result = @service.data_for_dates(@dates.first, @dates.last, by:) original_method_result = web_data(by, @dates.first, @dates.last) expect(result).to equal_with_indifferent_access(original_method_result) end end it "can generate grouped data, by day and month" do @user.update!(timezone: "UTC") # timezones considerations are not relevant here dates = @dates[0 .. 2] # we only need 3 days, crossing 2 months, to test this products = [@product, create(:product, user: @user)] permalinks = products.map(&:unique_permalink) dates.each do |date| create(:purchase, link: products.first, created_at: date) add_page_view(products.first, date) end ProductPageView.__elasticsearch__.refresh_index! index_model_records(Purchase) expect(@service.data_for_dates(dates.first, dates.last, by: :date, options: { group_by: :day })).to eq( dates: ["Wednesday, January 30th 2019", "Thursday, January 31st 2019", "Friday, February 1st 2019"], by_date: { views: { permalinks[0] => [1, 1, 1], permalinks[1] => [0, 0, 0] }, sales: { permalinks[0] => [1, 1, 1], permalinks[1] => [0, 0, 0] }, totals: { permalinks[0] => [100, 100, 100], permalinks[1] => [0, 0, 0] } } ) expect(@service.data_for_dates(dates.first, dates.last, by: :date, options: { group_by: :month })).to eq( dates: ["January 2019", "February 2019"], by_date: { views: { permalinks[0] => [2, 1], permalinks[1] => [0, 0] }, sales: { permalinks[0] => [2, 1], permalinks[1] => [0, 0] }, totals: { permalinks[0] => [200, 100], permalinks[1] => [0, 0] } } ) expect(@service.data_for_dates(dates.first, dates.last, by: :referral, options: { group_by: :day })).to eq( dates: ["Wednesday, January 30th 2019", "Thursday, January 31st 2019", "Friday, February 1st 2019"], by_referral: { views: { permalinks[0] => { "direct" => [1, 1, 1] } }, sales: { permalinks[0] => { "direct" => [1, 1, 1] } }, totals: { permalinks[0] => { "direct" => [100, 100, 100] } } } ) expect(@service.data_for_dates(dates.first, dates.last, by: :referral, options: { group_by: :month })).to eq( dates: ["January 2019", "February 2019"], by_referral: { views: { permalinks[0] => { "direct" => [2, 1] } }, sales: { permalinks[0] => { "direct" => [2, 1] } }, totals: { permalinks[0] => { "direct" => [200, 100] } } } ) end it "calls original method if cache shouldn't be used" do allow(@service).to receive(:use_cache?).and_return(false) expect(@service).not_to receive(:fetch_data_for_dates) expect(@service).to receive(:analytics_data).with(@dates.first, @dates.last, by: :date).and_call_original @service.data_for_dates(@dates.first, @dates.last, by: :date) end end describe "#generate_cache" do it "generates the cached data for all non-existent days of activity of users" do product = create(:product) service = described_class.new(product.user) # 10pm@UTC is always day+1@Tokyo: # Setting this shows that we're not generating cache for the 1st of August, but for the 2nd, # which is the first day of sales in the seller's time zone. product.user.update!(timezone: "Tokyo") create(:purchase, link: product, created_at: Time.utc(2020, 8, 1, 22)) create(:purchase, link: product, created_at: Time.utc(2020, 8, 3)) # 10pm@UTC is always day+1@Tokyo: # This results in "Today" in Tokyo being the 7th of August. travel_to Time.utc(2020, 8, 6, 22) # Generate a day in the cache, will show that we're not generating cache for existing cache day create(:computed_sales_analytics_day, key: service.send(:cache_key_for_data, Date.new(2020, 8, 4), by: :date), data: "{}") create(:computed_sales_analytics_day, key: service.send(:cache_key_for_data, Date.new(2020, 8, 3), by: :state), data: "{}") create(:computed_sales_analytics_day, key: service.send(:cache_key_for_data, Date.new(2020, 8, 5), by: :referral), data: "{}") # by date expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 2), by: :date) expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 3), by: :date) # The 4th of August for date isn't generated because it already exists expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 5), by: :date) # by state expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 2), by: :state) # The 3rd of August for state isn't generated because it already exists expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 4), by: :state) expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 5), by: :state) # by referral expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 2), by: :referral) expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 3), by: :referral) expect(service).to receive(:fetch_data).with(Date.new(2020, 8, 4), by: :referral) # The 5th of August for referral isn't generated because it already exists service.generate_cache end it "handles users with no sales" do user = create(:user) expect { described_class.new(user).generate_cache }.not_to raise_error end it "skips suspended users" do user = create(:tos_user) create(:purchase, link: create(:product, user:)) expect(user).not_to receive(:sales) described_class.new(user).generate_cache end end describe "#overwrite_cache" do before do travel_to Time.utc(2020, 1, 1) @user = create(:user, timezone: "London") @service = described_class.new(@user) end it "does not update data for yesterday, today, or any day after" do allow(@service).to receive(:use_cache?).and_return(true) expect(ComputedSalesAnalyticsDay).not_to receive(:upsert_data_from_key) @service.overwrite_cache(Date.yesterday) @service.overwrite_cache(Date.today) @service.overwrite_cache(Date.tomorrow) @service.overwrite_cache(Date.tomorrow + 1) end it "does not update data for days before analytics were generated" do allow(@service).to receive(:use_cache?).and_return(true) expect(ComputedSalesAnalyticsDay).not_to receive(:upsert_data_from_key) @service.overwrite_cache(Date.new(2012, 9, 1)) end it "does not update data when cache should not be used" do allow(@service).to receive(:use_cache?).and_return(false) expect(ComputedSalesAnalyticsDay).not_to receive(:upsert_data_from_key) @service.overwrite_cache(Date.yesterday) end it "regenerates and stores analytics for the date" do allow(@service).to receive(:use_cache?).and_return(true) date = 2.days.ago.to_date # generate data @service.send(:fetch_data, date) expect(@service.send(:fetch_data, date)).to equal_with_indifferent_access(@service.send(:analytics_data, date, date)) # add a page view add_page_view(create(:product, user: @user), date) ProductPageView.__elasticsearch__.refresh_index! # check that the stored data is indeed different than freshly generated data expect(@service.send(:fetch_data, date)).not_to equal_with_indifferent_access(@service.send(:analytics_data, date, date)) # overwrite cached data @service.overwrite_cache(date) # check that the stored data is now the same than freshly generated data expect(@service.send(:fetch_data, date)).to equal_with_indifferent_access(@service.send(:analytics_data, date, date)) end end describe "#use_cache?" do it "returns true if user is a large seller" do user = create(:user) service = described_class.new(user) expect(service.send(:use_cache?)).to eq(false) create(:large_seller, user:) expect(service.send(:use_cache?)).to eq(true) end end describe "#cache_key_for_data" do it "returns cache key for data by date" do user = create(:user, timezone: "Rome") cache_key = described_class.new(user).send(:cache_key_for_data, Date.new(2020, 12, 3)) expect(cache_key).to eq("seller_analytics_v0_user_#{user.id}_Rome_by_date_for_2020-12-03") end end describe "#user_cache_key" do it "returns cache key for the user and its timezone" do user = create(:user, timezone: "Paris") user_cache_key = described_class.new(user).send(:user_cache_key) expect(user_cache_key).to eq("seller_analytics_v0_user_#{user.id}_Paris") $redis.set(RedisKey.seller_analytics_cache_version, 3) user_cache_key = described_class.new(user).send(:user_cache_key) expect(user_cache_key).to eq("seller_analytics_v3_user_#{user.id}_Paris") end end describe "#analytics_data" do it "proxies method call to user" do user = create(:user, timezone: "London") start_date, end_date = Date.new(2019, 1, 1), Date.new(2019, 1, 7) dates = (start_date .. end_date).to_a expect(CreatorAnalytics::Web).to receive(:new).with(user:, dates:).thrice.and_call_original expect_any_instance_of(CreatorAnalytics::Web).to receive(:by_date).and_call_original expect_any_instance_of(CreatorAnalytics::Web).to receive(:by_state).and_call_original expect_any_instance_of(CreatorAnalytics::Web).to receive(:by_referral).and_call_original service = described_class.new(user) service.send(:analytics_data, start_date, end_date, by: :date) service.send(:analytics_data, start_date, end_date, by: :state) service.send(:analytics_data, start_date, end_date, by: :referral) end end describe "#fetch_data" do before do # We need to a known point in time to avoid DST issues when running tests. travel_to Time.utc(2020, 2, 1) @user = create(:user, timezone: "London") @service = described_class.new(@user) end it "returns cached data if it exists, generates the data if not" do date = Date.new(2020, 1, 1) expect(@service).to receive(:analytics_data).with(date, date, by: :date).once.and_return("foo") expect(@service.send(:fetch_data, date)).to eq("foo") expect(@service.send(:fetch_data, date)).to eq("foo") # from cache end it "does not cache the data if the date is yesterday, today, or any day after" do date = Date.new(2020, 2, 1) expect(ComputedSalesAnalyticsDay).not_to receive(:fetch_data_from_key) expect(@service).to receive(:analytics_data).with(date - 1, date - 1, by: :date).twice.and_return("foo", "bar") expect(@service).to receive(:analytics_data).with(date, date, by: :date).twice.and_return("baz", "qux") expect(@service).to receive(:analytics_data).with(date + 1, date + 1, by: :date).and_return("quux") expect(@service.send(:fetch_data, date - 1)).to eq("foo") expect(@service.send(:fetch_data, date - 1)).to eq("bar") expect(@service.send(:fetch_data, date)).to eq("baz") expect(@service.send(:fetch_data, date)).to eq("qux") expect(@service.send(:fetch_data, date + 1)).to eq("quux") end end describe "#uncached_dates" do it "returns all dates missing from cache" do user = create(:user) service = described_class.new(user) [Date.new(2020, 1, 1), Date.new(2020, 1, 3)].each do |date| create(:computed_sales_analytics_day, key: service.send(:cache_key_for_data, date), data: "{}") end dates = (Date.new(2020, 1, 1) .. Date.new(2020, 1, 4)).to_a expect(service.send(:uncached_dates, dates)).to match_array([ Date.new(2020, 1, 2), Date.new(2020, 1, 4) ]) end end describe "#requested_dates" do before do @user = create(:user, timezone: "London", created_at: Time.utc(2019)) travel_to Time.utc(2020) @service = described_class.new(@user) described_class.send(:public, :requested_dates) end it "constrains start and end dates to a maximum of Today" do expect(@service.requested_dates(Date.today + 2, Date.today + 5)).to eq([Date.today]) end it "constrains start date to a minimum of the user creation date" do # when requested dates span from the past to the future expect(@service.requested_dates(Date.new(1998), Date.today + 5)).to eq((Date.new(2019) .. Date.today).to_a) # when requested dates are all in the past expect(@service.requested_dates(Date.new(1998), Date.new(1999))).to eq([Date.new(2019)]) # when requested start date is greater than the user creation date, the constrained start is the same expect(@service.requested_dates(Date.new(2019, 5), Date.new(2019, 6)).first).to eq(Date.new(2019, 5)) end it "returns the correct array when the dates are valid" do expect(@service.requested_dates(Date.today - 5, Date.today - 3)).to eq((Date.today - 5 .. Date.today - 3).to_a) expect(@service.requested_dates(Date.today - 5, Date.today)).to eq((Date.today - 5 .. Date.today).to_a) expect(@service.requested_dates(Date.today - 5, Date.today - 5)).to eq([Date.today - 5]) expect(@service.requested_dates(Date.today, Date.today)).to eq([Date.today]) end it "handles nonsensical requested dates" do # when end_date < start_date, returns the end date expect(@service.requested_dates(Date.today - 5, Date.today - 10)).to eq([Date.today - 5]) # when end_date < start_date AND both of them are before the user creation date, returns the user creation date expect(@service.requested_dates(@user.created_at.to_date - 5, @user.created_at.to_date - 10)).to eq([@user.created_at.to_date]) # when end_date < start_date AND start date is in the future, return that date expect(@service.requested_dates(@user.created_at.to_date + 1, @user.created_at.to_date - 10)).to eq([@user.created_at.to_date + 1]) end it "returns at least a date whatever dates were requested" do expect(@service.requested_dates(100.years.ago, 50.years.ago)).not_to be_empty expect(@service.requested_dates(50.years.from_now, 100.years.from_now)).not_to be_empty expect(@service.requested_dates(100.years.ago, 100.years.from_now)).not_to be_empty end end describe "#fetch_data_for_dates" do before do @user = create(:user, timezone: "London") @service = described_class.new(@user) end it "returns a hash with the stored values" do dates = [Date.new(2020, 9, 1), Date.new(2020, 9, 2)] ComputedSalesAnalyticsDay.upsert_data_from_key( @service.send(:cache_key_for_data, dates[0], by: :date), { "foo" => "bar" } ) expect(@service.send(:fetch_data_for_dates, dates)).to eq( dates[0] => { "foo" => "bar" }, dates[1] => nil ) end end describe "#compile_data_for_dates_and_fill_missing" do before do @user = create(:user) @service = described_class.new(@user) end it "returns array of data for all days, including missing" do expect(@service).to receive(:analytics_data).with( Date.new(2020, 1, 2), Date.new(2020, 1, 3), by: :date ).and_return("data-for-day-two-and-three" => :bar) result = @service.send(:compile_data_for_dates_and_fill_missing, { Date.new(2020, 1, 1) => { "data-for-day-one" => :foo }, Date.new(2020, 1, 2) => nil, Date.new(2020, 1, 3) => nil, }, by: :date ) expect(result).to eq([ { "data-for-day-one" => :foo }, { "data-for-day-two-and-three" => :bar } ]) end end describe "#find_missing_date_ranges" do before do @service = described_class.new(build(:user)) end it "contiguous missing dates as ranges" do result = @service.send(:find_missing_date_ranges, Date.new(2020, 1, 1) => nil, Date.new(2020, 1, 2) => nil, Date.new(2020, 1, 3) => "data", Date.new(2020, 1, 4) => nil, Date.new(2020, 1, 5) => "data", Date.new(2020, 1, 6) => nil, Date.new(2020, 1, 7) => nil, Date.new(2020, 1, 8) => nil, ) expect(result).to eq([ Date.new(2020, 1, 1) .. Date.new(2020, 1, 2), Date.new(2020, 1, 4) .. Date.new(2020, 1, 4), Date.new(2020, 1, 6) .. Date.new(2020, 1, 8) ]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/creator_analytics/following_spec.rb
spec/services/creator_analytics/following_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::Following do before do @user = create(:user, timezone: "UTC") @service = described_class.new(@user) end describe "#by_date" do it "returns expected data" do add_event("added", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 1, 1)) add_event("removed", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 1, 2)) add_event("added", Time.utc(2021, 1, 2)) add_event("removed", Time.utc(2021, 1, 2)) add_event("added", Time.utc(2021, 1, 4)) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! expect(@service).to receive(:counts).and_call_original expect(@service).to receive(:first_follower_date).and_call_original result = nil travel_to Time.utc(2021, 1, 4) do result = @service.by_date(start_date: Date.new(2021, 1, 2), end_date: Date.new(2021, 1, 4)) end expect(result).to eq( dates: ["Saturday, January 2nd", "Sunday, January 3rd", "Monday, January 4th"], by_date: { new_followers: [2, 0, 1], followers_removed: [1, 0, 0], totals: [2, 2, 3] }, new_followers: 2, start_date: "Jan 2, 2021", end_date: "Today", first_follower_date: "Jan 1, 2021" ) end it "returns expected data when user has no followers" do expect(@service).not_to receive(:counts) expect(@service).to receive(:zero_counts).and_call_original result = @service.by_date(start_date: Date.new(2021, 1, 1), end_date: Date.new(2021, 1, 2)) expect(result).to eq( dates: ["Friday, January 1st", "Saturday, January 2nd"], by_date: { new_followers: [0, 0], followers_removed: [0, 0], totals: [0, 0] }, new_followers: 0, start_date: "Jan 1, 2021", end_date: "Jan 2, 2021", first_follower_date: nil ) end end describe "#net_total" do it "returns net total of followers" do add_event("added", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 1, 1)) add_event("removed", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 1, 2)) add_event("added", Time.utc(2021, 1, 2)) add_event("removed", Time.utc(2021, 1, 2)) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! expect(@service.net_total).to eq(2) end context "up to a specific date" do it "returns net total of followers before that date" do add_event("added", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 1, 2)) add_event("removed", Time.utc(2021, 1, 3)) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! expect(@service.net_total(before_date: Date.new(2021, 1, 4))).to eq(1) expect(@service.net_total(before_date: Date.new(2021, 1, 3))).to eq(2) expect(@service.net_total(before_date: Date.new(2021, 1, 2))).to eq(1) expect(@service.net_total(before_date: Date.new(2021, 1, 1))).to eq(0) end it "supports time zones" do add_event("added", Time.utc(2021, 1, 2, 1)) # Jan 2nd @ 1AM in UTC == Jan 1st @ 8PM in EST ConfirmedFollowerEvent.__elasticsearch__.refresh_index! before_date = Date.new(2021, 1, 2) expect(@service.net_total(before_date:)).to eq(0) @user.update!(timezone: "Eastern Time (US & Canada)") expect(@service.net_total(before_date:)).to eq(1) expect(@service.net_total).to eq(1) end end end describe "#first_follower_date" do it "returns nil if there are no followers" do expect(@service.first_follower_date).to eq(nil) end it "returns the date of the first follower" do add_event("added", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 3, 5)) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! expect(@service.first_follower_date).to eq(Date.new(2021, 1, 1)) end it "supports time zones" do add_event("added", Time.utc(2021, 1, 1)) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! @user.update!(timezone: "Eastern Time (US & Canada)") expect(@service.first_follower_date).to eq(Date.new(2020, 12, 31)) end end describe "#counts" do it "returns hash of followers added, removed and running net total by day" do # This also checks that: # - Days with no activity are handled: (2021, 1, 3) has no data so isn't returned by the internal ES query. # - Days with partial activity are handled: (2021, 1, 4) has no unfollows. add_event("added", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 1, 1)) add_event("removed", Time.utc(2021, 1, 1)) add_event("added", Time.utc(2021, 1, 2)) add_event("added", Time.utc(2021, 1, 2)) add_event("removed", Time.utc(2021, 1, 2)) add_event("added", Time.utc(2021, 1, 4)) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! expect(@service).to receive(:net_total).with(before_date: Date.new(2021, 1, 1)).and_call_original result = @service.send(:counts, (Date.new(2021, 1, 1) .. Date.new(2021, 1, 4)).to_a) expect(result).to eq({ new_followers: [2, 2, 0, 1], followers_removed: [1, 1, 0, 0], totals: [1, 2, 2, 3] }) expect(@service).to receive(:net_total).with(before_date: Date.new(2021, 1, 3)).and_call_original result = @service.send(:counts, (Date.new(2021, 1, 3) .. Date.new(2021, 1, 3)).to_a) expect(result).to eq({ new_followers: [0], followers_removed: [0], totals: [2] }) end end def add_event(name, timestamp) EsClient.index( index: ConfirmedFollowerEvent.index_name, body: { followed_user_id: @user.id, name:, timestamp: } ) end describe "DST handling" do context "when event occurs near midnight during DST" do it "correctly attributes event to the right day" do user = create(:user, timezone: "Pacific Time (US & Canada)") service = described_class.new(user) # Event at July 15, 00:30 PDT = July 15, 07:30 UTC EsClient.index( index: ConfirmedFollowerEvent.index_name, body: { followed_user_id: user.id, name: "added", timestamp: Time.utc(2025, 7, 15, 7, 30) } ) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! result = service.send(:counts, [Date.new(2025, 7, 14), Date.new(2025, 7, 15)]) expect(result[:new_followers]).to eq([0, 1]) end end context "when query spans DST transition" do it "correctly buckets events across DST boundary" do user = create(:user, timezone: "Pacific Time (US & Canada)") service = described_class.new(user) # Event on March 8 at 11:00 PM PST = March 9, 07:00 UTC (before DST starts) EsClient.index( index: ConfirmedFollowerEvent.index_name, body: { followed_user_id: user.id, name: "added", timestamp: Time.utc(2025, 3, 9, 7, 0) } ) # Event on March 10 at 01:00 AM PDT = March 10, 08:00 UTC (after DST starts) EsClient.index( index: ConfirmedFollowerEvent.index_name, body: { followed_user_id: user.id, name: "added", timestamp: Time.utc(2025, 3, 10, 8, 0) } ) ConfirmedFollowerEvent.__elasticsearch__.refresh_index! result = service.send(:counts, (Date.new(2025, 3, 8)..Date.new(2025, 3, 10)).to_a) expect(result[:new_followers]).to eq([1, 0, 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/services/creator_analytics/caching_proxy/formatters/by_referral_spec.rb
spec/services/creator_analytics/caching_proxy/formatters/by_referral_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::CachingProxy::Formatters::ByReferral do before do @user = create(:user) @dates = (Date.new(2021, 1, 1) .. Date.new(2021, 1, 5)).to_a create(:purchase, link: create(:product, user: @user), created_at: Date.new(2020, 8, 15)) @service = CreatorAnalytics::CachingProxy.new(@user) end describe "#merge_data_by_referral" do it "returns data merged by referral" do # notable: without `product` & `profile` and with an array for values for different days day_one = { by_referral: { views: { "tPsrl" => { "direct" => [1], "Twitter" => [1], "Facebook" => [1] }, "EpUED" => { "direct" => [1], "Twitter" => [1], "Facebook" => [1] } }, sales: { "tPsrl" => { "direct" => [1], "Twitter" => [1], "Facebook" => [1] }, "EpUED" => { "direct" => [1], "Twitter" => [1], "Facebook" => [1] } }, totals: { "tPsrl" => { "direct" => [1], "Twitter" => [1], "Facebook" => [1] }, "EpUED" => { "direct" => [1], "Twitter" => [1], "Facebook" => [1] } } }, dates_and_months: [ { date: "Friday, January 1st", month: "January 2021", month_index: 0 }, ] } # notable: 2 days fetched + new product day_two_and_three = { by_referral: { views: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "Mmwrc" => { "direct" => [1, 1], "Twitter" => [1, 1] } }, sales: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "Mmwrc" => { "direct" => [1, 1], "Twitter" => [1, 1] } }, totals: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "Mmwrc" => { "direct" => [1, 1], "Twitter" => [1, 1] } } }, dates_and_months: [ { date: "Saturday, January 2nd", month: "January 2021", month_index: 0 }, { date: "Sunday, January 3rd", month: "January 2021", month_index: 0 }, ] } # notable: 2 more days fetched + new product day_four_and_five = { by_referral: { views: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "Mmwrc" => { "direct" => [1, 1], "Twitter" => [1, 1] } }, sales: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "Mmwrc" => { "direct" => [1, 1], "Twitter" => [1, 1] } }, totals: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "Mmwrc" => { "direct" => [1, 1], "Twitter" => [1, 1] } } }, dates_and_months: [ { date: "Monday, January 4th", month: "January 2021", month_index: 0 }, { date: "Tuesday, January 5th", month: "January 2021", month_index: 0 }, ] } expect(@service.merge_data_by_referral([day_one, day_two_and_three, day_four_and_five], @dates)).to equal_with_indifferent_access( by_referral: { views: { "tPsrl" => { "direct" => [1, 1, 1, 1, 1], "Twitter" => [1, 1, 1, 1, 1], "Facebook" => [1, 0, 0, 0, 0] }, "EpUED" => { "direct" => [1, 1, 1, 1, 1], "Twitter" => [1, 1, 1, 1, 1], "Facebook" => [1, 0, 0, 0, 0] }, "Mmwrc" => { "direct" => [0, 1, 1, 1, 1], "Twitter" => [0, 1, 1, 1, 1] } }, sales: { "tPsrl" => { "direct" => [1, 1, 1, 1, 1], "Twitter" => [1, 1, 1, 1, 1], "Facebook" => [1, 0, 0, 0, 0] }, "EpUED" => { "direct" => [1, 1, 1, 1, 1], "Twitter" => [1, 1, 1, 1, 1], "Facebook" => [1, 0, 0, 0, 0] }, "Mmwrc" => { "direct" => [0, 1, 1, 1, 1], "Twitter" => [0, 1, 1, 1, 1] } }, totals: { "tPsrl" => { "direct" => [1, 1, 1, 1, 1], "Twitter" => [1, 1, 1, 1, 1], "Facebook" => [1, 0, 0, 0, 0] }, "EpUED" => { "direct" => [1, 1, 1, 1, 1], "Twitter" => [1, 1, 1, 1, 1], "Facebook" => [1, 0, 0, 0, 0] }, "Mmwrc" => { "direct" => [0, 1, 1, 1, 1], "Twitter" => [0, 1, 1, 1, 1] } } }, dates_and_months: [ { date: "Friday, January 1st", month: "January 2021", month_index: 0 }, { date: "Saturday, January 2nd", month: "January 2021", month_index: 0 }, { date: "Sunday, January 3rd", month: "January 2021", month_index: 0 }, { date: "Monday, January 4th", month: "January 2021", month_index: 0 }, { date: "Tuesday, January 5th", month: "January 2021", month_index: 0 }, ], start_date: "Jan 1, 2021", end_date: "Jan 5, 2021", first_sale_date: "Aug 14, 2020" ) end end describe "#group_referral_data_by_day" do it "reformats the data by day" do data = { dates_and_months: [ { date: "Friday, January 1st", month: "January 2021", month_index: 0 }, { date: "Saturday, January 2nd", month: "January 2021", month_index: 0 } ], start_date: "Jan 1, 2021", end_date: "Jan 7, 2021", by_referral: { views: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "Google" => [1, 1], "Facebook" => [1, 1] } }, sales: { "tPsrl" => { "direct" => [1, 1], "Tiktok" => [1, 1] }, "EpUED" => {} }, totals: { "tPsrl" => { "direct" => [1, 1], "Tiktok" => [1, 1] }, "EpUED" => {} } }, first_sale_date: "Aug 14, 2020" } expect(@service).to receive(:dates_and_months_to_days).with(data[:dates_and_months], without_years: nil).and_call_original expect(@service.group_referral_data_by_day(data)).to equal_with_indifferent_access( dates: [ "Friday, January 1st 2021", "Saturday, January 2nd 2021" ], by_referral: { views: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "Google" => [1, 1], "Facebook" => [1, 1] } }, sales: { "tPsrl" => { "direct" => [1, 1], "Tiktok" => [1, 1] }, "EpUED" => {} }, totals: { "tPsrl" => { "direct" => [1, 1], "Tiktok" => [1, 1] }, "EpUED" => {} } } ) expect(@service).to receive(:dates_and_months_to_days).with(data[:dates_and_months], without_years: true).and_call_original expect(@service.group_referral_data_by_day(data, days_without_years: true)).to equal_with_indifferent_access( dates: [ "Friday, January 1st", "Saturday, January 2nd" ], by_referral: { views: { "tPsrl" => { "direct" => [1, 1], "Twitter" => [1, 1] }, "EpUED" => { "Google" => [1, 1], "Facebook" => [1, 1] } }, sales: { "tPsrl" => { "direct" => [1, 1], "Tiktok" => [1, 1] }, "EpUED" => {} }, totals: { "tPsrl" => { "direct" => [1, 1], "Tiktok" => [1, 1] }, "EpUED" => {} } } ) end end describe "#group_referral_data_by_month" do it "reformats the data by month" do data = { dates_and_months: [ { date: "Saturday, July 31st", month: "July 2021", month_index: 0 }, { date: "Sunday, August 1st", month: "August 2021", month_index: 1 }, { date: "Monday, August 2nd", month: "August 2021", month_index: 1 } ], start_date: "July 31, 2021", end_date: "August 2, 2021", by_referral: { views: { "EpUED" => { "Google" => [1, 1, 1], "Facebook" => [1, 1, 1] }, }, sales: { "tPsrl" => { "direct" => [1, 1, 1], "Tiktok" => [1, 1, 1] }, }, totals: { "tPsrl" => { "direct" => [1, 1, 1], "Tiktok" => [1, 1, 1] }, } }, first_sale_date: "Aug 14, 2020" } expect(@service).to receive(:dates_and_months_to_months).and_call_original expect(@service.group_referral_data_by_month(data)).to equal_with_indifferent_access( dates: [ "July 2021", "August 2021" ], by_referral: { views: { "EpUED" => { "Google" => [1, 2], "Facebook" => [1, 2] } }, sales: { "tPsrl" => { "direct" => [1, 2], "Tiktok" => [1, 2] } }, totals: { "tPsrl" => { "direct" => [1, 2], "Tiktok" => [1, 2] } } } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/creator_analytics/caching_proxy/formatters/by_state_spec.rb
spec/services/creator_analytics/caching_proxy/formatters/by_state_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::CachingProxy::Formatters::ByState do before do @service = CreatorAnalytics::CachingProxy.new(build(:user)) end describe "#merge_data_by_state" do it "returns data merged by state" do day_one = { by_state: { views: { "tPsrl" => { "Canada" => 1, "United States" => [1, 1, 1, 1], "France" => 1 }, "PruAb" => { "Canada" => 1 } }, sales: { "tPsrl" => { "Canada" => 1 }, "PruAb" => { "Canada" => 1 } }, totals: { "tPsrl" => { "Canada" => 1 }, "PruAb" => { "Canada" => 1 } }, } } # notable: new data format + new product day_two = { by_state: { views: { "tPsrl" => { "Canada" => 1, "United States" => [1, 1, 1, 1], "France" => 1 }, "PruAb" => { "Brazil" => 1 }, "Mmwrc" => { "United States" => [1, 1, 1, 1], "Brazil" => 1 } }, sales: { "tPsrl" => { "Canada" => 1 }, "PruAb" => { "Canada" => 1 }, "Mmwrc" => { "United States" => [1, 1, 1, 1], "Canada" => 1 } }, totals: { "tPsrl" => { "Canada" => 1 }, "PruAb" => { "Canada" => 1 }, "Mmwrc" => { "France" => 1 } }, } } expect(@service.merge_data_by_state([day_one, day_two])).to equal_with_indifferent_access( by_state: { views: { "tPsrl" => { "Canada" => 2, "United States" => [2, 2, 2, 2], "France" => 2 }, "PruAb" => { "Canada" => 1, "Brazil" => 1 }, "Mmwrc" => { "United States" => [1, 1, 1, 1], "Brazil" => 1 } }, sales: { "tPsrl" => { "Canada" => 2 }, "PruAb" => { "Canada" => 2 }, "Mmwrc" => { "United States" => [1, 1, 1, 1], "Canada" => 1 } }, totals: { "tPsrl" => { "Canada" => 2 }, "PruAb" => { "Canada" => 2 }, "Mmwrc" => { "France" => 1 } } } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/creator_analytics/caching_proxy/formatters/by_date_spec.rb
spec/services/creator_analytics/caching_proxy/formatters/by_date_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorAnalytics::CachingProxy::Formatters::ByDate do before do @service = CreatorAnalytics::CachingProxy.new(build(:user)) end describe "#merge_data_by_date" do it "returns data merged by date" do day_one = { dates_and_months: [{ date: "Tuesday, June 30th", month: "June 2020", month_index: 0 }], start_date: "June 30, 2020", end_date: "June 30, 2020", by_date: { views: { "tPsrl" => [1], "PruAb" => [1] }, sales: { "tPsrl" => [1], "PruAb" => [1] }, totals: { "tPsrl" => [1], "PruAb" => [1] } }, first_sale_date: "Apr 10, 2019" } # notable: 2 days fetched + new product + product deleted day_two_and_three = { dates_and_months: [ { date: "Wednesday, July 1st", month: "July 2020", month_index: 0 }, { date: "Thursday, July 2nd", month: "July 2020", month_index: 0 } ], start_date: "July 1, 2020", end_date: "July 2, 2020", by_date: { views: { "tPsrl" => [1, 1], "Mmwrc" => [1, 1] }, sales: { "tPsrl" => [1, 1], "Mmwrc" => [1, 1] }, totals: { "tPsrl" => [1, 1], "Mmwrc" => [1, 1] } }, first_sale_date: "Apr 10, 2019" } expect(@service).to receive(:rebuild_month_index_values!).and_call_original expect(@service.merge_data_by_date([day_one, day_two_and_three])).to equal_with_indifferent_access( dates_and_months: [ { date: "Tuesday, June 30th", month: "June 2020", month_index: 0 }, { date: "Wednesday, July 1st", month: "July 2020", month_index: 1 }, { date: "Thursday, July 2nd", month: "July 2020", month_index: 1 }, ], by_date: { views: { "tPsrl" => [1, 1, 1], "PruAb" => [1, 0, 0], "Mmwrc" => [0, 1, 1] }, sales: { "tPsrl" => [1, 1, 1], "PruAb" => [1, 0, 0], "Mmwrc" => [0, 1, 1] }, totals: { "tPsrl" => [1, 1, 1], "PruAb" => [1, 0, 0], "Mmwrc" => [0, 1, 1] }, }, start_date: "June 30, 2020", end_date: "July 2, 2020", first_sale_date: "Apr 10, 2019", ) end end describe "#group_date_data_by_day" do it "reformats the data by day" do data = { dates_and_months: [ { date: "Friday, July 3rd", month: "July 2020", month_index: 0 }, { date: "Saturday, July 4th", month: "July 2020", month_index: 0 } ], start_date: "July 3, 2020", end_date: "July 4, 2020", by_date: { views: { "tPsrl" => [1, 1], "PruAb" => [1, 1] }, sales: { "tPsrl" => [1, 1], "PruAb" => [1, 1] }, totals: { "tPsrl" => [1, 1], "PruAb" => [1, 1] } }, first_sale_date: "Apr 10, 2019" } expect(@service).to receive(:dates_and_months_to_days).with(data[:dates_and_months], without_years: nil).and_call_original expect(@service.group_date_data_by_day(data)).to equal_with_indifferent_access( dates: [ "Friday, July 3rd 2020", "Saturday, July 4th 2020" ], by_date: { views: { "tPsrl" => [1, 1], "PruAb" => [1, 1] }, sales: { "tPsrl" => [1, 1], "PruAb" => [1, 1] }, totals: { "tPsrl" => [1, 1], "PruAb" => [1, 1] } } ) expect(@service).to receive(:dates_and_months_to_days).with(data[:dates_and_months], without_years: true).and_call_original expect(@service.group_date_data_by_day(data, days_without_years: true)).to equal_with_indifferent_access( dates: [ "Friday, July 3rd", "Saturday, July 4th" ], by_date: { views: { "tPsrl" => [1, 1], "PruAb" => [1, 1] }, sales: { "tPsrl" => [1, 1], "PruAb" => [1, 1] }, totals: { "tPsrl" => [1, 1], "PruAb" => [1, 1] } } ) end end describe "#group_date_data_by_month" do it "reformats the data by month" do data = { dates_and_months: [ { date: "Saturday, July 31st", month: "July 2021", month_index: 0 }, { date: "Sunday, August 1st", month: "August 2021", month_index: 1 }, { date: "Monday, August 2nd", month: "August 2021", month_index: 1 }, ], start_date: "July 31, 2021", end_date: "August 2, 2021", by_date: { views: { "tPsrl" => [1, 1, 1], "PruAb" => [1, 1, 1] }, sales: { "tPsrl" => [1, 1, 1], "PruAb" => [1, 1, 1] }, totals: { "tPsrl" => [1, 1, 1], "PruAb" => [1, 1, 1] } }, first_sale_date: "Apr 10, 2019" } expect(@service).to receive(:dates_and_months_to_months).and_call_original expect(@service.group_date_data_by_month(data)).to equal_with_indifferent_access( dates: [ "July 2021", "August 2021" ], by_date: { views: { "tPsrl" => [1, 2], "PruAb" => [1, 2] }, sales: { "tPsrl" => [1, 2], "PruAb" => [1, 2] }, totals: { "tPsrl" => [1, 2], "PruAb" => [1, 2] } } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/subscription/updater_service_spec.rb
spec/services/subscription/updater_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Subscription::UpdaterService, :vcr do include ManageSubscriptionHelpers include CurrencyHelper describe "#perform" do context "tiered membership subscription" do let(:gift) { nil } before :each do setup_subscription(free_trial:, gift:) @remote_ip = "11.22.33.44" @gumroad_guid = "abc123" allow_any_instance_of(Purchase).to receive(:mandate_options_for_stripe).and_return({ payment_method_options: { card: { mandate_options: { reference: StripeChargeProcessor::MANDATE_PREFIX + SecureRandom.hex, amount_type: "maximum", amount: 100_00, start_date: Time.current.to_i, interval: "sporadic", supported_types: ["india"] } } } }) travel_to(@originally_subscribed_at + 1.month) end let(:free_trial) { false } let(:same_plan_params) do { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: 0, } end let(:update_card_params) do params = same_plan_params.except(:use_existing_card) params.merge(CardParamsSpecHelper.success.to_stripejs_params) end let(:email) { generate(:email) } let(:update_contact_info_params) do same_plan_params.merge({ contact_info: { full_name: "Jane Gumroad", email:, street_address: "100 Main St", city: "San Francisco", state: "CA", zip_code: "12345", country: "US", }, }) end let(:upgrade_tier_params) do { price_id: @quarterly_product_price.external_id, variants: [@new_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @new_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @new_tier_quarterly_upgrade_cost_after_one_month, } end let(:upgrade_recurrence_params) do { price_id: @yearly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @original_tier_yearly_price.price_cents, perceived_upgrade_price_cents: @original_tier_yearly_upgrade_cost_after_one_month, } end let(:downgrade_tier_params) do { price_id: @quarterly_product_price.external_id, variants: [@lower_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @lower_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: 0, } end let(:downgrade_recurrence_params) do { price_id: @monthly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: 3_00, perceived_upgrade_price_cents: 0, } end let(:every_two_years_params) do { price_id: @every_two_years_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @original_tier_every_two_years_price.price_cents, perceived_upgrade_price_cents: @original_tier_every_two_years_upgrade_cost_after_one_month, } end describe "updating the credit card" do it "updates the subscription but not the user's card" do service = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: update_card_params, logged_in_user: @user, remote_ip: @remote_ip, ) expect do service.perform end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :subscription_giftee_added_card) @subscription.reload @user.reload expect(@subscription.credit_card).to be expect(@subscription.credit_card).not_to eq @credit_card expect(@user.credit_card).to be expect(@user.credit_card).to eq @credit_card end it "does not switch the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: update_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be false end context "when the new card requires e-mandate" do it "updates the subscription but not the user's card" do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: update_card_params.merge(StripePaymentMethodHelper.success_indian_card_mandate.to_stripejs_params), logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(@subscription.reload.credit_card).not_to eq @credit_card expect(@user.reload.credit_card).to eq @credit_card end end end describe "restarting a membership" do before :each do travel_to(@originally_subscribed_at + 4.months) @subscription.update!(cancelled_at: 1.day.ago, cancelled_by_buyer: true) end let(:existing_card_params) do { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @original_tier_quarterly_price.price_cents, } end context "using the existing card" do it "reactivates the subscription" do expect(@subscription).to receive(:send_restart_notifications!) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true @subscription.reload expect(@subscription).to be_alive expect(@subscription.cancelled_at).to be_nil end it "charges the existing card" do expect(@subscription).to receive(:send_restart_notifications!) old_card = @original_purchase.credit_card expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.purchases.successful.not_is_original_subscription_purchase.count }.by(1) last_purchase = @subscription.last_successful_charge expect(last_purchase.id).not_to eq @original_purchase.id expect(last_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents expect(last_purchase.credit_card).to eq old_card expect(last_purchase.is_upgrade_purchase).to eq false end it "does not update the user's credit card" do expect(@subscription).to receive(:send_restart_notifications!) expect do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.not_to change { @subscription.reload.credit_card } end.not_to change { @user.reload.credit_card } end it "raises error if both subscription and user payment methods are not supported by the creator" do paypal_credit_card = create(:credit_card, chargeable: build(:native_paypal_chargeable), user: @user) @subscription.update!(credit_card: paypal_credit_card) @user.update!(credit_card: paypal_credit_card) expect(@subscription).not_to receive(:send_restart_notifications!) expect(@subscription).not_to receive(:resubscribe!) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq false expect(result[:error_message]).to eq "There is a problem with creator's paypal account, please try again later (your card was not charged)." expect(@subscription.reload).not_to be_alive end it "does not send email when charge user fails" do travel_to(@originally_subscribed_at + 3.months) @subscription.update!(cancelled_at: 1.day.ago, cancelled_by_buyer: true) expect(@subscription).not_to receive(:send_restart_notifications!) service = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ) mock_error_msg = "error message" expect(service).to receive(:charge_user!).and_raise(Subscription::UpdateFailed, mock_error_msg) result = service.perform expect(result[:success]).to eq false expect(result[:error_message]).to eq mock_error_msg expect(@subscription.reload).not_to be_alive end it "does not raise error if the user payment method is not supported by the creator but subscription one is" do expect(@subscription).to receive(:send_restart_notifications!) paypal_credit_card = create(:credit_card, chargeable: build(:native_paypal_chargeable), user: @user) @user.update!(credit_card: paypal_credit_card) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload).to be_alive end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end end context "using a new card" do let(:params) do { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @original_tier_quarterly_price.price_cents, }.merge(StripePaymentMethodHelper.success.to_stripejs_params(prepare_future_payments: true)) end it "reactivates the subscription" do expect(@subscription).to receive(:send_restart_notifications!) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true @subscription.reload expect(@subscription).to be_alive expect(@subscription.cancelled_at).to be_nil end it "charges the new card" do expect(@subscription).to receive(:send_restart_notifications!) old_card = @original_purchase.credit_card expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.purchases.successful.not_is_original_subscription_purchase.count }.by(1) last_purchase = @subscription.last_successful_charge expect(last_purchase.id).not_to eq @original_purchase.id expect(last_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents expect(last_purchase.credit_card).not_to eq old_card expect(last_purchase.is_upgrade_purchase).to eq false end it "updates the subscription's card" do expect(@subscription).to receive(:send_restart_notifications!) old_subscription_card = @subscription.credit_card old_user_card = @user.credit_card Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(@subscription.reload.credit_card).to be expect(@subscription.credit_card).not_to eq old_subscription_card expect(@user.reload.credit_card).to be expect(@user.credit_card).to eq old_user_card end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end context "when the new card requires e-mandate" do let(:params) do { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @original_tier_quarterly_price.price_cents, }.merge(StripePaymentMethodHelper.success_indian_card_mandate.to_stripejs_params(prepare_future_payments: true)) end it "charges the new card and returns proper SCA response" do expect(@subscription).not_to receive(:send_restart_notifications!) old_card = @original_purchase.credit_card PostToPingEndpointsWorker.jobs.clear response = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(@subscription.reload.purchases.in_progress.not_is_original_subscription_purchase.count).to eq(1) expect(@subscription.alive?).to be true expect(@subscription.is_resubscription_pending_confirmation?).to be true expect(@subscription.credit_card.last_four_digits).to eq("0123") last_purchase = @subscription.purchases.last expect(last_purchase.id).not_to eq @original_purchase.id expect(last_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents expect(last_purchase.credit_card).not_to eq old_card expect(last_purchase.in_progress?).to be true expect(last_purchase.is_upgrade_purchase).to eq false expect(response[:success]).to be true expect(response[:requires_card_action]).to be true expect(response[:client_secret]).to be_present expect(response[:purchase][:id]).to eq(last_purchase.external_id) expect(PostToPingEndpointsWorker.jobs.size).to eq(0) end end end context "when the price has changed" do it "charges the pre-existing price" do old_price_cents = @original_tier_quarterly_price.price_cents @original_tier_quarterly_price.update!(price_cents: old_price_cents + 500) params = { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: old_price_cents, perceived_upgrade_price_cents: old_price_cents, } expect(@subscription.flat_fee_applicable?).to be false expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.purchases.successful.not_is_original_subscription_purchase.count }.by(1) last_purchase = @subscription.last_successful_charge expect(last_purchase.id).not_to eq @original_purchase.id expect(last_purchase.displayed_price_cents).to eq old_price_cents expect(@subscription.reload.flat_fee_applicable?).to be true end end context "changing plans" do it "allows downgrading recurrence immediately" do expect do params = downgrade_recurrence_params.merge(perceived_upgrade_price_cents: downgrade_recurrence_params[:perceived_price_cents]) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(result[:success_message]).to eq "Membership restarted" expect(@subscription.reload.flat_fee_applicable?).to be true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.price_cents).to eq @original_tier_monthly_price.price_cents end.not_to change { SubscriptionPlanChange.count } end it "allows upgrading recurrence immediately" do params = upgrade_recurrence_params.merge(perceived_upgrade_price_cents: upgrade_recurrence_params[:perceived_price_cents]) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(result[:success_message]).to eq "Membership restarted" expect(@subscription.reload.flat_fee_applicable?).to be true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.price_cents).to eq @original_tier_yearly_price.price_cents end it "allows downgrading tier immediately" do expect do params = downgrade_tier_params.merge(perceived_upgrade_price_cents: downgrade_tier_params[:perceived_price_cents]) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(result[:success_message]).to eq "Membership restarted" expect(@subscription.reload.flat_fee_applicable?).to be true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@lower_tier] expect(updated_purchase.price_cents).to eq @lower_tier_quarterly_price.price_cents end.not_to change { SubscriptionPlanChange.count } end it "allows upgrading tier immediately" do params = upgrade_tier_params.merge(perceived_upgrade_price_cents: upgrade_tier_params[:perceived_price_cents]) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(result[:success_message]).to eq "Membership restarted" expect(@subscription.reload.flat_fee_applicable?).to be true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@new_tier] expect(updated_purchase.price_cents).to eq @new_tier_quarterly_price.price_cents end it "allows upgrading tier immediately when card on record requires an e-mandate" do indian_cc = create(:credit_card, user: @user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate)) @subscription.credit_card = indian_cc @subscription.save! params = upgrade_tier_params.merge(perceived_upgrade_price_cents: upgrade_tier_params[:perceived_price_cents]) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(result[:requires_card_action]).to be true expect(@subscription.reload.flat_fee_applicable?).to be true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@new_tier] expect(updated_purchase.price_cents).to eq @new_tier_quarterly_price.price_cents end end describe "changing quantity" do before do setup_subscription(quantity: 2) end context "when increasing quantity" do it "immediately updates the purchase and charges the user" do expect(@subscription.flat_fee_applicable?).to be false travel_to(@originally_subscribed_at + 1.day) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: same_plan_params.merge({ quantity: 3, perceived_price_cents: 1797, perceived_upgrade_price_cents: 625 }), logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq(true) last_purchase = @subscription.last_successful_charge expect(last_purchase.id).not_to eq @original_purchase.id expect(last_purchase.displayed_price_cents).to eq 625 original_purchase = @subscription.original_purchase expect(original_purchase.displayed_price_cents).to eq 1797 expect(original_purchase.quantity).to eq 3 expect(@subscription.reload.flat_fee_applicable?).to be true end end context "when decreasing quantity" do it "creates a plan change and does not charge the user" do expect(@subscription.flat_fee_applicable?).to be false travel_to(@originally_subscribed_at + 1.day) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: same_plan_params.merge({ quantity: 1, perceived_price_cents: 599, perceived_upgrade_price_cents: 0 }), logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq(true) plan_change = @subscription.subscription_plan_changes.first expect(plan_change.quantity).to eq(1) expect(plan_change.perceived_price_cents).to eq 599 expect(@subscription.reload.flat_fee_applicable?).to be true end end end context "when the membership was cancelled by the creator" do it "does not allow restarting the membership" do @subscription.update!(cancelled_by_buyer: false) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq false expect(result[:error_message]).to eq "This subscription cannot be restarted." expect(@subscription.reload).not_to be_alive expect(@subscription.reload.flat_fee_applicable?).to be false end end context "when the product is deleted" do it "does not allow restarting the membership" do @product.mark_deleted! result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: existing_card_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq false expect(result[:error_message]).to eq "This subscription cannot be restarted." expect(@subscription.reload).not_to be_alive expect(@subscription.reload.flat_fee_applicable?).to be false end end end describe "updating card after charge failure but before cancellation" do before do travel_to(@originally_subscribed_at + @subscription.period + 1.minute) end it "updates the card and charges the user" do old_card = @original_purchase.credit_card old_subscription_card = @subscription.credit_card old_user_card = @user.credit_card params = { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @original_tier_quarterly_price.price_cents, }.merge(StripePaymentMethodHelper.success.to_stripejs_params(prepare_future_payments: true)) expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.purchases.successful.not_is_original_subscription_purchase.count }.by(1) last_purchase = @subscription.last_successful_charge expect(last_purchase.id).not_to eq @original_purchase.id expect(last_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents expect(last_purchase.credit_card).not_to eq old_card expect(last_purchase.is_upgrade_purchase).to eq false expect(@subscription.reload.credit_card).to be expect(@subscription.credit_card).not_to eq old_subscription_card expect(@user.reload.credit_card).to be expect(@user.credit_card).to eq old_user_card expect(@subscription.reload.flat_fee_applicable?).to be false end it "applies any plan changes immediately" do expect do params = downgrade_recurrence_params.merge(perceived_upgrade_price_cents: downgrade_recurrence_params[:perceived_price_cents]).merge(StripePaymentMethodHelper.success.to_stripejs_params(prepare_future_payments: true)) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(result[:success_message]).to eq "Your membership has been updated." updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.price_cents).to eq @original_tier_monthly_price.price_cents end.not_to change { SubscriptionPlanChange.count } expect(@subscription.reload.flat_fee_applicable?).to be true end it "updates the card and charges the user correctly if seller has a connected Stripe account" do old_card = @original_purchase.credit_card old_subscription_card = @subscription.credit_card old_user_card = @user.credit_card stripe_connect_account = create(:merchant_account_stripe_connect, user: @subscription.link.user)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/subscription/updater_service/tiered_membership_variant_and_price_update_spec.rb
spec/services/subscription/updater_service/tiered_membership_variant_and_price_update_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Subscription::UpdaterService – Tiered Membership Variant And Price Update Scenarios", :vcr do include ManageSubscriptionHelpers include CurrencyHelper describe "#perform" do context "tiered membership subscription" do before do setup_subscription @remote_ip = "11.22.33.44" @gumroad_guid = "abc123" travel_to(@originally_subscribed_at + 1.month) end let(:same_plan_params) do { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: 0, } end let(:email) { generate(:email) } let(:upgrade_tier_params) do { price_id: @quarterly_product_price.external_id, variants: [@new_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @new_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @new_tier_quarterly_upgrade_cost_after_one_month, } end let(:upgrade_recurrence_params) do { price_id: @yearly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @original_tier_yearly_price.price_cents, perceived_upgrade_price_cents: @original_tier_yearly_upgrade_cost_after_one_month, } end let(:downgrade_tier_params) do { price_id: @quarterly_product_price.external_id, variants: [@lower_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @lower_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: 0, } end let(:downgrade_recurrence_params) do { price_id: @monthly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: 3_00, perceived_upgrade_price_cents: 0, } end context "when variant has not changed" do context "nor has recurrence period" do it "does not change the variant or price" do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: same_plan_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@original_tier] expect(updated_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents end it "does not charge the user" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: same_plan_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.not_to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count } end it "does not switch the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: same_plan_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be false end end context "but recurrence period has changed" do context "to a price that is the same as or less than the current price" do it "does not change the price on the original subscription" do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: downgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true @original_purchase.reload updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@original_tier] expect(updated_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents end it "does not charge the user" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: downgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.not_to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count } end it "records that the user should be downgraded" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: downgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { SubscriptionPlanChange.count }.by(1) plan_change = @subscription.subscription_plan_changes.first expect(plan_change.tier).to eq @original_tier expect(plan_change.recurrence).to eq "monthly" expect(plan_change.perceived_price_cents).to eq 3_00 end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: downgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end end context "to a price that is greater than the current price" do it "creates a new 'original' subscription purchase and archives the old one" do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@original_tier] expect(updated_purchase.displayed_price_cents).to eq 1000 expect(updated_purchase.price_cents).to eq 1000 expect(updated_purchase.total_transaction_cents).to eq 1000 expect(updated_purchase.fee_cents).to eq 209 expect(updated_purchase.purchase_state).to eq "not_charged" expect(@subscription.last_payment_option.price).to eq @yearly_product_price expect(@original_purchase.reload.is_archived_original_subscription_purchase).to eq true end it "charges the user on a pro-rated basis and upgrades them immediately" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count }.by(1) upgrade_purchase = @subscription.purchases.last expect(upgrade_purchase.is_upgrade_purchase).to eq true expect(upgrade_purchase.total_transaction_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.displayed_price_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.price_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.total_transaction_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.fee_cents).to eq 158 end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end end end end context "when variant has changed" do context "but has the same recurrence period" do context "and is more expensive" do it "creates a new 'original' subscription purchase with the new variant and archives the old one" do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_tier_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform new_price_cents = @new_tier.prices.alive.find_by!(recurrence: BasePrice::Recurrence::QUARTERLY).price_cents updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@new_tier] expect(updated_purchase.displayed_price_cents).to eq new_price_cents expect(updated_purchase.purchase_state).to eq "not_charged" expect(@subscription.last_payment_option.price).to eq @quarterly_product_price # no change expect(@original_purchase.reload.is_archived_original_subscription_purchase).to eq true end it "charges the pro-rated rate for the new variant for the remainder of the period" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_tier_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count }.by(1) .and change { @product.user.reload.balances.count }.by(1) upgrade_purchase = @subscription.purchases.last expect(upgrade_purchase.is_upgrade_purchase).to eq true expect(upgrade_purchase.total_transaction_cents).to eq @new_tier_quarterly_upgrade_cost_after_one_month expect(upgrade_purchase.displayed_price_cents).to eq @new_tier_quarterly_upgrade_cost_after_one_month expect(upgrade_purchase.price_cents).to eq @new_tier_quarterly_upgrade_cost_after_one_month expect(upgrade_purchase.total_transaction_cents).to eq @new_tier_quarterly_upgrade_cost_after_one_month expect(upgrade_purchase.fee_cents).to eq 164 expect(upgrade_purchase.variant_attributes).to eq [@new_tier] # creator balance reflects upgrade purchase user_balances = @product.user.balances expect(user_balances.last.amount_cents).to eq @new_tier_quarterly_upgrade_cost_after_one_month - upgrade_purchase.fee_cents end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_tier_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end end end context "and recurrence period has changed" do context "to a more expensive one" do let(:params) do { price_id: @yearly_product_price.external_id, variants: [@new_tier.external_id], use_existing_card: true, perceived_price_cents: @new_tier_yearly_price.price_cents, perceived_upgrade_price_cents: @new_tier_yearly_upgrade_cost_after_one_month, } end it "creates a new 'original' subscription purchase with the new variant and price and archives the old one" do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@new_tier] expect(updated_purchase.displayed_price_cents).to eq 2000 expect(updated_purchase.price_cents).to eq 2000 expect(updated_purchase.total_transaction_cents).to eq 2000 expect(updated_purchase.fee_cents).to eq 338 expect(updated_purchase.purchase_state).to eq "not_charged" expect(@subscription.last_payment_option.price).to eq @yearly_product_price expect(@original_purchase.reload.is_archived_original_subscription_purchase).to eq true end it "charges the user on a pro-rated basis and upgrades them immediately" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count }.by(1) upgrade_purchase = @subscription.purchases.last expect(upgrade_purchase.is_upgrade_purchase).to eq true expect(upgrade_purchase.total_transaction_cents).to eq @new_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.displayed_price_cents).to eq @new_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.price_cents).to eq @new_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.total_transaction_cents).to eq @new_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.fee_cents).to eq 287 end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end end context "to a less expensive one" do let(:params) do { price_id: @monthly_product_price.external_id, variants: [@new_tier.external_id], use_existing_card: true, perceived_price_cents: 5_00, perceived_upgrade_price_cents: 0, } end it "does not change the variant or price immediately" do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@original_purchase.errors.full_messages).to be_empty @original_purchase.reload updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).to eq @original_purchase.id expect(@original_purchase.is_archived_original_subscription_purchase).to eq false expect(@original_purchase.variant_attributes).to eq [@original_tier] expect(@original_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents expect(@subscription.reload.price).to eq @quarterly_product_price end it "does not charge the user" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.not_to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count } end it "records that the plan should be changed at the end of the next billing period" do expect do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform end.to change { @subscription.reload.subscription_plan_changes.count }.by(1) plan_change = @subscription.subscription_plan_changes.first expect(plan_change.tier).to eq @new_tier expect(plan_change.recurrence).to eq "monthly" expect(plan_change.deleted_at).to be_nil expect(plan_change.perceived_price_cents).to eq 5_00 end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end end end end context "when purchase is taxable" do it "records the taxes due" do create(:zip_tax_rate, zip_code: nil, state: nil, country: Compliance::Countries::FRA.alpha2, combined_rate: 0.1, is_seller_responsible: false) @original_purchase.country = "France" @original_purchase.save! params = { price_id: @yearly_product_price.external_id, variants: [@new_tier.external_id], use_existing_card: true, perceived_price_cents: @new_tier_yearly_price.price_cents, perceived_upgrade_price_cents: @new_tier_yearly_upgrade_cost_after_one_month, } Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.was_purchase_taxable).to eq true expect(updated_purchase.gumroad_tax_cents).to eq 2_00 expect(updated_purchase.total_transaction_cents).to eq 22_00 end end context "when original price has changed in the interim" do before :each do @original_tier_quarterly_price.update!(price_cents: 7_99) end context "upgrading" do let(:params) do { 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_upgrade_cost_after_one_month, } end it "uses the new price" do expect do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@original_tier] expect(updated_purchase.displayed_price_cents).to eq @original_tier_yearly_price.price_cents expect(@original_purchase.reload.is_archived_original_subscription_purchase).to eq true end.to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count }.by(1) end it "charges the correct price difference" do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform upgrade_purchase = @subscription.purchases.last expect(upgrade_purchase.is_upgrade_purchase).to eq true expect(upgrade_purchase.total_transaction_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.displayed_price_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.price_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.total_transaction_cents).to eq @original_tier_yearly_upgrade_cost_after_one_month expect(upgrade_purchase.fee_cents).to eq 158 end it "switches the subscription to new flat fee" do expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end end context "downgrading" do it "does not change the price or charge the user" do params = { price_id: @monthly_product_price.external_id, variants: [@original_tier.external_id], use_existing_card: true, perceived_price_cents: 3_00, perceived_upgrade_price_cents: 0, } expect do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).to eq @original_purchase.id @original_purchase.reload expect(@original_purchase.variant_attributes).to eq [@original_tier] expect(@original_purchase.displayed_price_cents).to eq 5_99 end.not_to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count } end it "switches the subscription to new flat fee" do params = { price_id: @monthly_product_price.external_id, variants: [@original_tier.external_id], use_existing_card: true, perceived_price_cents: 3_00, perceived_upgrade_price_cents: 0, } expect(@subscription.flat_fee_applicable?).to be false result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end context "not changing plan" do it "does not change the price or charge the user" do params = { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: 0, } expect do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params:, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).to eq @original_purchase.id @original_purchase.reload expect(@original_purchase.variant_attributes).to eq [@original_tier] expect(@original_purchase.displayed_price_cents).to eq 5_99 expect(@subscription.reload.flat_fee_applicable?).to be false end.not_to change { @subscription.reload.purchases.not_is_original_subscription_purchase.count } end end end end context "when original purchase is not associated with a tier" do before :each do @original_purchase.variant_attributes = [] @original_purchase.save! end it "does not treat it as a plan change if the default tier and original recurrence are selected" do expect do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: same_plan_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true expect(@original_purchase.reload.variant_attributes).to eq [@original_tier] expect(@subscription.reload.flat_fee_applicable?).to be false end.not_to change { Purchase.count } end context "upgrading" do it "treats it as an upgrade if a more expensive tier is selected" do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_tier_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@new_tier] expect(updated_purchase.displayed_price_cents).to eq @new_tier_quarterly_price.price_cents expect(updated_purchase.purchase_state).to eq "not_charged" expect(@subscription.last_payment_option.price).to eq @quarterly_product_price # no change expect(@original_purchase.reload.is_archived_original_subscription_purchase).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end it "treats it as an upgrade if a more expensive recurrence is selected" do Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@original_tier] expect(updated_purchase.displayed_price_cents).to eq @original_tier_yearly_price.price_cents expect(updated_purchase.purchase_state).to eq "not_charged" expect(@subscription.last_payment_option.price).to eq @yearly_product_price expect(@original_purchase.reload.is_archived_original_subscription_purchase).to eq true expect(@subscription.reload.flat_fee_applicable?).to be true end context "default tier is sold out" do it "does not error" do @original_tier.update!(max_purchase_count: 0) result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: upgrade_recurrence_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.variant_attributes).to eq [@original_tier] end end end context "downgrading" do it "treats it as a downgrade if a less expensive tier is selected" do expect do result = Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: @gumroad_guid, params: downgrade_tier_params, logged_in_user: @user, remote_ip: @remote_ip, ).perform expect(result[:success]).to eq true @original_purchase.reload updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).to eq @original_purchase.id expect(updated_purchase.variant_attributes).to eq [@original_tier] expect(updated_purchase.displayed_price_cents).to eq @original_tier_quarterly_price.price_cents plan_change = @subscription.subscription_plan_changes.first expect(plan_change.tier).to eq @lower_tier expect(plan_change.recurrence).to eq "quarterly"
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/charge/create_service_spec.rb
spec/services/charge/create_service_spec.rb
# frozen_string_literal: false describe Charge::CreateService, :vcr do let(:seller_1) { create(:user) } let(:seller_2) { create(:user) } let(:price_1) { 5_00 } let(:price_2) { 10_00 } let(:price_3) { 10_00 } let(:price_4) { 10_00 } let(:price_5) { 10_00 } let(:product_1) { create(:product, user: seller_1, price_cents: price_1) } let(:product_2) { create(:product, user: seller_1, price_cents: price_2) } let(:product_3) { create(:product, user: seller_1, price_cents: price_3) } let(:product_4) { create(:product, user: seller_2, price_cents: price_4) } let(:product_5) { create(:product, user: seller_2, price_cents: price_5, discover_fee_per_thousand: 300) } let(:browser_guid) { SecureRandom.uuid } let(:common_order_params_without_payment) do { email: "buyer@gumroad.com", cc_zipcode: "12345", purchase: { full_name: "Edgar Gumstein", street_address: "123 Gum Road", country: "US", state: "CA", city: "San Francisco", zip_code: "94117" }, browser_guid:, ip_address: "0.0.0.0", session_id: "a107d0b7ab5ab3c1eeb7d3aaf9792977", is_mobile: false, } end let(:params) do { line_items: [ { uid: "unique-id-0", permalink: product_1.unique_permalink, perceived_price_cents: product_1.price_cents, quantity: 1 }, { uid: "unique-id-1", permalink: product_2.unique_permalink, perceived_price_cents: product_2.price_cents, quantity: 1 }, { uid: "unique-id-2", permalink: product_3.unique_permalink, perceived_price_cents: product_3.price_cents, quantity: 1 }, { uid: "unique-id-3", permalink: product_4.unique_permalink, perceived_price_cents: product_4.price_cents, quantity: 1 }, { uid: "unique-id-4", permalink: product_5.unique_permalink, perceived_price_cents: product_5.price_cents, quantity: 1 } ] }.merge(common_order_params_without_payment) end describe "#perform" do it "creates a charge and associates the purchases with it" do order, _ = Order::CreateService.new(params:).perform merchant_account = create(:merchant_account_stripe, user: seller_1) chargeable = create(:chargeable, card: StripePaymentMethodHelper.success) purchases = order.purchases.where(seller_id: seller_1.id) amount_cents = purchases.sum(&:total_transaction_cents) gumroad_amount_cents = purchases.sum(&:total_transaction_amount_for_gumroad_cents) setup_future_charges = false off_session = false statement_description = seller_1.name_or_username purchase_details = { "purchases{0}" => purchases.map(&:external_id).join(",") } mandate_options = { payment_method_options: { card: { mandate_options: { reference: anything, amount_type: "maximum", amount: purchases.max_by(&:total_transaction_cents).total_transaction_cents, start_date: Date.new(2023, 12, 26).to_time.to_i, interval: "sporadic", supported_types: ["india"] } } } } expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).with(merchant_account, chargeable, amount_cents, gumroad_amount_cents, instance_of(String), instance_of(String), statement_description:, transfer_group: instance_of(String), off_session:, setup_future_charges:, metadata: purchase_details, mandate_options:).and_call_original expect do expect do travel_to(Date.new(2023, 12, 26)) do charge = Charge::CreateService.new(order:, seller: seller_1, merchant_account:, chargeable:, purchases:, amount_cents:, gumroad_amount_cents:, setup_future_charges:, off_session:, statement_description:, mandate_options:).perform charge_intent = charge.charge_intent expect(charge_intent.succeeded?).to be true expect(charge.purchases.in_progress.count).to eq 3 expect(charge.purchases.pluck(:id)).to eq purchases.pluck(:id) expect(charge.order).to eq order expect(charge.seller).to eq seller_1 expect(charge.merchant_account).to eq merchant_account expect(charge.processor).to eq StripeChargeProcessor.charge_processor_id expect(charge.amount_cents).to eq amount_cents expect(charge.gumroad_amount_cents).to eq gumroad_amount_cents expect(charge.processor_transaction_id).to eq charge_intent.charge.id expect(charge.payment_method_fingerprint).to eq chargeable.fingerprint expect(charge.processor_fee_cents).to eq charge_intent.charge.fee expect(charge.processor_fee_currency).to eq charge_intent.charge.fee_currency expect(charge.credit_card_id).to be nil expect(charge.stripe_payment_intent_id).to eq charge_intent.id expect(charge.stripe_setup_intent_id).to be nil expect(charge.paypal_order_id).to be nil stripe_charge = Stripe::Charge.retrieve(id: charge_intent.charge.id) expect(stripe_charge.metadata.to_h.values).to eq(["G_-mnBf9b1j9A7a4ub4nFQ==,P5ppE6H8XIjy2JSCgUhbAw==,bfi_30HLgGWL8H2wo_Gzlg=="]) end end.to change { Charge.count }.by 1 end.not_to change { Purchase.count } end it "handles charge processor error and adds corresponding error on each purchase" do order, _ = Order::CreateService.new(params:).perform merchant_account = create(:merchant_account_stripe, user: seller_1) chargeable = create(:chargeable, card: StripePaymentMethodHelper.decline_cvc_check_fails) purchases = order.purchases.where(seller_id: seller_1.id) amount_cents = purchases.sum(&:total_transaction_cents) gumroad_amount_cents = purchases.sum(&:total_transaction_amount_for_gumroad_cents) setup_future_charges = false off_session = false statement_description = seller_1.name_or_username purchase_details = { "purchases{0}" => purchases.map(&:external_id).join(",") } mandate_options = { payment_method_options: { card: { mandate_options: { reference: anything, amount_type: "maximum", amount: purchases.max_by(&:total_transaction_cents).total_transaction_cents, start_date: Date.new(2023, 12, 26).to_time.to_i, interval: "sporadic", supported_types: ["india"] } } } } expect(ChargeProcessor).to receive(:create_payment_intent_or_charge!).with(merchant_account, chargeable, amount_cents, gumroad_amount_cents, instance_of(String), instance_of(String), statement_description:, transfer_group: instance_of(String), off_session:, setup_future_charges:, metadata: purchase_details, mandate_options:).and_call_original expect do expect do travel_to(Date.new(2023, 12, 26)) do charge = Charge::CreateService.new(order:, seller: seller_1, merchant_account:, chargeable:, purchases:, amount_cents:, gumroad_amount_cents:, setup_future_charges:, off_session:, statement_description:, mandate_options:).perform expect(charge.charge_intent).to be nil expect(charge.reload.purchases.in_progress.count).to eq 3 expect(charge.purchases.pluck(:id)).to eq purchases.pluck(:id) expect(charge.order).to eq order expect(charge.seller).to eq seller_1 expect(charge.merchant_account).to eq merchant_account expect(charge.processor).to eq StripeChargeProcessor.charge_processor_id expect(charge.amount_cents).to eq amount_cents expect(charge.gumroad_amount_cents).to eq gumroad_amount_cents expect(charge.processor_transaction_id).to be nil expect(charge.payment_method_fingerprint).to eq chargeable.fingerprint expect(charge.processor_fee_cents).to be nil expect(charge.processor_fee_currency).to be nil expect(charge.credit_card_id).to be nil expect(charge.stripe_payment_intent_id).to be nil expect(charge.stripe_setup_intent_id).to be nil expect(charge.paypal_order_id).to be nil purchases.each do |purchase| expect(purchase.stripe_error_code).to eq("incorrect_cvc") expect(purchase.errors.first.message).to eq("Your card's security code is incorrect.") end end end.to change { Charge.count }.by 1 end.not_to change { Purchase.count } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/early_fraud_warning/update_service_spec.rb
spec/services/early_fraud_warning/update_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe EarlyFraudWarning::UpdateService, :vcr do let(:processor_transaction_id) { "ch_2O8n7J9e1RjUNIyY1rs9MIRL" } describe "for a Purchase" do let(:purchase) { create(:purchase, stripe_transaction_id: processor_transaction_id) } let!(:dispute) { create(:dispute_formalized, purchase:) } let!(:refund) { create(:refund, purchase:) } shared_examples_for "creates a new record (with purchase)" do it "creates a new record" do expect do described_class.new(record).perform! end.to change(EarlyFraudWarning, :count).by(1) expect(record.dispute).to eq(dispute) expect(record.purchase).to eq(purchase) expect(record.refund).to eq(refund) expect(record.fraud_type).to eq("made_with_stolen_card") expect(record.actionable).to eq(false) expect(record.charge_risk_level).to eq("normal") expect(record.processor_created_at).not_to be_nil expect(record.resolution).to eq(EarlyFraudWarning::RESOLUTION_UNKNOWN) end end shared_examples_for "updates the record (with purchase)" do it "updates the record" do expect(record.purchase).to eq(purchase) expect(record.dispute).to be_nil expect(record.refund).to be_nil expect(record.actionable).to be(true) described_class.new(record).perform! expect(record.purchase).to eq(purchase) expect(record.dispute).to eq(dispute) expect(record.refund).to eq(refund) expect(record.fraud_type).to eq("made_with_stolen_card") expect(record.actionable).to eq(false) expect(record.charge_risk_level).to eq("normal") end end context "when the record is resolved" do let!(:record) do create( :early_fraud_warning, purchase:, actionable: false, resolved_at: Time.current, resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED ) end it "raises error" do expect do described_class.new(record).perform! end.to raise_error(EarlyFraudWarning::UpdateService::AlreadyResolvedError) end end context "when the purchase belongs to a Stripe Connect account" do let(:merchant_account) { create(:merchant_account_stripe_connect, charge_processor_merchant_id: "acct_1O9tZ6GFgEK9GGWT") } let(:purchase) { create(:purchase, merchant_account:) } let!(:dispute) { create(:dispute, purchase:) } let!(:refund) { create(:refund, purchase:) } before do expect(Stripe::Radar::EarlyFraudWarning).to( receive(:retrieve) .with( { id: record.processor_id, expand: %w(charge) }, { stripe_account: merchant_account.charge_processor_merchant_id }, ) .and_call_original ) end context "when the record is not yet persisted" do let(:record) { EarlyFraudWarning.new(processor_id: "issfr_1O9ttzGFgEK9GGWTiwPNm9WO", purchase:) } it_behaves_like "creates a new record (with purchase)" end context "when the record is persisted" do let(:record) do create( :early_fraud_warning, processor_id: "issfr_1O9ttzGFgEK9GGWTiwPNm9WO", purchase:, ) end it_behaves_like "updates the record (with purchase)" end end context "when the purchase does not belong to a Stripe Connect account" do let(:record) { EarlyFraudWarning.new(processor_id: "issfr_0O8n7K9e1RjUNIyYmTbvMMLa", purchase:) } before do expect(Stripe::Radar::EarlyFraudWarning).to( receive(:retrieve) .with({ id: record.processor_id, expand: %w(charge) }) .and_call_original ) end context "when the record is not yet persisted" do it_behaves_like "creates a new record (with purchase)" end context "when the record is persisted" do let(:record) do create( :early_fraud_warning, processor_id: "issfr_0O8n7K9e1RjUNIyYmTbvMMLa", purchase:, ) end it_behaves_like "updates the record (with purchase)" end end end describe "for a Charge", :vcr do let(:purchase) { create(:purchase, stripe_transaction_id: processor_transaction_id) } let(:charge) { create(:charge, processor_transaction_id:, purchases: [purchase]) } let!(:dispute) { create(:dispute_formalized, purchase: nil, charge:) } let!(:refund) { create(:refund, purchase:) } shared_examples_for "creates a new record (with charge)" do it "creates a new record" do expect do described_class.new(record).perform! end.to change(EarlyFraudWarning, :count).by(1) expect(record.dispute).to eq(dispute) expect(record.charge).to eq(charge) expect(record.refund).to eq(refund) expect(record.fraud_type).to eq("made_with_stolen_card") expect(record.actionable).to eq(false) expect(record.charge_risk_level).to eq("normal") expect(record.processor_created_at).not_to be_nil expect(record.resolution).to eq(EarlyFraudWarning::RESOLUTION_UNKNOWN) end end shared_examples_for "updates the record (with charge)" do it "updates the record" do expect(record.charge).to eq(charge) expect(record.dispute).to be_nil expect(record.refund).to be_nil expect(record.actionable).to be(true) described_class.new(record).perform! expect(record.charge).to eq(charge) expect(record.dispute).to eq(dispute) expect(record.refund).to eq(refund) expect(record.fraud_type).to eq("made_with_stolen_card") expect(record.actionable).to eq(false) expect(record.charge_risk_level).to eq("normal") end end context "when the record is resolved" do let!(:record) do create( :early_fraud_warning, purchase: nil, charge:, actionable: false, resolved_at: Time.current, resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED ) end it "raises error" do expect do described_class.new(record).perform! end.to raise_error(EarlyFraudWarning::UpdateService::AlreadyResolvedError) end end context "when the purchase belongs to a Stripe Connect account" do let(:merchant_account) { create(:merchant_account_stripe_connect, charge_processor_merchant_id: "acct_1O9tZ6GFgEK9GGWT") } let(:purchase) { create(:purchase, merchant_account:) } let(:charge) { create(:charge, merchant_account:, purchases: [purchase]) } let!(:dispute) { create(:dispute, purchase: nil, charge:) } let!(:refund) { create(:refund, purchase:) } before do expect(Stripe::Radar::EarlyFraudWarning).to( receive(:retrieve) .with( { id: record.processor_id, expand: %w(charge) }, { stripe_account: merchant_account.charge_processor_merchant_id }, ) .and_call_original ) end context "when the record is not yet persisted" do let(:record) { EarlyFraudWarning.new(processor_id: "issfr_1O9ttzGFgEK9GGWTiwPNm9WO", charge:) } it_behaves_like "creates a new record (with charge)" end context "when the record is persisted" do let(:record) do create( :early_fraud_warning, processor_id: "issfr_1O9ttzGFgEK9GGWTiwPNm9WO", purchase: nil, charge: ) end it_behaves_like "updates the record (with charge)" end end context "when the purchase does not belong to a Stripe Connect account" do let(:record) { EarlyFraudWarning.new(processor_id: "issfr_0O8n7K9e1RjUNIyYmTbvMMLa", charge:) } before do expect(Stripe::Radar::EarlyFraudWarning).to( receive(:retrieve) .with({ id: record.processor_id, expand: %w(charge) }) .and_call_original ) end context "when the record is not yet persisted" do it_behaves_like "creates a new record (with charge)" end context "when the record is persisted" do let(:record) do create( :early_fraud_warning, processor_id: "issfr_0O8n7K9e1RjUNIyYmTbvMMLa", purchase: nil, charge: ) end it_behaves_like "updates the record (with charge)" end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/recommended_products/checkout_service_spec.rb
spec/services/recommended_products/checkout_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe RecommendedProducts::CheckoutService do let(:recommender_model_name) { RecommendedProductsService::MODEL_SALES } let(:products) { create_list(:product, 5) } let(:seller1) { create(:user) } let(:product1) { create(:product, user: seller1) } let(:seller2) { create(:user) } let(:product2) { create(:product, user: seller2) } let(:seller_with_no_recommendations) { create(:user, recommendation_type: User::RecommendationType::NO_RECOMMENDATIONS) } let(:product3) { create(:product, user: seller_with_no_recommendations) } let(:purchaser) { create(:user) } let!(:purchase) { create(:purchase, purchaser:, link: product2) } before do products.first.update!(user: seller1) index_model_records(Link) end describe ".fetch_for_cart" do it "initializes with the correct arguments" do expect(RecommendedProducts::CheckoutService).to receive(:new).with( purchaser:, cart_product_ids: [product1.id, product3.id], recommender_model_name:, recommended_by: RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION, target: Product::Layout::PROFILE, limit: 5, recommendation_type: nil, ).and_call_original described_class.fetch_for_cart( purchaser:, cart_product_ids: [product1.id, product3.id], recommender_model_name:, limit: 5 ) end end describe ".fetch_for_receipt" do it "initializes with the correct arguments" do expect(RecommendedProducts::CheckoutService).to receive(:new).with( purchaser:, cart_product_ids: [purchase.link.id], recommender_model_name:, recommended_by: RecommendationType::GUMROAD_RECEIPT_RECOMMENDATION, target: Product::Layout::PROFILE, limit: 5 ).and_call_original described_class.fetch_for_receipt( purchaser:, receipt_product_ids: [purchase.link.id], recommender_model_name:, limit: 5 ) end end describe "#result" do it "passes user IDs for seller with recommendations turned on whose products are in the cart" do expect(RecommendedProductsService).to receive(:fetch).with( model: RecommendedProductsService::MODEL_SALES, ids: [product1.id, product3.id, product2.id], exclude_ids: [product1.id, product3.id, product2.id], number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: [seller1.id], ).and_return(Link.where(id: products.first.id)) product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [product1.id, product3.id], recommender_model_name:, limit: 5 ) expect(product_infos.map(&:product)).to eq([products.first]) expect(product_infos.map(&:recommended_by).uniq).to eq([RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION]) expect(product_infos.map(&:recommender_model_name).uniq).to eq([recommender_model_name]) expect(product_infos.map(&:target).uniq).to eq([Product::Layout::PROFILE]) end it "calls search_products with the correct arguments" do expect_any_instance_of(RecommendedProducts::CheckoutService).to receive(:search_products).with( size: 5, sort: ProductSortKey::FEATURED, user_id: [seller1.id], is_alive_on_profile: true, exclude_ids: [product1.id, product3.id, product2.id] ).and_call_original described_class.fetch_for_cart( purchaser:, cart_product_ids: [product1.id, product3.id], recommender_model_name:, limit: 5 ) end describe "affiliate recommendations" do let(:recommendable_product) { create(:product, :recommendable) } let!(:affiliate) do create( :direct_affiliate, seller: recommendable_product.user, products: [recommendable_product], affiliate_user: seller1 ) end context "when at least one of the creators has direct affiliate recommendations turned on" do before do seller1.update!(recommendation_type: User::RecommendationType::DIRECTLY_AFFILIATED_PRODUCTS) end it "returns the user's products and products that are directly affiliated and recommendable" do expect(RecommendedProductsService).to receive(:fetch).with( model: RecommendedProductsService::MODEL_SALES, ids: [product1.id, product3.id, product2.id], exclude_ids: [product1.id, product3.id, product2.id], number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: nil, ).and_return(Link.where(id: [product2.id, recommendable_product.id])) product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [product1.id, product3.id], recommender_model_name:, limit: 5 ) expect(product_infos.map(&:product)).to eq([recommendable_product, products.first]) expect(product_infos.first.affiliate_id).to eq(affiliate.external_id_numeric) expect(product_infos.map(&:recommended_by).uniq).to eq([RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION]) expect(product_infos.map(&:recommender_model_name).uniq).to eq([recommender_model_name]) expect(product_infos.map(&:target).uniq).to eq([Product::Layout::PROFILE]) end end context "when at least one of the creators has Gumroad affiliate recommendations turned on" do before do seller1.update!(recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS) end it "returns the user's products and products that are recommendable" do expect(RecommendedProductsService).to receive(:fetch).with( model: RecommendedProductsService::MODEL_SALES, ids: [product1.id, product3.id, product2.id], exclude_ids: [product1.id, product3.id, product2.id], number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: nil, ).and_return(Link.where(id: [products.first.id, products.second.id, recommendable_product.id])) product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [product1.id, product3.id], recommender_model_name:, limit: 5 ) expect(product_infos.map(&:product)).to eq([products.first, recommendable_product]) expect(product_infos.second.affiliate_id).to eq(affiliate.external_id_numeric) expect(product_infos.map(&:recommended_by).uniq).to eq([RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION]) expect(product_infos.map(&:recommender_model_name).uniq).to eq([recommender_model_name]) expect(product_infos.map(&:target).uniq).to eq([Product::Layout::PROFILE]) end end end context "when a NSFW product is returned by the service" do let!(:nsfw_product) { create(:product, :recommendable, is_adult: true) } before do allow(RecommendedProductsService).to receive(:fetch).and_return(Link.where(id: nsfw_product.id)) end context "when there are NSFW products in the cart" do let(:cart_product) do create( :product, user: create(:user, recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS), is_adult: true ) end it "includes that product in the results" do product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [cart_product.id], recommender_model_name:, limit: 5 ) expect(product_infos.first.product).to eq(nsfw_product) expect(product_infos.map(&:recommended_by).uniq).to eq([RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION]) expect(product_infos.map(&:recommender_model_name).uniq).to eq([recommender_model_name]) expect(product_infos.map(&:target).uniq).to eq([Product::Layout::PROFILE]) end end context "when there aren't NSFW products in the cart" do let(:cart_product) do create( :product, user: create(:user, recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS) ) end context "when providing affiliate recommendations" do it "excludes the product from the results" do product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [cart_product.id], recommender_model_name:, limit: 5 ) expect(product_infos).to eq([]) end end context "when not providing affiliate recommendations" do let(:cart_product) { create(:product, user: nsfw_product.user) } it "includes that product in the results" do product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [cart_product.id], recommender_model_name:, limit: 5 ) expect(product_infos.first.product).to eq(nsfw_product) expect(product_infos.map(&:recommended_by).uniq).to eq([RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION]) expect(product_infos.map(&:recommender_model_name).uniq).to eq([recommender_model_name]) expect(product_infos.map(&:target).uniq).to eq([Product::Layout::PROFILE]) end end end context "when the product is not visible" do let(:product) { create(:product, :recommendable) } let(:banned_product) { create(:product, :recommendable, banned_at: Time.current) } let(:deleted_product) { create(:product, :recommendable, deleted_at: Time.current) } let(:purchase_disabled_product) { create(:product, :recommendable, purchase_disabled_at: Time.current) } let(:not_shown_on_profile_product) { create(:product, :recommendable, archived: true) } it "doesn't include that product in the results" do allow(RecommendedProductsService).to receive(:fetch).and_return( Link.where( id: [product.id, banned_product.id, deleted_product.id, purchase_disabled_product.id, not_shown_on_profile_product.id] ) ) product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [create(:product, user: create(:user, recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS)).id], recommender_model_name:, limit: 5 ) expect(product_infos.map(&:product)).to eq([product]) expect(product_infos.map(&:recommended_by).uniq).to eq([RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION]) expect(product_infos.map(&:recommender_model_name).uniq).to eq([recommender_model_name]) expect(product_infos.map(&:target).uniq).to eq([Product::Layout::PROFILE]) end context "when the recommendation model returns fewer than the limit" do let!(:additional_product1) { create(:product, user: seller1) } let!(:additional_product2) { create(:product, user: seller1, archived: true) } let!(:additional_product3) { create(:product, user: seller1, deleted_at: Time.current) } before do index_model_records(Link) end it "fills out the results with the users' products" do expect(RecommendedProductsService).to receive(:fetch).with( { model: RecommendedProductsService::MODEL_SALES, ids: [product1.id, product2.id], exclude_ids: [product1.id, product2.id], number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: [seller1.id], } ).and_return(Link.where(id: products.first.id)) product_infos = described_class.fetch_for_cart( purchaser:, cart_product_ids: [product1.id], recommender_model_name:, limit: 5 ) expect(product_infos.map(&:product)).to eq([products.first, additional_product1]) end end context "when a bundle is one of the associated products" do let!(:bundle) { create(:product, :bundle) } it "excludes the bundle's products from the results" do expect(RecommendedProductsService).to receive(:fetch).with( exclude_ids: [bundle.id, purchase.link.id, *bundle.bundle_products.pluck(:product_id)], ids: [bundle.id, purchase.link.id], model: RecommendedProductsService::MODEL_SALES, number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: [bundle.user.id], ).and_call_original described_class.fetch_for_cart( purchaser:, cart_product_ids: [bundle.id], recommender_model_name:, limit: 5 ) 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/services/recommended_products/discover_service_spec.rb
spec/services/recommended_products/discover_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe RecommendedProducts::DiscoverService do let(:purchaser) { create(:user) } let(:products) { create_list(:product, 5) } let(:products_relation) { Link.where(id: products.map(&:id)) } let(:recommender_model_name) { RecommendedProductsService::MODEL_SALES } before do products.last.update!(deleted_at: Time.current) products.second_to_last.update!(archived: true) end describe ".fetch" do it "initializes with the correct arguments" do expect(RecommendedProducts::DiscoverService).to receive(:new).with( purchaser:, cart_product_ids: [products.first.id], recommender_model_name:, recommended_by: RecommendationType::GUMROAD_PRODUCTS_FOR_YOU_RECOMMENDATION, target: Product::Layout::DISCOVER, limit: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, ).and_call_original described_class.fetch( purchaser:, cart_product_ids: [products.first.id], recommender_model_name:, ) end end describe "#product_infos" do let(:product_infos) do described_class.fetch( purchaser:, cart_product_ids:, recommender_model_name:, ) end context "without a purchaser" do let(:purchaser) { nil } context "without card_product_ids" do let(:cart_product_ids) { [] } it "returns an empty array" do expect(product_infos).to eq([]) end end context "with cart_product_ids" do let(:cart_product) { create(:product) } let(:cart_product_ids) { [cart_product.id] } it "returns product infos" do expect(RecommendedProductsService).to receive(:fetch).with( { model: RecommendedProductsService::MODEL_SALES, ids: [cart_product.id], exclude_ids: [cart_product.id], number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: nil, } ).and_return(products_relation) expect(product_infos.map(&:product)).to eq(products.take(3)) expect(product_infos.map(&:affiliate_id).uniq).to eq([nil]) expect(product_infos.map(&:recommended_by).uniq).to eq([RecommendationType::GUMROAD_PRODUCTS_FOR_YOU_RECOMMENDATION]) expect(product_infos.map(&:recommender_model_name).uniq).to eq([recommender_model_name]) expect(product_infos.map(&:target).uniq).to eq([Product::Layout::DISCOVER]) end end end context "with a purchaser" do context "when the purchaser doesn't have purchases" do context "without card_product_ids" do let(:cart_product_ids) { [] } it "returns an empty array" do expect(product_infos).to eq([]) end end end context "when the purchaser has purchases" do let!(:purchase) { create(:purchase, purchaser:) } let(:cart_product_ids) { [] } it "returns product infos" do expect(RecommendedProductsService).to receive(:fetch).with( { model: RecommendedProductsService::MODEL_SALES, ids: [purchase.link.id], exclude_ids: [purchase.link.id], number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: nil, } ).and_return(products_relation) expect(product_infos.map(&:product)).to eq(products.take(3)) end context "when a NSFW product is returned by the service" do let(:nsfw_product) { create(:product, is_adult: true) } it "excludes that product from the results" do allow(RecommendedProductsService).to receive(:fetch).and_return(Link.where(id: [nsfw_product.id] + products.map(&:id))) expect(product_infos.map(&:product)).to eq(products.take(3)) 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/services/collaborator/update_service_spec.rb
spec/services/collaborator/update_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Collaborator::UpdateService do describe "#process" do let(:seller) { create(:user) } let(:product1) { create(:product, user: seller) } let(:product2) { create(:product, user: seller) } let(:product3) { create(:product, user: seller) } let(:apply_to_all_products) { false } let(:collaborator) { create(:collaborator, apply_to_all_products:, seller:, affiliate_basis_points: 40_00) } let(:enabled_products) { [product2, product3] } before do create(:product_affiliate, affiliate: collaborator, product: product1, affiliate_basis_points: 30_00) create(:product_affiliate, affiliate: collaborator, product: product2, affiliate_basis_points: 30_00) end let(:params) do { apply_to_all_products: true, percent_commission: 50, products: enabled_products.map { { id: _1.external_id } } } end context "with apply_to_all_products true" do it "updates the collaborator and its products, setting the existing percent commission on newly enabled products" do expect do result = described_class.new(seller:, collaborator_id: collaborator.external_id, params:).process expect(result).to eq({ success: true }) end.to have_enqueued_mail(AffiliateMailer, :collaborator_update).with { collaborator.id } collaborator.reload expect(collaborator.affiliate_basis_points).to eq 50_00 expect(collaborator.apply_to_all_products).to eq true expect(collaborator.products).to match_array enabled_products expect(collaborator.product_affiliates.find_by(product: product2).affiliate_basis_points).to eq 50_00 expect(collaborator.product_affiliates.find_by(product: product3).affiliate_basis_points).to eq 50_00 end end context "with apply_to_all_products false" do let(:apply_to_all_products) { true } let(:params) do { apply_to_all_products: false, percent_commission: nil, products: [ { id: product2.external_id, percent_commission: 25 }, { id: product3.external_id, percent_commission: 50 } ] } end it "uses the product percent_commission for the specific product" do result = described_class.new(seller:, collaborator_id: collaborator.external_id, params:).process expect(result).to eq({ success: true }) collaborator.reload expect(collaborator.affiliate_basis_points).to eq 40_00 # does not set default commission to nil expect(collaborator.apply_to_all_products).to eq false expect(collaborator.products).to match_array enabled_products expect(collaborator.product_affiliates.find_by(product: product2).affiliate_basis_points).to eq 25_00 expect(collaborator.product_affiliates.find_by(product: product3).affiliate_basis_points).to eq 50_00 end end it "raises an error if the collaborator does not belong to the seller" do expect do described_class.new(seller:, collaborator_id: create(:collaborator).external_id, params:).process end.to raise_error ActiveRecord::RecordNotFound end it "raises an error if product cannot be found" do params[:products] = [{ id: SecureRandom.hex }] expect do described_class.new(seller:, collaborator_id: collaborator.external_id, params:).process end.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/services/collaborator/create_service_spec.rb
spec/services/collaborator/create_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Collaborator::CreateService do describe "#process" do let(:seller) { create(:user) } let(:collaborating_user) { create(:user) } let(:products) { create_list(:product, 3, user: seller) } let!(:enabled_products) { products.first(2) } let(:params) do { email: collaborating_user.email, apply_to_all_products: true, percent_commission: 30, products: enabled_products.map { { id: _1.external_id } } } end context "with 'apply_to_all_products' enabled" do it "creates a collaborator" do expect do result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) end.to change { seller.collaborators.count }.from(0).to(1) .and change { ProductAffiliate.count }.from(0).to(2) collaborator = seller.collaborators.find_by(affiliate_user_id: collaborating_user.id) expect(collaborator.apply_to_all_products).to eq true expect(collaborator.affiliate_percentage).to eq 30 enabled_products.each do |product| pa = collaborator.product_affiliates.find_by(product:) expect(pa).to be_present expect(pa.affiliate_percentage).to eq 30 end end end context "with 'apply_to_all_products' disabled" do let(:product1) { enabled_products.first } let(:product2) { enabled_products.last } let(:params) do { email: collaborating_user.email, apply_to_all_products: false, percent_commission: nil, products: [ { id: product1.external_id, percent_commission: 25 }, { id: product2.external_id, percent_commission: 50 }, ], } end it "creates a collaborator" do expect do result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) end.to change { seller.collaborators.count }.from(0).to(1) .and change { ProductAffiliate.count }.from(0).to(2) collaborator = seller.collaborators.find_by(affiliate_user_id: collaborating_user.id) expect(collaborator.apply_to_all_products).to eq false expect(collaborator.affiliate_percentage).to be_nil pa = collaborator.product_affiliates.find_by(product: product1) expect(pa).to be_present expect(pa.affiliate_percentage).to eq 25 pa = collaborator.product_affiliates.find_by(product: product2) expect(pa).to be_present expect(pa.affiliate_percentage).to eq 50 end it "returns an error when commission is missing" do params[:products] = [ { id: product1.external_id, percent_commission: 50 }, { id: product2.external_id }, ] expect do result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "Product affiliates affiliate basis points must be greater than or equal to 100" }) end.to change { seller.collaborators.count }.by(0) .and change { ProductAffiliate.count }.by(0) end end it "creates a collaborator if the user is associated with a deleted collaborator" do create(:collaborator, seller:, affiliate_user: collaborating_user, deleted_at: Time.current) expect do result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) end.to change { seller.collaborators.count }.from(1).to(2) .and change { ProductAffiliate.count }.from(0).to(2) end it "returns an error if the user cannot be found" do params[:email] = "foo@example.com" result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "The email address isn't associated with a Gumroad account." }) end it "returns an error if the user is already a collaborator, regardless of invitation status" do collaborator = create( :collaborator, :with_pending_invitation, seller:, affiliate_user: collaborating_user ) result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "The user is already a collaborator" }) collaborator.collaborator_invitation.destroy! result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "The user is already a collaborator" }) end it "returns an error if product cannot be found" do params[:products] = [{ id: "abc123" }] result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "Product not found" }) end it "returns an error if the user requires approval of any collaborator requests" do collaborating_user.update!(require_collab_request_approval: true) result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "You cannot add this user as a collaborator" }) end it "returns an error if the seller is using a Brazilian Stripe Connect account" do brazilian_stripe_account = create(:merchant_account_stripe_connect, user: seller, country: "BR") seller.update!(check_merchant_account_is_linked: true) expect(seller.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "You cannot add a collaborator because you are using a Brazilian Stripe account." }) end it "returns an error if the collaborating user is using a Brazilian Stripe Connect account" do brazilian_stripe_account = create(:merchant_account_stripe_connect, user: collaborating_user, country: "BR") collaborating_user.update!(check_merchant_account_is_linked: true) expect(collaborating_user.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account result = described_class.new(seller:, params:).process expect(result).to eq({ success: false, message: "This user cannot be added as a collaborator because they use a Brazilian Stripe account." }) end describe "email notifications" do it "sends a collaborator invitation email when a collaborator is invited" do expect do result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) end .to have_enqueued_mail(AffiliateMailer, :collaborator_invited).with { Collaborator.last.id } end it "sends a collaborator creation email when a collaborator is added" do create(:collaborator, seller: collaborating_user, affiliate_user: seller) expect do result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) end .to have_enqueued_mail(AffiliateMailer, :collaborator_creation).with { Collaborator.last.id } end end describe "invitations" do context "when reciprocal collaboration exists" do let!(:reciprocal_collaboration) do create(:collaborator, seller: collaborating_user, affiliate_user: seller) end it "does not build a collaborator invitation" do result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) collaborator = seller.collaborators.find_by(affiliate_user: collaborating_user) expect(collaborator.collaborator_invitation).to be_nil end it "builds a collaborator invitation when invitation not accepted" do create(:collaborator_invitation, collaborator: reciprocal_collaboration) result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) collaborator = seller.collaborators.find_by(affiliate_user: collaborating_user) expect(collaborator.collaborator_invitation).to be_present end it "builds a collaborator invitation when reciprocal collaboration is soft deleted" do reciprocal_collaboration.mark_deleted! result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) collaborator = seller.collaborators.find_by(affiliate_user: collaborating_user) expect(collaborator.collaborator_invitation).to be_present end end it "builds a collaborator invitation when reciprocal collaboration does not exist" do result = described_class.new(seller:, params:).process expect(result).to eq({ success: true }) collaborator = seller.collaborators.find_by(affiliate_user: collaborating_user) expect(collaborator.collaborator_invitation).to be_present end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/order/charge_service_spec.rb
spec/services/order/charge_service_spec.rb
# frozen_string_literal: false describe Order::ChargeService, :vcr do include StripeMerchantAccountHelper describe "#perform" do let(:seller_1) { create(:user) } let(:seller_2) { create(:user) } let(:seller_3) { create(:user) } let(:product_1) { create(:product, user: seller_1, price_cents: 10_00) } let(:product_2) { create(:product, user: seller_1, price_cents: 20_00) } let(:free_product_1) { create(:product, user: seller_1, price_cents: 0) } let(:free_product_2) { create(:product, user: seller_1, price_cents: 0) } let(:free_trial_membership_product) do recurrence_price_values = [ { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 100 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 1000 } }, { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 50 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 500 } } ] create(:membership_product_with_preset_tiered_pricing, :with_free_trial_enabled, user: seller_2, recurrence_price_values:) end let(:product_3) { create(:product, user: seller_2, price_cents: 30_00) } let(:product_4) { create(:product, user: seller_2, price_cents: 40_00) } let(:product_5) { create(:product, user: seller_2, price_cents: 50_00, discover_fee_per_thousand: 300) } let(:product_6) { create(:product, user: seller_3, price_cents: 60_00) } let(:product_7) { create(:product, user: seller_3, price_cents: 70_00, discover_fee_per_thousand: 400) } let(:browser_guid) { SecureRandom.uuid } let(:common_order_params_without_payment) do { email: "buyer@gumroad.com", cc_zipcode: "12345", purchase: { full_name: "Edgar Gumstein", street_address: "123 Gum Road", country: "US", state: "CA", city: "San Francisco", zip_code: "94117" }, browser_guid:, ip_address: "0.0.0.0", session_id: "a107d0b7ab5ab3c1eeb7d3aaf9792977", is_mobile: false, } end let(:successful_payment_params) { StripePaymentMethodHelper.success.to_stripejs_params } let(:sca_payment_params) { StripePaymentMethodHelper.success_with_sca.to_stripejs_params } let(:indian_mandate_payment_params) { StripePaymentMethodHelper.success_indian_card_mandate.to_stripejs_params } let(:pp_native_payment_params) do { billing_agreement_id: "B-12345678910" } end let(:fail_payment_params) { StripePaymentMethodHelper.decline_expired.to_stripejs_params } let(:payment_params_with_future_charges) { StripePaymentMethodHelper.success.to_stripejs_params(prepare_future_payments: true) } let(:line_items_params) do { line_items: [ { uid: "unique-id-0", permalink: product_1.unique_permalink, perceived_price_cents: product_1.price_cents, quantity: 1 }, { uid: "unique-id-1", permalink: product_2.unique_permalink, perceived_price_cents: product_2.price_cents, quantity: 1 } ] } end let(:multi_seller_line_items_params) do { line_items: [ { uid: "unique-id-0", permalink: product_1.unique_permalink, perceived_price_cents: product_1.price_cents, quantity: 1 }, { uid: "unique-id-1", permalink: product_2.unique_permalink, perceived_price_cents: product_2.price_cents, quantity: 1 }, { uid: "unique-id-2", permalink: product_3.unique_permalink, perceived_price_cents: product_3.price_cents, quantity: 1 }, { uid: "unique-id-3", permalink: product_4.unique_permalink, perceived_price_cents: product_4.price_cents, quantity: 1 }, { uid: "unique-id-4", permalink: product_5.unique_permalink, perceived_price_cents: product_5.price_cents, quantity: 1 }, { uid: "unique-id-5", permalink: product_6.unique_permalink, perceived_price_cents: product_6.price_cents, quantity: 1 }, { uid: "unique-id-6", permalink: product_7.unique_permalink, perceived_price_cents: product_7.price_cents, quantity: 1 } ] } end before do allow_any_instance_of(Purchase).to receive(:flat_fee_applicable?).and_return(true) end it "charges all purchases in the order with the payment method provided in params" do params = line_items_params.merge!(common_order_params_without_payment).merge!(successful_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.successful.count).to eq(2) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.purchases.successful.count).to eq(2) expect(charge.amount_cents).to eq(order.purchases.sum(&:total_transaction_cents)) expect(charge.gumroad_amount_cents).to eq(order.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) expect(order.purchases.pluck(:stripe_transaction_id).uniq).to eq([charge.processor_transaction_id]) expect(order.purchases.pluck(:stripe_fingerprint).uniq).to eq([charge.payment_method_fingerprint]) expect(charge.processor_fee_cents).to be_present expect(charge.processor_fee_currency).to eq("usd") expect(charge.stripe_payment_intent_id).to be_present expect(charge.purchases.where(link_id: product_1.id).last.fee_cents).to eq(209) expect(charge.purchases.where(link_id: product_2.id).last.fee_cents).to eq(338) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.first.purchase_response) expect(charge_responses[charge_responses.keys[1]]).to eq(order.purchases.last.purchase_response) end it "charges all purchases in the order when seller has a Stripe merchant account" do seller_stripe_account = create(:merchant_account, user: seller_1, charge_processor_merchant_id: create_verified_stripe_account(country: "US").id) params = line_items_params.merge!(common_order_params_without_payment).merge!(successful_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.successful.count).to eq(2) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.purchases.successful.count).to eq(2) expect(charge.merchant_account).to eq(seller_stripe_account) expect(charge.amount_cents).to eq(order.purchases.sum(&:total_transaction_cents)) expect(charge.gumroad_amount_cents).to eq(order.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) expect(order.purchases.pluck(:stripe_transaction_id).uniq).to eq([charge.processor_transaction_id]) expect(order.purchases.pluck(:stripe_fingerprint).uniq).to eq([charge.payment_method_fingerprint]) expect(charge.processor_fee_cents).to be_present expect(charge.processor_fee_currency).to eq("usd") expect(charge.stripe_payment_intent_id).to be_present expect(charge.purchases.where(link_id: product_1.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_1.id).last.fee_cents).to eq(209) expect(charge.purchases.where(link_id: product_2.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_2.id).last.fee_cents).to eq(338) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.first.purchase_response) expect(charge_responses[charge_responses.keys[1]]).to eq(order.purchases.last.purchase_response) end it "charges 2.9% + 30c of processor fee when seller has a Stripe merchant account and existing credit card is used for payment" do seller_stripe_account = create(:merchant_account, user: seller_1, charge_processor_merchant_id: create_verified_stripe_account(country: "US").id) buyer = create(:user) buyer.credit_card = create(:credit_card) buyer.save! params = line_items_params.merge!(common_order_params_without_payment) order, _ = Order::CreateService.new(params:, buyer:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.successful.count).to eq(2) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.purchases.successful.count).to eq(2) expect(charge.merchant_account).to eq(seller_stripe_account) expect(charge.amount_cents).to eq(order.purchases.sum(&:total_transaction_cents)) expect(charge.gumroad_amount_cents).to eq(order.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) expect(order.purchases.pluck(:stripe_transaction_id).uniq).to eq([charge.processor_transaction_id]) expect(order.purchases.pluck(:stripe_fingerprint).uniq).to eq([charge.payment_method_fingerprint]) expect(charge.processor_fee_cents).to be_present expect(charge.processor_fee_currency).to eq("usd") expect(charge.stripe_payment_intent_id).to be_present expect(charge.credit_card).to eq(buyer.credit_card) expect(charge.payment_method_fingerprint).to eq(buyer.credit_card.stripe_fingerprint) expect(charge.purchases.where(link_id: product_1.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_1.id).last.fee_cents).to eq(209) expect(charge.purchases.where(link_id: product_2.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_2.id).last.fee_cents).to eq(338) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.first.purchase_response) expect(charge_responses[charge_responses.keys[1]]).to eq(order.purchases.last.purchase_response) end it "does not charge Gumroad fee and taxes when seller has a Brazilian Stripe Connect account" do seller_1.update!(check_merchant_account_is_linked: true) seller_stripe_account = create(:merchant_account_stripe_connect, user: seller_1, country: "BR", charge_processor_merchant_id: "acct_1SOZwzEbKUAyPzq3") params = line_items_params.merge!(common_order_params_without_payment).merge!(successful_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.successful.count).to eq(2) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.purchases.successful.count).to eq(2) expect(charge.merchant_account).to eq(seller_stripe_account) expect(charge.amount_cents).to eq(order.purchases.sum(&:total_transaction_cents)) expect(charge.gumroad_amount_cents).to eq 0 expect(order.purchases.pluck(:stripe_transaction_id).uniq).to eq([charge.processor_transaction_id]) expect(order.purchases.pluck(:stripe_fingerprint).uniq).to eq([charge.payment_method_fingerprint]) expect(charge.processor_fee_cents).to be_present expect(charge.processor_fee_currency).to eq("brl") expect(charge.stripe_payment_intent_id).to be_present expect(charge.purchases.where(link_id: product_1.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_1.id).last.fee_cents).to eq 0 expect(charge.purchases.where(link_id: product_2.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_2.id).last.fee_cents).to eq 0 expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.first.purchase_response) expect(charge_responses[charge_responses.keys[1]]).to eq(order.purchases.last.purchase_response) end it "charges the correct custom fee when seller has custom Gumroad fee set" do seller_1.update!(custom_fee_per_thousand: 50) seller_stripe_account = create(:merchant_account, user: seller_1, charge_processor_merchant_id: create_verified_stripe_account(country: "US").id) params = line_items_params.merge!(common_order_params_without_payment).merge!(successful_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.successful.count).to eq(2) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.purchases.successful.count).to eq(2) expect(charge.merchant_account).to eq(seller_stripe_account) expect(charge.amount_cents).to eq(order.purchases.sum(&:total_transaction_cents)) expect(charge.gumroad_amount_cents).to eq 397 expect(order.purchases.pluck(:stripe_transaction_id).uniq).to eq([charge.processor_transaction_id]) expect(order.purchases.pluck(:stripe_fingerprint).uniq).to eq([charge.payment_method_fingerprint]) expect(charge.stripe_payment_intent_id).to be_present expect(charge.purchases.where(link_id: product_1.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_1.id).last.fee_cents).to eq 159 # 5% of $10 + 50c + 2.9% of $10 + 30c expect(charge.purchases.where(link_id: product_2.id).last.merchant_account).to eq(seller_stripe_account) expect(charge.purchases.where(link_id: product_2.id).last.fee_cents).to eq 238 # 5% of $20 + 50c + 2.9% of $20 + 30c expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.first.purchase_response) expect(charge_responses[charge_responses.keys[1]]).to eq(order.purchases.last.purchase_response) end it "returns error responses for all purchases if corresponding charge fails" do params = line_items_params.merge!(common_order_params_without_payment).merge!(fail_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.purchases.failed.count).to eq(2) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to include(success: false, error_message: "Your card has expired.") expect(charge_responses[charge_responses.keys[1]]).to include(success: false, error_message: "Your card has expired.") end it "returns error responses with USD formatted price even when product display currency is EUR" do allow_any_instance_of(Purchase) .to receive(:get_rate).with(Currency::EUR.to_sym).and_return(0.8) eur_product = create(:product, user: seller_1, price_cents: 10_00, price_currency_type: Currency::EUR) eur_line_items_params = { line_items: [ { uid: "unique-id-eur", permalink: eur_product.unique_permalink, perceived_price_cents: eur_product.price_cents, quantity: 1 } ] } params = eur_line_items_params.merge!(common_order_params_without_payment).merge!(fail_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(1) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.purchases.failed.count).to eq(1) expect(charge_responses.size).to eq(1) response = charge_responses[charge_responses.keys[0]] expect(response).to include(success: false) expect(response[:formatted_price]).to eq("$12.50") end it "returns SCA response if the payment method provided in params requires SCA" do params = line_items_params.merge!(common_order_params_without_payment).merge!(sca_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.purchases.in_progress.count).to eq(2) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) expect(charge_responses[charge_responses.keys[1]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) end it "creates multiple charges in case of purchases from different sellers" do params = multi_seller_line_items_params.merge!(common_order_params_without_payment).merge!(payment_params_with_future_charges) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(7) charge_responses = nil expect do expect do charge_responses = Order::ChargeService.new(order:, params:).perform end.to change(Charge, :count).by(3) end.to change(Purchase.successful, :count).by(7) expect(order.reload.charges.count).to eq(3) expect(order.purchases.successful.count).to eq(7) charge1 = order.charges.first expect(charge1.seller).to eq(product_1.user) expect(charge1.purchases.successful.count).to eq(2) expect(charge1.purchases.pluck(:link_id)).to eq([product_1.id, product_2.id]) expect(charge1.amount_cents).to eq(product_1.price_cents + product_2.price_cents) expect(charge1.amount_cents).to eq(charge1.purchases.sum(:total_transaction_cents)) expect(charge1.gumroad_amount_cents).to eq(charge1.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) charge2 = order.charges.second expect(charge2.seller).to eq(product_3.user) expect(charge2.purchases.successful.count).to eq(3) expect(charge2.purchases.pluck(:link_id)).to eq([product_3.id, product_4.id, product_5.id]) expect(charge2.amount_cents).to eq(product_3.price_cents + product_4.price_cents + product_5.price_cents) expect(charge2.amount_cents).to eq(charge2.purchases.sum(:total_transaction_cents)) expect(charge2.gumroad_amount_cents).to eq(charge2.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) charge3 = order.charges.last expect(charge3.seller).to eq(product_6.user) expect(charge3.purchases.successful.count).to eq(2) expect(charge3.purchases.pluck(:link_id)).to eq([product_6.id, product_7.id]) expect(charge3.amount_cents).to eq(product_6.price_cents + product_7.price_cents) expect(charge3.amount_cents).to eq(charge3.purchases.sum(:total_transaction_cents)) expect(charge3.gumroad_amount_cents).to eq(charge3.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) expect(charge_responses.size).to eq(7) 7.times do |index| expect(charge_responses[charge_responses.keys[index]]).to eq(order.purchases[index].purchase_response) end end it "creates a charge with no amount if all the items from a seller are free" do free_line_items_params = { line_items: [ { uid: "unique-id-0", permalink: free_product_1.unique_permalink, perceived_price_cents: 0, quantity: 1 }, { uid: "unique-id-1", permalink: free_product_2.unique_permalink, perceived_price_cents: 0, quantity: 1 } ] } params = free_line_items_params.merge!(common_order_params_without_payment) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.successful.count).to eq(2) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.purchases.successful.count).to eq(2) expect(charge.amount_cents).to be(nil) expect(charge.gumroad_amount_cents).to be(nil) expect(charge.processor).to be(nil) expect(charge.processor_transaction_id).to be(nil) expect(charge.merchant_account_id).to be(nil) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.first.purchase_response) expect(charge_responses[charge_responses.keys[1]]).to eq(order.purchases.last.purchase_response) end it "creates a charge with no amount for a free trial membership product" do line_items_params = { line_items: [ { uid: "unique-id-0", permalink: free_trial_membership_product.unique_permalink, perceived_price_cents: 100_00, is_free_trial_purchase: true, perceived_free_trial_duration: { amount: free_trial_membership_product.free_trial_duration_amount, unit: free_trial_membership_product.free_trial_duration_unit }, quantity: 1 } ] } params = line_items_params.merge!(common_order_params_without_payment).merge!(successful_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(1) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.not_charged.count).to eq(1) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.purchases.not_charged.count).to eq(1) expect(charge.amount_cents).to be(nil) expect(charge.gumroad_amount_cents).to be(nil) expect(charge.processor).to be(nil) expect(charge.processor_transaction_id).to be(nil) expect(charge.merchant_account_id).to be(nil) expect(charge.credit_card_id).to be_present expect(charge.stripe_setup_intent_id).to be_present expect(charge_responses.size).to eq(1) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.last.purchase_response) end it "creates charges with no amounts for sellers whose items don't require an immediate payment" do line_items_params = { line_items: [ { uid: "unique-id-0", permalink: free_trial_membership_product.unique_permalink, perceived_price_cents: 100_00, is_free_trial_purchase: true, perceived_free_trial_duration: { amount: free_trial_membership_product.free_trial_duration_amount, unit: free_trial_membership_product.free_trial_duration_unit }, quantity: 1 }, { uid: "unique-id-1", permalink: free_product_2.unique_permalink, perceived_price_cents: 0, quantity: 1 } ] } params = line_items_params.merge!(common_order_params_without_payment).merge!(successful_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.reload.purchases.not_charged.count).to eq(1) expect(order.reload.purchases.successful.count).to eq(1) expect(order.charges.count).to eq(2) charge_1 = order.charges.where(seller_id: seller_1.id).last expect(charge_1.purchases.successful.count).to eq(1) expect(charge_1.amount_cents).to be(nil) expect(charge_1.gumroad_amount_cents).to be(nil) expect(charge_1.processor).to be(nil) expect(charge_1.processor_transaction_id).to be(nil) expect(charge_1.merchant_account_id).to be(nil) expect(charge_1.credit_card_id).to be(nil) expect(charge_1.stripe_setup_intent_id).to be(nil) charge_2 = order.charges.where(seller_id: seller_2.id).last expect(charge_2.purchases.not_charged.count).to eq(1) expect(charge_2.amount_cents).to be(nil) expect(charge_2.gumroad_amount_cents).to be(nil) expect(charge_2.processor).to be(nil) expect(charge_2.processor_transaction_id).to be(nil) expect(charge_2.merchant_account_id).to be(nil) expect(charge_2.credit_card_id).to be_present expect(charge_2.stripe_setup_intent_id).to be_present expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to eq(order.purchases.first.purchase_response) expect(charge_responses[charge_responses.keys[1]]).to eq(order.purchases.last.purchase_response) end it "includes free purchases in charges along with the paid purchases" do expect(CustomerMailer).not_to receive(:receipt) free_line_items_params = { line_items: [ { uid: "unique-id-7", permalink: free_trial_membership_product.unique_permalink, perceived_price_cents: 100_00, is_free_trial_purchase: true, perceived_free_trial_duration: { amount: free_trial_membership_product.free_trial_duration_amount, unit: free_trial_membership_product.free_trial_duration_unit }, quantity: 1 }, { uid: "unique-id-8", permalink: free_product_1.unique_permalink, perceived_price_cents: 0, quantity: 1 }, { uid: "unique-id-9", permalink: free_product_2.unique_permalink, perceived_price_cents: 0, quantity: 1 } ] } line_items_params = { line_items: multi_seller_line_items_params[:line_items] + free_line_items_params[:line_items] } params = line_items_params.merge!(common_order_params_without_payment).merge!(payment_params_with_future_charges) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(10) charge_responses = nil expect do charge_responses = Order::ChargeService.new(order:, params:).perform end.to change(Charge, :count).by(3) .and change(Purchase.successful, :count).by(9) .and change(Purchase.not_charged, :count).by(1) expect(order.reload.charges.count).to eq(3) expect(order.purchases.successful.count).to eq(9) expect(order.purchases.not_charged.count).to eq(1) charge1 = order.charges.first expect(charge1.seller).to eq(product_1.user) expect(charge1.purchases.successful.count).to eq(4) expect(charge1.purchases.pluck(:link_id)).to eq([product_1.id, product_2.id, free_product_1.id, free_product_2.id]) expect(charge1.amount_cents).to eq(product_1.price_cents + product_2.price_cents) expect(charge1.amount_cents).to eq(charge1.purchases.sum(:total_transaction_cents)) expect(charge1.gumroad_amount_cents).to eq(charge1.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) charge2 = order.charges.second expect(charge2.seller).to eq(product_3.user) expect(charge2.purchases.successful.count).to eq(3) expect(charge2.purchases.not_charged.count).to eq(1) expect(charge2.purchases.pluck(:link_id)).to eq([product_3.id, product_4.id, product_5.id, free_trial_membership_product.id]) expect(charge2.amount_cents).to eq(product_3.price_cents + product_4.price_cents + product_5.price_cents) expect(charge2.amount_cents).to eq(charge2.purchases.successful.sum(:total_transaction_cents)) expect(charge2.gumroad_amount_cents).to eq(charge2.purchases.successful.sum(&:total_transaction_amount_for_gumroad_cents)) charge3 = order.charges.last expect(charge3.seller).to eq(product_6.user) expect(charge3.purchases.successful.count).to eq(2) expect(charge3.purchases.pluck(:link_id)).to eq([product_6.id, product_7.id]) expect(charge3.amount_cents).to eq(product_6.price_cents + product_7.price_cents) expect(charge3.amount_cents).to eq(charge3.purchases.sum(:total_transaction_cents)) expect(charge3.gumroad_amount_cents).to eq(charge3.purchases.sum(&:total_transaction_amount_for_gumroad_cents)) expect(charge_responses.size).to eq(10) expect(charge_responses.values).to match_array(order.purchases.map { _1.purchase_response }) end context "when payment method requires mandate" do let!(:membership_product) { create(:membership_product_with_preset_tiered_pricing, user: seller_1) } let!(:membership_product_2) { create(:membership_product, price_cents: 10_00, user: seller_1) } let(:single_line_item_params_for_mandate) do { line_items: [ { uid: "unique-id-0", permalink: membership_product.unique_permalink, perceived_price_cents: 3_00, quantity: 1 } ] } end let(:line_items_params_for_mandate) do { line_items: [ { uid: "unique-id-0", permalink: membership_product.unique_permalink, perceived_price_cents: 3_00, quantity: 1 }, { uid: "unique-id-1", permalink: membership_product_2.unique_permalink, perceived_price_cents: 10_00, quantity: 1 } ] } end it "creates a mandate for a single membership purchase" do params = single_line_item_params_for_mandate.merge!(common_order_params_without_payment).merge!(indian_mandate_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(1) Order::ChargeService.new(order:, params:).perform expect(order.purchases.in_progress.count).to eq(1) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.credit_card.stripe_payment_intent_id).to be_present expect(charge.credit_card.stripe_payment_intent_id).to eq(charge.stripe_payment_intent_id) stripe_payment_intent = Stripe::PaymentIntent.retrieve(charge.credit_card.stripe_payment_intent_id) expect(stripe_payment_intent.payment_method_options.card.mandate_options).to be_present mandate_options = stripe_payment_intent.payment_method_options.card.mandate_options expect(mandate_options.amount).to eq(3_00) expect(mandate_options.amount_type).to eq("maximum") expect(mandate_options.interval).to eq("month") expect(mandate_options.interval_count).to eq(1) end it "creates a mandate for multiple membership purchases" do params = line_items_params_for_mandate.merge!(common_order_params_without_payment).merge!(indian_mandate_payment_params) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) Order::ChargeService.new(order:, params:).perform expect(order.purchases.in_progress.count).to eq(2) expect(order.charges.count).to eq(1) charge = order.charges.last expect(charge.credit_card.stripe_payment_intent_id).to be_present expect(charge.credit_card.stripe_payment_intent_id).to eq(charge.stripe_payment_intent_id) stripe_payment_intent = Stripe::PaymentIntent.retrieve(charge.credit_card.stripe_payment_intent_id)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/order/confirm_service_spec.rb
spec/services/order/confirm_service_spec.rb
# frozen_string_literal: false describe Order::ConfirmService, :vcr do describe "#perform" do let(:seller) { create(:user) } let(:product_1) { create(:product, user: seller, price_cents: 5_00) } let(:product_2) { create(:product, user: seller, price_cents: 10_00) } let(:browser_guid) { SecureRandom.uuid } let(:common_order_params_without_payment) do { email: "buyer@gumroad.com", cc_zipcode: "12345", purchase: { full_name: "Edgar Gumstein", street_address: "123 Gum Road", country: "US", state: "CA", city: "San Francisco", zip_code: "94117" }, browser_guid:, ip_address: "0.0.0.0", session_id: "a107d0b7ab5ab3c1eeb7d3aaf9792977", is_mobile: false, } end let(:sca_payment_params) { StripePaymentMethodHelper.success_with_sca.to_stripejs_params } let(:params) do { line_items: [ { uid: "unique-id-0", permalink: product_1.unique_permalink, perceived_price_cents: product_1.price_cents, quantity: 1 }, { uid: "unique-id-1", permalink: product_2.unique_permalink, perceived_price_cents: product_2.price_cents, quantity: 1 } ] }.merge!(common_order_params_without_payment).merge!(sca_payment_params) end it "calls Purchase::ConfirmService#perform for all purchases in the order" do expect(Purchase::ConfirmService).to receive(:new).exactly(2).times.and_call_original allow_any_instance_of(Purchase).to receive(:confirm_charge_intent!).and_return(nil) allow_any_instance_of(Purchase).to receive(:increment_sellers_balance!).and_return(nil) allow_any_instance_of(Purchase).to receive(:financial_transaction_validation).and_return(nil) order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.purchases.in_progress.count).to eq(2) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) expect(charge_responses[charge_responses.keys[1]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) client_secret = charge_responses[charge_responses.keys[0]][:client_secret] confirmation_params = { client_secret:, stripe_error: nil } responses, _ = Order::ConfirmService.new(order:, params: confirmation_params).perform expect(order.purchases.successful.count).to eq(2) expect(responses.size).to eq(2) expect(responses[responses.keys[0]]).to eq(Purchase.find(responses.keys[0]).purchase_response) expect(responses[responses.keys[1]]).to eq(Purchase.find(responses.keys[1]).purchase_response) end it "returns error responses for all purchases in case of SCA failure" do expect(Purchase::ConfirmService).to receive(:new).exactly(2).times.and_call_original order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.purchases.in_progress.count).to eq(2) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) expect(charge_responses[charge_responses.keys[1]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) client_secret = charge_responses[charge_responses.keys[0]][:client_secret] confirmation_params = { client_secret:, stripe_error: { code: "invalid_request_error", message: "We are unable to authenticate your payment method." } } responses, _ = Order::ConfirmService.new(order:, params: confirmation_params).perform expect(order.purchases.failed.count).to eq(2) expect(responses.size).to eq(2) expect(responses[responses.keys[0]]).to include({ success: false, error_message: "We are unable to authenticate your payment method." }) expect(responses[responses.keys[1]]).to include({ success: false, error_message: "We are unable to authenticate your payment method." }) end it "returns purchase error responses and offer codes in case of SCA failure with offer codes applied" do offer_code = create(:offer_code, user: seller, products: [product_1, product_2]) params[:purchase][:discount_code] = offer_code.code params[:line_items].each { _1[:perceived_price_cents] -= 100 } expect(Purchase::ConfirmService).to receive(:new).exactly(2).times.and_call_original order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq(2) charge_responses = Order::ChargeService.new(order:, params:).perform expect(order.purchases.in_progress.count).to eq(2) expect(charge_responses.size).to eq(2) expect(charge_responses[charge_responses.keys[0]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) expect(charge_responses[charge_responses.keys[1]]).to include(success: true, requires_card_action: true, client_secret: anything, order: { id: order.external_id, stripe_connect_account_id: nil }) client_secret = charge_responses[charge_responses.keys[0]][:client_secret] confirmation_params = { client_secret:, stripe_error: { code: "invalid_request_error", message: "We are unable to authenticate your payment method." } } responses, offer_code_responses = Order::ConfirmService.new(order:, params: confirmation_params).perform expect(order.purchases.failed.count).to eq(2) expect(responses.size).to eq(2) expect(responses[responses.keys[0]]).to include({ success: false, error_message: "We are unable to authenticate your payment method." }) expect(responses[responses.keys[1]]).to include({ success: false, error_message: "We are unable to authenticate your payment method." }) expect(offer_code_responses.size).to eq(1) expect(offer_code_responses[0][:code]).to eq(offer_code.code) expect(offer_code_responses[0][:products].size).to eq(2) expect(offer_code_responses[0][:products].keys).to match_array([product_1.unique_permalink, product_2.unique_permalink]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/order/response_helpers_spec.rb
spec/services/order/response_helpers_spec.rb
# frozen_string_literal: true describe Order::ResponseHelpers do let(:seller) { create(:user) } let(:usd_product) { create(:product, user: seller, price_cents: 15_00, price_currency_type: Currency::USD) } let(:eur_product) { create(:product, user: seller, price_cents: 15_00, price_currency_type: Currency::EUR) } let(:gbp_product) { create(:product, user: seller, price_cents: 15_00, price_currency_type: Currency::GBP) } let(:test_class) do Class.new do include Order::ResponseHelpers end end let(:test_instance) { test_class.new } describe "#error_response" do it "returns error response for failed purchase" do purchase = create(:failed_purchase, link: usd_product, total_transaction_cents: 15_00, error_code: "insufficient_funds") response = test_instance.send(:error_response, "Payment declined", purchase:) expect(response).to include( success: false, error_message: "Payment declined", permalink: usd_product.unique_permalink, name: usd_product.name, formatted_price: "$15", error_code: "insufficient_funds", is_tax_mismatch: false, ip_country: purchase.ip_country, ) end it "returns formatted price using USD total transaction cents" do purchase = create(:failed_purchase, link: eur_product, total_transaction_cents: 25_00, error_code: "generic_decline") response = test_instance.send(:error_response, "Payment declined", purchase:) expect(response[:formatted_price]).to eq("$25") end it "sets is_tax_mismatch to true when error_code is TAX_VALIDATION_FAILED" do purchase = create(:failed_purchase, link: usd_product, total_transaction_cents: 10_00, error_code: PurchaseErrorCode::TAX_VALIDATION_FAILED) response = test_instance.send(:error_response, "Tax validation failed", purchase:) expect(response[:is_tax_mismatch]).to eq(true) expect(response[:error_code]).to eq(PurchaseErrorCode::TAX_VALIDATION_FAILED) end it "handles CN card country code correctly" do purchase = create(:failed_purchase, link: usd_product, total_transaction_cents: 10_00, card_country: "C2") response = test_instance.send(:error_response, "Payment failed", purchase:) expect(response[:card_country]).to eq("China") end it "handles nil purchase gracefully" do response = test_instance.send(:error_response, "Generic error", purchase: nil) expect(response).to include( success: false, error_message: "Generic error", name: nil, formatted_price: "$0", error_code: nil, is_tax_mismatch: false ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/order/create_service_spec.rb
spec/services/order/create_service_spec.rb
# frozen_string_literal: false require "shared_examples/order_association_with_cart_post_checkout" describe Order::CreateService, :vcr do let(:seller_1) { create(:user) } let(:seller_2) { create(:user) } let(:price_1) { 5_00 } let(:price_2) { 10_00 } let(:price_3) { 10_00 } let(:price_4) { 10_00 } let(:price_5) { 10_00 } let(:product_1) { create(:product, user: seller_1, price_cents: price_1) } let(:product_2) { create(:product, user: seller_1, price_cents: price_2) } let(:product_3) { create(:product, user: seller_1, price_cents: price_3) } let(:product_4) { create(:product, user: seller_2, price_cents: price_4) } let(:product_5) { create(:product, user: seller_2, price_cents: price_5, discover_fee_per_thousand: 300) } let(:browser_guid) { SecureRandom.uuid } let(:common_order_params_without_payment) do { email: "buyer@gumroad.com", cc_zipcode: "12345", purchase: { full_name: "Edgar Gumstein", street_address: "123 Gum Road", country: "US", state: "CA", city: "San Francisco", zip_code: "94117" }, browser_guid:, ip_address: "0.0.0.0", session_id: "a107d0b7ab5ab3c1eeb7d3aaf9792977", is_mobile: false, } end let(:params) do { line_items: [ { uid: "unique-id-0", permalink: product_1.unique_permalink, perceived_price_cents: product_1.price_cents, quantity: 1 }, { uid: "unique-id-1", permalink: product_2.unique_permalink, perceived_price_cents: product_2.price_cents, quantity: 1 }, { uid: "unique-id-2", permalink: product_3.unique_permalink, perceived_price_cents: product_3.price_cents, quantity: 1 }, { uid: "unique-id-3", permalink: product_4.unique_permalink, perceived_price_cents: product_4.price_cents, quantity: 1 }, { uid: "unique-id-4", permalink: product_5.unique_permalink, perceived_price_cents: product_5.price_cents, quantity: 1 } ] }.merge(common_order_params_without_payment) end describe "#perform" do it "creates an order along with the associated purchases in progress" do expect do expect do expect do order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq 5 end.to change { Order.count }.by 1 end.not_to change { Charge.count } end.to change { Purchase.count }.by 5 end it "calls Purchase::CreateService for all line items in params with is_part_of_combined_charge set to true" do params[:line_items].each do |line_item_params| expect(Purchase::CreateService).to receive(:new).with(product: Link.find_by(unique_permalink: line_item_params[:permalink]), params: hash_including(is_part_of_combined_charge: true), buyer: nil).and_call_original end order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq 5 expect(order.purchases.is_part_of_combined_charge.count).to eq 5 end it "sets all the common fields on all purchases correctly" do order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq 5 expect(order.purchases.pluck(:email).uniq).to eq([common_order_params_without_payment[:email]]) expect(order.purchases.pluck(:browser_guid).uniq).to eq([common_order_params_without_payment[:browser_guid]]) expect(order.purchases.pluck(:session_id).uniq).to eq([common_order_params_without_payment[:session_id]]) expect(order.purchases.pluck(:is_mobile).uniq).to eq([common_order_params_without_payment[:is_mobile]]) expect(order.purchases.pluck(:ip_address).uniq).to eq([common_order_params_without_payment[:ip_address]]) expect(order.purchases.pluck(:full_name).uniq).to eq([common_order_params_without_payment[:purchase][:full_name]]) expect(order.purchases.pluck(:street_address).uniq).to eq([common_order_params_without_payment[:purchase][:street_address]]) expect(order.purchases.pluck(:state).uniq).to eq([common_order_params_without_payment[:purchase][:state]]) expect(order.purchases.pluck(:city).uniq).to eq([common_order_params_without_payment[:purchase][:city]]) expect(order.purchases.pluck(:zip_code).uniq).to eq([common_order_params_without_payment[:purchase][:zip_code]]) end it "sets the buyer when provided" do buyer = create(:user, email: "buyer@gumroad.com") order, _ = Order::CreateService.new(params:, buyer:).perform expect(order.purchaser).to eq buyer end it_behaves_like "order association with cart post checkout" do let(:user) { create(:buyer_user) } let(:sign_in_user_action) { @signed_in = true } let(:call_action) { Order::CreateService.new(params:, buyer: @signed_in ? user : nil).perform } let(:browser_guid) { "123" } before do params[:browser_guid] = browser_guid end end it "saves the referrer info correctly" do params[:line_items][0][:referrer] = "https://facebook.com" params[:line_items][1][:referrer] = "https://google.com" order, _ = Order::CreateService.new(params:).perform expect(order.purchases.first.referrer).to eq "https://facebook.com" expect(order.purchases.second.referrer).to eq "https://google.com" end it "returns failure responses with correct errors for purchases that fail" do product_2.update!(max_purchase_count: 2) params[:line_items][1][:quantity] = 3 params[:line_items][3][:permalink] = "non-existent" order, purchase_responses, _ = Order::CreateService.new(params:).perform expect(order.purchases.count).to eq(4) expect(order.purchases.in_progress.count).to eq(3) expect(order.purchases.failed.count).to eq(1) expect(purchase_responses.size).to eq(2) expect(purchase_responses[params[:line_items][1][:uid]]).to include( success: false, error_message: "You have chosen a quantity that exceeds what is available.", name: "The Works of Edgar Gumstein", error_code: "exceeding_product_quantity") expect(purchase_responses[params[:line_items][3][:uid]]).to include( success: false, error_message: "Product not found", name: nil, error_code: nil) end it "creates an order along with the associated purchases in progress when merchant account is a Brazilian Stripe Connect account" do seller_2.update!(check_merchant_account_is_linked: true) create(:merchant_account_stripe_connect, charge_processor_merchant_id: "acct_1QADdCGy0w4tFIUe", country: "BR", user: seller_2) expect do expect do expect do order, _ = Order::CreateService.new(params:).perform expect(order.purchases.in_progress.count).to eq 5 end.to change { Order.count }.by 1 end.not_to change { Charge.count } end.to change { Purchase.count }.by 5 end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/helper/client_spec.rb
spec/services/helper/client_spec.rb
# frozen_string_literal: true require "spec_helper" describe Helper::Client do let(:helper) { Helper::Client.new } let(:conversation_id) { "123456" } let(:timestamp) { DateTime.current.to_i } describe "#create_hmac_digest" do let(:secret_key) { "secret_key" } before do allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_SECRET").and_return(secret_key) end context "when payload is query params" do it "creates a digest from url-encoded payload" do params = { key: "value", timestamp: } expected_digest = OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), secret_key, params.to_query) expect(helper.create_hmac_digest(params:)).to eq(expected_digest) end end context "when payload is JSON" do it "creates a digest from JSON string" do json = { key: "value", timestamp: } expected_digest = OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), secret_key, json.to_json) expect(helper.create_hmac_digest(json:)).to eq(expected_digest) end end context "when both params and json are provided" do it "raises an error" do params = { key: "value", timestamp: } json = { another_key: "another_value", timestamp: } expect { helper.create_hmac_digest(params:, json:) }.to raise_error(RuntimeError, "Either params or json must be provided, but not both") end end context "when neither params nor json are provided" do it "raises an error" do expect { helper.create_hmac_digest }.to raise_error(RuntimeError, "Either params or json must be provided, but not both") end end end describe "#close_conversation" do it "sends a PATCH request to close the conversation" do stub_request(:patch, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/") .with( body: hash_including(status: "closed", timestamp: instance_of(Integer)), headers: { "Content-Type" => "application/json" } ) .to_return(status: 200) expect(helper.close_conversation(conversation_id:)).to be true end context "when the request fails" do it "notifies Bugsnag" do stub_request(:patch, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/") .with( body: hash_including(status: "closed", timestamp: instance_of(Integer)), headers: { "Content-Type" => "application/json" } ) .to_return(status: 422) expect(Bugsnag).to receive(:notify).with("Helper error: could not close conversation", conversation_id:) expect(helper.close_conversation(conversation_id:)).to be false end end end describe "#send_reply" do let(:message) { "Test reply message" } it "sends a POST request to send a reply" do stub_request(:post, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/emails/") .to_return(status: 200) expect(helper.send_reply(conversation_id:, message:)).to be true end it "sends a POST request to send a draft" do stub_request(:post, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/emails/") .with(body: hash_including(message:, draft: true, timestamp: instance_of(Integer))) .to_return(status: 200) expect(helper.send_reply(conversation_id:, message:, draft: true)).to be true end it "handles optional response_to" do response_to = "previous_message_id" stub_request(:post, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/emails/") .with(body: hash_including(response_to:, timestamp: instance_of(Integer))) .to_return(status: 200) expect(helper.send_reply(conversation_id:, message:, response_to:)).to be true end context "when the request fails" do it "notifies Bugsnag" do stub_request(:post, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/emails/") .to_return(status: 422) expect(Bugsnag).to receive(:notify).with("Helper error: could not send reply", conversation_id:, message:) expect(helper.send_reply(conversation_id:, message:)).to be false end end end describe "#add_note" do let(:message) { "Test note message" } it "sends a POST request to add a note" do stub_request(:post, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/notes/") .with(body: hash_including(message: message, timestamp: instance_of(Integer))) .to_return(status: 200) expect(helper.add_note(conversation_id:, message:)).to be true end context "when the request fails" do it "notifies Bugsnag" do stub_request(:post, "https://api.helper.ai/api/v1/mailboxes/gumroad/conversations/#{conversation_id}/notes/") .to_return(status: 422) expect(Bugsnag).to receive(:notify).with("Helper error: could not add note", conversation_id:, message:) expect(helper.add_note(conversation_id:, message:)).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/services/helper/unblock_email_service_spec.rb
spec/services/helper/unblock_email_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Helper::UnblockEmailService do include ActionView::Helpers::TextHelper describe "#process" do let(:conversation_id) { "123" } let(:email_id) { "456" } let(:email) { "sam@example.com" } let(:unblock_email_service) { described_class.new(conversation_id:, email_id:, email:) } before do create(:user, email:) allow_any_instance_of(Helper::Client).to receive(:add_note).and_return(true) allow_any_instance_of(Helper::Client).to receive(:send_reply).and_return(true) allow_any_instance_of(Helper::Client).to receive(:close_conversation).and_return(true) allow_any_instance_of(EmailSuppressionManager).to receive(:unblock_email).and_return(true) allow_any_instance_of(EmailSuppressionManager).to receive(:reasons_for_suppression).and_return({}) Feature.activate(:helper_unblock_emails) end it "returns nil when feature is not active" do Feature.deactivate(:helper_unblock_emails) expect(unblock_email_service.process).to be_nil end context "when email is blocked by gumroad" do let(:reply) do <<~REPLY Hey there, Happy to help today! We noticed your purchase attempts failed as they were flagged as potentially fraudulent. Don’t worry, our system can occasionally throw a false alarm. We have removed these blocks, so could you please try making the purchase again? In case it still fails, we recommend trying with a different browser and/or a different internet connection. If those attempts still don't work, feel free to write back to us and we will investigate further. Thanks! REPLY end before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], email, nil) end context "when recent blocked purchase is present" do let(:blocked_ip_address) { "127.0.0.1" } let(:recent_blocked_purchase) { create(:purchase, email:, ip_address: blocked_ip_address) } before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], blocked_ip_address, nil, expires_in: 1.month) end it "unblocks the buyer" do expect do unblock_email_service.recent_blocked_purchase = recent_blocked_purchase unblock_email_service.process expect(unblock_email_service.replied?).to eq true end.to change { recent_blocked_purchase.buyer_blocked? }.from(true).to(false) end context "when auto_reply_for_blocked_emails_in_helper feature is active" do before do Feature.activate(:auto_reply_for_blocked_emails_in_helper) end it "sends reply to the customer and closes the conversation" do expect_any_instance_of(Helper::Client).to receive(:send_reply).with(conversation_id:, message: simple_format(reply)) expect_any_instance_of(Helper::Client).to receive(:close_conversation).with(conversation_id:) unblock_email_service.recent_blocked_purchase = recent_blocked_purchase unblock_email_service.process end end context "when auto_reply_for_blocked_emails_in_helper feature is not active" do it "drafts the reply" do expect_any_instance_of(Helper::Client).to receive(:send_reply).with(conversation_id:, message: simple_format(reply), draft: true, response_to: email_id) unblock_email_service.recent_blocked_purchase = recent_blocked_purchase unblock_email_service.process end end end context "when recent blocked purchase is not present" do before do Feature.activate(:auto_reply_for_blocked_emails_in_helper) end it "unblocks the email" do expect do expect_any_instance_of(Helper::Client).to receive(:send_reply).with(conversation_id:, message: simple_format(reply)) expect_any_instance_of(Helper::Client).to receive(:close_conversation).with(conversation_id:) unblock_email_service.process end.to change { BlockedObject.email.find_active_object(email).present? }.from(true).to(false) end end end context "when email is suppressed by SendGrid" do let(:reply) do <<~REPLY Hey, Sorry about that! It seems our email provider stopped sending you emails after a few of them bounced. I’ve fixed this and you should now start receiving emails as usual. Please let us know if you don't and we'll take a closer look! Also, please add our email to your contacts list and ensure that you haven't accidentally marked any emails from us as spam. Hope this helps! REPLY end context "when reasons for suppressions are present" do before do reasons_for_suppression = { gumroad: [{ list: :bounces, reason: "Bounced reason 1" }, { list: :spam_reports, reason: "Email was reported as spam" }], creators: [{ list: :bounces, reason: "Bounced reason 2" }] } allow_any_instance_of(EmailSuppressionManager).to receive(:reasons_for_suppression).and_return(reasons_for_suppression) end it "adds as a note to the conversation" do expected_reasons = <<~REASONS.chomp • The email sam@example.com was suppressed in SendGrid. Subuser: gumroad, List: bounces, Reason: Bounced reason 1 • The email sam@example.com was suppressed in SendGrid. Subuser: gumroad, List: spam_reports, Reason: Email was reported as spam • The email sam@example.com was suppressed in SendGrid. Subuser: creators, List: bounces, Reason: Bounced reason 2 REASONS expect_any_instance_of(Helper::Client).to receive(:add_note).with(conversation_id:, message: expected_reasons) unblock_email_service.process end end context "when auto_reply_for_blocked_emails_in_helper feature is active" do before do Feature.activate(:auto_reply_for_blocked_emails_in_helper) end it "unblocks email and sends reply to the customer and closes the conversation" do expect_any_instance_of(EmailSuppressionManager).to receive(:unblock_email) expect_any_instance_of(Helper::Client).to receive(:send_reply).with(conversation_id:, message: simple_format(reply)) expect_any_instance_of(Helper::Client).to receive(:close_conversation).with(conversation_id:) unblock_email_service.process expect(unblock_email_service.replied?). to eq true end end context "when auto_reply_for_blocked_emails_in_helper feature is not active" do before do Feature.deactivate(:auto_reply_for_blocked_emails_in_helper) end it "unblocks email and drafts the reply" do expect_any_instance_of(EmailSuppressionManager).to receive(:unblock_email) expect_any_instance_of(Helper::Client).to receive(:send_reply).with(conversation_id:, message: simple_format(reply), draft: true, response_to: email_id) unblock_email_service.process expect(unblock_email_service.replied?). to eq true end end context "when email is not found in SendGrid suppression lists" do before do allow_any_instance_of(EmailSuppressionManager).to receive(:unblock_email).and_return(false) end it "doesn't send a reply" do expect_any_instance_of(Helper::Client).not_to receive(:send_reply) unblock_email_service.process end end context "when a reply is already sent" do before do allow_any_instance_of(Helper::UnblockEmailService).to receive(:replied?).and_return(true) end it "unblocks email and doesn't send a reply again" do expect_any_instance_of(EmailSuppressionManager).to receive(:unblock_email) expect_any_instance_of(Helper::Client).not_to receive(:send_reply) unblock_email_service.process end end end context "when email is blocked by creator" do let(:reply) do <<~REPLY Hey there, It looks like a creator has blocked you from purchasing their products. Please reach out to them directly to resolve this. Feel free to write back to us if you have any questions. Thanks! REPLY end before do allow_any_instance_of(EmailSuppressionManager).to receive(:unblock_email).and_return(false) BlockedCustomerObject.block_email!(email:, seller_id: create(:user).id) end context "when auto_reply_for_blocked_emails_in_helper feature is active" do before do Feature.activate(:auto_reply_for_blocked_emails_in_helper) end it "drafts the reply" do expect_any_instance_of(Helper::Client).to receive(:send_reply).with(conversation_id:, message: simple_format(reply), draft: true, response_to: email_id) unblock_email_service.process end end context "when auto_reply_for_blocked_emails_in_helper feature is not active" do before do Feature.deactivate(:auto_reply_for_blocked_emails_in_helper) end it "drafts a reply" do expect_any_instance_of(Helper::Client).to receive(:send_reply).with(conversation_id:, message: simple_format(reply), draft: true, response_to: email_id) unblock_email_service.process 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/services/onetime/compile_gumroad_daily_analytics_from_beginning_spec.rb
spec/services/onetime/compile_gumroad_daily_analytics_from_beginning_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::CompileGumroadDailyAnalyticsFromBeginning do it "compiles analytics from the start of Gumroad" do stub_const("GUMROAD_STARTED_DATE", Date.parse("2023-01-01")) allow(Date).to receive(:today).and_return(Date.new(2023, 1, 15)) expect(GumroadDailyAnalytic).to receive(:import).exactly(15).times.and_call_original Onetime::CompileGumroadDailyAnalyticsFromBeginning.process expect(GumroadDailyAnalytic.all.size).to eq(15) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/revert_to_product_level_refund_policies_spec.rb
spec/services/onetime/revert_to_product_level_refund_policies_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Onetime::RevertToProductLevelRefundPolicies do describe ".reset_last_processed_id" do before do $redis.set(described_class::LAST_PROCESSED_ID_KEY, 123) end it "clears the last processed ID" do expect { described_class.reset_last_processed_id }.to change { $redis.get(described_class::LAST_PROCESSED_ID_KEY) }.from("123").to(nil) end end describe "#initialize" do let!(:seller) { create(:user, refund_policy_enabled: true) } let(:seller_ids) { [seller.id] } it "accepts seller IDs directly" do service = described_class.new(seller_ids: seller_ids) expect(service.seller_ids).to eq(seller_ids) end it "raises error when seller_ids is empty" do expect { described_class.new(seller_ids: []) }.to raise_error(ArgumentError, /Seller ids not found/) end end describe "#process" do let!(:seller_with_refund) { create(:user) } before do described_class.reset_last_processed_id allow(Rails.logger).to receive(:info) allow(ReplicaLagWatcher).to receive(:watch) seller_with_refund.update!(refund_policy_enabled: true) end it "watches for replica lag" do service = described_class.new(seller_ids: [seller_with_refund.id]) service.process expect(ReplicaLagWatcher).to have_received(:watch) end it "skips sellers that were already processed in previous runs" do $redis.set(described_class::LAST_PROCESSED_ID_KEY, 0) service = described_class.new(seller_ids: [seller_with_refund.id]) service.process expect(Rails.logger).to have_received(:info).with(/Seller: #{seller_with_refund.id}.*skipped \(already processed in previous run\)/) end it "skips inactive sellers" do allow_any_instance_of(User).to receive(:account_active?).and_return(false) service = described_class.new(seller_ids: [seller_with_refund.id]) expect do service.process end.not_to have_enqueued_mail(ContactingCreatorMailer, :product_level_refund_policies_reverted) expect(Rails.logger).to have_received(:info).with(/Seller: #{seller_with_refund.id}.*skipped \(not active\)/) end it "processes active sellers with refund_policy_enabled=true" do service = described_class.new(seller_ids: [seller_with_refund.id]) expect do service.process end.to have_enqueued_mail(ContactingCreatorMailer, :product_level_refund_policies_reverted).with(seller_with_refund.id) expect(Rails.logger).to have_received(:info).with(/Seller: #{seller_with_refund.id}.*processed and email sent/) expect(seller_with_refund.reload.refund_policy_enabled?).to be false end it "does not send emails to sellers with refund_policy_enabled=false" do seller_without_refund = create(:user) seller_without_refund.update!(refund_policy_enabled: false) service = described_class.new(seller_ids: [seller_without_refund.id]) expect do service.process end.not_to have_enqueued_mail(ContactingCreatorMailer, :product_level_refund_policies_reverted) expect(Rails.logger).to have_received(:info).with(/Seller: #{seller_without_refund.id}.*skipped \(already processed\)/) end it "updates Redis with the last processed index" do service = described_class.new(seller_ids: [seller_with_refund.id]) allow($redis).to receive(:set).and_call_original service.process expect($redis).to have_received(:set).with( described_class::LAST_PROCESSED_ID_KEY, kind_of(Integer), ex: 1.month ).once end it "handles errors during processing and tracks invalid seller IDs" do error_seller = create(:user) error_seller.update_column(:flags, error_seller.flags | (1 << 46)) expect(error_seller.refund_policy_enabled?).to be true service = described_class.new(seller_ids: [seller_with_refund.id, error_seller.id]) allow(User).to receive(:find).and_call_original allow(User).to receive(:find).with(error_seller.id).and_raise(StandardError.new("Test error")) expect do service.process end.to have_enqueued_mail(ContactingCreatorMailer, :product_level_refund_policies_reverted).with(seller_with_refund.id) .and not_have_enqueued_mail(ContactingCreatorMailer, :product_level_refund_policies_reverted).with(error_seller.id) expect(service.invalid_seller_ids).to include(a_hash_including(error_seller.id => "Test error")) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/notify_sellers_with_refund_policies_spec.rb
spec/services/onetime/notify_sellers_with_refund_policies_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::NotifySellersWithRefundPolicies do let(:seller_one) { create(:user) } let(:seller_two) { create(:user) } let(:product_one) { create(:product, user: seller_one) } let(:product_two) { create(:product, user: seller_two) } let!(:product_refund_policy_one) { create(:product_refund_policy, product: product_one) } let!(:product_refund_policy_two) { create(:product_refund_policy, product: product_two) } describe ".reset_last_processed_seller_id" do it "deletes the redis key" do $redis.set(described_class::LAST_PROCESSED_ID_KEY, 123) described_class.reset_last_processed_seller_id expect($redis.get(described_class::LAST_PROCESSED_ID_KEY)).to be_nil end end describe "#process" do subject(:process) { described_class.new(max_id: product_refund_policy_two.id).process } it "sends emails to all eligible sellers" do expect do process end.to have_enqueued_mail(ContactingCreatorMailer, :upcoming_refund_policy_change).with(seller_one.id) .and have_enqueued_mail(ContactingCreatorMailer, :upcoming_refund_policy_change).with(seller_two.id) end it "marks all eligible sellers as notified" do expect do process end.to change { seller_one.reload.upcoming_refund_policy_change_email_sent? }.from(false).to(true) .and change { seller_two.reload.upcoming_refund_policy_change_email_sent? }.from(false).to(true) end it "updates the last processed id in redis" do process expect($redis.get(described_class::LAST_PROCESSED_ID_KEY).to_i).to eq(product_refund_policy_two.id) end context "when one seller was already notified" do before do seller_one.update!(upcoming_refund_policy_change_email_sent: true) end it "only sends email to non-notified seller" do expect do process end.to have_enqueued_mail(ContactingCreatorMailer, :upcoming_refund_policy_change).with(seller_two.id) .exactly(:once) end it "does not update already notified seller" do expect do process end.to not_change { seller_one.reload.upcoming_refund_policy_change_email_sent? } .and change { seller_two.reload.upcoming_refund_policy_change_email_sent? }.from(false).to(true) end end context "when product_refund_policy has no product" do before do product_refund_policy_one.update_column(:product_id, nil) end it "only processes seller with valid product" do expect do process end.to have_enqueued_mail(ContactingCreatorMailer, :upcoming_refund_policy_change).with(seller_two.id) .exactly(:once) end it "only updates seller with valid product" do expect do process end.to not_change { seller_one.reload.upcoming_refund_policy_change_email_sent? } .and change { seller_two.reload.upcoming_refund_policy_change_email_sent? }.from(false).to(true) end end context "when there's a last processed id in redis" do before do $redis.set(described_class::LAST_PROCESSED_ID_KEY, product_refund_policy_one.id) end it "only processes records after the last processed id" do expect do process end.to have_enqueued_mail(ContactingCreatorMailer, :upcoming_refund_policy_change).with(seller_two.id) .exactly(:once) end it "only updates sellers after the last processed id" do expect do process end.to not_change { seller_one.reload.upcoming_refund_policy_change_email_sent? } .and change { seller_two.reload.upcoming_refund_policy_change_email_sent? }.from(false).to(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/services/onetime/send_gumroad_day_fee_saved_email_spec.rb
spec/services/onetime/send_gumroad_day_fee_saved_email_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::SendGumroadDayFeeSavedEmail do before do @eligible_seller_1 = create(:user, gumroad_day_timezone: "Pacific Time (US & Canada)") create(:purchase, price_cents: 206_20, link: create(:product, user: @eligible_seller_1), created_at: DateTime.new(2024, 4, 4, 12, 0, 0, "-07:00")) @eligible_seller_2 = create(:user, gumroad_day_timezone: "Mumbai") create(:purchase, price_cents: 106_20, link: create(:product, user: @eligible_seller_2), created_at: DateTime.new(2024, 4, 4, 12, 0, 0, "+05:30")) @ineligible_seller_1 = create(:user, timezone: "Melbourne") create(:purchase, price_cents: 206_20, link: create(:product, user: @ineligible_seller_1), created_at: DateTime.new(2024, 4, 3, 12, 0, 0, "+11:00")) @ineligible_seller_2 = create(:user, gumroad_day_timezone: "Pacific Time (US & Canada)") create(:free_purchase, link: create(:product, user: @ineligible_seller_2), created_at: DateTime.new(2024, 4, 4, 12, 0, 0, "-07:00")) @eligible_seller_3 = create(:user, gumroad_day_timezone: "Melbourne") create(:purchase, price_cents: 100_00, link: create(:product, user: @eligible_seller_3), created_at: DateTime.new(2024, 4, 4, 12, 0, 0, "+11:00")) @eligible_seller_4 = create(:user, gumroad_day_timezone: "UTC") create(:purchase, price_cents: 10_00, link: create(:product, user: @eligible_seller_4), created_at: DateTime.new(2024, 4, 4, 12, 0, 0)) @eligible_seller_5 = create(:user, gumroad_day_timezone: "Eastern Time (US & Canada)") create(:purchase, price_cents: 25_00, link: create(:product, user: @eligible_seller_5), created_at: DateTime.new(2024, 4, 4, 12, 0, 0, "-04:00")) end it "enqueues the email for correct users with proper arguments" do expect do described_class.process end.to have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_1.id).once .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_2.id).once .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_3.id).once .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_4.id).once .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_5.id).once .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @ineligible_seller_1.id).exactly(0).times .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @ineligible_seller_2.id).exactly(0).times expect($redis.get("gumroad_day_fee_saved_email_last_user_id").to_i).to eq @eligible_seller_5.id end context "when email has already been sent to some users" do before do $redis.set("gumroad_day_fee_saved_email_last_user_id", @eligible_seller_3.id) end it "does not enqueue for users who have already been sent the email" do expect($redis.get("gumroad_day_fee_saved_email_last_user_id").to_i).to eq @eligible_seller_3.id expect do described_class.process end.to have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_1.id).exactly(0).times .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_2.id).exactly(0).times .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_3.id).exactly(0).times .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_4.id).once .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @eligible_seller_5.id).once .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @ineligible_seller_1.id).exactly(0).times .and have_enqueued_mail(CreatorMailer, :gumroad_day_fee_saved).with(seller_id: @ineligible_seller_2.id).exactly(0).times expect($redis.get("gumroad_day_fee_saved_email_last_user_id").to_i).to eq @eligible_seller_5.id end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/index_products_with_allowed_offer_codes_spec.rb
spec/services/onetime/index_products_with_allowed_offer_codes_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::IndexProductsWithAllowedOfferCodes do let(:creator) { create(:user) } let(:product1) { create(:product, user: creator) } let(:product2) { create(:product, user: creator) } let(:product3) { create(:product, user: creator) } describe ".process", :sidekiq_inline do context "elasticsearch indexing", :elasticsearch_wait_for_refresh do before do Link.__elasticsearch__.create_index!(force: true) end context "with product-specific offer codes" do it "indexes offer codes into product documents" do product1.__elasticsearch__.index_document product2.__elasticsearch__.index_document es_product1 = Link.search(query: { term: { _id: product1.id } }).results.first es_product2 = Link.search(query: { term: { _id: product2.id } }).results.first expect(es_product1).to be_present expect(es_product2).to be_present expect(es_product1._source.offer_codes).to eq([]) expect(es_product2._source.offer_codes).to eq([]) create(:offer_code, user: creator, code: "BLACKFRIDAY2025", products: [product1, product2]) described_class.process es_product1 = Link.search(query: { term: { _id: product1.id } }).results.first es_product2 = Link.search(query: { term: { _id: product2.id } }).results.first expect(es_product1._source.offer_codes).to eq(["BLACKFRIDAY2025"]) expect(es_product2._source.offer_codes).to eq(["BLACKFRIDAY2025"]) end end context "with universal offer codes" do it "indexes universal offer codes into all matching product documents" do product1.__elasticsearch__.index_document product2.__elasticsearch__.index_document product3.__elasticsearch__.index_document es_product1 = Link.search(query: { term: { _id: product1.id } }).results.first expect(es_product1._source.offer_codes).to eq([]) create(:offer_code, user: creator, code: "BLACKFRIDAY2025", universal: true, currency_type: product1.price_currency_type, amount_percentage: 20) described_class.process es_product1 = Link.search(query: { term: { _id: product1.id } }).results.first es_product2 = Link.search(query: { term: { _id: product2.id } }).results.first es_product3 = Link.search(query: { term: { _id: product3.id } }).results.first expect(es_product1._source.offer_codes).to eq(["BLACKFRIDAY2025"]) expect(es_product2._source.offer_codes).to eq(["BLACKFRIDAY2025"]) expect(es_product3._source.offer_codes).to eq(["BLACKFRIDAY2025"]) 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/services/onetime/enable_refund_policy_for_sellers_without_refund_policies_spec.rb
spec/services/onetime/enable_refund_policy_for_sellers_without_refund_policies_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Onetime::EnableRefundPolicyForSellersWithoutRefundPolicies do let(:service) { described_class.new } describe ".reset_last_processed_seller_id" do it "deletes the redis key" do $redis.set(described_class::LAST_PROCESSED_SELLER_ID_KEY, 123) described_class.reset_last_processed_seller_id expect($redis.get(described_class::LAST_PROCESSED_SELLER_ID_KEY)).to be_nil end end describe "#process" do let!(:seller1) { create(:user, username: "seller1") } let!(:seller2) { create(:user, username: "seller2") } let!(:seller_with_product_policy) { create(:user, username: "sellerwithpolicies") } let!(:product) { create(:product, user: seller_with_product_policy) } let!(:product_refund_policy) { create(:product_refund_policy, product:, seller: seller_with_product_policy) } before do seller1.update!(refund_policy_enabled: false) seller2.update!(refund_policy_enabled: false) seller_with_product_policy.update!(refund_policy_enabled: false) described_class.reset_last_processed_seller_id end it "enables refund policy for eligible sellers" do service.process expect(seller1.reload.refund_policy_enabled?).to be true expect(seller2.reload.refund_policy_enabled?).to be true end it "skips sellers who have product refund policies" do service.process expect(seller_with_product_policy.reload.refund_policy_enabled?).to be false end it "processes sellers in batches and updates redis key" do allow(ReplicaLagWatcher).to receive(:watch) service.process expect(ReplicaLagWatcher).to have_received(:watch) expect($redis.get(described_class::LAST_PROCESSED_SELLER_ID_KEY).to_i).to eq(User.last.id) end context "when resuming from last processed id" do before do $redis.set(described_class::LAST_PROCESSED_SELLER_ID_KEY, seller1.id) end it "starts from the next seller after last processed id" do service.process expect(seller1.reload.refund_policy_enabled?).to be false expect(seller2.reload.refund_policy_enabled?).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/services/onetime/email_creators_quarterly_recap_spec.rb
spec/services/onetime/email_creators_quarterly_recap_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::EmailCreatorsQuarterlyRecap do let(:start_time) { 89.days.ago } let(:end_time) { 1.day.from_now } let(:installment) { create(:installment, allow_comments: false) } let(:service) { described_class.new(installment_external_id: installment&.external_id, start_time:, end_time:) } it "sends an email to users with a sale in the last 90 days" do purchase = create(:purchase) expect do service.process end.to have_enqueued_mail(OneOffMailer, :email_using_installment).with( email: purchase.seller.form_email, installment_external_id: installment.external_id, reply_to: described_class::DEFAULT_REPLY_TO_EMAIL ).once end it "does not send an email to users with no sales in the last 90 days" do create(:purchase, created_at: 100.days.ago) expect do service.process end.to_not have_enqueued_mail(OneOffMailer, :email_using_installment) end it "does not send an email to deleted or suspended users" do deleted_user = create(:user, :deleted) deleted_user_product = create(:product, user: deleted_user) tos_user = create(:tos_user) tos_user_product = create(:product, user: tos_user) create(:purchase, created_at: 100.days.ago) create(:purchase, seller: deleted_user, link: deleted_user_product) create(:purchase, seller: tos_user, link: tos_user_product) expect do service.process end.to_not have_enqueued_mail(OneOffMailer, :email_using_installment) end context "when the provided installment is not found" do let(:installment) { nil } it "does not send the email" do create(:purchase) expect do service.process end.to raise_error("Installment not found") end end it "does not send the email if the provided installment is published" do create(:purchase) installment.update!(published_at: Time.current) expect do service.process end.to raise_error("Installment must not be published or scheduled to publish") end it "does not send the email if the installment allows comments" do create(:purchase) installment.update!(allow_comments: true) expect do service.process end.to raise_error("Installment must not allow comments") end context "when the provided time range is too short" do let(:start_time) { 10.days.ago } it "does not send the email" do create(:purchase) expect do service.process end.to raise_error("Date range must be at least 85 days") end end it "skips sending the email to users in the skip_user_ids list" do purchase1 = create(:purchase) purchase2 = create(:purchase) expect do expect do described_class.new(installment_external_id: installment.external_id, start_time:, end_time:, skip_user_ids: [purchase1.seller.id]).process end.to have_enqueued_mail(OneOffMailer, :email_using_installment).with(installment_external_id: installment.external_id, email: purchase2.seller.form_email, reply_to: described_class::DEFAULT_REPLY_TO_EMAIL) end.to_not have_enqueued_mail(OneOffMailer, :email_using_installment).with(installment_external_id: installment.external_id, email: purchase1.seller.form_email, reply_to: described_class::DEFAULT_REPLY_TO_EMAIL) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/remove_stale_recipients_spec.rb
spec/services/onetime/remove_stale_recipients_spec.rb
# frozen_string_literal: true RSpec.describe Onetime::RemoveStaleRecipients do describe ".process" do let(:follower) { create(:follower) } let(:purchase) { create(:purchase, can_contact: true) } let(:timestamp) { Time.current } before do Feature.activate(:log_email_events) end context "when processing followers" do it "marks stale followers as deleted and records stale timestamp" do freeze_time do EmailEvent.log_send_events(follower.email, timestamp) event = EmailEvent.find_by(email_digest: Digest::SHA1.hexdigest(follower.email).first(12)) event.update!( first_unopened_email_sent_at: 366.days.ago, unopened_emails_count: 10 ) described_class.process expect(follower.reload.deleted?).to be true expect(event.reload.marked_as_stale_at).to eq Time.current end end it "does not mark non-stale followers as deleted" do freeze_time do EmailEvent.log_send_events(follower.email, timestamp) event = EmailEvent.find_by(email_digest: Digest::SHA1.hexdigest(follower.email).first(12)) event.update!( first_unopened_email_sent_at: 364.days.ago, unopened_emails_count: 10 ) described_class.process expect(follower.reload.deleted?).to be false expect(event.reload.marked_as_stale_at).to be_nil end end end context "when processing purchases" do it "marks stale purchase emails as uncontactable and records stale timestamp" do freeze_time do EmailEvent.log_send_events(purchase.email, timestamp) event = EmailEvent.find_by(email_digest: Digest::SHA1.hexdigest(purchase.email).first(12)) event.update!( first_unopened_email_sent_at: 366.days.ago, unopened_emails_count: 10 ) described_class.process expect(purchase.reload.can_contact).to be false expect(event.reload.marked_as_stale_at).to eq Time.current end end it "does not mark non-stale purchase emails as uncontactable" do freeze_time do EmailEvent.log_send_events(purchase.email, timestamp) event = EmailEvent.find_by(email_digest: Digest::SHA1.hexdigest(purchase.email).first(12)) event.update!( first_unopened_email_sent_at: 364.days.ago, unopened_emails_count: 10 ) described_class.process expect(purchase.reload.can_contact).to be true expect(event.reload.marked_as_stale_at).to be_nil 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/services/onetime/enable_refund_policy_for_sellers_with_refund_policies_spec.rb
spec/services/onetime/enable_refund_policy_for_sellers_with_refund_policies_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Onetime::EnableRefundPolicyForSellersWithRefundPolicies do let(:service) { described_class.new } describe ".reset_last_processed_seller_id" do it "deletes the redis key" do $redis.set(described_class::LAST_PROCESSED_ID_KEY, 123) described_class.reset_last_processed_seller_id expect($redis.get(described_class::LAST_PROCESSED_ID_KEY)).to be_nil end end describe "#process" do let!(:seller_without_policies) { create(:user) } let!(:seller_with_product_policy) { create(:user) } let!(:product) { create(:product, user: seller_with_product_policy) } let!(:product_refund_policy) { create(:product_refund_policy, product:, seller: seller_with_product_policy) } before do seller_without_policies.update!(refund_policy_enabled: false) seller_with_product_policy.update!(refund_policy_enabled: false) described_class.reset_last_processed_seller_id end it "enables refund policy for sellers with policies" do expect do service.process end.to have_enqueued_mail(ContactingCreatorMailer, :refund_policy_enabled_email).with(seller_with_product_policy.id) .and not_have_enqueued_mail(ContactingCreatorMailer, :refund_policy_enabled_email).with(seller_without_policies.id) expect(seller_with_product_policy.reload.refund_policy_enabled?).to be true expect(seller_with_product_policy.refund_policy.max_refund_period_in_days).to eq(30) expect(seller_without_policies.reload.refund_policy_enabled?).to be false end context "when the seller has all eligible refund policies as no refunds" do before do product_refund_policy.update!(max_refund_period_in_days: 0) end it "sets refund policy to no refunds for eligible sellers" do service.process refund_policy = seller_with_product_policy.reload.refund_policy expect(refund_policy.max_refund_period_in_days).to eq(0) end end it "processes sellers in batches and updates redis key" do allow(ReplicaLagWatcher).to receive(:watch) service.process expect(ReplicaLagWatcher).to have_received(:watch) expect($redis.get(described_class::LAST_PROCESSED_ID_KEY).to_i).to be > 0 end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/backfill_payment_option_installment_snapshots_spec.rb
spec/services/onetime/backfill_payment_option_installment_snapshots_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::BackfillPaymentOptionInstallmentSnapshots 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) } describe ".perform" do context "when payment_option has installment plan but no snapshot" do it "creates snapshot with correct attributes" do payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) original_purchase = build(:purchase, link: product, subscription: subscription, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 4900) original_purchase.save!(validate: false) second_purchase = build(:purchase, link: product, subscription: subscription, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) second_purchase.save!(validate: false) expect(payment_option.installment_plan_snapshot).to be_nil described_class.perform snapshot = payment_option.reload.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 context "when payment_option already has snapshot" do it "skips creating duplicate snapshot" do payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) original_snapshot = create(:installment_plan_snapshot, payment_option: payment_option, number_of_installments: 3, recurrence: "monthly", total_price_cents: 14700) expect do described_class.perform end.not_to change { InstallmentPlanSnapshot.count } expect(payment_option.reload.installment_plan_snapshot).to eq(original_snapshot) end end context "when payment_option has no installment plan" do it "skips creating snapshot" do regular_subscription = create(:subscription, is_installment_plan: false) payment_option = create(:payment_option, subscription: regular_subscription, installment_plan: nil) expect do described_class.perform end.not_to change { InstallmentPlanSnapshot.count } expect(payment_option.reload.installment_plan_snapshot).to be_nil end end context "when subscription has no original purchase" do it "skips creating snapshot" do payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) subscription.purchases.destroy_all expect do described_class.perform end.not_to change { InstallmentPlanSnapshot.count } expect(payment_option.reload.installment_plan_snapshot).to be_nil end end context "when error occurs during processing" do it "handles errors gracefully and continues processing" do subscription1 = create(:subscription, link: product, user: seller) payment_option1 = create(:payment_option, subscription: subscription1, installment_plan: installment_plan) purchase1 = build(:purchase, link: product, subscription: subscription1, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 4900) purchase1.save!(validate: false) purchase1_2 = build(:purchase, link: product, subscription: subscription1, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) purchase1_2.save!(validate: false) subscription2 = create(:subscription, link: product, user: seller) payment_option2 = create(:payment_option, subscription: subscription2, installment_plan: installment_plan) purchase2 = build(:purchase, link: product, subscription: subscription2, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 4900) purchase2.save!(validate: false) purchase2_2 = build(:purchase, link: product, subscription: subscription2, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) purchase2_2.save!(validate: false) allow(InstallmentPlanSnapshot).to receive(:create!).and_call_original allow(InstallmentPlanSnapshot).to receive(:create!) .with(hash_including(payment_option: payment_option1)) .and_raise(StandardError.new("Test error")) expect(Rails.logger).to receive(:error).with(/Failed to backfill PaymentOption #{payment_option1.id}/) described_class.perform expect(payment_option1.reload.installment_plan_snapshot).to be_nil expect(payment_option2.reload.installment_plan_snapshot).to be_present end end context "when processing multiple payment_options" do it "creates snapshots for all eligible payment_options" do payment_options = 3.times.map do |i| sub = create(:subscription, link: product, user: seller) payment_option = create(:payment_option, subscription: sub, installment_plan: installment_plan) purchase = build(:purchase, link: product, subscription: sub, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 4900) purchase.save!(validate: false) purchase2 = build(:purchase, link: product, subscription: sub, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) purchase2.save!(validate: false) payment_option end expect do described_class.perform end.to change { InstallmentPlanSnapshot.count }.by(3) payment_options.each do |payment_option| snapshot = payment_option.reload.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 end context "when deriving price from payment history" do it "calculates total from completed installments" do original_purchase = build(:purchase, link: product, subscription: subscription, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 5000, installment_plan: installment_plan) original_purchase.save!(validate: false) second_purchase = build(:purchase, link: product, subscription: subscription, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) second_purchase.save!(validate: false) third_purchase = build(:purchase, link: product, subscription: subscription, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) third_purchase.save!(validate: false) payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) described_class.perform snapshot = payment_option.reload.installment_plan_snapshot expect(snapshot.total_price_cents).to eq(14800) end it "extrapolates total from partial payment history" do original_purchase = build(:purchase, link: product, subscription: subscription, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 5000, installment_plan: installment_plan) original_purchase.save!(validate: false) second_purchase = build(:purchase, link: product, subscription: subscription, is_installment_payment: true, price_cents: 5000, installment_plan: installment_plan) second_purchase.save!(validate: false) payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) described_class.perform snapshot = payment_option.reload.installment_plan_snapshot expect(snapshot.total_price_cents).to eq(15000) end it "skips when only one payment exists" do original_purchase = build(:purchase, link: product, subscription: subscription, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 14700, installment_plan: installment_plan) original_purchase.save!(validate: false) payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) expect(Rails.logger).to receive(:info).with(/insufficient payment history/) described_class.perform expect(payment_option.reload.installment_plan_snapshot).to be_nil end it "reverse-engineers total from first two payments" do original_purchase = build(:purchase, link: product, subscription: subscription, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) original_purchase.save!(validate: false) product.update!(price_cents: 19700) second_purchase = build(:purchase, link: product, subscription: subscription, is_installment_payment: true, price_cents: 4900, installment_plan: installment_plan) second_purchase.save!(validate: false) payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) described_class.perform snapshot = payment_option.reload.installment_plan_snapshot expect(snapshot.total_price_cents).to eq(14700) end it "skips when price changed between first and second payment" do original_purchase = build(:purchase, link: product, subscription: subscription, is_original_subscription_purchase: true, is_installment_payment: true, price_cents: 5000, installment_plan: installment_plan) original_purchase.save!(validate: false) product.update!(price_cents: 19700) second_purchase = build(:purchase, link: product, subscription: subscription, is_installment_payment: true, price_cents: 6567, installment_plan: installment_plan) second_purchase.save!(validate: false) payment_option = create(:payment_option, subscription: subscription, installment_plan: installment_plan) expect(Rails.logger).to receive(:warn).with(/price likely changed mid-subscription/) described_class.perform expect(payment_option.reload.installment_plan_snapshot).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/services/onetime/base_spec.rb
spec/services/onetime/base_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Onetime::Base do class Onetime::TestScript < Onetime::Base def process(message) Rails.logger.info(message) end end let(:time_now) { Time.current } let(:created_log_files) { [] } let(:script_instance) { Onetime::TestScript.new } let(:message) { "Hello, world!" } before do allow(Time).to receive(:current).and_return(time_now) allow(script_instance).to receive(:enable_logger).and_wrap_original do |method, _| log_file_name = "log/test_script_#{time_now.strftime('%Y-%m-%d_%H-%M-%S')}.log" created_log_files << Rails.root.join(log_file_name) method.call end end after(:each) do created_log_files.each { FileUtils.rm_f(_1) } created_log_files.clear end describe "#process_with_logging" do it "calls the process method" do expect(script_instance).to receive(:process) script_instance.process_with_logging(message) end it "logs the start and finish times" do expect(Rails.logger).to receive(:info).with("Started process at #{time_now}") expect(Rails.logger).to receive(:info).with(message) expect(Rails.logger).to receive(:info).with("Finished process at #{time_now} in 0.0 seconds") script_instance.process_with_logging(message) end it "creates and closes a custom logger" do expect(Logger).to receive(:new).and_call_original expect_any_instance_of(Logger).to receive(:close) script_instance.process_with_logging(message) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/disable_recurring_subscription_notifications_spec.rb
spec/services/onetime/disable_recurring_subscription_notifications_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::DisableRecurringSubscriptionNotifications do it "disables recurring subscription charge email and push for users that have them enabled" do user1 = create(:user) # Explicitly enable both flags (email may be disabled by default for new users) user1.enable_recurring_subscription_charge_email = true user1.enable_recurring_subscription_charge_push_notification = true user1.save! user2 = create(:user) # Enable only push on second user; email remains as-is (default may already be false) user2.enable_recurring_subscription_charge_push_notification = true user2.save! user3 = create(:user) # Already disabled for both user3.enable_recurring_subscription_charge_email = false user3.enable_recurring_subscription_charge_push_notification = false user3.save! described_class.process expect(user1.reload.enable_recurring_subscription_charge_email).to be(false) expect(user1.enable_recurring_subscription_charge_push_notification).to be(false) expect(user2.reload.enable_recurring_subscription_charge_email).to be(false) expect(user2.enable_recurring_subscription_charge_push_notification).to be(false) expect(user3.reload.enable_recurring_subscription_charge_email).to be(false) expect(user3.enable_recurring_subscription_charge_push_notification).to be(false) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/add_new_vr_taxonomies_spec.rb
spec/services/onetime/add_new_vr_taxonomies_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::AddNewVrTaxonomies do before do Taxonomy.delete_all three_d = Taxonomy.create!(slug: "3d") three_d_assets = Taxonomy.create!(slug: "3d-assets", parent: three_d) Taxonomy.create!(slug: "unity", parent: three_d_assets) gaming = Taxonomy.create!(slug: "gaming") Taxonomy.create!(slug: "vrchat", parent: gaming) end it "moves the vrchat taxonomy to 3d" do described_class.process expect(Taxonomy.find_by(slug: "vrchat").parent.slug).to eq("3d") end it "creates the correct number of new taxonomies" do new_taxonomies_count = 81 old_taxonomy_count = Taxonomy.count expect do described_class.process end.to change { Taxonomy.count }.from(old_taxonomy_count).to(old_taxonomy_count + new_taxonomies_count) end it "doesn't create taxonomies without a parent" do old_root_taxonomy_count = Taxonomy.where(parent: nil).count described_class.process expect(Taxonomy.where(parent: nil).count).to eq(old_root_taxonomy_count) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/create_product_refund_policies_for_user_spec.rb
spec/services/onetime/create_product_refund_policies_for_user_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Onetime::CreateProductRefundPoliciesForUser do let(:user) { create(:user) } let(:service) { described_class.new(user_id: user.id, max_refund_period_in_days: max_refund_period_in_days) } let(:max_refund_period_in_days) { 0 } describe "#initialize" do it "sets the user_id" do expect(service.user_id).to eq(user.id) end it "sets the max_refund_period_in_days to 0 by default" do service_with_defaults = described_class.new(user_id: user.id) expect(service_with_defaults.max_refund_period_in_days).to eq(0) end it "allows custom max_refund_period_in_days" do custom_service = described_class.new(user_id: user.id, max_refund_period_in_days: 30) expect(custom_service.max_refund_period_in_days).to eq(30) end it "initializes empty results hash" do expect(service.results).to eq({ success: [], errors: [] }) end end describe "#process" do let!(:product_without_policy_1) { create(:product, user: user, product_refund_policy_enabled: false) } let!(:product_without_policy_2) { create(:product, user: user, product_refund_policy_enabled: false) } let!(:product_with_policy) { create(:product, user: user) } let!(:existing_policy) { create(:product_refund_policy, product: product_with_policy, seller: user) } before do allow(Rails.logger).to receive(:info) allow(Rails.logger).to receive(:error) end it "creates refund policies for products without policies" do expect do service.process end.to change { ProductRefundPolicy.count }.by(2) end it "does not create policies for products that already have one" do service.process expect(product_with_policy.reload.product_refund_policy).to eq(existing_policy) end it "sets the correct values" do service.process product_without_policy_1.reload expect(product_without_policy_1.product_refund_policy_enabled).to be true expect(product_without_policy_1.product_refund_policy.max_refund_period_in_days).to eq(0) expect(product_without_policy_1.reload.product_refund_policy.seller).to eq(user) product_without_policy_2.reload expect(product_without_policy_2.product_refund_policy_enabled).to be true expect(product_without_policy_2.product_refund_policy.max_refund_period_in_days).to eq(0) expect(product_without_policy_2.reload.product_refund_policy.seller).to eq(user) end it "returns results with successful creations" do results = service.process expect(results[:success].count).to eq(2) expect(results[:success].first).to include( product_id: product_without_policy_1.id, product_name: product_without_policy_1.name, policy_title: "No refunds allowed" ) expect(results[:success].second).to include( product_id: product_without_policy_2.id, product_name: product_without_policy_2.name, policy_title: "No refunds allowed" ) end context "when there are no products without policies" do let!(:product_without_policy_1) { nil } let!(:product_without_policy_2) { nil } it "returns empty results" do results = service.process expect(results[:success]).to be_empty expect(results[:errors]).to be_empty end it "logs zero products found" do service.process expect(Rails.logger).to have_received(:info).with( "Found 0 products without refund policies" ) end end context "with custom refund period" do let(:max_refund_period_in_days) { 30 } it "creates policies with the specified refund period" do service.process product_without_policy_1.reload expect(product_without_policy_1.product_refund_policy.max_refund_period_in_days).to eq(30) product_without_policy_2.reload expect(product_without_policy_2.product_refund_policy.max_refund_period_in_days).to eq(30) end end context "when user does not exist" do let(:service) { described_class.new(user_id: 999_999_999) } it "raises ActiveRecord::RecordNotFound" do expect { service.process }.to raise_error(ActiveRecord::RecordNotFound) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/onetime/set_max_allowed_refund_period_for_purchase_refund_policies_spec.rb
spec/services/onetime/set_max_allowed_refund_period_for_purchase_refund_policies_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::SetMaxAllowedRefundPeriodForPurchaseRefundPolicies do let(:purchase_1) { create(:purchase) } let(:purchase_2) { create(:purchase) } let(:purchase_3) { create(:purchase) } let(:purchase_4) { create(:purchase) } let!(:purchase_refund_policy_1) do purchase_1.create_purchase_refund_policy!( title: "30-day money back guarantee", max_refund_period_in_days: nil, created_at: PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON - 1.day ) end let!(:purchase_refund_policy_2) do purchase_2.create_purchase_refund_policy!( title: "7-day money back guarantee", max_refund_period_in_days: nil, created_at: PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON - 1.day ) end let!(:purchase_refund_policy_3) do purchase_3.create_purchase_refund_policy!( title: "No refunds allowed", max_refund_period_in_days: nil, created_at: PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON - 1.day ) end let!(:purchase_refund_policy_already_set) do purchase_4.create_purchase_refund_policy!(title: "14-day money back guarantee", max_refund_period_in_days: 14) end let(:service) { described_class.new(max_id: purchase_refund_policy_already_set.id) } describe "#process" do before do described_class.reset_last_processed_id end it "updates max_refund_period_in_days for policies with nil values" do expect { service.process }.to change { purchase_refund_policy_1.reload.max_refund_period_in_days }.from(nil).to(30) .and change { purchase_refund_policy_2.reload.max_refund_period_in_days }.from(nil).to(7) .and change { purchase_refund_policy_3.reload.max_refund_period_in_days }.from(nil).to(0) end it "does not update policies that already have max_refund_period_in_days set" do expect { service.process }.not_to change { purchase_refund_policy_already_set.reload.max_refund_period_in_days } end describe "policies reuse data from previous policies" do let!(:product) { create(:product) } let!(:product_refund_policy) { create(:product_refund_policy, product:, title: "6-month money back guarantee", max_refund_period_in_days: 183) } let(:purchase) { create(:purchase, link: product) } let!(:purchase_refund_policy) do purchase.create_purchase_refund_policy!( title: "30-day money back guarantee", max_refund_period_in_days: 30, created_at: PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON - 1.day ) end let(:new_purchase) { create(:purchase, link: product) } let!(:new_purchase_refund_policy) do new_purchase.create_purchase_refund_policy!( title: "30-day money back guarantee", max_refund_period_in_days: nil, created_at: PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON - 1.day ) end let(:service_with_reuse) { described_class.new(max_id: new_purchase_refund_policy.id) } context "when policy title matches product refund policy title" do before do new_purchase_refund_policy.update!(title: product_refund_policy.title) end it "reuses max_refund_period_in_days from product refund policy" do expect { service_with_reuse.process }.to change { new_purchase_refund_policy.reload.max_refund_period_in_days }.from(nil).to(183) end end context "when policy title does not match product refund policy title" do before do purchase_refund_policy.update!(title: purchase_refund_policy.title) end it "reuses max_refund_period_in_days from previous policy with same title" do expect { service_with_reuse.process }.to change { new_purchase_refund_policy.reload.max_refund_period_in_days }.from(nil).to(30) end end end context "when title doesn't match any known pattern" do let(:purchase_unknown) { create(:purchase) } let!(:purchase_refund_policy_unknown) do purchase_unknown.create_purchase_refund_policy!( title: "Custom refund policy", max_refund_period_in_days: nil, created_at: PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON - 1.day ) end let(:service_with_unknown) { described_class.new(max_id: purchase_refund_policy_unknown.id) } it "skips records with unmatched titles" do expect { service_with_unknown.process }.not_to change { purchase_refund_policy_unknown.reload.max_refund_period_in_days } end end end describe "PurchaseRefundPolicy#determine_max_refund_period_in_days" do it "returns correct days for known titles" do policy_no_refunds = build(:purchase_refund_policy, title: "No refunds allowed") policy_7_days = build(:purchase_refund_policy, title: "7-day money back guarantee") policy_14_days = build(:purchase_refund_policy, title: "14-day money back guarantee") policy_30_days = build(:purchase_refund_policy, title: "30-day money back guarantee") policy_6_months = build(:purchase_refund_policy, title: "6-month money back guarantee") expect(policy_no_refunds.determine_max_refund_period_in_days).to eq(0) expect(policy_7_days.determine_max_refund_period_in_days).to eq(7) expect(policy_14_days.determine_max_refund_period_in_days).to eq(14) expect(policy_30_days.determine_max_refund_period_in_days).to eq(30) expect(policy_6_months.determine_max_refund_period_in_days).to eq(183) end it "returns nil for unknown titles" do policy_unknown = build(:purchase_refund_policy, title: "Unknown policy") expect(policy_unknown.determine_max_refund_period_in_days).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/services/onetime/notify_sellers_about_paypal_payouts_removal_spec.rb
spec/services/onetime/notify_sellers_about_paypal_payouts_removal_spec.rb
# frozen_string_literal: true require "spec_helper" describe Onetime::NotifySellersAboutPaypalPayoutsRemoval do before do @eligible_seller_1 = create(:user_with_compliance_info) create(:payment_completed, user: @eligible_seller_1, created_at: Date.new(2025, 2, 10)) @eligible_seller_2 = create(:user) create(:user_compliance_info_singapore, user: @eligible_seller_2) create(:payment_completed, user: @eligible_seller_2, created_at: Date.new(2025, 7, 7)) @eligible_seller_3 = create(:user) create(:user_compliance_info_canada, user: @eligible_seller_3) create(:payment_completed, user: @eligible_seller_3, created_at: Date.new(2025, 2, 5)) @eligible_seller_4 = create(:user) create(:user_compliance_info, country: "France", user: @eligible_seller_4) create(:payment_completed, user: @eligible_seller_4, created_at: Date.new(2025, 4, 15)) @ineligible_seller_1 = create(:user) create(:user_compliance_info_uae, user: @ineligible_seller_1) create(:payment_completed, user: @ineligible_seller_1, created_at: Date.new(2025, 5, 20)) @ineligible_seller_2 = create(:user) create(:user_compliance_info, user: @ineligible_seller_2, country: "India") create(:payment_completed, user: @ineligible_seller_2, created_at: Date.new(2025, 3, 25)) @ineligible_seller_3 = create(:user_with_compliance_info) create(:payment_completed, user: @ineligible_seller_3, processor: PayoutProcessorType::STRIPE, stripe_transfer_id: "t_12345", stripe_connect_account_id: "acct_12345", created_at: Date.new(2025, 3, 25)) @ineligible_seller_4 = create(:user_with_compliance_info) create(:payment_completed, user: @ineligible_seller_4, created_at: Date.new(2024, 12, 31)) @ineligible_seller_5 = create(:user_with_compliance_info) create(:payment_failed, user: @ineligible_seller_5, created_at: Date.new(2025, 5, 20)) @ineligible_seller_6 = create(:user_with_compliance_info) end it "enqueues the email for correct sellers with proper arguments" do expect do described_class.process end.to have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_1.id).once .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_2.id).once .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_3.id).once .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_4.id).once .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_1.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_2.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_3.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_4.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_5.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_6.id).exactly(0).times expect($redis.get("notified_paypal_removal_till_user_id").to_i).to eq @eligible_seller_4.id end context "when email has already been sent to some sellers" do before do $redis.set("notified_paypal_removal_till_user_id", @eligible_seller_2.id) end it "does not enqueue for sellers who have already been sent the email" do expect($redis.get("notified_paypal_removal_till_user_id").to_i).to eq @eligible_seller_2.id expect do described_class.process end.to have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_1.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_2.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_3.id).once .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@eligible_seller_4.id).once .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_1.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_2.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_3.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_4.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_5.id).exactly(0).times .and have_enqueued_mail(ContactingCreatorMailer, :paypal_suspension_notification).with(@ineligible_seller_6.id).exactly(0).times expect($redis.get("notified_paypal_removal_till_user_id").to_i).to eq @eligible_seller_4.id end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/product_review/update_service_spec.rb
spec/services/product_review/update_service_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe ProductReview::UpdateService do let(:purchaser) { create(:user) } let(:purchase) { create(:purchase, purchaser:) } let(:product_review) do create(:product_review, purchase:, rating: 3, message: "Original message") end describe "#update" do it "returns the product review" do returned_product_review = described_class .new(product_review, rating: 5, message: "Updated message") .update expect(returned_product_review).to eq(product_review) end it "updates the product review with the new rating and message" do expect do described_class.new(product_review, rating: 5, message: "Updated message").update end.to change { product_review.rating }.from(3).to(5) .and change { product_review.message }.from("Original message").to("Updated message") end context "with video_options" do let(:video_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/video.mp4" } let(:blob) do ActiveStorage::Blob.create_and_upload!( io: fixture_file_upload("test-small.jpg"), filename: "test-small.jpg", content_type: "image/jpeg" ) end context "when create option with url is provided" do let!(:existing_pending_video) do create( :product_review_video, :pending_review, product_review: product_review ) end it "creates a new video associated with the product review" do expect do described_class.new( product_review, rating: 4, message: "With video", video_options: { create: { url: video_url, thumbnail_signed_id: blob.signed_id } } ).update end.to change { product_review.videos.count }.by(1) .and change { existing_pending_video.reload.deleted? }.from(false).to(true) new_video = product_review.videos.last expect(new_video.approval_status).to eq("pending_review") expect(new_video.video_file.url).to eq(video_url) expect(new_video.video_file.thumbnail.signed_id).to eq(blob.signed_id) end end context "when destroy option with id is provided" do let!(:video) { create(:product_review_video, product_review:) } it "marks the video as deleted" do expect do described_class.new( product_review, rating: 4, message: "Remove video", video_options: { destroy: { id: video.external_id } } ).update end.to change { video.reload.deleted? }.from(false).to(true) 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/services/purchase/update_bundle_purchase_content_service_spec.rb
spec/services/purchase/update_bundle_purchase_content_service_spec.rb
# frozen_string_literal: false describe Purchase::UpdateBundlePurchaseContentService do describe "#perform" do let(:seller) { create(:named_seller) } let(:purchaser) { create(:buyer_user) } let(:bundle) { create(:product, user: seller, is_bundle: true) } let(:product) { create(:product, user: seller) } let!(:bundle_product) { create(:bundle_product, bundle:, product:, updated_at: 1.year.ago) } let(:versioned_product) { create(:product_with_digital_versions, user: seller, name: "Versioned product") } let!(:versioned_bundle_product) { create(:bundle_product, bundle:, product: versioned_product, variant: versioned_product.alive_variants.first, quantity: 3, updated_at: 1.year.from_now) } let(:outdated_purchase) { create(:purchase, link: bundle) } before do outdated_purchase.create_artifacts_and_send_receipt! outdated_purchase.product_purchases.last.destroy! end it "creates purchases for missing bundle products" do expect(Purchase::CreateBundleProductPurchaseService).to receive(:new).with(outdated_purchase, versioned_bundle_product).and_call_original expect(Purchase::CreateBundleProductPurchaseService).to_not receive(:new).with(outdated_purchase, bundle_product) expect do described_class.new(outdated_purchase).perform end.to have_enqueued_mail(CustomerLowPriorityMailer, :bundle_content_updated).with(outdated_purchase.id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/purchase/mark_successful_service_spec.rb
spec/services/purchase/mark_successful_service_spec.rb
# frozen_string_literal: false describe Purchase::MarkSuccessfulService do describe "#handle_purchase_success" do it "calls save_gumroad_day_timezone on seller if purchase is neither free nor a test purchase" do expect_any_instance_of(User).to receive(:save_gumroad_day_timezone).and_call_original Purchase::MarkSuccessfulService.new(create(:purchase, purchase_state: "in_progress")).perform end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/purchase/sync_status_with_charge_processor_service_spec.rb
spec/services/purchase/sync_status_with_charge_processor_service_spec.rb
# frozen_string_literal: false describe Purchase::SyncStatusWithChargeProcessorService, :vcr do before do @initial_balance = 200 @seller = create(:user, unpaid_balance_cents: @initial_balance) @product = create(:product, user: @seller) end it "marks a free purchase as successful and returns true" do offer_code = create(:offer_code, products: [@product], amount_cents: 100) purchase = create(:free_purchase, link: @product, purchase_state: "in_progress", offer_code:) purchase.process! expect(purchase.reload.in_progress?).to be(true) expect(purchase.free_purchase?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) end it "marks a free gift purchase as successful and marks the associated giftee purchase as successful too in case of a successful gift purchase and returns true" do gift = create(:gift) offer_code = create(:offer_code, products: [gift.link], amount_cents: 100) purchase_given = build(:free_purchase, link: gift.link, gift_given: gift, is_gift_sender_purchase: true, offer_code:, purchase_state: "in_progress") purchase_received = create(:free_purchase, link: gift.link, gift_received: purchase_given.gift, is_gift_receiver_purchase: true, purchase_state: "in_progress") purchase_given.process! expect(purchase_given.reload.in_progress?).to be(true) expect(purchase_given.free_purchase?).to be(true) expect(purchase_given.stripe_transaction_id).to be(nil) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase_given).perform).to be(true) expect(purchase_given.reload.successful?).to be(true) expect(purchase_received.reload.gift_receiver_purchase_successful?).to be(true) expect(purchase_given.gift.successful?).to be(true) end it "marks a free purchase for a subscription as succcessful and creates the subscription and returns true" do product = create(:product, :is_subscription, user: @seller) offer_code = create(:offer_code, products: [product], amount_cents: 100) purchase = create(:free_purchase, link: product, purchase_state: "in_progress", offer_code:, price: product.default_price) purchase.process! expect(purchase.reload.in_progress?).to be(true) expect(purchase.free_purchase?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(purchase.subscription.alive?).to be(true) end it "marks a free purchase for a subscription as successful and does not create a subscription if one is already present and returns true" do product = create(:product, :is_subscription, user: @seller) offer_code = create(:offer_code, products: [product], amount_cents: 100) purchase = create(:free_purchase, link: product, purchase_state: "in_progress", offer_code:, price: product.default_price) purchase.process! subscription = create(:subscription, link: product) subscription.purchases << purchase expect(purchase.reload.in_progress?).to be(true) expect(purchase.free_purchase?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(purchase.subscription).to eq(subscription) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(purchase.subscription).to eq(subscription) expect(purchase.subscription.alive?).to be(true) end it "marks the purchase as successful and returns true if purchase's charge was successful" do purchase = create(:purchase, link: @product, purchase_state: "in_progress", chargeable: create(:chargeable)) purchase.process! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).not_to be(nil) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance + purchase.payment_cents) end it "marks the purchase that is part of a combined charge as successful and returns true" do product = create(:product, user: @seller, price_cents: 10_00) params = { email: "buyer@gumroad.com", cc_zipcode: "12345", purchase: { full_name: "Edgar Gumstein", zip_code: "94117" }, browser_guid: SecureRandom.uuid, ip_address: "0.0.0.0", session_id: "a107d0b7ab5ab3c1eeb7d3aaf9792977", is_mobile: false, line_items: [ { uid: "unique-id-0", permalink: product.unique_permalink, perceived_price_cents: product.price_cents, quantity: 1 } ] }.merge(StripePaymentMethodHelper.success.to_stripejs_params) allow_any_instance_of(Charge).to receive(:id).and_return(1234567) order, _ = Order::CreateService.new(params:).perform Order::ChargeService.new(order:, params:).perform purchase = order.purchases.last purchase.update!(purchase_state: "in_progress", stripe_transaction_id: nil) expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(purchase.stripe_transaction_id).to be_present expect(purchase.charge.processor_transaction_id).to be_present expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance + purchase.payment_cents) end it "marks the associated gift and giftee purchase as successful too in case of a successful gift purchase" do gift = create(:gift) purchase_given = build(:purchase, link: gift.link, gift_given: gift, is_gift_sender_purchase: true, chargeable: create(:chargeable), purchase_state: "in_progress") purchase_received = create(:purchase, link: gift.link, gift_received: purchase_given.gift, is_gift_receiver_purchase: true, purchase_state: "in_progress") purchase_given.process! expect(purchase_given.reload.in_progress?).to be(true) expect(purchase_given.stripe_transaction_id).not_to be(nil) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase_given).perform).to be(true) expect(purchase_given.reload.successful?).to be(true) expect(purchase_received.reload.gift_receiver_purchase_successful?).to be(true) expect(purchase_given.gift.successful?).to be(true) end it "creates a subscription in case of a successful subscription purchase" do product = create(:product, :is_subscription, user: @seller) purchase = create(:purchase, link: product, purchase_state: "in_progress", chargeable: create(:chargeable), price: product.default_price) purchase.process! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).not_to be(nil) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(purchase.reload.subscription.alive?).to be(true) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance + purchase.payment_cents) end it "does not try to create a new subscription if one is already present" do product = create(:product, :is_subscription, user: @seller) purchase = create(:purchase, link: product, purchase_state: "in_progress", chargeable: create(:chargeable), price: product.default_price) purchase.process! subscription = create(:subscription, link: product) subscription.purchases << purchase expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).not_to be(nil) expect(purchase.subscription).to eq(subscription) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(purchase.subscription).to eq(subscription) expect(purchase.reload.subscription.alive?).to be(true) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance + purchase.payment_cents) end it "does not increment seller's balance again if it is already done once for this purchase" do purchase = create(:purchase, link: @product, purchase_state: "in_progress", chargeable: create(:chargeable)) purchase.process! purchase.increment_sellers_balance! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).to be_present expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance + purchase.payment_cents) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance + purchase.payment_cents) end it "marks the purchase as failed and returns false if purchase's charge was not successful" do purchase = create(:purchase, link: @product, purchase_state: "in_progress", chargeable: create(:chargeable_success_charge_decline)) purchase.process! purchase.stripe_transaction_id = nil purchase.save! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase, mark_as_failed: true).perform).to be(false) expect(purchase.reload.failed?).to be(true) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) end it "does not raise any error and returns false if purchase's merchant account is nil" do purchase = create(:purchase, link: @product, purchase_state: "in_progress", chargeable: create(:chargeable_success_charge_decline)) purchase.process! purchase.merchant_account_id = nil purchase.save! expect(purchase.reload.in_progress?).to be(true) expect(purchase.merchant_account_id).to be(nil) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase, mark_as_failed: true).perform).to be(false) expect(purchase.reload.failed?).to be(true) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) end it "does not mark purchase as failed if mark_as_failed flag is not set" do purchase = create(:purchase, link: @product, purchase_state: "in_progress", chargeable: create(:chargeable_success_charge_decline)) purchase.process! purchase.merchant_account_id = nil purchase.save! expect(purchase.reload.in_progress?).to be(true) expect(purchase.merchant_account_id).to be(nil) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(false) expect(purchase.reload.in_progress?).to be(true) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) end it "marks a free preorder authorization purchase as preorder_authorization_successful and returns true if mark_as_failed flag is set" do offer_code = create(:offer_code, products: [@product], amount_cents: 100) purchase = create(:free_purchase, link: @product, purchase_state: "in_progress", offer_code:, is_preorder_authorization: true, preorder: create(:preorder)) purchase.process! expect(purchase.reload.in_progress?).to be(true) expect(purchase.free_purchase?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase, mark_as_failed: true).perform).to be(true) expect(purchase.reload.preorder_authorization_successful?).to be(true) end context "for a paypal connect purchase" do it "marks the purchase as successful and returns true if purchase's charge was successful" do merchant_account = create(:merchant_account_paypal, user: @product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L", currency: "gbp") purchase = create(:purchase, link: @product, purchase_state: "in_progress", chargeable: create(:native_paypal_chargeable)) purchase.process! purchase.stripe_transaction_id = nil purchase.save! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(purchase.charge_processor_id).to eq(PaypalChargeProcessor.charge_processor_id) expect(purchase.merchant_account).to eq(merchant_account) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(purchase.balance_transactions).to be_empty expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) end it "marks the purchase as failed and returns false if purchase's charge has been refunded" do merchant_account = create(:merchant_account_paypal, user: @product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L", currency: "gbp") purchase = create(:purchase, link: @product, purchase_state: "in_progress", chargeable: create(:native_paypal_chargeable)) purchase.process! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).to be_present expect(purchase.merchant_account).to eq(merchant_account) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) PaypalRestApi.new.refund(capture_id: purchase.stripe_transaction_id, merchant_account:) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase, mark_as_failed: true).perform).to be(false) expect(purchase.reload.failed?).to be(true) expect(purchase.balance_transactions).to be_empty expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) end end context "for a Stripe Connect purchase" do it "marks the purchase as successful and returns true if purchase's charge was successful" do merchant_account = create(:merchant_account_stripe_connect, user: @product.user, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d", currency: "usd") purchase = create(:purchase, id: 88, link: @product, purchase_state: "in_progress", merchant_account:) purchase.process! purchase.stripe_transaction_id = nil purchase.save! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(purchase.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id) expect(purchase.merchant_account).to eq(merchant_account) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase).perform).to be(true) expect(purchase.reload.successful?).to be(true) expect(purchase.stripe_transaction_id).to eq("ch_3Mf0bBKQKir5qdfM1FZ0agOH") expect(purchase.balance_transactions).to be_empty expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) end it "marks the purchase as failed and returns false if purchase's charge has been refunded" do merchant_account = create(:merchant_account_stripe_connect, user: @product.user, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d", currency: "usd") purchase = create(:purchase, id: 90, link: @product, purchase_state: "in_progress", merchant_account:) purchase.process! purchase.stripe_transaction_id = nil purchase.save! expect(purchase.reload.in_progress?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(purchase.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id) expect(purchase.merchant_account).to eq(merchant_account) expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) expect(Purchase::SyncStatusWithChargeProcessorService.new(purchase, mark_as_failed: true).perform).to be(false) expect(purchase.reload.successful?).to be(false) expect(purchase.reload.failed?).to be(true) expect(purchase.stripe_transaction_id).to be(nil) expect(purchase.balance_transactions).to be_empty expect(@seller.reload.unpaid_balance_cents).to eq(@initial_balance) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/purchase/create_bundle_product_purchase_service_spec.rb
spec/services/purchase/create_bundle_product_purchase_service_spec.rb
# frozen_string_literal: false describe Purchase::CreateBundleProductPurchaseService do describe "#perform" do let(:seller) { create(:named_seller) } let(:purchaser) { create(:buyer_user) } let(:bundle) { create(:product, user: seller, is_bundle: true) } let(:versioned_product) { create(:product_with_digital_versions, user: seller, name: "Versioned product") } let!(:versioned_bundle_product) { create(:bundle_product, bundle:, product: versioned_product, variant: versioned_product.alive_variants.first, quantity: 3) } let(:purchase) { create(:purchase, link: bundle, purchaser:, zip_code: "12345", quantity: 2) } before do purchase.purchase_custom_fields << build(:purchase_custom_field, name: "Key", value: "Value", bundle_product: versioned_bundle_product) end it "creates a bundle product purchase" do described_class.new(purchase, versioned_bundle_product).perform bundle_product_purchase = Purchase.last expect(bundle_product_purchase.link).to eq(versioned_product) expect(bundle_product_purchase.quantity).to eq(6) expect(bundle_product_purchase.variant_attributes).to eq([versioned_product.alive_variants.first]) expect(bundle_product_purchase.total_transaction_cents).to eq(0) expect(bundle_product_purchase.displayed_price_cents).to eq(0) expect(bundle_product_purchase.fee_cents).to eq(0) expect(bundle_product_purchase.price_cents).to eq(0) expect(bundle_product_purchase.gumroad_tax_cents).to eq(0) expect(bundle_product_purchase.shipping_cents).to eq(0) expect(bundle_product_purchase.is_bundle_product_purchase).to eq(true) expect(bundle_product_purchase.is_bundle_purchase).to eq(false) expect(bundle_product_purchase.purchaser).to eq(purchaser) expect(bundle_product_purchase.email).to eq(purchase.email) expect(bundle_product_purchase.full_name).to eq(purchase.full_name) expect(bundle_product_purchase.street_address).to eq(purchase.street_address) expect(bundle_product_purchase.country).to eq(purchase.country) expect(bundle_product_purchase.state).to eq(purchase.state) expect(bundle_product_purchase.zip_code).to eq(purchase.zip_code) expect(bundle_product_purchase.city).to eq(purchase.city) expect(bundle_product_purchase.ip_address).to eq(purchase.ip_address) expect(bundle_product_purchase.ip_state).to eq(purchase.ip_state) expect(bundle_product_purchase.ip_country).to eq(purchase.ip_country) expect(bundle_product_purchase.browser_guid).to eq(purchase.browser_guid) expect(bundle_product_purchase.referrer).to eq(purchase.referrer) expect(bundle_product_purchase.was_product_recommended).to eq(purchase.was_product_recommended) expect(bundle_product_purchase.purchase_custom_fields.sole).to have_attributes(name: "Key", value: "Value", bundle_product: nil) expect(purchase.product_purchases).to eq([bundle_product_purchase]) end context "gifting a bundle" do let(:gifter_email) { "gifter@example.com" } let(:giftee_email) { "giftee@example.com" } let(:receiver_bundle_purchase) { create(:purchase, :gift_receiver, link: bundle, email: giftee_email) } let(:sender_bundle_purchase) { create(:purchase, :gift_sender, link: bundle, email: gifter_email) } let!(:bundle_level_gift) do create( :gift, link: bundle, gifter_purchase: sender_bundle_purchase, giftee_purchase: receiver_bundle_purchase, gifter_email: gifter_email, giftee_email: giftee_email ) end before do receiver_bundle_purchase.reload sender_bundle_purchase.reload end it "creates a bundle product purchase with the correct is_gift_sender_purchase flag" do described_class.new(sender_bundle_purchase, versioned_bundle_product).perform bundle_product_purchase = Purchase.last expect(bundle_product_purchase.is_gift_sender_purchase).to eq(true) expect(bundle_product_purchase.is_gift_receiver_purchase).to eq(false) expect(bundle_product_purchase.gift).to be_present expect(bundle_product_purchase.gift.link).to eq(versioned_bundle_product.product) expect(bundle_product_purchase.gift.gifter_purchase).to eq(bundle_product_purchase) expect(bundle_product_purchase.gift.giftee_purchase).to be_nil expect(bundle_product_purchase.gift.gifter_email).to eq(gifter_email) expect(bundle_product_purchase.gift.giftee_email).to eq(giftee_email) end it "creates a bundle product purchase with the correct is_gift_receiver_purchase flag" do described_class.new(receiver_bundle_purchase, versioned_bundle_product).perform bundle_product_purchase = Purchase.last expect(bundle_product_purchase.is_gift_sender_purchase).to eq(false) expect(bundle_product_purchase.is_gift_receiver_purchase).to eq(true) expect(bundle_product_purchase.gift).to be_present expect(bundle_product_purchase.gift.link).to eq(versioned_bundle_product.product) expect(bundle_product_purchase.gift.gifter_purchase).to be_nil expect(bundle_product_purchase.gift.giftee_purchase).to eq(bundle_product_purchase) expect(bundle_product_purchase.gift.gifter_email).to eq(gifter_email) expect(bundle_product_purchase.gift.giftee_email).to eq(giftee_email) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/purchase/confirm_service_spec.rb
spec/services/purchase/confirm_service_spec.rb
# frozen_string_literal: false describe Purchase::ConfirmService, :vcr do include ManageSubscriptionHelpers let(:user) { create(:user) } let(:chargeable) { build(:chargeable, card: StripePaymentMethodHelper.success_sca_not_required) } context "when purchase has been marked as failed" do # Sometimes we mark a purchase failed before the confirmation request comes from the UI, # if time to complete SCA expired or a parallel purchase has been made. let(:purchase) { create(:failed_purchase, chargeable:) } it "returns an error message" do expect(ChargeProcessor).not_to receive(:confirm_payment_intent!) error_message = Purchase::ConfirmService.new(purchase:, params: {}).perform expect(error_message).to eq("There is a temporary problem, please try again (your card was not charged).") end end context "when SCA fails" do context "for a classic product" do let(:purchase) { create(:purchase_in_progress, chargeable:) } before do purchase.process! params = { stripe_error: { code: "invalid_request_error", message: "We are unable to authenticate your payment method." } } @error_message = Purchase::ConfirmService.new(purchase:, params:).perform end it "marks purchase as failed and returns an error message" do expect(@error_message).to eq("We are unable to authenticate your payment method.") expect(purchase.reload.purchase_state).to eq("failed") end it "does not enqueue activate integrations worker" do expect(@error_message).to eq("We are unable to authenticate your payment method.") expect(ActivateIntegrationsWorker.jobs.size).to eq(0) end end context "for a pre-order product" do let(:product) { create(:product_with_files, is_in_preorder_state: true) } let(:preorder_product) { create(:preorder_link, link: product, release_at: 25.hours.from_now) } let(:authorization_purchase) { create(:purchase_in_progress, link: product, chargeable:, is_preorder_authorization: true) } before do preorder_product.build_preorder(authorization_purchase) end it "marks pre-order as authorization_failed and returns an error message" do params = { stripe_error: { code: "invalid_request_error", message: "We are unable to authenticate your payment method." } } error_message = Purchase::ConfirmService.new(purchase: authorization_purchase, params:).perform expect(error_message).to eq("We are unable to authenticate your payment method.") expect(authorization_purchase.reload.purchase_state).to eq("preorder_authorization_failed") expect(authorization_purchase.preorder.state).to eq("authorization_failed") end end context "for a membership upgrade purchase" do before do setup_subscription @indian_cc = create(:credit_card, user: user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate)) @subscription.credit_card = @indian_cc @subscription.save! params = { price_id: @quarterly_product_price.external_id, variants: [@new_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @new_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @new_tier_quarterly_price.price_cents, } Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: "abc123", params:, logged_in_user: user, remote_ip: "11.22.33.44", ).perform @membership_upgrade_purchase = @subscription.reload.purchases.in_progress.last end it "reverts the subscription to old tier and returns an error message" do expect(@membership_upgrade_purchase.purchase_state).to eq("in_progress") expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] expect_any_instance_of(Purchase::BaseService).to receive(:mark_items_failed).and_call_original params = { stripe_error: { code: "invalid_request_error", message: "We are unable to authenticate your payment method." } } error_message = Purchase::ConfirmService.new(purchase: @membership_upgrade_purchase, params:).perform expect(error_message).to eq("We are unable to authenticate your payment method.") expect(@membership_upgrade_purchase.reload.purchase_state).to eq("failed") expect(@subscription.reload.original_purchase.variant_attributes).to eq [@original_tier] end end context "for a membership restart purchase" do before do setup_subscription @indian_cc = create(:credit_card, user: user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate)) @subscription.credit_card = @indian_cc @subscription.save! @subscription.update!(cancelled_at: @originally_subscribed_at + 4.months, cancelled_by_buyer: true) params = { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @original_tier_quarterly_price.price_cents, }.merge(StripePaymentMethodHelper.success_indian_card_mandate.to_stripejs_params(prepare_future_payments: true)) Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: "abc123", params:, logged_in_user: user, remote_ip: "11.22.33.44", ).perform @membership_restart_purchase = @subscription.reload.purchases.in_progress.last end it "marks the purchase as failed and unsubscribes the membership" do expect(@membership_restart_purchase.purchase_state).to eq("in_progress") expect(@subscription.reload.is_resubscription_pending_confirmation?).to be true expect(@subscription.alive?).to be(true) expect(@subscription).not_to receive(:send_restart_notifications!) expect(@subscription).to receive(:unsubscribe_and_fail!).and_call_original expect_any_instance_of(Purchase::BaseService).to receive(:mark_items_failed).and_call_original params = { stripe_error: { code: "invalid_request_error", message: "We are unable to authenticate your payment method." } } error_message = Purchase::ConfirmService.new(purchase: @membership_restart_purchase, params:).perform expect(error_message).to eq("We are unable to authenticate your payment method.") expect(@membership_restart_purchase.reload.failed?).to be true expect(@subscription.reload.is_resubscription_pending_confirmation?).to be false expect(@subscription.alive?).to be(false) end end end context "when SCA succeeds" do context "for a classic product" do let(:purchase) { create(:purchase_in_progress, chargeable:) } before do purchase.process! end it "marks purchase as successful" do allow_any_instance_of(Stripe::PaymentIntent).to receive(:confirm) error_message = Purchase::ConfirmService.new(purchase:, params: {}).perform expect(error_message).to be_nil expect(purchase.reload.purchase_state).to eq("successful") end it "does not return an error if purchase is already successful" do purchase.update_balance_and_mark_successful! expect(purchase.reload.purchase_state).to eq("successful") allow_any_instance_of(Stripe::PaymentIntent).to receive(:confirm) error_message = Purchase::ConfirmService.new(purchase:, params: {}).perform expect(error_message).to be_nil expect(purchase.reload.purchase_state).to eq("successful") end it "enqueues activate integrations worker" do allow_any_instance_of(Stripe::PaymentIntent).to receive(:confirm) error_message = Purchase::ConfirmService.new(purchase:, params: {}).perform expect(error_message).to be_nil expect(purchase.reload.purchase_state).to eq("successful") expect(ActivateIntegrationsWorker).to have_enqueued_sidekiq_job(purchase.id) end context "when charge processor is unavailable" do before do allow(ChargeProcessor).to receive(:confirm_payment_intent!).and_raise(ChargeProcessorUnavailableError) end it "marks purchase as failed and returns an error message" do error_message = Purchase::ConfirmService.new(purchase:, params: {}).perform expect(error_message).to eq("There is a temporary problem, please try again (your card was not charged).") expect(purchase.reload.purchase_state).to eq("failed") end end end context "for a pre-order product" do let(:product) { create(:product_with_files, is_in_preorder_state: true) } let(:preorder_product) { create(:preorder_link, link: product, release_at: 25.hours.from_now) } let(:authorization_purchase) { create(:purchase_in_progress, link: product, chargeable:, is_preorder_authorization: true) } before do preorder_product.build_preorder(authorization_purchase) end it "marks pre-order successful" do error_message = Purchase::ConfirmService.new(purchase: authorization_purchase, params: {}).perform expect(error_message).to be_nil expect(authorization_purchase.reload.purchase_state).to eq("preorder_authorization_successful") expect(authorization_purchase.preorder.state).to eq("authorization_successful") end end context "for a membership upgrade purchase" do before do setup_subscription @indian_cc = create(:credit_card, user: user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate)) @subscription.credit_card = @indian_cc @subscription.save! params = { price_id: @quarterly_product_price.external_id, variants: [@new_tier.external_id], quantity: 1, use_existing_card: true, perceived_price_cents: @new_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @new_tier_quarterly_price.price_cents, } Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: "abc123", params:, logged_in_user: user, remote_ip: "11.22.33.44", ).perform @membership_upgrade_purchase = @subscription.reload.purchases.in_progress.last end it "marks the purchase as successful and updates integrations" do expect(@membership_upgrade_purchase.purchase_state).to eq("in_progress") expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] allow_any_instance_of(Purchase).to receive(:confirm_charge_intent!).and_return true expect(@subscription).not_to receive(:send_restart_notifications!) expect(@subscription).to receive(:handle_purchase_success) error_message = Purchase::ConfirmService.new(purchase: @membership_upgrade_purchase, params: {}).perform expect(error_message).to be nil expect(@subscription.reload.original_purchase.variant_attributes).to eq [@new_tier] end end context "for a membership restart purchase" do before do setup_subscription @indian_cc = create(:credit_card, user: user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate)) @subscription.credit_card = @indian_cc @subscription.save! @subscription.update!(cancelled_at: @originally_subscribed_at + 4.months, cancelled_by_buyer: true) params = { price_id: @quarterly_product_price.external_id, variants: [@original_tier.external_id], quantity: 1, perceived_price_cents: @original_tier_quarterly_price.price_cents, perceived_upgrade_price_cents: @original_tier_quarterly_price.price_cents, }.merge(StripePaymentMethodHelper.success_indian_card_mandate.to_stripejs_params(prepare_future_payments: true)) Subscription::UpdaterService.new( subscription: @subscription, gumroad_guid: "abc123", params:, logged_in_user: user, remote_ip: "11.22.33.44", ).perform @membership_restart_purchase = @subscription.reload.purchases.in_progress.last end it "marks the purchase as successful and sends membership restart notifications" do expect(@membership_restart_purchase.purchase_state).to eq("in_progress") expect(@subscription.reload.is_resubscription_pending_confirmation?).to be true expect(@subscription.alive?).to be(true) allow_any_instance_of(Purchase).to receive(:confirm_charge_intent!).and_return true expect(@subscription).to receive(:send_restart_notifications!) expect(@subscription).to receive(:handle_purchase_success) error_message = Purchase::ConfirmService.new(purchase: @membership_restart_purchase, params: {}).perform expect(error_message).to be nil expect(@subscription.is_resubscription_pending_confirmation?).to be false expect(@subscription.alive?).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/services/purchase/associate_bundle_product_level_gift_service_spec.rb
spec/services/purchase/associate_bundle_product_level_gift_service_spec.rb
# frozen_string_literal: false describe Purchase::AssociateBundleProductLevelGiftService do describe "#perform" do let(:seller) { create(:named_seller) } let(:gifter_email) { "gifter@example.com" } let(:giftee_email) { "giftee@example.com" } let(:bundle) { create(:product, :bundle, user: seller) } let(:bundle_product) { bundle.bundle_products.first } let!(:sender_bundle_purchase) { create(:purchase, :gift_sender, link: bundle, email: gifter_email) } let!(:receiver_bundle_purchase) { create(:purchase, :gift_receiver, link: bundle, email: giftee_email) } let!(:bundle_level_gift) do create( :gift, link: bundle, gifter_purchase: sender_bundle_purchase, giftee_purchase: receiver_bundle_purchase, gifter_email: gifter_email, giftee_email: giftee_email ) end let(:sender_product_purchase) do create( :bundle_product_purchase, bundle_purchase: sender_bundle_purchase, product_purchase: create(:purchase, link: bundle_product.product, seller:, is_gift_sender_purchase: true, is_bundle_product_purchase: true) ).product_purchase end let(:receiver_product_purchase) do create( :bundle_product_purchase, bundle_purchase: receiver_bundle_purchase, product_purchase: create(:purchase, link: bundle_product.product, seller:, is_gift_receiver_purchase: true, is_bundle_product_purchase: true) ).product_purchase end before do sender_bundle_purchase.reload receiver_bundle_purchase.reload end context "when both product purchases exist" do before do sender_product_purchase receiver_product_purchase end it "creates a full Gift record" do expect do described_class.new(bundle_purchase: sender_bundle_purchase, bundle_product: bundle_product).perform end.to change(Gift, :count).by(1) product_level_gift = sender_product_purchase.reload.gift expect(product_level_gift.link).to eq(bundle_product.product) expect(product_level_gift.gifter_purchase).to eq(sender_product_purchase) expect(product_level_gift.giftee_purchase).to eq(receiver_product_purchase) expect(product_level_gift.gifter_email).to eq(gifter_email) expect(product_level_gift.giftee_email).to eq(giftee_email) expect(product_level_gift.id).not_to eq(bundle_level_gift.id) # Re-running should not create a duplicate when both sides present expect do described_class.new(bundle_purchase: sender_bundle_purchase, bundle_product: bundle_product).perform end.to change(Gift, :count).by(0) end it "is indifferent to which bundle purchase instance is passed (sender or receiver)" do described_class.new(bundle_purchase: receiver_bundle_purchase, bundle_product: bundle_product).perform product_level_gift = Gift.where(gifter_purchase: sender_product_purchase).first! expect(product_level_gift.giftee_purchase).to eq(receiver_product_purchase) expect(product_level_gift.link).to eq(bundle_product.product) end end context "when bundle_product does not belong to the bundle" do it "does nothing" do unrelated_bundle = create(:product, :bundle, user: seller) unrelated_bundle_product = unrelated_bundle.bundle_products.first expect do described_class.new(bundle_purchase: sender_bundle_purchase, bundle_product: unrelated_bundle_product).perform end.to change(Gift, :count).by(0) end end context "when only one side's product purchase exists" do it "creates a Gift with the available side associated" do # Only the sender's product purchase exists. sender_product_purchase expect do described_class.new(bundle_purchase: sender_bundle_purchase, bundle_product: bundle_product).perform end.to change(Gift, :count).by(1) # Product level gift is created with the sender's product purchase only. product_level_gift = sender_product_purchase.reload.gift expect(product_level_gift.link).to eq(bundle_product.product) expect(product_level_gift.gifter_purchase).to eq(sender_product_purchase) expect(product_level_gift.giftee_purchase).to be_nil expect(product_level_gift.gifter_email).to eq(gifter_email) expect(product_level_gift.giftee_email).to eq(giftee_email) # Now, the receiver's product purchase is created too. receiver_product_purchase expect do described_class.new(bundle_purchase: receiver_bundle_purchase, bundle_product: bundle_product).perform end.to change(Gift, :count).by(0) # The product level gift is updated to include the receiver's product purchase. product_level_gift.reload expect(product_level_gift.link).to eq(bundle_product.product) expect(product_level_gift.gifter_purchase).to eq(sender_product_purchase) expect(product_level_gift.giftee_purchase).to eq(receiver_product_purchase) expect(product_level_gift.gifter_email).to eq(gifter_email) expect(product_level_gift.giftee_email).to eq(giftee_email) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/purchase/create_service_spec.rb
spec/services/purchase/create_service_spec.rb
# frozen_string_literal: false include CurrencyHelper describe Purchase::CreateService, :vcr do let(:user) { create(:user) } let(:email) { "sahil@gumroad.com" } let(:buyer) { create(:user, email:) } let(:zip_code) { "12345" } let(:price) { 600 } let(:max_purchase_count) { nil } let(:product) { create(:product, user:, price_cents: price, max_purchase_count:) } let(:subscription_product) { create(:subscription_product, user:, price_cents: price) } let(:browser_guid) { SecureRandom.uuid } let(:successful_card_chargeable) do CardParamsHelper.build_chargeable( StripePaymentMethodHelper.success.with_zip_code(zip_code).to_stripejs_params, browser_guid ) end let(:successful_paypal_chargeable) { build(:paypal_chargeable) } let(:failed_chargeable) do CardParamsHelper.build_chargeable( StripePaymentMethodHelper.decline.to_stripejs_params, browser_guid ) end let(:base_params) do { purchase: { email:, quantity: 1, perceived_price_cents: price, ip_address: "0.0.0.0", session_id: "a107d0b7ab5ab3c1eeb7d3aaf9792977", is_mobile: false, browser_guid: } } end let(:params) do base_params[:purchase].merge!( card_data_handling_mode: "stripejs.0", credit_card_zipcode: zip_code, chargeable: successful_card_chargeable ) base_params end let(:paypal_params) do base_params[:purchase].merge!( chargeable: successful_paypal_chargeable ) base_params end let(:native_paypal_params) do base_params[:purchase].merge!( chargeable: build(:native_paypal_chargeable) ) base_params end let(:base_subscription_params) do base_params[:purchase].delete(:perceived_price_cents) base_params[:price_id] = subscription_product.prices.alive.first.external_id base_params end let(:subscription_params) do base_subscription_params[:purchase].merge!( card_data_handling_mode: "stripejs.0", credit_card_zipcode: zip_code, chargeable: successful_card_chargeable ) base_subscription_params end let(:base_preorder_params) do base_params[:purchase][:is_preorder_authorization] = "true" base_params end let(:preorder_params) do base_preorder_params[:purchase].merge!( card_data_handling_mode: "stripejs.0", credit_card_zipcode: zip_code, chargeable: successful_card_chargeable ) base_preorder_params end let(:paypal_preorder_params) do base_preorder_params[:purchase].merge!( chargeable: successful_paypal_chargeable ) base_preorder_params end let(:shipping_params) do params[:purchase].merge!( full_name: "Edgar Gumstein", street_address: "123 Gum Road", country: "LY", state: "CA", city: "San Francisco", zip_code: "94117" ) params end it "creates a purchase and sets the proper state" do expect do purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq "successful" expect(purchase.card_country).to be_present expect(purchase.stripe_fingerprint).to be_present expect(purchase.reload.succeeded_at).to be_present expect(purchase.ip_address).to eq "0.0.0.0" expect(purchase.session_id).to eq "a107d0b7ab5ab3c1eeb7d3aaf9792977" expect(purchase.card_data_handling_mode).to eq CardDataHandlingMode::TOKENIZE_VIA_STRIPEJS expect(purchase.purchase_refund_policy.title).to eq(product.user.refund_policy.title) expect(purchase.purchase_refund_policy.fine_print).to eq(product.user.refund_policy.fine_print) end.to change { Purchase.count }.by 1 end it "sets the buyer when provided" do purchase, _ = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.purchaser).to eq buyer end context "when the product has a product refund policy enabled" do before do product.user.update!(refund_policy_enabled: false) product.update!(product_refund_policy_enabled: true) end context "when the refund policy has a fine print" do let!(:refund_policy) do create(:product_refund_policy, fine_print: "This is a product-level refund policy", product:, seller: user) end it "saves product refund policy fine print on purchase" do purchase, _ = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.purchase_refund_policy.max_refund_period_in_days).to eq(30) expect(purchase.purchase_refund_policy.title).to eq("30-day money back guarantee") expect(purchase.purchase_refund_policy.fine_print).to eq("This is a product-level refund policy") end context "when the account-level refund policy is enabled" do before do user.refund_policy.update!(fine_print: "This is an account-level refund policy") user.update!(refund_policy_enabled: true) end it "saves the seller-level refund policy" do purchase, _ = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.purchase_refund_policy.max_refund_period_in_days).to eq(30) expect(purchase.purchase_refund_policy.title).to eq("30-day money back guarantee") expect(purchase.purchase_refund_policy.fine_print).to eq("This is an account-level refund policy") end context "when seller_refund_policy_disabled_for_all feature flag is set to true" do before do Feature.activate(:seller_refund_policy_disabled_for_all) end it "saves product refund policy fine print on purchase" do purchase, _ = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.purchase_refund_policy.title).to eq("30-day money back guarantee") expect(purchase.purchase_refund_policy.fine_print).to eq("This is a product-level refund policy") end end end end context "when the refund policy has no fine print" do let!(:refund_policy) do create(:product_refund_policy, fine_print: "", product:, seller: user) end it "saves product refund policy title on purchase" do purchase, _ = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.purchase_refund_policy.max_refund_period_in_days).to eq(30) expect(purchase.purchase_refund_policy.title).to eq("30-day money back guarantee") expect(purchase.purchase_refund_policy.fine_print).to eq(nil) end context "when the account-level refund policy is enabled" do before do user.refund_policy.update!(max_refund_period_in_days: 0) user.update!(refund_policy_enabled: true) end it "saves the seller-level refund policy" do purchase, _ = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.purchase_refund_policy.max_refund_period_in_days).to eq(0) expect(purchase.purchase_refund_policy.title).to eq("No refunds allowed") expect(purchase.purchase_refund_policy.fine_print).to eq(nil) end end end end context "when the purchase has an upsell" do let(:product) { create(:product_with_digital_versions, user:) } let(:upsell) { create(:upsell, seller: user, product:) } let!(:upsell_variant) { create(:upsell_variant, upsell:, selected_variant: product.alive_variants.first, offered_variant: product.alive_variants.second) } before do params[:variants] = [product.alive_variants.second.external_id] params[:purchase][:perceived_price_cents] = 100 params[:accepted_offer] = { id: upsell.external_id, original_product_id: product.external_id, original_variant_id: product.alive_variants.first.external_id, } end context "when the upsell is valid" do it "creates an upsell purchase record" do purchase, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.upsell_purchase.upsell).to eq(upsell) expect(purchase.upsell_purchase.upsell_variant).to eq(upsell_variant) expect(purchase.upsell_purchase.selected_product).to eq(product) expect(error).to be_nil end end context "when the upsell is paused" do before do upsell.update!(paused: true) end it "returns an error" do _, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(error).to eq("Sorry, this offer is no longer available.") end end context "when the upsell variant doesn't exist" do before do params[:accepted_offer][:original_variant_id] = "invalid" end it "returns an error" do _, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(error).to eq("The upsell purchase must have an associated upsell variant.") end end end context "when the purchase has a cross-sell" do let(:selected_product) { create(:product, user:) } let(:product) { create(:product_with_digital_versions, user:) } let(:cross_sell) { create(:upsell, seller: user, product:, variant: product.alive_variants.first, selected_products: [selected_product], offer_code: create(:offer_code, user:, products: [product]), cross_sell: true) } before do params[:purchase][:perceived_price_cents] = 0 params[:variants] = [product.alive_variants.first.external_id] params[:accepted_offer] = { id: cross_sell.external_id, original_product_id: selected_product.external_id, } params[:cart_items] = [ { permalink: product.unique_permalink, price_cents: 0, }, { permalink: selected_product.unique_permalink, price_cents: 0, } ] end context "when the cross-sell is valid" do it "creates an upsell purchase record" do purchase, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.upsell_purchase.upsell).to eq(cross_sell) expect(purchase.upsell_purchase.upsell_variant).to eq(nil) expect(purchase.upsell_purchase.selected_product).to eq(selected_product) expect(purchase.offer_code).to eq(cross_sell.offer_code) expect(purchase.purchase_offer_code_discount.offer_code).to eq(cross_sell.offer_code) expect(purchase.purchase_offer_code_discount.offer_code_amount).to eq(100) expect(purchase.purchase_offer_code_discount.offer_code_is_percent?).to eq(false) expect(purchase.purchase_offer_code_discount.pre_discount_minimum_price_cents).to eq(100) expect(error).to be_nil end end context "when the selected product isn't in the cart" do before do params[:cart_items] = [{ permalink: product.unique_permalink, price_cents: 0 }] end it "returns an error" do _, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(error).to eq("The cart does not have any products to which the upsell applies.") end context "when the cross-sell is a replacement cross-sell" do before do cross_sell.update!(replace_selected_products: true) end it "creates an upsell purchase record" do purchase, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.upsell_purchase.upsell).to eq(cross_sell) expect(purchase.upsell_purchase.upsell_variant).to eq(nil) expect(purchase.upsell_purchase.selected_product).to eq(selected_product) expect(purchase.offer_code).to eq(cross_sell.offer_code) expect(purchase.purchase_offer_code_discount.offer_code).to eq(cross_sell.offer_code) expect(purchase.purchase_offer_code_discount.offer_code_amount).to eq(100) expect(purchase.purchase_offer_code_discount.offer_code_is_percent?).to eq(false) expect(purchase.purchase_offer_code_discount.pre_discount_minimum_price_cents).to eq(100) expect(error).to be_nil end end end context "when the purchase already has an offer code" do let(:existing_offer_code) { create(:offer_code, user:, products: [product], amount_cents: 200, code: "existing789") } before do params[:purchase][:offer_code] = existing_offer_code end it "retains the existing offer code instead of using the upsell offer code" do purchase, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(purchase.upsell_purchase.upsell).to eq(cross_sell) expect(purchase.upsell_purchase.selected_product).to eq(selected_product) expect(purchase.offer_code).to eq(existing_offer_code) expect(purchase.purchase_offer_code_discount.offer_code).to eq(existing_offer_code) expect(purchase.purchase_offer_code_discount.offer_code_amount).to eq(200) expect(error).to be_nil end end end describe "bundle purchases" do let(:product) { create(:product, :bundle) } context "when the bundle's products have not changed" do before do product.bundle_products.create(product: create(:product, user: product.user), deleted_at: Time.current) params[:purchase][:perceived_price_cents] = 100 params[:bundle_products] = [ { product_id: product.bundle_products.first.product.external_id, variant_id: nil, quantity: 1, }, { product_id: product.bundle_products.second.product.external_id, variant_id: nil, quantity: 1, } ] end it "creates a purchase" do purchase, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(error).to be_nil expect(purchase.purchase_state).to eq("successful") expect(purchase.is_bundle_purchase?).to eq(true) end end context "when the bundle's products have changed" do before do params[:purchase][:perceived_price_cents] = 100 params[:bundle_products] = [ { product_id: product.bundle_products.first.product.external_id, variant_id: nil, quantity: 1, } ] end it "returns an error" do _, error = Purchase::CreateService.new( product:, params:, buyer: ).perform expect(error).to eq("The bundle's contents have changed. Please refresh the page!") end end end context "when the discount code has a minimum amount" do let(:seller) { create(:named_seller) } let(:product1) { create(:product, name: "Product 1", user: seller) } let(:product2) { create(:product, name: "Product 2", user: seller) } let(:product3) { create(:product, name: "Product 3", user: seller) } let(:offer_code) { create(:offer_code, user: seller, products: [product1, product3], minimum_amount_cents: 200) } context "when the cart items meet the minimum amount" do before do params[:purchase][:perceived_price_cents] = 0 params[:cart_items] = [ { permalink: product1.unique_permalink, price_cents: 100, }, { permalink: product3.unique_permalink, price_cents: 100, } ] params[:purchase][:discount_code] = offer_code.code end it "creates the purchase" do purchase, error = Purchase::CreateService.new( product: product1, params:, buyer: ).perform expect(purchase.offer_code).to eq(offer_code) expect(purchase.link).to eq(product1) expect(error).to be_nil end end context "when the cart items don't meet the minimum amount" do before do params[:purchase][:perceived_price_cents] = 0 params[:cart_items] = [ { permalink: product1.unique_permalink, price_cents: 100, }, { permalink: product2.unique_permalink, price_cents: 100, } ] params[:purchase][:discount_code] = offer_code.code end it "creates the purchase" do _, error = Purchase::CreateService.new( product: product1, params:, buyer: ).perform expect(error).to eq("Sorry, you have not met the offer code's minimum amount.") end end end context "for failed purchase" do it "creates a purchase and sets the proper state" do params[:purchase][:chargeable] = failed_chargeable purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq "failed" expect(purchase.card_country).to be_present expect(purchase.stripe_fingerprint).to be_present end it "does not enqueue activate integrations worker" do params[:purchase][:chargeable] = failed_chargeable purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq "failed" expect(ActivateIntegrationsWorker.jobs.size).to eq(0) end describe "handling of unexpected errors" do context "when a rate limit error occurs" do it "does not leave the purchase in in_progress state" do expect do expect do expect do expect(Stripe::PaymentIntent).to receive(:create).and_raise(Stripe::RateLimitError) Purchase::CreateService.new(product:, params:).perform end.to raise_error(ChargeProcessorError) end.to change { Purchase.failed.count }.by(1) end.not_to change { Purchase.in_progress.count } end end context "when a generic Stripe error occurs" do it "does not leave the purchase in in_progress state" do expect do expect(Stripe::PaymentIntent).to receive(:create).and_raise(Stripe::IdempotencyError) purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq("failed") end.not_to change { Purchase.in_progress.count } end end context "when a generic Braintree error occurs" do it "does not leave the purchase in in_progress state" do expect do expect(Braintree::Transaction).to receive(:sale).and_raise(Braintree::BraintreeError) purchase, _ = Purchase::CreateService.new(product:, params: paypal_params).perform expect(purchase.purchase_state).to eq("failed") end.not_to change { Purchase.in_progress.count } end end context "when a PayPal connection error occurs" do it "does not leave the purchase in in_progress state" do create(:merchant_account_paypal, user: product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L", currency: "gbp") expect do expect_any_instance_of(PayPal::PayPalHttpClient).to receive(:execute).and_raise(PayPalHttp::HttpError.new(418, OpenStruct.new(details: [OpenStruct.new(description: "IO Error")]), nil)) purchase, _ = Purchase::CreateService.new(product:, params: native_paypal_params).perform expect(purchase.purchase_state).to eq("failed") end.not_to change { Purchase.in_progress.count } end end context "when unexpected runtime error occurs mid purchase" do it "does not leave the purchase in in_progress state" do expect do expect do expect do expect_any_instance_of(Purchase).to receive(:charge!).and_raise(RuntimeError) Purchase::CreateService.new(product:, params: paypal_params).perform end.to raise_error(RuntimeError) end.to change { Purchase.failed.count }.by(1) end.not_to change { Purchase.in_progress.count } end end end end it "enqueues activate integrations worker if purchase succeeds" do purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq("successful") expect(ActivateIntegrationsWorker).to have_enqueued_sidekiq_job(purchase.id) end it "saves the users locale in json_data" do params[:purchase][:locale] = "de" purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.locale).to eq "de" end describe "purchases that require SCA" do describe "preorder" do let(:product_in_preorder) { create(:product, user:, price_cents: price, is_in_preorder_state: true) } let!(:preorder_product) { create(:preorder_link, link: product_in_preorder) } before do allow_any_instance_of(StripeSetupIntent).to receive(:requires_action?).and_return(true) end it "creates an in_progress purchase and scheduled a job to check for abandoned SCA later" do expect do expect do purchase, _ = Purchase::CreateService.new(product: product_in_preorder, params: preorder_params).perform expect(purchase.purchase_state).to eq "in_progress" expect(purchase.preorder.state).to eq "in_progress" expect(FailAbandonedPurchaseWorker).to have_enqueued_sidekiq_job(purchase.id) end.to change(Purchase, :count).by(1) end.to change(Preorder, :count).by(1) end end describe "classic product" do before do allow_any_instance_of(StripeChargeIntent).to receive(:requires_action?).and_return(true) end it "creates an in_progress purchase and scheduled a job to check for abandoned SCA later" do expect do purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq "in_progress" expect(FailAbandonedPurchaseWorker).to have_enqueued_sidekiq_job(purchase.id) end.to change { Purchase.count }.by 1 end end describe "membership" do before do allow_any_instance_of(StripeChargeIntent).to receive(:requires_action?).and_return(true) end it "creates an in_progress purchase and renders a proper response" do expect do expect do purchase, _ = Purchase::CreateService.new(product: subscription_product, params: subscription_params).perform expect(purchase.purchase_state).to eq "in_progress" expect(FailAbandonedPurchaseWorker).to have_enqueued_sidekiq_job(purchase.id) end.to change(Purchase.in_progress, :count).by(1) end.not_to change(Subscription, :count) end end end describe "perceived_price_cents" do context "when present" do it "sets the purchase's perceived_price_cents" do purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.perceived_price_cents).to eq 600 end end context "when absent" do it "sets the purchase's perceived_price_cents to nil" do params[:purchase][:perceived_price_cents] = nil purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.perceived_price_cents).to be_nil end end end describe "is_mobile" do it "sets is_mobile to `false` if not mobile" do purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.is_mobile).to be false end it "sets is_mobile to `true` if is mobile" do params[:purchase][:is_mobile] = true purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.is_mobile).to be true end end describe "multi_buy" do it "sets is_multi_buy field to true if purchase is part of multi-buy" do params[:purchase][:is_multi_buy] = "true" purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.is_multi_buy).to be true end it "sets is_multi_buy field to false if purchase is not part of multi-buy" do params[:purchase][:is_multi_buy] = nil purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.is_multi_buy).to be false end end describe "expiry fields" do it "allows a bad expiry_date" do _, error = Purchase::CreateService.new( product:, params: params.merge(expiry_date: "01/01/2011") ).perform expect(error).to be_nil end it "accepts 4 digit expiry year and does not prepend it with 20" do params[:expiry_date] = "12/2023" purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq "successful" expect(purchase.card_expiry_month).to eq 12 expect(purchase.card_expiry_year).to eq 2023 end context "with expiry date field instead of month and year" do it "accepts expiry date in one field" do params[:expiry_month] = params[:expiry_year] = "" params[:expiry_date] = "12/23" purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq "successful" expect(purchase.card_expiry_month).to eq 12 expect(purchase.card_expiry_year).to eq 2023 end it "accepts 5 digit expiry date field with spaces and dash" do params[:expiry_month] = params[:expiry_year] = "" params[:expiry_date] = "12 - 23" purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.purchase_state).to eq "successful" expect(purchase.card_expiry_month).to eq 12 expect(purchase.card_expiry_year).to eq 2023 end end end context "when the user has a different currency" do describe "english pound" do it "sets the displayed price on the purchase" do product.update!(price_currency_type: :gbp, price_cents: 600) product.reload purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.displayed_price_cents).to eq price expect(purchase.displayed_price_currency_type).to eq :gbp expect(purchase.price_cents).to eq 919 expect(purchase.total_transaction_cents).to eq 919 expect(purchase.rate_converted_to_usd).to eq "0.652571" end end describe "yen" do before :each do product.update!(price_currency_type: :jpy, price_cents: 100) product.reload end it "sets the displayed price on the purchase" do purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.price_cents).to eq 128 # in usd expect(purchase.total_transaction_cents).to eq 128 # in usd expect(purchase.displayed_price_cents).to eq 100 # in jpy end it "properly increments users balance" do params[:purchase][:perceived_price_cents] = 100 Purchase::CreateService.new( product:, params: ).perform expect(user.unpaid_balance_cents).to eq 31 # 128c (price) - 13c (10% flat fee) - 50c - 4c (2.9% cc fee) - 30c (fixed cc fee) end end end describe "purchase emails" do it "sends the correct purchase emails" do mail_double = double allow(mail_double).to receive(:deliver_later) expect(ContactingCreatorMailer).to receive(:notify).and_return(mail_double) Purchase::CreateService.new(product:, params:).perform expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(Purchase.last.id).on("critical") end it "sends the correct purchase emails for zero plus links" do mail_double = double allow(mail_double).to receive(:deliver_later) expect(ContactingCreatorMailer).to receive(:notify).and_return(mail_double) product.update!(price_range: "0+") params[:purchase].merge!(perceived_price_cents: 0, price_range: "0") Purchase::CreateService.new(product:, params:).perform expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(Purchase.last.id).on("critical") end it "does not send the purchase emails to creator for free downloads if notifications are disabled" do expect(ContactingCreatorMailer).to_not receive(:mail) user.update!(enable_free_downloads_email: true) product.update!(price_range: "0") params[:purchase].merge!(perceived_price_cents: 0, price_range: "0") Sidekiq::Testing.inline! do Purchase::CreateService.new(product:, params:).perform end end it "does not send the purchase notification to creator for free downloads if notifications are disabled" do user.update!(enable_free_downloads_push_notification: true) product.update!(price_range: "0") params[:purchase].merge!(perceived_price_cents: 0, price_range: "0") Sidekiq::Testing.inline! do Purchase::CreateService.new(product:, params:).perform end expect(PushNotificationWorker.jobs.size).to eq(0) end it "does not send the owner an email update if they've turned off payment notifications" do user.update_attribute(:enable_payment_email, false) expect(ContactingCreatorMailer).to_not receive(:mail) Sidekiq::Testing.inline! do Purchase::CreateService.new(product:, params:).perform end end it "does not send the creator a push notification if they've turned off payment notifications" do user.update!(enable_payment_push_notification: true) Sidekiq::Testing.inline! do Purchase::CreateService.new(product:, params:).perform end expect(PushNotificationWorker.jobs.size).to eq(0) end end context "with quantity greater than 1" do let(:quantity_params) do params[:purchase].merge!(quantity: 4) params end it "creates a purchase with quantity set" do expect do purchase, _ = Purchase::CreateService.new(product:, params: quantity_params).perform expect(purchase.quantity).to eq 4 end.to change { Purchase.count }.by(1) end context "and greater than what is available for the product" do it "returns an error" do product.update!(max_purchase_count: 3) purchase, error = Purchase::CreateService.new(product:, params: quantity_params).perform expect(purchase.failed?).to be true expect(purchase.error_code).to eq "exceeding_product_quantity" expect(error).to eq "You have chosen a quantity that exceeds what is available." end end end context "with url redirect" do it "creates a UrlRedirect object" do expect do Purchase::CreateService.new(product:, params:).perform end.to change { UrlRedirect.count }.by(1) end end context "with url_parameters" do it "parses 'url_parameters' containing single quotes correctly and allows purchase" do params[:purchase][:url_parameters] = "{'source_url':'https%3A%2F%2Fwww.afrodjmac.com%2Fblog%2F2013%2F01%2F10%2Ffender-rhodes-ableton-live-pack'}" purchase, _ = Purchase::CreateService.new(product:, params:).perform expect(purchase.url_parameters["source_url"]).to eq "https%3A%2F%2Fwww.afrodjmac.com%2Fblog%2F2013%2F01%2F10%2Ffender-rhodes-ableton-live-pack" expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(Purchase.last.id, JSON.parse(params[:purchase][:url_parameters])) end it "parses 'url_parameters' not containing single quotes correctly and allows purchase" do params[:purchase][:url_parameters] = "{\"source_url\":\"https%3A%2F%2Fwww.afrodjmac.com%2Fblog%2F2013%2F01%2F10%2Ffender-rhodes-ableton-live-pack\"}" purchase, _ = Purchase::CreateService.new(product:, params:).perform
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/purchase/variant_updater_service_spec.rb
spec/services/purchase/variant_updater_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::VariantUpdaterService do describe ".perform" do context "when the product has variants" do before :each do @product = create(:product) @category1 = create(:variant_category, link: @product, title: "Color") category2 = create(:variant_category, link: @product, title: "Size") @blue_variant = create(:variant, variant_category: @category1, name: "Blue") @green_variant = create(:variant, variant_category: @category1, name: "Green") @small_variant = create(:variant, variant_category: category2, name: "Small") end context "and the purchase has a variant for the category" do it "updates the variant" do purchase = create( :purchase, link: @product, variant_attributes: [@blue_variant, @small_variant] ) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: @green_variant.external_id, quantity: purchase.quantity, ).perform expect(success).to be true expect(purchase.reload.variant_attributes).to match_array [@green_variant, @small_variant] end end context "and the purchase doesn't have a variant for the category" do it "adds the variant" do purchase = create( :purchase, link: @product, variant_attributes: [@small_variant] ) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: @green_variant.external_id, quantity: purchase.quantity, ).perform expect(success).to be true expect(purchase.reload.variant_attributes).to match_array [@small_variant, @green_variant] end end context "and there is insufficient inventory" do context "when switching variants" do it "returns an error" do red_variant = create(:variant, variant_category: @category1, name: "Red", max_purchase_count: 1) purchase = create( :purchase, link: @product, quantity: 2, variant_attributes: [@small_variant] ) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: red_variant.external_id, quantity: purchase.quantity, ).perform expect(success).to be false purchase.reload expect(purchase.variant_attributes).to eq [@small_variant] expect(purchase.quantity).to eq 2 end end context "when not switching variants" do it "returns an error" do purchase = create( :purchase, link: @product, quantity: 2, variant_attributes: [@small_variant] ) @small_variant.update!(max_purchase_count: 3) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: @small_variant.external_id, quantity: 4, ).perform expect(success).to be false expect(purchase.reload.quantity).to eq 2 end end end context "gift sender purchase" do let(:gift_sender_purchase) do create( :purchase, link: @product, variant_attributes: [@blue_variant], is_gift_sender_purchase: true ) end let(:gift_receiver_purchase) do create( :purchase, link: @product, variant_attributes: [@blue_variant], is_gift_receiver_purchase: true, ) end before do create(:gift, gifter_purchase: gift_sender_purchase, giftee_purchase: gift_receiver_purchase) gift_sender_purchase.reload gift_receiver_purchase.reload end it "invokes the service on the gift receiver purchase" do allow(Purchase::VariantUpdaterService).to receive(:new).and_call_original expect(Purchase::VariantUpdaterService).to receive(:new).with( purchase: gift_receiver_purchase, variant_id: @green_variant.external_id, quantity: 1, ).and_call_original success = Purchase::VariantUpdaterService.new( purchase: gift_sender_purchase, variant_id: @green_variant.external_id, quantity: 1, ).perform expect(success).to be true expect(gift_sender_purchase.reload.variant_attributes).to eq [@green_variant] expect(gift_receiver_purchase.reload.variant_attributes).to eq [@green_variant] end end end context "when the product has SKUs" do before :each do @product = create(:physical_product) create(:variant_category, link: @product, title: "Color") create(:variant_category, link: @product, title: "Size") @large_blue_sku = create(:sku, link: @product, name: "Blue - large") @small_green_sku = create(:sku, link: @product, name: "Green - small") end context "and the purchase has a SKU" do it "updates the SKU" do purchase = create( :physical_purchase, link: @product, variant_attributes: [@large_blue_sku] ) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: @small_green_sku.external_id, quantity: purchase.quantity, ).perform expect(success).to be true expect(purchase.reload.variant_attributes).to eq [@small_green_sku] end end context "and the purchase doesn't have a SKU" do it "adds the SKU" do purchase = create( :physical_purchase, link: @product ) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: @small_green_sku.external_id, quantity: purchase.quantity, ).perform expect(success).to be true expect(purchase.reload.variant_attributes).to eq [@small_green_sku] end end context "and there is insufficient inventory" do it "returns an error" do medium_green_sku = create(:sku, link: @product, name: "Green - medium", max_purchase_count: 1) purchase = create( :physical_purchase, link: @product, quantity: 2, variant_attributes: [@large_blue_sku] ) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: medium_green_sku.external_id, quantity: purchase.quantity, ).perform expect(success).to be false expect(purchase.reload.variant_attributes).to eq [@large_blue_sku] end end end context "with invalid arguments" do context "such as an invalid variant_id" do it "returns an error" do purchase = create(:purchase) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: "fake-id", quantity: purchase.quantity, ).perform expect(success).to be false end end context "such as a variant that doesn't belong to the right product" do it "returns an error" do purchase = create(:purchase) variant = create(:variant) success = Purchase::VariantUpdaterService.new( purchase:, variant_id: variant.external_id, quantity: purchase.quantity, ).perform expect(success).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/services/workflow/manage_service_spec.rb
spec/services/workflow/manage_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Workflow::ManageService do before do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE) # create(:payment_completed, user: seller) end describe "#process" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } context "when workflow does not exist" do let(:params) { { name: "My workflow", permalink: product.unique_permalink, workflow_type: Workflow::PRODUCT_TYPE, send_to_past_customers: false } } it "creates a product workflow" do params[:send_to_past_customers] = true expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.name).to eq("My workflow") expect(workflow.workflow_type).to eq(Workflow::PRODUCT_TYPE) expect(workflow.link).to eq(product) expect(workflow.seller_id).to eq(seller.id) expect(workflow.published_at).to be_nil expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil expect(workflow.send_to_past_customers).to be(true) end it "creates a variant workflow" do variant_category = create(:variant_category, link: product) variant = create(:variant, variant_category:) params[:workflow_type] = Workflow::VARIANT_TYPE params[:variant_external_id] = variant.external_id expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.name).to eq("My workflow") expect(workflow.workflow_type).to eq(Workflow::VARIANT_TYPE) expect(workflow.link).to eq(product) expect(workflow.seller_id).to eq(seller.id) expect(workflow.base_variant).to eq(variant) expect(workflow.workflow_trigger).to be_nil expect(workflow.send_to_past_customers).to be(false) end it "creates a seller workflow" do params[:workflow_type] = Workflow::SELLER_TYPE expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.workflow_type).to eq(Workflow::SELLER_TYPE) expect(workflow.link).to be_nil expect(workflow.seller_id).to eq(seller.id) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil end it "creates an audience workflow" do params[:workflow_type] = Workflow::AUDIENCE_TYPE expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.workflow_type).to eq(Workflow::AUDIENCE_TYPE) expect(workflow.link).to be_nil expect(workflow.seller_id).to eq(seller.id) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil end it "creates a follower workflow" do params[:workflow_type] = Workflow::FOLLOWER_TYPE expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.workflow_type).to eq(Workflow::FOLLOWER_TYPE) expect(workflow.link).to be_nil expect(workflow.seller_id).to eq(seller.id) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil end it "creates an affiliate workflow" do params[:workflow_type] = Workflow::AFFILIATE_TYPE params[:affiliate_products] = [product.unique_permalink] expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.workflow_type).to eq(Workflow::AFFILIATE_TYPE) expect(workflow.link).to be_nil expect(workflow.seller_id).to eq(seller.id) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil expect(workflow.affiliate_products).to eq([product.unique_permalink]) end it "creates a workflow with 'member_cancellation' trigger" do params[:workflow_trigger] = Workflow::MEMBER_CANCELLATION_WORKFLOW_TRIGGER expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.workflow_type).to eq(Workflow::PRODUCT_TYPE) expect(workflow.link).to eq(product) expect(workflow.seller_id).to eq(seller.id) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to eq(Workflow::MEMBER_CANCELLATION_WORKFLOW_TRIGGER) end it "creates a workflow with the new customer trigger when 'workflow_type' is 'audience'" do params[:workflow_type] = Workflow::AUDIENCE_TYPE params[:workflow_trigger] = Workflow::MEMBER_CANCELLATION_WORKFLOW_TRIGGER expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.workflow_type).to eq(Workflow::AUDIENCE_TYPE) expect(workflow.workflow_trigger).to be_nil end it "creates an abandoned cart workflow with a ready-made installment" do create(:payment_completed, user: seller) params.merge!( workflow_type: Workflow::ABANDONED_CART_TYPE, bought_products: ["F"], ) expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) .and change { Installment.count }.from(0).to(1) workflow = Workflow.last expect(workflow.workflow_type).to eq(Workflow::ABANDONED_CART_TYPE) expect(workflow.link).to be_nil expect(workflow.seller_id).to eq(seller.id) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil expect(workflow.bought_products).to eq(["F"]) expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil expect(workflow.installments.count).to eq(1) installment = workflow.installments.alive.sole expect(installment.name).to eq("You left something in your cart") expect(installment.message).to eq(%Q(<p>When you're ready to buy, <a href="#{Rails.application.routes.url_helpers.checkout_index_url(host: UrlService.domain_with_protocol)}" target="_blank" rel="noopener noreferrer nofollow">complete checking out</a>.</p><product-list-placeholder />)) expect(installment.installment_type).to eq(Installment::ABANDONED_CART_TYPE) expect(installment.json_data).to eq(workflow.json_data) expect(installment.seller_id).to eq(workflow.seller_id) expect(installment.send_emails).to be(true) expect(installment.installment_rule.time_period).to eq(InstallmentRule::HOUR) expect(installment.installment_rule.delayed_delivery_time).to eq(24.hours) end it "returns error if seller is not eligible for abandoned cart workflows" do params[:workflow_type] = Workflow::ABANDONED_CART_TYPE expect do service = described_class.new(seller:, params:, product:, workflow: nil) expect(service.process).to eq([false, "You must have at least one completed payout to create an abandoned cart workflow"]) end.not_to change { Workflow.count } end describe "filters" do before do params.merge!( bought_products: ["F"], paid_more_than: "", paid_less_than: "10", created_after: "2019-01-01", created_before: "2020-12-31", bought_from: "United States", ) end it "creates a workflow with filters" do expect do expect(described_class.new(seller:, params:, product:, workflow: nil).process).to eq([true, nil]) end.to change { Workflow.count }.from(0).to(1) workflow = Workflow.last expect(workflow.bought_products).to eq(["F"]) expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil expect(workflow.paid_more_than_cents).to be_nil expect(workflow.paid_less_than_cents).to eq(1000) expect(workflow.affiliate_products).to be_nil expect(workflow.workflow_trigger).to be_nil timezone = ActiveSupport::TimeZone[seller.timezone] expect(workflow.created_after).to eq(timezone.parse("2019-01-01").as_json) expect(workflow.created_before).to eq(timezone.parse("2020-12-31").end_of_day.as_json) expect(workflow.bought_from).to eq("United States") end it "returns false if the paid filters are invalid" do params[:paid_more_than] = "10" params[:paid_less_than] = "5" expect do service = described_class.new(seller:, params:, product:, workflow: nil) expect(service.process).to eq([false, "Please enter valid paid more than and paid less than values."]) end.not_to change { Workflow.count } end it "returns false if the date filters are invalid" do params[:created_after] = "2020-12-31" params[:created_before] = "2019-01-01" expect do service = described_class.new(seller:, params:, product:, workflow: nil) expect(service.process).to eq([false, "Please enter valid before and after dates."]) end.not_to change { Workflow.count } end end end context "when workflow already exists" do let!(:workflow) { create(:workflow, seller:, link: product, workflow_type: Workflow::PRODUCT_TYPE) } let!(:installment1) { create(:workflow_installment, workflow:, name: "Installment 1") } let!(:installment2) { create(:workflow_installment, workflow:, name: "Installment 3", installment_type: Installment::PRODUCT_TYPE, deleted_at: 2.days.ago) } let(:params) { { name: "Updated workflow name", permalink: product.unique_permalink, workflow_type: Workflow::AFFILIATE_TYPE, affiliate_products: [product.unique_permalink], send_to_past_customers: false } } it "updates the workflow and its installments" do expect_any_instance_of(Workflow).to_not receive(:schedule_installment) expect do expect(described_class.new(seller:, params:, product:, workflow:).process).to eq([true, nil]) end.to change { Workflow.count }.by(0) .and change { workflow.reload.name }.from(workflow.name).to("Updated workflow name") .and change { workflow.workflow_type }.from(Workflow::PRODUCT_TYPE).to(Workflow::AFFILIATE_TYPE) .and change { workflow.affiliate_products }.from(nil).to([product.unique_permalink]) expect(workflow.link).to be_nil expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil expect(workflow.published_at).to be_nil expect(installment1.reload.installment_type).to eq(Installment::AFFILIATE_TYPE) expect(installment1.json_data).to eq(workflow.json_data) expect(installment1.seller_id).to eq(workflow.seller_id) expect(installment1.link_id).to eq(workflow.link_id) expect(installment1.base_variant_id).to eq(workflow.base_variant_id) expect(installment1.is_for_new_customers_of_workflow).to eq(!workflow.send_to_past_customers) # Deleted installments are not touched expect(installment2.reload.installment_type).to eq(Installment::PRODUCT_TYPE) end it "updates the workflow name but ignores all other params if the workflow was previously published" do workflow.update!(first_published_at: 10.days.ago) params[:send_to_past_customers] = true expect do expect(described_class.new(seller:, params:, product:, workflow:).process).to eq([true, nil]) end.to change { Workflow.count }.by(0) .and change { workflow.reload.name }.from(workflow.name).to("Updated workflow name") expect(workflow.workflow_type).to eq(Workflow::PRODUCT_TYPE) expect(workflow.link).to eq(product) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil expect(workflow.send_to_past_customers).to be(false) expect(workflow.affiliate_products).to be_nil end context "when changing the workflow type to 'abandoned_cart'" do it "updates the workflow, deletes all existing installments and creates a ready-made abandoned cart installment" do params[:workflow_type] = Workflow::ABANDONED_CART_TYPE expect do expect(described_class.new(seller:, params:, product:, workflow:).process).to eq([true, nil]) end.to change { Workflow.count }.by(0) .and change { workflow.reload.workflow_type }.from(Workflow::PRODUCT_TYPE).to(Workflow::ABANDONED_CART_TYPE) .and change { workflow.installments.deleted.count }.by(1) expect(workflow.link).to be_nil expect(workflow.installments.alive.count).to eq(1) expect(installment1.reload).to be_deleted installment = workflow.installments.alive.sole expect(installment.name).to eq("You left something in your cart") expect(installment.message).to eq(%Q(<p>When you're ready to buy, <a href="#{Rails.application.routes.url_helpers.checkout_index_url(host: UrlService.domain_with_protocol)}" target="_blank" rel="noopener noreferrer nofollow">complete checking out</a>.</p><product-list-placeholder />)) expect(installment.installment_type).to eq(Installment::ABANDONED_CART_TYPE) expect(installment.json_data).to eq(workflow.json_data) expect(installment.seller_id).to eq(workflow.seller_id) expect(installment.send_emails).to be(true) end end context "when changing the workflow type from 'abandoned_cart' to another type" do it "updates the workflow and deletes the abandoned cart installment" do workflow.update!(workflow_type: Workflow::ABANDONED_CART_TYPE) workflow.installments.alive.find_each(&:mark_deleted!) abandoned_cart_installment = create(:workflow_installment, workflow:, installment_type: Installment::ABANDONED_CART_TYPE) params[:workflow_type] = Workflow::PRODUCT_TYPE expect do expect(described_class.new(seller:, params:, product:, workflow:).process).to eq([true, nil]) end.to change { Workflow.count }.by(0) .and change { workflow.reload.workflow_type }.from(Workflow::ABANDONED_CART_TYPE).to(Workflow::PRODUCT_TYPE) .and change { workflow.installments.deleted.count }.by(1) expect(workflow.link).to eq(product) expect(workflow.installments.alive).to be_empty expect(abandoned_cart_installment.reload).to be_deleted end end it "updates the workflow filters" do workflow.update!(paid_more_than_cents: 50, bought_products: ["abc"], created_before: ActiveSupport::TimeZone[seller.timezone].parse("2025-05-10").end_of_day) params.merge!( workflow_type: Workflow::SELLER_TYPE, bought_products: ["F"], paid_more_than: "", paid_less_than: "10", created_after: "2019-01-01", created_before: "2020-12-31", bought_from: "United States", affiliate_products: [], ) timezone = ActiveSupport::TimeZone[seller.timezone] expect do expect(described_class.new(seller:, params:, product:, workflow:).process).to eq([true, nil]) end.to change { Workflow.count }.by(0) .and change { workflow.reload.bought_products }.from(["abc"]).to(["F"]) .and change { workflow.paid_more_than_cents }.from(50).to(nil) .and change { workflow.paid_less_than_cents }.from(nil).to(1000) .and change { workflow.created_after }.from(nil).to(timezone.parse("2019-01-01").as_json) .and change { workflow.created_before }.from(timezone.parse("2025-05-10").end_of_day.as_json).to(timezone.parse("2020-12-31").end_of_day.as_json) .and change { workflow.bought_from }.from(nil).to("United States") expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil expect(workflow.affiliate_products).to be_nil expect(workflow.workflow_trigger).to be_nil end it "updates the workflow and publishes it if the save action is 'save_and_publish'" do params[:save_action_name] = Workflow::SAVE_AND_PUBLISH_ACTION create(:payment_completed, user: seller) expect_any_instance_of(Workflow).to receive(:schedule_installment).with(installment1) expect do expect(described_class.new(seller:, params:, product:, workflow:).process).to eq([true, nil]) end.to change { Workflow.count }.by(0) .and change { workflow.reload.name }.from(workflow.name).to("Updated workflow name") expect(workflow.workflow_type).to eq(Workflow::AFFILIATE_TYPE) expect(workflow.link).to be_nil expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil expect(workflow.published_at).to be_present expect(workflow.first_published_at).to eq(workflow.published_at) expect(workflow.installments.alive.pluck(:published_at)).to eq([workflow.published_at]) # Deleted installments are not touched expect(installment2.reload.installment_type).to eq(Installment::PRODUCT_TYPE) expect(installment2.reload.alive?).to be(false) expect(installment2.reload.published_at).to be_nil end it "updates the workflow and unpublishes it if the save action is 'save_and_unpublish'" do stripe_connect_account = create(:merchant_account_stripe_connect, user: seller) create(:purchase, seller:, link: product, merchant_account: stripe_connect_account) workflow.publish! params[:save_action_name] = Workflow::SAVE_AND_UNPUBLISH_ACTION params[:paid_less_than] = "50" expect_any_instance_of(Workflow).to_not receive(:schedule_installment) expect do expect do expect do expect(described_class.new(seller:, params:, product:, workflow:).process).to eq([true, nil]) end.to change { Workflow.count }.by(0) .and change { workflow.reload.name }.from(workflow.name).to("Updated workflow name") .and change { workflow.published_at }.from(kind_of(Time)).to(nil) end.not_to change { workflow.reload.first_published_at } end.not_to change { workflow.reload.paid_less_than_cents } # Does not update attributes other than 'name' as the workflow was previously published expect(workflow.workflow_type).to eq(Workflow::PRODUCT_TYPE) expect(workflow.link).to eq(product) expect(workflow.base_variant).to be_nil expect(workflow.workflow_trigger).to be_nil expect(workflow.published_at).to be_nil expect(workflow.first_published_at).to be_present expect(workflow.installments.alive.pluck(:published_at)).to eq([nil]) end it "does not save changes while publishing the workflow if the seller's email is not confirmed" do stripe_connect_account = create(:merchant_account_stripe_connect, user: seller) create(:purchase, seller:, link: product, merchant_account: stripe_connect_account) seller.update!(confirmed_at: nil) params[:save_action_name] = Workflow::SAVE_AND_PUBLISH_ACTION expect do service = described_class.new(seller:, params:, product:, workflow:) expect(service.process).to eq([false, "You have to confirm your email address before you can do that."]) end.not_to change { workflow.reload.name } expect(workflow.affiliate_products).to be_nil end it "returns an error if the paid filters are invalid" do params[:workflow_type] = Workflow::PRODUCT_TYPE params[:paid_more_than] = "10" params[:paid_less_than] = "5" expect do service = described_class.new(seller:, params:, product:, workflow:) expect(service.process).to eq([false, "Please enter valid paid more than and paid less than values."]) end.not_to change { workflow.reload } end it "returns an error if the date filters are invalid" do params[:workflow_type] = Workflow::PRODUCT_TYPE params[:created_after] = "2020-12-31" params[:created_before] = "2019-01-01" expect do service = described_class.new(seller:, params:, product:, workflow:) expect(service.process).to eq([false, "Please enter valid before and after dates."]) end.not_to change { workflow.reload } end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/workflow/save_installments_service_spec.rb
spec/services/workflow/save_installments_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Workflow::SaveInstallmentsService do before do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE) stripe_connect_account = create(:merchant_account_stripe_connect, user: seller) create(:purchase, seller:, link: product, merchant_account: stripe_connect_account) end describe "#process" do let(:seller) { create(:user) } let(:preview_email_recipient) { seller } let(:product) { create(:product, user: seller) } let!(:workflow) { create(:workflow, seller:, link: product, workflow_type: Workflow::PRODUCT_TYPE) } let(:params) { { save_action_name: Workflow::SAVE_ACTION, send_to_past_customers: false, installments: [] } } let(:default_installment_params) do { name: "An email", message: "Lorem ipsum", time_duration: 1, time_period: "hour", send_preview_email: false, files: [], } end def process_and_perform_assertions_for_created_installments params[:installments] = [default_installment_params.merge(id: SecureRandom.uuid, files: [{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/file1.mp4", position: 1, stream_only: true, subtitle_files: [{ url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub1-uuid/en.srt", language: "English" }, { url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub2-uuid/es.srt", language: "Spanish" }] }, { external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/file.pdf", position: 2, stream_only: false, subtitle_files: [] }])] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { workflow.installments.alive.count }.by(1) installment = workflow.installments.alive.last expect(installment.name).to eq("An email") expect(installment.message).to eq("Lorem ipsum") expect(installment.send_emails).to be(true) expect(installment.installment_type).to eq(workflow.workflow_type) expect(installment.json_data).to eq(workflow.json_data) expect(installment.seller_id).to eq(workflow.seller_id) expect(installment.link_id).to eq(workflow.link_id) expect(installment.base_variant_id).to eq(workflow.base_variant_id) expect(installment.is_for_new_customers_of_workflow).to eq(!workflow.send_to_past_customers) expect(installment.published_at).to eq(workflow.published_at) expect(installment.workflow_installment_published_once_already).to eq(workflow.first_published_at.present?) expect(installment.installment_rule.delayed_delivery_time).to eq(1.hour.to_i) expect(installment.installment_rule.time_period).to eq("hour") expect(installment.alive_product_files.count).to eq(2) file1 = installment.alive_product_files.first expect(file1.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/file1.mp4") expect(file1.position).to eq(1) expect(file1.stream_only).to be(true) expect(file1.filegroup).to eq("video") expect(file1.subtitle_files.alive.pluck(:language, :url)).to eq([["English", "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub1-uuid/en.srt"], ["Spanish", "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub2-uuid/es.srt"]]) file2 = installment.alive_product_files.last expect(file2.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/file.pdf") expect(file2.position).to eq(2) expect(file2.stream_only).to be(false) expect(file2.filegroup).to eq("document") end def process_and_perform_assertions_for_updated_installments installment = create(:workflow_installment, seller:, link: product, workflow:, name: "Installment 1", message: "Message 1") video = create(:product_file, installment:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/video.mp", link: nil, position: 1, stream_only: true) video.subtitle_files << create(:subtitle_file, product_file: video, language: "English", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub1-uuid/en.srt") video.subtitle_files << create(:subtitle_file, product_file: video, language: "Spanish", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub2-uuid/es.srt") pdf = create(:product_file, installment:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/doc.pdf", link: nil, position: 2, stream_only: false) audio = create(:product_file, installment:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/audio.mp3", link: nil, position: 3, stream_only: false) params[:installments] = [default_installment_params.merge(id: installment.external_id, name: "Installment 1 (edited)", message: "Updated message", time_duration: 2, time_period: "day", files: [{ external_id: video.external_id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/video.mp4", position: 1, stream_only: true, subtitle_files: [{ url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub1-uuid/en.srt", language: "English" }, { url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub2-uuid/es.srt", language: "German" }] }, { external_id: pdf.external_id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/doc.pdf", position: 2, stream_only: false, subtitle_files: [] }, { external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/book.epub", position: 3, stream_only: false, subtitle_files: [] }])] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { workflow.installments.alive.count }.by(0) expect(installment.reload.name).to eq("Installment 1 (edited)") expect(installment.message).to eq("Updated message") expect(installment.send_emails).to be(true) expect(installment.installment_type).to eq(workflow.workflow_type) expect(installment.json_data).to eq(workflow.json_data) expect(installment.seller_id).to eq(workflow.seller_id) expect(installment.link_id).to eq(workflow.link_id) expect(installment.base_variant_id).to eq(workflow.base_variant_id) expect(installment.is_for_new_customers_of_workflow).to eq(!workflow.send_to_past_customers) expect(installment.published_at).to eq(workflow.published_at) expect(installment.workflow_installment_published_once_already).to eq(workflow.first_published_at.present?) expect(installment.installment_rule.delayed_delivery_time).to eq(2.days.to_i) expect(installment.installment_rule.time_period).to eq("day") expect(installment.alive_product_files.count).to eq(3) file1 = installment.alive_product_files.first expect(file1.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/video.mp4") expect(file1.position).to eq(1) expect(file1.stream_only).to be(true) expect(file1.filegroup).to eq("video") expect(file1.subtitle_files.alive.pluck(:language, :url)).to eq([["English", "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub1-uuid/en.srt"], ["German", "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/sub2-uuid/es.srt"]]) file2 = installment.alive_product_files.second expect(file2.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/doc.pdf") expect(file2.position).to eq(2) expect(file2.stream_only).to be(false) expect(file2.filegroup).to eq("document") file3 = installment.alive_product_files.last expect(file3.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/book.epub") expect(file3.position).to eq(3) expect(file3.stream_only).to be(false) expect(file3.filegroup).to eq("document") expect(audio.reload.alive?).to be(false) end describe "for an abandoned cart workflow" do let!(:workflow) { create(:workflow, seller:, link: product, workflow_type: Workflow::ABANDONED_CART_TYPE) } it "returns an error when the number of saved installments are zero" do params[:installments] = [] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do success, error = service.process expect(success).to be(false) expect(error.full_messages.first).to eq("An abandoned cart workflow can only have one email.") end.to_not change { workflow.installments.alive.count } end it "returns an error while saving more than one installment" do params[:installments] = [default_installment_params, default_installment_params] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do success, error = service.process expect(success).to be(false) expect(error.full_messages.first).to eq("An abandoned cart workflow can only have one email.") end.to_not change { workflow.installments.alive.count } end it "saves only one installment" do params[:installments] = [default_installment_params.merge(message: "Lorem ipsum<product-list-placeholder></product-list-placeholder>")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do success, error = service.process expect(success).to be(true) expect(error).to be_nil end.to change { workflow.installments.alive.count }.by(1) installment = workflow.installments.alive.last expect(installment.message).to eq("Lorem ipsum<product-list-placeholder></product-list-placeholder>") end it "appends the <product-list-placeholder /> tag to the message if it's missing" do params[:installments] = [default_installment_params.merge(message: "Lorem ipsum")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do service.process end.to change { workflow.installments.alive.count }.by(1) installment = workflow.installments.alive.last expect(installment.message).to eq("Lorem ipsum<product-list-placeholder></product-list-placeholder>") end end it "creates installments" do expect_any_instance_of(Workflow).to_not receive(:schedule_installment) process_and_perform_assertions_for_created_installments end it "creates installments and publishes them if save_action_name is 'save_and_publish'" do params[:save_action_name] = Workflow::SAVE_AND_PUBLISH_ACTION expect_any_instance_of(Workflow).to receive(:schedule_installment).with(kind_of(Installment)) expect do process_and_perform_assertions_for_created_installments end.to change { workflow.reload.published_at }.from(nil).to(kind_of(Time)) .and change { workflow.first_published_at }.from(nil).to(kind_of(Time)) .and change { workflow.installments.alive.pluck(:published_at).uniq }.from([]).to([kind_of(Time)]) end it "updates installments" do expect_any_instance_of(Workflow).to_not receive(:schedule_installment) process_and_perform_assertions_for_updated_installments end it "updates installments and publishes them if save_action_name is 'save_and_publish'" do params[:save_action_name] = Workflow::SAVE_AND_PUBLISH_ACTION expect_any_instance_of(Workflow).to receive(:schedule_installment).with(kind_of(Installment)) expect do process_and_perform_assertions_for_updated_installments end.to change { workflow.reload.published_at }.from(nil).to(kind_of(Time)) .and change { workflow.first_published_at }.from(nil).to(kind_of(Time)) expect(workflow.installments.alive.pluck(:published_at).uniq).to eq([workflow.published_at]) end it "updates installments and unpublishes them if save_action_name is 'save_and_unpublish'" do workflow.publish! params[:save_action_name] = Workflow::SAVE_AND_UNPUBLISH_ACTION expect_any_instance_of(Workflow).to_not receive(:schedule_installment) expect do expect do process_and_perform_assertions_for_updated_installments end.to change { workflow.reload.published_at }.from(kind_of(Time)).to(nil) end.not_to change { workflow.first_published_at } expect(workflow.installments.alive.pluck(:published_at).uniq).to eq([nil]) end context "when delayed_delivery_time changes" do let(:installment) { create(:installment, workflow:, name: "Installment 1", message: "Message 1") } let!(:installment_rule) { create(:installment_rule, installment:, delayed_delivery_time: 1.hour.to_i, time_period: "hour") } context "when installment has been published" do before do workflow.update!(published_at: Time.current) installment.update!(published_at: workflow.published_at) end it "reschedules that installment" do expect(SendWorkflowPostEmailsJob).to receive(:perform_async).with(installment.id, installment.published_at.iso8601) params[:installments] = [default_installment_params.merge(id: installment.external_id, time_duration: 2, time_period: "day")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do service.process end.to change { installment.reload.installment_rule.delayed_delivery_time }.from(1.hour.to_i).to(2.days.to_i) .and change { installment.reload.installment_rule.time_period }.from("hour").to("day") end it "does not reschedule that installment if save_action_name is other than 'save'" do expect(SendWorkflowPostEmailsJob).not_to receive(:perform_async) expect_any_instance_of(Workflow).to_not receive(:schedule_installment) params[:installments] = [default_installment_params.merge(id: installment.external_id, time_duration: 2, time_period: "day", send_preview_email: true)] params[:save_action_name] = Workflow::SAVE_AND_PUBLISH_ACTION service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do service.process end.to change { installment.reload.installment_rule.delayed_delivery_time }.from(1.hour.to_i).to(2.days.to_i) .and change { installment.reload.installment_rule.time_period }.from("hour").to("day") end end context "when installment has not been published" do it "does not reschedule that installment" do expect(SendWorkflowPostEmailsJob).not_to receive(:perform_async) params[:installments] = [default_installment_params.merge(id: installment.external_id, time_duration: 2, time_period: "day")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do service.process end.to change { installment.reload.installment_rule.delayed_delivery_time }.from(1.hour.to_i).to(2.days.to_i) .and change { installment.reload.installment_rule.time_period }.from("hour").to("day") end end end it "reschedules a newly added installment if the workflow is already published" do workflow.publish! expect_any_instance_of(Workflow).to receive(:schedule_installment).with(kind_of(Installment), old_delayed_delivery_time: nil) params[:installments] = [default_installment_params.merge(id: SecureRandom.uuid, time_duration: 1, time_period: "hour")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do service.process end.to change { workflow.installments.alive.count }.by(1) installment = workflow.installments.alive.last expect(installment.installment_rule.delayed_delivery_time).to eq(1.hour.to_i) expect(installment.installment_rule.time_period).to eq("hour") expect(installment.published_at).to eq(workflow.published_at) end it "does not reschedule an installment if the delayed_delivery_time does not change" do expect(SendWorkflowPostEmailsJob).not_to receive(:perform_async) installment = create(:installment, workflow:) create(:installment_rule, installment:, delayed_delivery_time: 1.hour.to_i, time_period: "hour") params[:installments] = [default_installment_params.merge(id: installment.external_id, time_duration: 1, time_period: "hour")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do service.process end.not_to change { installment.reload.installment_rule.delayed_delivery_time } end it "deletes installments that are missing from the params" do installment = create(:installment, workflow:) attached_file = create(:product_file, installment:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/doc.pdf", link: nil) service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { workflow.installments.alive.count }.by(-1) expect(installment.reload.deleted_at).to be_present # But keeps the attached file alive expect(attached_file.reload.alive?).to be(true) end it "updates the 'send_to_past_customers' flag only if the workflow is yet to be published" do # If the workflow is yet to be published, the 'send_to_past_customers' flag is updated params[:send_to_past_customers] = true params[:save_action_name] = Workflow::SAVE_AND_PUBLISH_ACTION service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { workflow.reload.send_to_past_customers }.from(false).to(true) # Since the workflow is already published, the 'send_to_past_customers' flag will be ignored afterwards params[:send_to_past_customers] = false service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.not_to change { workflow.reload.send_to_past_customers } end it "maintains a mapping of old and new installment ids" do installment1 = create(:installment, workflow:, name: "Installment 1", message: "Message 1") create(:installment, workflow:, name: "Installment 2", message: "Message 2") new_installment_temporary_id = SecureRandom.uuid params[:installments] = [ActionController::Parameters.new(id: installment1.external_id, name: "Installment 1 (edited)", message: "Updated message"), ActionController::Parameters.new(id: new_installment_temporary_id, name: "Installment 3", message: "Message 3")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { workflow.installments.alive.count }.by(0) .and change { workflow.installments.count }.by(1) expect(service.old_and_new_installment_id_mapping).to eq( installment1.external_id => installment1.external_id, new_installment_temporary_id => workflow.installments.last.external_id ) end it "does not save installments if there are errors" do params[:installments] = [default_installment_params.merge(id: SecureRandom.uuid, message: "")] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do success, errors = service.process expect(success).to be(false) expect(errors.full_messages.first).to eq("Please include a message as part of the update.") end.to_not change { workflow.installments.alive.count } expect(service.errors.full_messages.first).to eq("Please include a message as part of the update.") end it "does not save installments while publishing if the seller's email is not confirmed" do seller.update!(confirmed_at: nil) installment = create(:workflow_installment, seller:, link: product, workflow:, name: "Installment 1", message: "Message 1") params[:installments] = [ default_installment_params.merge(id: installment.external_id, name: "Installment 1 (edited)", message: "Updated message", time_duration: 2, time_period: "day", files: []), default_installment_params.merge(id: SecureRandom.uuid, message: "Test") ] params[:save_action_name] = Workflow::SAVE_AND_PUBLISH_ACTION service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do success, errors = service.process expect(success).to be(false) expect(errors.full_messages.first).to eq("You have to confirm your email address before you can do that.") end.not_to change { workflow.reload.published_at } expect(workflow.installments.alive.sole.id).to eq(installment.id) expect(installment.reload.name).to eq("Installment 1") end describe "email preview" do context "for an abandoned cart workflow" do let(:workflow) { create(:abandoned_cart_workflow, seller:) } it "sends preview email" do installment = workflow.installments.alive.first params[:installments] = [default_installment_params.merge(id: installment.external_id, name: "Updated name", message: "Updated description<product-list-placeholder></product-list-placeholder>", send_preview_email: true)] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect do service.process end.to change { installment.reload.name }.from("You left something in your cart").to("Updated name") .and change { installment.message }.from("When you're ready to buy, complete checking out.<product-list-placeholder />Thanks!").to("Updated description<product-list-placeholder></product-list-placeholder>") .and have_enqueued_mail(CustomerMailer, :abandoned_cart_preview).with(seller.id, installment.id) end end context "for a non-abandoned cart workflow" do it "sends preview email" do expect(PostSendgridApi).to receive(:process).with(post: an_instance_of(Installment), recipients: [{ email: preview_email_recipient.email }], preview: true) installment = create(:installment, workflow:) params[:installments] = [default_installment_params.merge(id: installment.external_id, name: "Updated name", send_preview_email: true)] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { installment.reload.name }.from(installment.name).to("Updated name") end end it "does not send preview email if the reciepient hasn't confirmed their email address yet" do expect(PostSendgridApi).not_to receive(:process) installment = create(:installment, workflow:) preview_email_recipient.update!(email: "new@example.com") params[:installments] = [default_installment_params.merge(id: installment.external_id, name: "Updated name", send_preview_email: true)] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to_not change { installment.reload.name } expect(service.errors.full_messages.first).to eq("You have to confirm your email address before you can do that.") end it "does not send preview email if send_preview_email is false" do expect(PostSendgridApi).not_to receive(:process) installment = create(:installment, workflow:) params[:installments] = [default_installment_params.merge(id: installment.external_id, name: "Updated name", send_preview_email: false)] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { installment.reload.name }.from(installment.name).to("Updated name") end end it "processes upsell cards in the installment message" do product = create(:product, user: seller, price_cents: 1000) message_with_upsell = %(<p>Check out this product:</p><upsell-card productid="#{product.external_id}" discount='{"type":"fixed","cents":500}'></upsell-card>) params[:installments] = [default_installment_params.merge(id: SecureRandom.uuid, message: message_with_upsell)] service = described_class.new(seller:, params:, workflow:, preview_email_recipient:) expect { service.process }.to change { Upsell.count }.by(1) .and change { OfferCode.count }.by(1) .and change { workflow.installments.alive.count }.by(1) installment = workflow.installments.alive.last expect(installment.message).to include("<upsell-card") upsell = Upsell.last expect(installment.message).to include("id=\"#{upsell.external_id}\"") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/iffy/product/ingest_service_spec.rb
spec/services/iffy/product/ingest_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::Product::IngestService do include SignedUrlHelper include Rails.application.routes.url_helpers let(:user) { create(:user) } let!(:merchant_account) { create(:merchant_account, user: user) } let(:product) { create(:product, user:, name: "Test Product", description: "A test product description.") } let(:service) { described_class.new(product) } describe "#perform" do context "when the API request is successful" do let(:successful_parsed_response) { { "status" => "success", "message" => "Content ingested successfully" } } let(:successful_response) { instance_double(HTTParty::Response, code: 200, parsed_response: successful_parsed_response, success?: true) } before do allow(HTTParty).to receive(:post).and_return(successful_response) end it "sends the correct data to the Iffy API and returns the response" do expect(HTTParty).to receive(:post).with( Iffy::Product::IngestService::URL, { body: { clientId: product.external_id, clientUrl: product.long_url, name: product.name, entity: "Product", text: "Name: Test Product Description: A test product description. ", fileUrls: [], user: { clientId: user.external_id, protected: user.vip_creator?, email: user.email, username: user.username, stripeAccountId: user.stripe_account&.charge_processor_merchant_id } }.to_json, headers: { "Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}" } } ) result = service.perform expect(result).to eq(successful_parsed_response) end end context "when the API request fails" do let(:error_parsed_response) { { "error" => { "message" => "API error" } } } let(:error_response) { instance_double(HTTParty::Response, code: 400, parsed_response: error_parsed_response, success?: false) } before do allow(HTTParty).to receive(:post).and_return(error_response) end it "raises an error with the appropriate message" do expect { service.perform }.to raise_error("Iffy error for product ID #{product.id}: 400 - API error") end end context "with rich content and images" do let(:gif_preview) { create(:asset_preview_gif, link: product) } let(:jpg_preview) { create(:asset_preview_jpg, link: product) } let(:image_file) { create(:product_file, link: product, filegroup: "image") } let(:rich_content) do create(:rich_content, entity: product, description: [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Rich content text" }] } ]) end before do gif_preview jpg_preview image_file rich_content allow(service).to receive(:signed_download_url_for_s3_key_and_filename).and_return("https://example.com/image.jpg") allow(URI).to receive(:open).and_return(double(content_type: "image/jpeg", read: "image_data")) allow(HTTParty).to receive(:post).and_return(instance_double(HTTParty::Response, code: 200, parsed_response: { "status" => "success" }, success?: true)) end it "includes rich content text and image URLs in the API request" do expect(HTTParty).to receive(:post).with( Iffy::Product::IngestService::URL, hash_including( body: { clientId: product.external_id, clientUrl: product.long_url, name: product.name, entity: "Product", text: "Name: #{product.name} Description: #{product.description} Rich content text", fileUrls: [ gif_preview.url, jpg_preview.url ], user: { clientId: user.external_id, protected: user.vip_creator?, email: user.email, username: user.username, stripeAccountId: user.stripe_account&.charge_processor_merchant_id } }.to_json, headers: { "Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}" } ) ) service.perform end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/iffy/product/flag_service_spec.rb
spec/services/iffy/product/flag_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::Product::FlagService do describe "#perform" do let(:product) { create(:product) } let(:service) { described_class.new(product.external_id) } it "unpublishes the product" do service.perform product.reload expect(product.is_unpublished_by_admin).to be(true) expect(product.purchase_disabled_at).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/services/iffy/product/mark_compliant_service_spec.rb
spec/services/iffy/product/mark_compliant_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::Product::MarkCompliantService do describe "#perform" do let(:product) { create(:product, is_unpublished_by_admin: true) } let(:service) { described_class.new(product.external_id) } it "publishes the product" do service.perform product.reload expect(product.is_unpublished_by_admin).to be(false) expect(product.purchase_disabled_at).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/services/iffy/user/ban_service_spec.rb
spec/services/iffy/user/ban_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::User::BanService do describe "#perform" do let(:user) { create(:user) } let(:service) { described_class.new(user.external_id) } context "when the user can be suspended" do it "suspends the user and adds a comment" do expect_any_instance_of(User).to receive(:flag_for_tos_violation!).with( author_name: "Iffy", content: "Banned for a policy violation on #{Time.current.to_fs(:formatted_date_full_month)} (Adult (18+) content)", bulk: true ).and_call_original expect_any_instance_of(User).to receive(:suspend_for_tos_violation!).with( author_name: "Iffy", content: "Banned for a policy violation on #{Time.current.to_fs(:formatted_date_full_month)} (Adult (18+) content)", bulk: true ).and_call_original expect do service.perform end.to change { user.reload.user_risk_state }.from("not_reviewed").to("suspended_for_tos_violation") expect(user.tos_violation_reason).to eq("Adult (18+) content") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/iffy/user/suspend_service_spec.rb
spec/services/iffy/user/suspend_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::User::SuspendService do describe "#perform" do let(:user) { create(:user) } let(:service) { described_class.new(user.external_id) } context "when the user cannot be flagged for TOS violation" do before do allow_any_instance_of(User).to receive(:can_flag_for_tos_violation?).and_return(false) end it "does not flag the user" do service.perform user.reload expect(user.tos_violation_reason).to be_nil expect(user.flagged?).to be(false) end end context "when the user can be flagged" do before do allow_any_instance_of(User).to receive(:can_flag_for_tos_violation?).and_return(true) end it "flags the user and adds a comment" do expect_any_instance_of(User).to receive(:flag_for_tos_violation!).with( author_name: "Iffy", content: "Suspended for a policy violation on #{Time.current.to_fs(:formatted_date_full_month)} (Adult (18+) content)", bulk: true ).and_call_original expect do service.perform end.to change { user.reload.user_risk_state }.from("not_reviewed").to("flagged_for_tos_violation") expect(user.tos_violation_reason).to eq("Adult (18+) content") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/iffy/user/mark_compliant_service_spec.rb
spec/services/iffy/user/mark_compliant_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::User::MarkCompliantService do describe "#perform" do let(:user) { create(:user, user_risk_state: :suspended_for_tos_violation) } let(:service) { described_class.new(user.external_id) } it "marks the user as compliant and adds a comment with Iffy as the author" do expect_any_instance_of(User).to receive(:mark_compliant!).with(author_name: "Iffy").and_call_original expect do service.perform end.to change { user.reload.user_risk_state }.from("suspended_for_tos_violation").to("compliant") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/iffy/profile/ingest_service_spec.rb
spec/services/iffy/profile/ingest_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::Profile::IngestService do include Rails.application.routes.url_helpers let(:user) { create(:user, name: "Test User", bio: "A test user bio.") } let!(:merchant_account) { create(:merchant_account, user: user) } let(:service) { described_class.new(user) } before do stub_const("Iffy::Profile::IngestService::TEST_MODE", false) end describe "#perform" do context "when the API request is successful" do let(:successful_parsed_response) { { "status" => "success", "message" => "Content ingested successfully" } } let(:successful_response) { instance_double(HTTParty::Response, code: 200, parsed_response: successful_parsed_response, success?: true) } before do allow(HTTParty).to receive(:post).and_return(successful_response) end it "sends the correct data to the Iffy API and returns the response" do expect(HTTParty).to receive(:post).with( Iffy::Profile::IngestService::URL, { body: { clientId: user.external_id, clientUrl: user.profile_url, name: user.display_name, entity: "Profile", text: "Test User A test user bio. ", fileUrls: [], user: { clientId: user.external_id, protected: user.vip_creator?, email: user.email, username: user.username, stripeAccountId: user.stripe_account&.charge_processor_merchant_id } }.to_json, headers: { "Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}" } } ) result = service.perform expect(result).to eq(successful_parsed_response) end end context "when the API request fails" do let(:error_parsed_response) { { "error" => { "message" => "API error" } } } let(:error_response) { instance_double(HTTParty::Response, code: 400, parsed_response: error_parsed_response, success?: false) } before do allow(HTTParty).to receive(:post).and_return(error_response) end it "raises an error with the appropriate message" do expect { service.perform }.to raise_error("Iffy error for user ID #{user.id}: 400 - API error") end end context "with rich text sections and images" do before do create(:seller_profile_rich_text_section, seller: user, json_data: { text: { content: [ { type: "paragraph", content: [{ text: "Rich content text" }] }, { type: "image", attrs: { src: "https://example.com/image1.jpg" } }, { type: "image", attrs: { src: "https://example.com/image2.jpg" } } ] } }) allow(HTTParty).to receive(:post).and_return(instance_double(HTTParty::Response, code: 200, parsed_response: { "status" => "success" }, success?: true)) end it "includes rich content text and image URLs in the API request" do expect(HTTParty).to receive(:post).with( Iffy::Profile::IngestService::URL, hash_including( body: { clientId: user.external_id, clientUrl: user.profile_url, name: user.display_name, entity: "Profile", text: "Test User A test user bio. Rich content text", fileUrls: [ "https://example.com/image1.jpg", "https://example.com/image2.jpg" ], user: { clientId: user.external_id, protected: user.vip_creator?, email: user.email, username: user.username, stripeAccountId: user.stripe_account&.charge_processor_merchant_id } }.to_json, headers: { "Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}" } ) ) service.perform end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/iffy/post/ingest_service_spec.rb
spec/services/iffy/post/ingest_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::Post::IngestService do let(:user) { create(:user) } let!(:merchant_account) { create(:merchant_account, user: user) } let(:installment) { create(:installment, seller: user, name: "Test Post", message: "<p>A test post message.</p>") } let(:service) { described_class.new(installment) } describe "#perform" do context "when the API request is successful" do let(:successful_parsed_response) { { "status" => "success", "message" => "Content ingested successfully" } } let(:successful_response) { instance_double(HTTParty::Response, code: 200, parsed_response: successful_parsed_response, success?: true) } before do allow(HTTParty).to receive(:post).and_return(successful_response) end it "sends the correct data to the Iffy API and returns the response" do expect(HTTParty).to receive(:post).with( Iffy::Post::IngestService::URL, { body: { clientId: installment.external_id, clientUrl: installment.full_url, name: installment.name, entity: "Post", text: "Name: Test Post Message: A test post message.", fileUrls: [], user: { clientId: user.external_id, protected: user.vip_creator?, email: user.email, username: user.username, stripeAccountId: user.stripe_account&.charge_processor_merchant_id } }.to_json, headers: { "Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}" } } ) result = service.perform expect(result).to eq(successful_parsed_response) end end context "when the API request fails" do let(:error_parsed_response) { { "error" => { "message" => "API error" } } } let(:error_response) { instance_double(HTTParty::Response, code: 400, parsed_response: error_parsed_response, success?: false) } before do allow(HTTParty).to receive(:post).and_return(error_response) end it "raises an error with the appropriate message" do expect { service.perform }.to raise_error("Iffy error for installment ID #{installment.id}: 400 - API error") end end context "with rich content and images" do let(:message_with_images) { "<p>Rich content text</p><img src='https://example.com/image1.jpg'><img src='https://example.com/image2.jpg'>" } let(:installment_with_images) { create(:installment, seller: user, name: "Test Post with Images", message: message_with_images) } let(:service_with_images) { described_class.new(installment_with_images) } before do allow(HTTParty).to receive(:post).and_return(instance_double(HTTParty::Response, code: 200, parsed_response: { "status" => "success" }, success?: true)) end it "includes rich content text and image URLs in the API request" do expect(HTTParty).to receive(:post).with( Iffy::Post::IngestService::URL, hash_including( body: { clientId: installment_with_images.external_id, clientUrl: installment_with_images.full_url, name: installment_with_images.name, entity: "Post", text: "Name: Test Post with Images Message: Rich content text", fileUrls: [ "https://example.com/image1.jpg", "https://example.com/image2.jpg" ], user: { clientId: user.external_id, protected: user.vip_creator?, email: user.email, username: user.username, stripeAccountId: user.stripe_account&.charge_processor_merchant_id } }.to_json, headers: { "Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}" } ) ) service_with_images.perform end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/iffy/post/flag_service_spec.rb
spec/services/iffy/post/flag_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::Post::FlagService do describe "#perform" do let(:user) { create(:user) } let(:post) { create(:installment, seller: user, published_at: Time.current) } let(:service) { described_class.new(post.external_id) } it "unpublishes the post and sets is_unpublished_by_admin to true" do service.perform post.reload expect(post.published_at).to be_nil expect(post.is_unpublished_by_admin?).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/services/iffy/post/mark_compliant_service_spec.rb
spec/services/iffy/post/mark_compliant_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Iffy::Post::MarkCompliantService do describe "#perform" do let(:user) { create(:user) } let(:post) { create(:installment, seller: user) } let(:service) { described_class.new(post.external_id) } it "publishes the post if it is unpublished by admin" do post.unpublish!(is_unpublished_by_admin: true) expect(post.published_at).to be_nil expect(post.is_unpublished_by_admin?).to be true service.perform post.reload expect(post.published_at).to be_present expect(post.is_unpublished_by_admin?).to be false end it "does not publish the post if it is unpublished but not by admin" do post.unpublish!(is_unpublished_by_admin: false) expect(post.published_at).to be_nil expect(post.is_unpublished_by_admin?).to be false service.perform post.reload expect(post.published_at).to be_nil expect(post.is_unpublished_by_admin?).to be false end context "when the post is already published" do let(:post) { create(:installment, seller: user, published_at: Time.current) } it "does not change the post's published status" do expect(post.published_at).to be_present service.perform expect(post.reload.published_at).to be_present end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/stripe_balance_enforcer.rb
spec/support/stripe_balance_enforcer.rb
# frozen_string_literal: true require_relative "stripe_charges_helper" require_relative "stripe_payment_method_helper" # Ensures that the Stripe test account has a sufficient balance to run the # suite (e.g. instant payout E2E tests). class StripeBalanceEnforcer include StripeChargesHelper # As of July 2025, running the suite requires a balance of ~$70. 100x that as # a buffer should be sufficient for the foreseeable future. DEFAULT_MINIMUM_BALANCE_CENTS = 70_00 * 100 def self.ensure_sufficient_balance(minimum_balance_cents = DEFAULT_MINIMUM_BALANCE_CENTS) new(minimum_balance_cents).ensure_sufficient_balance end def initialize(minimum_balance_cents) @minimum_balance_cents = minimum_balance_cents end private_class_method :new def ensure_sufficient_balance top_up! if insufficient_balance? end private attr_reader :minimum_balance_cents def insufficient_balance? current_balance_cents < minimum_balance_cents end def current_balance_cents balance = Stripe::Balance.retrieve usd_balance = balance.available.find { |b| b["currency"] == "usd" } usd_balance ? usd_balance["amount"] : 0 end def top_up! available_balance_card = StripePaymentMethodHelper.success_available_balance payment_method_id = available_balance_card.to_stripejs_payment_method_id create_stripe_charge( payment_method_id, # This is the maximum amount that can be charged per transaction. Use # the largest possible value to reduce top up frequency. amount: 999_999_99, currency: "usd", confirm: true ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/capybara_helpers.rb
spec/support/capybara_helpers.rb
# frozen_string_literal: true module CapybaraHelpers def wait_for_valid(javascript_expression) page.document.synchronize do raise Capybara::ElementNotFound unless page.evaluate_script(javascript_expression) end end def wait_for_visible(selector) wait_for_valid %($('#{selector}:visible').length > 0) end def wait_for_ajax Timeout.timeout(Capybara.default_max_wait_time) do loop until finished_all_ajax_requests? end end def finished_all_ajax_requests? page.evaluate_script(<<~EOS) ((typeof window.jQuery === 'undefined') || jQuery.active === 0) && !window.__activeRequests EOS end def visit(url) page.visit(url) return if Capybara.current_driver == :rack_test Timeout.timeout(Capybara.default_max_wait_time) do loop until page.evaluate_script("document.readyState") == "complete" end wait_for_ajax end def wait_until_true Timeout.timeout(Capybara.default_max_wait_time) do until yield sleep 1 end end end def js_style_encode_uri_component(comp) # CGI.escape encodes spaces to "+" # but encodeURIComponent in JS encodes them to "%20" CGI.escape(comp).gsub("+", "%20") end def fill_in_color(field, color) field.execute_script("Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), 'value').set.call(this, arguments[0]); this.dispatchEvent(new Event('input', { bubbles: true }))", color) end def have_nth_table_row_record(n, text, exact_text: true) have_selector("tbody tr:nth-child(#{n}) > td", text:, exact_text:, normalize_ws: true) end def get_client_time_zone page.evaluate_script("Intl.DateTimeFormat().resolvedOptions().timeZone") end def unfocus find("body").click end def fill_in_datetime(field, with:) element = find_field(field) element.click element.execute_script("this.value = arguments[0]; this.dispatchEvent(new Event('blur', {bubbles: true}));", with) end def accept_browser_dialog wait = Selenium::WebDriver::Wait.new(timeout: 30) wait.until do page.driver.browser.switch_to.alert true rescue Selenium::WebDriver::Error::NoAlertPresentError false end page.driver.browser.switch_to.alert.accept end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/product_row_helpers.rb
spec/support/product_row_helpers.rb
# frozen_string_literal: true module ProductRowHelpers def find_product_row(product) find("[role=listitem]", text: product.name) end def drag_product_row(product, to:) product_row = find_product_row(product) to_product_row = find_product_row(to) within product_row do find("[aria-grabbed]").drag_to to_product_row end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/rich_text_editor_helpers.rb
spec/support/rich_text_editor_helpers.rb
# frozen_string_literal: true module RichTextEditorHelpers def set_rich_text_editor_input(node, to_text:) node.native.clear node.base.send_keys(to_text) end def rich_text_editor_select_all(node) node.native.send_keys(ctrl_key, "a") end def drag_file_embed_to(name:, to:) file_embed = find_embed(name:) file_embed.drag_to(to) end def wait_for_image_to_finish_uploading expect(page).to_not have_selector("img[src*='blob:']") end def toggle_file_group(name) find("[role=treeitem] h4", text: name, match: :first).click end def find_file_group(name) find("[role=treeitem] h4", text: name, match: :first).ancestor("[role=treeitem]") end def within_file_group(name, &block) within find_file_group(name), &block end def have_file_group(name) have_selector("[role=treeitem] h4", text: name) end def ctrl_key page.driver.browser.capabilities.platform_name.include?("mac") ? :command : :control end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/sales_related_products_infos_helpers.rb
spec/support/sales_related_products_infos_helpers.rb
# frozen_string_literal: true module SalesRelatedProductsInfosHelpers def rebuild_srpis_cache CachedSalesRelatedProductsInfo.delete_all Link.ids.each do UpdateCachedSalesRelatedProductsInfosJob.new.perform(_1) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/preview_box_helpers.rb
spec/support/preview_box_helpers.rb
# frozen_string_literal: true module PreviewBoxHelpers def in_preview(&block) scroll_to find("aside", text: "Preview") within_section "Preview", section_element: :aside do block.call end end def expect_current_step(step) if step === :product_preview expect(page).to have_selector(".product-main") elsif step === :purchase_form expect(page).to have_section("Checkout") elsif step === :receipt expect(page).to have_section("Your purchase was successful!") elsif step === :content expect(page).to have_selector("[role=tree][aria-label=Files]") elsif step === :rich_content expect(page).to have_selector("[aria-label='Product content']") else expect(false).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/support/overlay_helpers.rb
spec/support/overlay_helpers.rb
# frozen_string_literal: true module OverlayHelpers def setup_overlay_data @creator = create(:user) @products = { thank_you: create(:product, price_cents: 8353, user: @creator, name: "Thank you - The Works of Edgar Gumstein"), offer_code: create(:product, user: @creator, price_cents: 700), pwyw: create(:product, user: @creator, price_cents: 0, customizable_price: true), subscription: create(:subscription_product_with_versions, user: @creator, subscription_duration: :monthly), vanilla: create(:product, user: @creator, price_cents: 507, name: "Vanilla - The Works of Edgar Gumstein"), with_custom_permalink: create(:product, user: @creator, custom_permalink: "custom"), variant: create(:product, user: @creator), yen: create(:product, user: @creator, price_currency_type: "jpy", price_cents: 934), physical: create(:physical_product, user: @creator, require_shipping: true, price_cents: 1325) } create(:offer_code, products: [@products[:offer_code]], amount_cents: 100) create(:price, link: @products[:subscription], recurrence: "quarterly", price_cents: 250) create(:price, link: @products[:subscription], recurrence: "yearly", price_cents: 800) variant_category = create(:variant_category, link: @products[:variant]) %w[Wurble Hatstand].each { |name| create(:variant, name:, variant_category:) } @products[:physical].shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) end def create_page(urls, single_mode = false, trigger_checkout: false, template_name: "overlay_page.html.erb", custom_domain_base_uri: nil, query_params: {}) template = Rails.root.join("spec", "support", "fixtures", template_name) filename = Rails.root.join("public", "overlay_spec_page_#{urls.join('_').gsub(/[^a-zA-Z]/, '_')}.html") File.delete(filename) if File.exist?(filename) urls.map! { |url| url.start_with?("http") ? url : "#{PROTOCOL}://#{DOMAIN}/l/#{url}" } File.open(filename, "w") do |f| f.write(ERB.new(File.read(template)).result_with_hash( urls:, single_mode:, trigger_checkout:, js_nonce:, custom_domain_base_uri: custom_domain_base_uri.presence || UrlService.root_domain_with_protocol )) end "/#{filename.basename}?x=#{Time.current.to_i}&#{query_params.to_param}" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factory_bot_linting.rb
spec/support/factory_bot_linting.rb
# frozen_string_literal: true class FactoryBotLinting def process Rails.application.load_seed VCR.turn_on! cassette_options = { match_requests_on: [:method, uri_matcher] } FactoryBot.factories.each do |factory| VCR.use_cassette("factory_linting/factories/#{factory.name}/all_requests", cassette_options) do FactoryBot.lint [factory] end end end private def match_ignoring_trailing_id(uri_1, uri_2, uri_regexp) uri_1_id = uri_1.match(uri_regexp) { $1 } r1_without_id = uri_1.gsub(uri_1_id, "") uri_2_id = uri_2.match(uri_regexp) { $1 } r2_without_id = uri_2_id && uri_2.gsub(uri_2_id, "") r2_without_id && (r1_without_id == r2_without_id) end def uri_matcher lambda do |request_1, request_2| uri_1, uri_2 = request_1.uri, request_2.uri pwnedpasswords_range_regexp = %r(https://api.pwnedpasswords.com/range/(.+)/?\z) stripe_collection_regexp = %r(https://api.stripe.com/v1/accounts|tokens|customers|payment_methods/?\z) stripe_member_regexp = %r(https://api.stripe.com/v1/accounts|tokens|payment_methods/(.+)/?\z) case uri_1 when pwnedpasswords_range_regexp match_ignoring_trailing_id(uri_1, uri_2, pwnedpasswords_range_regexp) when stripe_collection_regexp uri_1 == uri_2 when stripe_member_regexp match_ignoring_trailing_id(uri_1, uri_2, stripe_member_regexp) else uri_1 == uri_2 end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/secure_headers_helpers.rb
spec/support/secure_headers_helpers.rb
# frozen_string_literal: true module SecureHeadersHelpers def set_nonce_in_script_src_csp(nonce_value) new_config = SecureHeaders::Configuration.dup new_config.csp.script_src << "'nonce-#{nonce_value}'" SecureHeaders::Configuration.instance_variable_set("@default_config", new_config) end def remove_nonce_from_script_src_csp(nonce_value) new_config = SecureHeaders::Configuration.dup new_config.csp.script_src.delete("'nonce-#{nonce_value}'") if new_config.csp.respond_to?(:script_src) SecureHeaders::Configuration.instance_variable_set("@default_config", new_config) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/discover_helpers.rb
spec/support/discover_helpers.rb
# frozen_string_literal: true module DiscoverHelpers def taxonomy_url(taxonomy_path, query_params = {}) UrlService.discover_full_path(taxonomy_path, query_params) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/product_variants_helpers.rb
spec/support/product_variants_helpers.rb
# frozen_string_literal: true # Helper methods for the versions/variants part of the product edit page module ProductVariantsHelpers def version_rows all("[aria-label='Version editor']") end def version_option_rows all("[role=listitem]") end def remove_version_option click_on "Remove version" end def tier_rows all("[role=list][aria-label='Tier editor'] [role=listitem]") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/mail_body_extensions.rb
spec/support/mail_body_extensions.rb
# frozen_string_literal: true module MailBodyExtensions def sanitized @_sanitized ||= ActionView::Base.full_sanitizer .sanitize(self.encoded) .gsub("\r\n", " ") .gsub(/\s{2,}/, " ") end end # Extend Mail::Body to include the above module Mail::Body.include(MailBodyExtensions)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/checkout_helpers.rb
spec/support/checkout_helpers.rb
# frozen_string_literal: true module CheckoutHelpers def add_to_cart(product, cart: false, pwyw_price: nil, option: nil, rent: false, recurrence: nil, logged_in_user: nil, quantity: 1, offer_code: nil, ppp_factor: nil, **params) choose "Rent" if rent && product.purchase_type != "rent_only" choose option == "Untitled" ? product.name : option if option.present? select recurrence, from: "Recurrence" if recurrence.present? quantity_field = first(:field, "Quantity", minimum: 0) quantity_field&.set quantity if quantity.present? fill_in "Name a fair price", with: pwyw_price if pwyw_price.present? if product.purchase_info_for_product_page(logged_in_user, Capybara.current_session.driver.browser.manage.all_cookies.find { |cookie| cookie[:name] == "_gumroad_guid" }&.[](:value)).present? buy_text = "Purchase again" elsif cart buy_text = "Add to cart" elsif product.is_recurring_billing buy_text = "Subscribe" elsif product.purchase_type == "rent_only" || rent buy_text = "Rent" else buy_text = "I want this!" end within find(:article) do buy_button = find(:link, buy_text) uri = URI.parse buy_button[:href] expect(uri.path).to eq "/checkout" query = Rack::Utils.parse_query(uri.query) expect(query["product"]).to eq(product.unique_permalink) expect(query["quantity"]).to eq(quantity.to_s) expect(query["code"]).to eq(offer_code&.code) expect(query["rent"]).to eq(rent ? "true" : nil) expect(query["option"]).to eq(option.present? ? (product.is_physical ? product.skus.alive.find_by(name: option)&.external_id : product.variant_categories.alive.first&.variants&.alive&.find_by(name: option)&.external_id) : nil) if pwyw_price.present? pwyw_price = (pwyw_price * 100) if offer_code.present? pwyw_price += offer_code.amount_cents if offer_code.amount_cents.present? pwyw_price /= ((100 - offer_code.amount_percentage) / 100.0) if offer_code.amount_percentage.present? end pwyw_price /= ppp_factor if ppp_factor.present? end expect(query["price"]).to eq(pwyw_price && pwyw_price.to_i.to_s) params.each { |key, value| expect(query[key.to_s]).to eq(value.to_s) } buy_button.click end within_cart_item(product.name) do expect(page).to have_text((pwyw_price.to_i * quantity / 100).to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse) if pwyw_price.present? expect(page).to have_text("Qty: #{quantity}") expect(page).to have_text("#{variant_label(product)}: #{option == "Untitled" ? product.name : option}") if option.present? expect(page).to have_text(recurrence) if recurrence.present? expect(page).to have_text("one #{product.free_trial_details[:duration][:unit]} free") if product.free_trial_enabled end expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) if offer_code.present? && ((offer_code.amount_cents || 0) > 0 || (offer_code.amount_percentage || 0) > 0) end def fill_checkout_form(product, email: "test@gumroad.com", address: nil, offer_code: nil, is_free: false, country: nil, zip_code: "94107", vat_id: nil, abn_id: nil, gst_id: nil, qst_id: nil, mva_id: nil, cn_id: nil, ird_id: nil, sst_id: nil, vsk_id: nil, trn_id: nil, oman_vat_number: nil, unp_id: nil, rut_id: nil, nit_id: nil, cpj_id: nil, ruc_id: nil, tn_id: nil, tin_id: nil, rfc_id: nil, inn_id: nil, pib_id: nil, brn_id: nil, vkn_id: nil, edrpou_id: nil, mst_id: nil, kra_pin_id: nil, firs_tin_id: nil, tra_tin: nil, gift: nil, custom_fields: [], credit_card: {}, logged_in_user: nil) fill_in "Email address", with: email if email.present? && logged_in_user.nil? if gift&.dig(:email).present? check "Give as a gift" expect(page).to have_text("Note: Free trials will be charged immediately. The membership will not auto-renew.") if product.is_recurring_billing fill_in "Recipient email address", with: gift[:email] fill_in "A personalized message (optional)", with: gift[:note] end fill_in "Business VAT ID (optional)", with: vat_id if vat_id.present? fill_in "Business ABN ID (optional)", with: abn_id if abn_id.present? fill_in "Business MVA ID (optional)", with: mva_id if mva_id.present? fill_in "Business GST ID (optional)", with: gst_id if gst_id.present? fill_in "Business QST ID (optional)", with: qst_id if qst_id.present? fill_in "Business CN ID (optional)", with: cn_id if cn_id.present? fill_in "Business IRD ID (optional)", with: ird_id if ird_id.present? fill_in "Business SST ID (optional)", with: sst_id if sst_id.present? fill_in "Business VSK ID (optional)", with: vsk_id if vsk_id.present? fill_in "Business TRN ID (optional)", with: trn_id if trn_id.present? fill_in "Business UNP ID (optional)", with: unp_id if unp_id.present? fill_in "Business RUT ID (optional)", with: rut_id if rut_id.present? fill_in "Business NIT ID (optional)", with: nit_id if nit_id.present? fill_in "Business CPJ ID (optional)", with: cpj_id if cpj_id.present? fill_in "Business RUC ID (optional)", with: ruc_id if ruc_id.present? fill_in "Business TN ID (optional)", with: tn_id if tn_id.present? fill_in "Business TIN ID (optional)", with: tin_id if tin_id.present? fill_in "Business RFC ID (optional)", with: rfc_id if rfc_id.present? fill_in "Business INN ID (optional)", with: inn_id if inn_id.present? fill_in "Business PIB ID (optional)", with: pib_id if pib_id.present? fill_in "Business BRN ID (optional)", with: brn_id if brn_id.present? fill_in "Business VKN ID (optional)", with: vkn_id if vkn_id.present? fill_in "Business EDRPOU ID (optional)", with: edrpou_id if edrpou_id.present? fill_in "Business MST ID (optional)", with: mst_id if mst_id.present? fill_in "Business KRA PIN (optional)", with: kra_pin_id if kra_pin_id.present? fill_in "Business FIRS TIN (optional)", with: firs_tin_id if firs_tin_id.present? fill_in "Business TRA TIN (optional)", with: tra_tin if tra_tin.present? fill_in "Business VAT Number (optional)", with: oman_vat_number if oman_vat_number.present? select country, from: "Country" if country.present? if address.present? || product.is_physical || product.require_shipping? address = {} if address.nil? fill_in "Full name", with: "Gumhead Moneybags" fill_in "Street address", with: address[:street] || "1640 17th St" fill_in "City", with: address[:city] || "San Francisco" country_value = find_field("Country").value if country_value == "US" select address[:state] || "CA", from: "State" elsif country_value == "CA" select address[:state] || "QC", from: "Province" else fill_in "County", with: address[:state] end fill_in country_value == "US" ? "ZIP code" : "Postal", with: address[:zip_code] || "94107" else fill_in "ZIP code", with: zip_code if zip_code.present? && !is_free end if offer_code.present? fill_in "Discount code", with: offer_code click_on "Apply" expect(page).to have_selector("[aria-label='Discount code']", text: offer_code) end custom_fields.each do |field| case field[:type] when "terms" check "I accept" when "checkbox" check field[:name] when "text" fill_in field[:name], with: "Not nothing" end end if logged_in_user&.id == product.user.id expect(page).to have_alert("This will be a test purchase as you are the creator of at least one of the products. Your payment method will not be charged.") elsif logged_in_user&.credit_card.present? && logged_in_user.credit_card.charge_processor_id != PaypalChargeProcessor.charge_processor_id expect(page).to have_command("Use a different card?") expect(page).to have_selector("[aria-label='Saved credit card']", text: logged_in_user.credit_card.visual) elsif !credit_card.nil? && !is_free fill_in_credit_card(**credit_card) end end def check_out(product, error: nil, email: "test@gumroad.com", is_free: false, gift: nil, sca: nil, should_verify_address: false, cart_item_count: 1, logged_in_user: nil, **params, &block) fill_checkout_form(product, email:, is_free:, logged_in_user:, gift:, **params) block.call if block_given? expect do click_on is_free ? "Get" : "Pay", exact: true if should_verify_address if page.has_text?("We are unable to verify your shipping address. Is your address correct?", wait: 5) click_on "Yes, it is" elsif page.has_text?("You entered this address:", wait: 5) && page.has_text?("We recommend using this format:", wait: 5) click_on "No, continue" end end within_sca_frame { click_on sca ? "Complete" : "Fail" } unless sca.nil? if error.present? expect(page).to have_alert(text: error) if error != true else if gift.present? || product.is_in_preorder_state # Specific cases where we show the receipt instead of the product content expect(page).to have_text("Your purchase was successful!") expect(page).to have_text(logged_in_user&.email&.downcase || email&.downcase) else # The alert show/hide timing can cause specs to be flaky expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to #{logged_in_user&.email&.downcase || email&.downcase}", visible: :all) end expect(page).to have_text("You bought this for #{gift[:email] || gift[:name]}") if gift&.dig(:email).present? || gift&.dig(:name).present? expect(page).to have_text(product.name) if logged_in_user.present? || User.alive.where(email:).exists? expect(page).to_not have_text("Create an account to access all of your purchases in one place") else expect(page).to have_text("Create an account to access all of your purchases in one place") end end end.to change { product.preorder_link.present? ? product.sales.preorder_authorization_successful.count : product.sales.successful.count }.by(error.blank? && logged_in_user&.id != product.user.id && (product.not_free_trial_enabled || gift.present?) ? cart_item_count : 0) .and change { product.preorder_link.present? ? product.sales.preorder_authorization_failed.count : product.sales.failed.count }.by(error.present? && error != true ? 1 : 0) .and change { product&.subscriptions&.count }.by(error.blank? && product.is_recurring_billing ? 1 : 0) end end def fill_in_credit_card(number: "4242424242424242", expiry: StripePaymentMethodHelper::EXPIRY_MMYY, cvc: "123", zip_code: nil) within_fieldset "Card information" do within_frame do fill_in "Card number", with: number, visible: false if number.present? fill_in "MM / YY", with: expiry, visible: false if expiry.present? fill_in "CVC", with: cvc, visible: false if cvc.present? fill_in "ZIP", with: zip_code, visible: false if zip_code.present? end end fill_in "Name on card", with: "Gumhead Moneybags" end def within_sca_frame(&block) expect(page).to have_selector("iframe[src^='https://js.stripe.com/v3/three-ds-2-challenge']", wait: 240) within_frame(page.find("[src^='https://js.stripe.com/v3/three-ds-2-challenge']")) do within_frame("challengeFrame", &block) end end def within_cart_item(name, &block) within find("h4", text: name, match: :first).ancestor("[role=listitem]"), &block end def complete_purchase(product, **params) add_to_cart(product, **params) check_out(product) end def have_cart_item(name) have_selector("[role=listitem] h4", text: name) end private VARIANT_LABELS = { Link::NATIVE_TYPE_CALL => "Duration", Link::NATIVE_TYPE_COFFEE => "Amount", Link::NATIVE_TYPE_MEMBERSHIP => "Tier", Link::NATIVE_TYPE_PHYSICAL => "Variant", }.freeze def variant_label(product) VARIANT_LABELS[product.native_type] || "Version" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/aria_extensions.rb
spec/support/aria_extensions.rb
# frozen_string_literal: true Capybara.modify_selector(:button) do expression_filter(:role, default: true) do |xpath| xpath[XPath.attr(:role).equals("button").or ~XPath.attr(:role)] end end Capybara.modify_selector(:link) do expression_filter(:role, default: true) do |xpath| xpath[XPath.attr(:role).equals("link").or ~XPath.attr(:role)] end expression_filter(:inert, :boolean, default: false) do |xpath, disabled| xpath[disabled ? XPath.attr(:"inert") : (~XPath.attr(:"inert"))] end end # capybara_accessible_selectors does have an implementation for this, but it doesn't use XPath, # so combining it into :command would be very difficult Capybara.add_selector(:menuitem, locator_type: [String, Symbol]) do xpath do |locator, **options| xpath = XPath.descendant[XPath.attr(:role).equals("menuitem")] unless locator.nil? locator = locator.to_s matchers = [XPath.string.n.is(locator), XPath.attr(:title).is(locator), XPath.attr(:'aria-label').is(locator)] xpath = xpath[matchers.reduce(:|)] end xpath end expression_filter(:disabled, :boolean, default: false) do |xpath, disabled| xpath[disabled ? XPath.attr(:"inert") : (~XPath.attr(:"inert"))] end end Capybara.add_selector(:radio_button, locator_type: [String, Symbol]) do xpath do |locator, **options| xpath = XPath.descendant[[XPath.self(:input).attr(:type).is("radio"), XPath.attr(:role).one_of("radio", "menuitemradio")].reduce(:|)] xpath = locate_field(xpath, locator, **options) xpath += XPath.descendant[XPath.attr(:role).one_of("radio", "menuitemradio")][XPath.string.n.is(locator)] if locator xpath end filter_set(:_field, %i[name]) node_filter(:disabled, :boolean) { |node, value| !(value ^ (node.disabled? || node["inert"] == "true")) } node_filter(:checked, :boolean) { |node, value| !(value ^ (node.checked? || node["aria-checked"] == "true")) } node_filter(:unchecked, :boolean) { |node, value| (value ^ (node.checked? || node["aria-checked"] == "true")) } node_filter(%i[option with]) do |node, value| val = node.value (value.is_a?(Regexp) ? value.match?(val) : val == value.to_s).tap do |res| add_error("Expected value to be #{value.inspect} but it was #{val.inspect}") unless res end end describe_node_filters do |option: nil, with: nil, **| desc = +"" desc << " with value #{option.inspect}" if option desc << " with value #{with.inspect}" if with desc end end Capybara.add_selector(:tooltip, locator_type: [nil]) do xpath do |locator| # TODO: Remove once incorrect locator_type raises an error instead of just logging a warning raise "Tooltip does not support a locator, use the `text:` option instead" if locator.present? XPath.anywhere[XPath.attr(:role) == "tooltip"] end node_filter(:attached, default: true) do |node| node["id"] == (node.query_scope["aria-describedby"] || node.query_scope.ancestor("[aria-describedby]")["aria-describedby"]) end end Capybara.add_selector(:status, locator_type: [nil]) do xpath do |locator| # TODO: Remove once incorrect locator_type raises an error instead of just logging a warning raise "Status does not support a locator, use the text: option" if locator.present? XPath.anywhere[XPath.attr(:role) == "status"] end end Capybara.add_selector(:command) do xpath do |locator, **options| %i[link button menuitem tab_button].map do |selector| expression_for(selector, locator, **options) end.reduce(:union) end node_filter(:disabled, :boolean, default: false, skip_if: :all) { |node, value| !(value ^ node.disabled?) } expression_filter(:disabled, :boolean, default: false, skip_if: :all) { |xpath, val| val ? xpath : xpath[~XPath.attr(:"inert")] } expression_filter(:role, default: true) do |xpath| xpath[XPath.attr(:role).one_of("button", "link", "menuitem", "tab").or ~XPath.attr(:role)] end end Capybara.add_selector(:combo_box_list_box, locator_type: Capybara::Node::Element) do xpath do |input| ids = (input[:"aria-owns"] || input[:"aria-controls"])&.split(/\s+/)&.compact raise Capybara::ElementNotFound, "listbox cannot be found without attributes aria-owns or aria-controls" if !ids || ids.empty? XPath.anywhere[[ [XPath.attr(:role) == "listbox", XPath.self(:datalist)].reduce(:|), ids.map { |id| XPath.attr(:id) == id }.reduce(:|) ].reduce(:&)] end end Capybara.add_selector(:image, locator_type: [String, Symbol]) do xpath do |locator, src: nil| xpath = XPath.descendant(:img) xpath = xpath[XPath.attr(:alt).is(locator)] if locator xpath = xpath[XPath.attr(:src).is(src)] if src xpath end end Capybara.add_selector(:tablist, locator_type: [String, Symbol]) do xpath do |locator, **options| xpath = XPath.descendant[XPath.attr(:role) == "tablist"] xpath = xpath[XPath.attr(:"aria-label").is(locator)] if locator xpath end end Capybara.modify_selector(:tab_button) do xpath do |name| XPath.descendant[[ XPath.attr(:role) == "tab", XPath.ancestor[XPath.attr(:role) == "tablist"], XPath.string.n.is(name.to_s) | XPath.attr(:"aria-label").is(name.to_s) ].reduce(:&)] end end Capybara.modify_selector(:table) do xpath do |locator| xpath = XPath.descendant(:table) xpath = xpath[ XPath.attr(:"aria-label").is(locator) | XPath.child(:caption)[XPath.string.n.is(locator)] ] if locator xpath end end # support any element with `aria-role` - the default implementation enforces this to be an `input` element # replace aria-disabled with inert Capybara.modify_selector(:combo_box) do xpath do |locator, **options| xpath = XPath.descendant[XPath.attr(:role) == "combobox"] locate_field(xpath, locator, **options) end # with exact enabled options node_filter(:enabled_options) do |node, options| options = Array(options) actual = options_text(node, expression_for(:list_box_option, nil)) { |n| n["inert"] != "true" } match_all_options?(actual, options).tap do |res| add_error("Expected enabled options #{options.inspect} found #{actual.inspect}") unless res end end # with exact enabled options node_filter(:with_enabled_options) do |node, options| options = Array(options) actual = options_text(node, expression_for(:list_box_option, nil)) { |n| n["inert"] != "true" } match_some_options?(actual, options).tap do |res| add_error("Expected with at least enabled options #{options.inspect} found #{actual.inspect}") unless res end end # with exact disabled options node_filter(:disabled_options) do |node, options| options = Array(options) actual = options_text(node, expression_for(:list_box_option, nil)) { |n| n["inert"] == "true" } match_all_options?(actual, options).tap do |res| add_error("Expected disabled options #{options.inspect} found #{actual.inspect}") unless res end end # with exact enabled options node_filter(:with_disabled_options) do |node, options| options = Array(options) actual = options_text(node, expression_for(:list_box_option, nil)) { |n| n["inert"] == "true" } match_some_options?(actual, options).tap do |res| add_error("Expected with at least disabled options #{options.inspect} found #{actual.inspect}") unless res end end end # override table_row selector to support colspan class Capybara::Selector # TODO: This appears not to work - see the empty header workaround in ProductsTable and MembershipsTable. We should investigate and fix the XPath. def position_considering_colspan(xpath) siblings = xpath.preceding_sibling siblings[XPath.attr(:colspan).inverse].count.plus(siblings.attr(:colspan).sum).plus(1) end end Capybara.modify_selector(:table_row) do xpath do |locator| xpath = XPath.descendant(:tr) if locator.is_a? Hash locator.reduce(xpath) do |xp, (header, cell)| header_xp = XPath.ancestor(:table)[1].descendant(:tr)[1].descendant(:th)[XPath.string.n.is(header)] cell_xp = XPath.descendant(:td)[ XPath.string.n.is(cell) & position_considering_colspan(XPath).equals(position_considering_colspan(header_xp)) ] xp.where(cell_xp) end elsif locator initial_td = XPath.descendant(:td)[XPath.string.n.is(locator.shift)] tds = locator.reverse.map { |cell| XPath.following_sibling(:td)[XPath.string.n.is(cell)] } .reduce { |xp, cell| xp.where(cell) } xpath[initial_td[tds]] else xpath end end end Capybara.add_selector(:table_cell) do xpath do |header| header_xp = XPath.ancestor(:table)[1].descendant(:tr)[1].descendant(:th)[XPath.string.n.is(header)] XPath.descendant(:td)[position_considering_colspan(XPath).equals(position_considering_colspan(header_xp))] end end # add matching by aria-label and handle disabled state Capybara.modify_selector(:disclosure) do xpath do |name, **| match_name = XPath.string.n.is(name.to_s) | XPath.attr(:"aria-label").equals(name.to_s) button = (XPath.self(:button) | (XPath.attr(:role) == "button")) & match_name aria = XPath.descendant[XPath.attr(:id) == XPath.anywhere[button][XPath.attr(:"aria-expanded")].attr(:"aria-controls")] details = XPath.descendant(:details)[XPath.child(:summary)[match_name]] aria + details end end Capybara.modify_selector(:disclosure_button) do xpath do |name, **| match_name = XPath.string.n.is(name.to_s) | XPath.attr(:"aria-label").equals(name.to_s) XPath.descendant[[ (XPath.self(:button) | (XPath.attr(:role) == "button")), XPath.attr(:"aria-expanded"), match_name ].reduce(:&)] + XPath.descendant(:summary)[match_name] end expression_filter(:disabled, :boolean, default: false) do |xpath, val| disabled = XPath.attr(:disabled) | XPath.attr(:inert) xpath[val ? disabled : ~disabled] end describe_expression_filters end module Capybara module Node module Actions def click_command(locator = nil, **options) find(:command, locator, **options).click end alias_method :click_on, :click_command end class Element alias_method :base_hover, :hover def hover puts "NOTE: Please consider using an interaction method other than .hover to ensure proper accessibility" base_hover end end end module RSpecMatchers %i[tooltip radio_button command image tablist status table_row list_box_option].each do |selector| define_method "have_#{selector}" do |locator = nil, **options, &optional_filter_block| Matchers::HaveSelector.new(selector, locator, **options, &optional_filter_block) end end end end RSpec::Matchers.define :have_table_rows_in_order do |expected_rows| match do |actual| return false unless expected_rows.is_a?(Array) && expected_rows.any? all_table_rows = actual.all(:table_row) actual_row_positions = [] expected_rows.each_with_index do |row_data, index| # `#find` fails the assertion if the row is not found, thus we do not # need to handle this error in our own `failure_message` implementation. found_row = actual.find(:table_row, row_data) actual_row_positions << all_table_rows.index(found_row) end actual_row_positions.each_index do |index| next if index == 0 prev_position = actual_row_positions[index - 1] current_position = actual_row_positions[index] if current_position < prev_position @out_of_order_indices = [index - 1, index] return false end end true end failure_message do |actual| first_index, second_index = @out_of_order_indices first_row = expected_rows[first_index] second_row = expected_rows[second_index] <<~TEXT expected table rows to be in order, but row #{second_row.inspect} appeared before row #{first_row.inspect} TEXT end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/default_account_params_builder_service.rb
spec/support/default_account_params_builder_service.rb
# frozen_string_literal: true class DefaultAccountParamsBuilderService def initialize(country: "US") @country = country @default_currency = case country when "CA" Currency::CAD when "US" Currency::USD else raise "Unsupported country" end @params = {} end def perform build_common_params build_individual_address build_external_account build_ssn_last_4 if @country == "US" to_h end def to_h @params.dup end private def build_common_params @params.deep_merge!({ country: @country, default_currency: @default_currency, type: "custom", business_type: "individual", tos_acceptance: { date: 1427846400, ip: "54.234.242.13" }, business_profile: { url: "www.gumroad.com", product_description: "Test product", mcc: "5734" # Books, Periodicals, and Newspapers }, individual: { verification: { document: { front: "file_identity_document_success" } }, dob: { day: 1, month: 1, year: 1901 }, first_name: "Chuck", last_name: "Bartowski", phone: "0000000000", id_number: "000000000", email: "me@example.com", }, requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES }) end def build_individual_address address = case @country when "CA" { line1: "address_full_match", city: "Toronto", state: "ON", postal_code: "M4C 1T2", country: "CA" } when "US" { line1: "address_full_match", city: "San Francisco", state: "CA", postal_code: "94107", country: "US" } else raise "Unsupported country" end @params.deep_merge!( individual: { address: } ) end def build_external_account bank_account = case @country when "CA" { object: "bank_account", country: "CA", currency: Currency::CAD, routing_number: "11000-000", account_number: "000123456789" } when "US" { object: "bank_account", country: "US", currency: Currency::USD, routing_number: "111000000", account_number: "000123456789" } else raise "Unsupported country" end @params.deep_merge!(external_account: bank_account) end def build_ssn_last_4 @params.deep_merge!( individual: { ssn_last_4: "0000" } ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/card_params_spec_helper.rb
spec/support/card_params_spec_helper.rb
# frozen_string_literal: true # A collection of card parameters for the Stripe payment processor. Use these in preference to hardcoding card numbers # into tests where possible, and expand as necessary, ensuring that only cards listed in the Stripe testing # documentation are included in our specs. # Stripe Test Cards: https://stripe.com/docs/testing # All card parameter hash's expose card params without zip code data. To add zip code use with_zip_code on the hash. # All card parameter functions are named such that the first word is 'success' or 'decline' indicating the default # behavior expected on any action with the payment processor. The following words define what's unqiue about the card # and what will be different in the format: [context] [action]. # All parameters by default are in the default format of card data handling mode 'stripe'. To get 'stripejs' versions # use the to_stripejs_params module CardParamsSpecHelper module ExtensionMethods def to_stripe_card_hash stripe_params = { token: self[:token] } stripe_params[:address_zip] = self[:cc_zipcode] if self[:cc_zipcode] stripe_params[:currency] = "usd" stripe_params end def to_stripejs_token_obj Stripe::Token.retrieve(self[:token]) end def to_stripejs_token to_stripejs_token_obj.id end def to_stripejs_fingerprint to_stripejs_token_obj.card.fingerprint end def to_stripejs_params begin stripejs_params = { card_data_handling_mode: CardDataHandlingMode::TOKENIZE_VIA_STRIPEJS, stripe_token: to_stripejs_token } rescue Stripe::InvalidRequestError, Stripe::APIConnectionError, Stripe::APIError, Stripe::CardError => e stripejs_params = CardParamsSpecHelper::StripeJs.build_error(e.json_body[:type], e.json_body[:message], code: e.json_body[:code]) end stripejs_params end def with_zip_code(zip_code = "12345") with(:cc_zipcode, zip_code) end def with(key, value) copy = clone copy[key] = value copy.extend(ExtensionMethods) copy end def without(key) copy = clone copy.delete(key) copy.extend(ExtensionMethods) copy end end class StripeJs def self.error_unavailable build_error("api_error", "stripe api has gone downnnn") end def self.build_error(type, message, code: nil) { card_data_handling_mode: CardDataHandlingMode::TOKENIZE_VIA_STRIPEJS, stripe_error: { type:, message:, code: } } end end module_function def build(token: "tok_visa") card_params = { token: } card_params.extend(ExtensionMethods) card_params end def success build end def success_debit_visa build(token: "tok_visa_debit") end def card_number(card_type) case card_type when :success "4242 4242 4242 4242" when :success_with_sca "4000 0025 0000 3155" when :success_indian_card_mandate "4000 0035 6000 0123" when :success_charge_decline "4000 0000 0000 0341" when :decline "4000 0000 0000 0002" else "4242 4242 4242 4242" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/makara_proxy_extensions.rb
spec/support/makara_proxy_extensions.rb
# frozen_string_literal: true # Inspired by https://github.com/instacart/makara/blob/e45ba090fce998dad9e9a2759426f4695009cfae/spec/support/proxy_extensions.rb module ProxyExtensions attr_reader :primary_pool, :replica_pool, :id def primary_for?(sql) pool_for(sql) == primary_pool end def would_stick?(sql) should_stick?(:execute, [sql]) end def connection_for(sql) pool_for(sql) do |pool| pool.provide do |connection| connection end end end def pool_for(sql) appropriate_pool(:execute, [sql]) do |pool| pool end end def sticky=(s) @sticky = s end end Makara::Proxy.send(:include, ProxyExtensions)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/product_page_view_helpers.rb
spec/support/product_page_view_helpers.rb
# frozen_string_literal: true module ProductPageViewHelpers def add_page_view(product, timestamp = Time.current.iso8601, extra_body = {}) extra_body[:referrer_domain] = extra_body[:referrer_domain].presence || "direct" EsClient.index( index: ProductPageView.index_name, body: { product_id: product.id, seller_id: product.user_id, timestamp: }.merge(extra_body) ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/product_edit_page_helpers.rb
spec/support/product_edit_page_helpers.rb
# frozen_string_literal: true module ProductEditPageHelpers def save_change(expect_alert: true, expect_message: "Changes saved!") click_on "Save changes" wait_for_ajax if expect_alert expect(page).to have_alert(text: expect_message) end expect(page).to have_button "Save changes" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/pay_workflow_helpers.rb
spec/support/pay_workflow_helpers.rb
# frozen_string_literal: true # TODO: Remove this when the new checkout experience is rolled out module PayWorkflowHelpers def fill_cc_details(card_number: "4242424242424242", card_expiry: StripePaymentMethodHelper::EXPIRY_MMYY, card_cvc: "123", zip_code: nil) within_fieldset "Card information" do within_frame(0) do fill_in "Card number", with: card_number, visible: false fill_in "MM / YY", with: card_expiry, visible: false fill_in "CVC", with: card_cvc, visible: false fill_in "ZIP", with: zip_code, visible: false if zip_code.present? end end fill_in "Name on card", with: "Edgar Gumroad" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/stripe_charges_helper.rb
spec/support/stripe_charges_helper.rb
# frozen_string_literal: true module StripeChargesHelper def create_stripe_charge(payment_method_id, **charge_params) payment_intent = create_stripe_payment_intent(payment_method_id, **charge_params) Stripe::Charge.retrieve(id: payment_intent.latest_charge) end def create_stripe_payment_intent(payment_method_id, **charge_params) payload = { payment_method: payment_method_id, payment_method_types: ["card"] } payload.merge!(charge_params) Stripe::PaymentIntent.create(payload) end def create_stripe_setup_intent(payment_method_id, **charge_params) stripe_customer = Stripe::Customer.create(payment_method: payment_method_id) payload = { payment_method: payment_method_id, customer: stripe_customer.id, payment_method_types: ["card"], usage: "off_session" } payload.merge!(charge_params) Stripe::SetupIntent.create(payload) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/mock_table_helpers.rb
spec/support/mock_table_helpers.rb
# frozen_string_literal: true module MockTableHelpers def create_mock_model(name: "MockModel#{SecureRandom.hex(6)}", constantize: true, &block) table_name = "#{name.tableize}_#{SecureRandom.hex}" model = Class.new(ApplicationRecord) model.define_singleton_method(:name) { name } model.table_name = table_name if block_given? ActiveRecord::Base.connection.create_table(table_name, temporary: true, &block) else create_mock_table(model) end Object.const_set(name, model) if constantize && !Object.const_defined?(name) model end def create_mock_table(model) ActiveRecord::Base.connection.create_table(model.table_name, temporary: true) do |t| t.integer :user_id t.string :title t.string :subtitle t.timestamps null: false end model.belongs_to(:user, optional: true) end def drop_table(table_name) ActiveRecord::Base.connection.drop_table(table_name, temporary: true, if_exists: true) end def destroy_mock_model(model) drop_table(model.table_name) ensure Object.send(:remove_const, model.name) if Object.const_defined?(model.name) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/payments_helper.rb
spec/support/payments_helper.rb
# frozen_string_literal: true module PaymentsHelper def create_payment_with_purchase(seller, created_at_date, payment_type = :payment_completed, product: nil, amount_cents: nil, ip_country: nil) amount_cents ||= [1000, 2000, 1500].sample product ||= create(:product, user: seller) payment = create( payment_type, user: seller, amount_cents:, payout_period_end_date: created_at_date, created_at: created_at_date ) purchase = create( :purchase, seller:, price_cents: amount_cents, total_transaction_cents: amount_cents, purchase_success_balance: create(:balance, payments: [payment]), created_at: created_at_date, succeeded_at: created_at_date, ip_country:, link: product ) payment.amount_cents = purchase.total_transaction_cents payment.save! { payment:, purchase: } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/capybara_driver.rb
spec/support/capybara_driver.rb
# frozen_string_literal: true webdriver_client = Selenium::WebDriver::Remote::Http::Default.new(open_timeout: 120, read_timeout: 120) Capybara.register_driver :chrome do |app| options = Selenium::WebDriver::Chrome::Options.new options.add_emulation(device_metrics: { width: 1440, height: 900, touch: false }) options.add_preference("intl.accept_languages", "en-US") options.logging_prefs = { driver: "DEBUG" } Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: webdriver_client, options:) end Capybara.register_driver :tablet_chrome do |app| options = Selenium::WebDriver::Chrome::Options.new options.add_emulation(device_metrics: { width: 800, height: 1024, touch: true }) options.add_preference("intl.accept_languages", "en-US") options.logging_prefs = { driver: "DEBUG" } Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: webdriver_client, options:) end Capybara.register_driver :mobile_chrome do |app| options = Selenium::WebDriver::Chrome::Options.new options.add_emulation(device_name: "iPhone 8") options.add_preference("intl.accept_languages", "en-US") options.logging_prefs = { driver: "DEBUG" } Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: webdriver_client, options:) end def docker_browser_args args = [ "--headless", "--no-sandbox", "--start-maximized", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-popup-blocking", "--user-data-dir=/tmp/chrome", # Workaround https://bugs.chromium.org/p/chromedriver/issues/detail?id=2650&q=load&sort=-id&colspec=ID%20Status%20Pri%20Owner%20Summary "--disable-site-isolation-trials", ] args << "--disable-gpu" if Gem.win_platform? args end Capybara.register_driver :docker_headless_chrome do |app| Capybara::Selenium::Driver.load_selenium options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts| docker_browser_args.each { |arg| opts.args << arg } opts.args << "--window-size=1440,900" end options.add_preference("intl.accept_languages", "en-US") options.logging_prefs = { driver: "DEBUG" } Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: webdriver_client, options:) end Capybara.register_driver :selenium_chrome_headless_billy_custom do |app| Capybara::Selenium::Driver.load_selenium options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts| docker_browser_args.each { |arg| opts.args << arg } opts.args << "--enable-features=NetworkService,NetworkServiceInProcess" opts.args << "--ignore-certificate-errors" opts.args << "--proxy-server=#{Billy.proxy.host}:#{Billy.proxy.port}" opts.args << "--window-size=1440,900" end options.add_preference("intl.accept_languages", "en-US") options.logging_prefs = { driver: "DEBUG" } Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: webdriver_client, options:) end Capybara.register_driver :docker_headless_tablet_chrome do |app| Capybara::Selenium::Driver.load_selenium options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts| docker_browser_args.each { |arg| opts.args << arg } opts.args << "--window-size=800,1024" end options.add_preference("intl.accept_languages", "en-US") options.logging_prefs = { driver: "DEBUG" } Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: webdriver_client, options:) end Capybara.register_driver :docker_headless_mobile_chrome do |app| Capybara::Selenium::Driver.load_selenium options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts| docker_browser_args.each { |arg| opts.args << arg } end options.add_preference("intl.accept_languages", "en-US") options.logging_prefs = { driver: "DEBUG" } Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: webdriver_client, options:) end RSpec.configure do |config| config.before(:each, type: :system) do driven_by :rack_test end config.before(:each, type: :system, js: true) do driven_by ENV["IN_DOCKER"] == "true" ? :docker_headless_chrome : :chrome end config.before(:each, :mobile_view) do |example| driven_by ENV["IN_DOCKER"] == "true" ? :docker_headless_mobile_chrome : :mobile_chrome end config.before(:each, billy: true) do |example| driven_by ENV["IN_DOCKER"] == "true" ? :selenium_chrome_headless_billy_custom : :selenium_chrome_billy end config.before(:each, :tablet_view) do |example| driven_by ENV["IN_DOCKER"] == "true" ? :docker_headless_tablet_chrome : :tablet_chrome end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/shoulda_matchers.rb
spec/support/shoulda_matchers.rb
# frozen_string_literal: true Shoulda::Matchers.configure do |config| config.integrate do |with| with.test_framework :rspec with.library :rails end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/geoip_mocking.rb
spec/support/geoip_mocking.rb
# frozen_string_literal: true RSpec.configure do |config| config.before(:each) do full_description = RSpec.current_example&.full_description || "" if full_description.include?("invalid UTF-8") || full_description.include?("underlying GEOIP has invalid") allow(GEOIP).to receive(:city).and_return( double( country: double({ name: "Unit\xB7ed States", iso_code: "U\xB7S" }), most_specific_subdivision: double({ iso_code: "C\xB7A" }), city: double({ name: "San F\xB7rancisco" }), postal: double({ code: "941\xB703" }), location: double({ latitude: "103\xB7103", longitude: "103\xB7103" }) ) ) else geoip_mock_data = { # Private/local IPs "127.0.0.1" => nil, "192.168.1.1" => nil, # North America "54.234.242.13" => { country: "United States", code: "US", region: "VA", city: "Ashburn", postal: "20147" }, "104.193.168.19" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "199.241.200.176" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "216.38.135.1" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "4.167.234.0" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "12.38.32.0" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "64.115.250.0" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "67.183.58.7" => { country: "United States", code: "US", region: "WA", city: "Seattle", postal: "98101" }, "72.229.28.185" => { country: "United States", code: "US", region: "NY", city: "New York", postal: "10001" }, "12.12.128.128" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "101.198.198.0" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "199.21.86.138" => { country: "United States", code: "US", region: "CA", city: "San Francisco", postal: "94110" }, "76.66.210.142" => { country: "Canada", code: "CA", region: "ON", city: "Toronto", postal: "M5H 2N2" }, "184.65.213.114" => { country: "Canada", code: "CA", region: "BC", city: "Vancouver", postal: "V6B 1A1" }, "192.206.151.131" => { country: "Canada", code: "CA", region: "ON", city: "Toronto", postal: "M5H 2N2" }, "104.163.219.131" => { country: "Canada", code: "CA", region: "QC", city: "Montreal", postal: "H1A 0A1" }, # Europe "2.47.255.255" => { country: "Italy", code: "IT", region: "RM", city: "Rome", postal: "00100" }, "93.99.163.13" => { country: "Czechia", code: "CZ", region: "10", city: "Prague", postal: "11000" }, "46.140.123.45" => { country: "Switzerland", code: "CH", region: "ZH", city: "Zurich", postal: "8001" }, "84.210.138.89" => { country: "Norway", code: "NO", region: "03", city: "Oslo", postal: "0150" }, "213.220.126.106" => { country: "Iceland", code: "IS", region: "1", city: "Reykjavik", postal: "101" }, "85.127.28.23" => { country: "Austria", code: "AT", region: "9", city: "Vienna", postal: "1010" }, "176.36.232.147" => { country: "Ukraine", code: "UA", region: "30", city: "Kiev", postal: "01001" }, "178.168.0.1" => { country: "Moldova", code: "MD", region: "C", city: "Chisinau", postal: "2000" }, "178.220.0.1" => { country: "Serbia", code: "RS", region: "00", city: "Belgrade", postal: "11000" }, "93.84.113.217" => { country: "Belarus", code: "BY", region: "HM", city: "Minsk", postal: "220000" }, "95.167.0.0" => { country: "Russia", code: "RU", region: "MOW", city: "Moscow", postal: "101000" }, "193.145.138.32" => { country: "Switzerland", code: "CH", region: "ZH", city: "Zurich", postal: "8001" }, "193.145.147.158" => { country: "Switzerland", code: "CH", region: "ZH", city: "Zurich", postal: "8001" }, "182.23.143.254" => { country: "Turkey", code: "TR", region: "34", city: "Istanbul", postal: "34000" }, # Asia-Pacific "103.251.65.149" => { country: "Australia", code: "AU", region: "NSW", city: "Sydney", postal: "2000" }, "103.6.151.4" => { country: "Singapore", code: "SG", region: "01", city: "Singapore", postal: "018956" }, "126.0.0.1" => { country: "Japan", code: "JP", region: "13", city: "Tokyo", postal: "100-0001" }, "121.72.165.118" => { country: "New Zealand", code: "NZ", region: "AUK", city: "Auckland", postal: "1010" }, "1.174.208.0" => { country: "Taiwan", code: "TW", region: "TPE", city: "Taipei", postal: "100" }, "1.208.105.19" => { country: "South Korea", code: "KR", region: "11", city: "Seoul", postal: "04524" }, "1.255.49.75" => { country: "South Korea", code: "KR", region: "11", city: "Seoul", postal: "04524" }, "103.48.196.103" => { country: "India", code: "IN", region: "DL", city: "New Delhi", postal: "110001" }, "113.161.94.110" => { country: "Vietnam", code: "VN", region: "79", city: "Ho Chi Minh City", postal: "700000" }, "171.96.70.108" => { country: "Thailand", code: "TH", region: "10", city: "Bangkok", postal: "10200" }, "175.143.0.1" => { country: "Malaysia", code: "MY", region: "14", city: "Kuala Lumpur", postal: "50000" }, "78.188.0.1" => { country: "Turkey", code: "TR", region: "34", city: "Istanbul", postal: "34000" }, # Africa & Middle East "196.25.255.250" => { country: "South Africa", code: "ZA", region: "WC", city: "Cape Town", postal: "8000" }, "41.184.122.50" => { country: "Nigeria", code: "NG", region: "LA", city: "Lagos", postal: "100001" }, "84.235.49.128" => { country: "Saudi Arabia", code: "SA", region: "01", city: "Riyadh", postal: "11564" }, "185.93.245.44" => { country: "United Arab Emirates", code: "AE", region: "DU", city: "Dubai", postal: "00000" }, "156.208.0.0" => { country: "Egypt", code: "EG", region: "C", city: "Cairo", postal: "11511" }, "105.158.0.1" => { country: "Morocco", code: "MA", region: "07", city: "Casablanca", postal: "20000" }, "31.146.180.0" => { country: "Georgia", code: "GE", region: "TB", city: "Tbilisi", postal: "0100" }, "41.188.156.75" => { country: "Tanzania", code: "TZ", region: "26", city: "Dar es Salaam", postal: "11000" }, "41.90.0.1" => { country: "Kenya", code: "KE", region: "110", city: "Nairobi", postal: "00100" }, "5.37.0.0" => { country: "Oman", code: "OM", region: "MA", city: "Muscat", postal: "112" }, "77.69.128.1" => { country: "Bahrain", code: "BH", region: "13", city: "Manama", postal: "317" }, # Americas (South/Central) "181.49.0.1" => { country: "Colombia", code: "CO", region: "DC", city: "Bogota", postal: "110111" }, "186.101.88.2" => { country: "Ecuador", code: "EC", region: "P", city: "Quito", postal: "170150" }, "186.15.0.1" => { country: "Costa Rica", code: "CR", region: "SJ", city: "San Jose", postal: "1000" }, "187.189.0.1" => { country: "Mexico", code: "MX", region: "CMX", city: "Mexico City", postal: "06000" }, "189.144.240.120" => { country: "Mexico", code: "MX", region: "CMX", city: "Mexico City", postal: "06000" }, "200.68.0.1" => { country: "Chile", code: "CL", region: "RM", city: "Santiago", postal: "8320000" }, # Other Regions "2.132.97.1" => { country: "Kazakhstan", code: "KZ", region: "ALA", city: "Almaty", postal: "050000" }, "91.196.77.77" => { country: "Uzbekistan", code: "UZ", region: "TK", city: "Tashkent", postal: "100000" }, "41.208.70.70" => { country: "Libya", code: "LY", region: "TB", city: "Tripoli", postal: "00000" }, "109.110.31.255" => { country: "Latvia", code: "LV", region: "RIX", city: "Riga", postal: "LV-1000" }, # IPv6 addresses "2001:861:5bc0:cb60:500d:3535:e6a7:62a0" => { country: "France", code: "FR", region: "BFC", city: "Belfort", postal: "90000" } } allow(GeoIp).to receive(:lookup) do |ip| data = geoip_mock_data[ip] next nil if data.nil? GeoIp::Result.new( country_name: data[:country], country_code: data[:code], region_name: data[:region], city_name: data[:city], postal_code: data[:postal], latitude: nil, longitude: 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/support/iffy_helper.rb
spec/support/iffy_helper.rb
# frozen_string_literal: true module IffySpecHelper def set_headers(json: nil) hmac = OpenSSL::HMAC.hexdigest("sha256", GlobalConfig.get("IFFY_WEBHOOK_SECRET"), json.to_json) request.headers["X-Signature"] = hmac request.headers["Content-Type"] = "application/json" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false