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/db/migrate/20240724013512_add_deleted_at_index_to_product_files.rb
db/migrate/20240724013512_add_deleted_at_index_to_product_files.rb
# frozen_string_literal: true class AddDeletedAtIndexToProductFiles < ActiveRecord::Migration[7.1] def up change_table :product_files, bulk: true do |t| t.index :deleted_at t.change :id, :bigint, null: false, auto_increment: true t.change :link_id, :bigint t.change :installment_id, :bigint t.change :flags, :bigint, null: false t.change :deleted_at, :datetime, limit: 6 t.change :deleted_from_cdn_at, :datetime, limit: 6 t.change :created_at, :datetime, limit: 6 t.change :updated_at, :datetime, limit: 6 end end def down change_table :product_files, bulk: true do |t| t.remove_index :deleted_at t.change :id, :int, null: false, auto_increment: true t.change :link_id, :int t.change :installment_id, :int t.change :flags, :int, null: false t.change :deleted_at, :datetime, precision: nil t.change :deleted_from_cdn_at, :datetime, precision: nil t.change :created_at, :datetime, precision: nil t.change :updated_at, :datetime, precision: nil end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factory_bot_linting_spec.rb
spec/factory_bot_linting_spec.rb
# frozen_string_literal: true require "support/factory_bot_linting.rb" RSpec.describe FactoryBotLinting do it "#process" do expect { described_class.new.process }.to_not raise_error end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true ENV["RAILS_ENV"] = "test" BUILDING_ON_CI = !ENV["CI"].nil? require File.expand_path("../config/environment", __dir__) require "capybara/rails" require "capybara/rspec" require "rspec/rails" require "paper_trail/frameworks/rspec" require "pundit/rspec" Dir.glob(Rails.root.join("spec", "support", "**", "*.rb")).each { |f| require f } JsonMatchers.schema_root = "spec/support/schemas" KnapsackPro::Adapters::RSpecAdapter.bind ActiveRecord::Migration.maintain_test_schema! # Capybara settings Capybara.test_id = "data-testid" Capybara.default_max_wait_time = 25 Capybara.app_host = "#{PROTOCOL}://#{DOMAIN}" Capybara.server = :puma Capybara.server_port = URI(Capybara.app_host).port Capybara.threadsafe = true Capybara.enable_aria_label = true Capybara.enable_aria_role = true FactoryBot.definition_file_paths << Rails.root.join("spec", "support", "factories") Mongoid.load!(Rails.root.join("config", "mongoid.yml")) Braintree::Configuration.logger = Logger.new(File::NULL) PayPal::SDK.logger = Logger.new(File::NULL) unless BUILDING_ON_CI # super_diff error formatting doesn't work well on CI, and for flaky Capybara specs it can potentially obfuscate the actual error require "super_diff/rspec-rails" SuperDiff.configure { |config| config.actual_color = :green } end # NOTE Add only valid errors here. Do not errors we should handle and fix on specs themselves JSErrorReporter.set_global_ignores [ /Warning: %s: Support for defaultProps will be removed from function components in a future major release/, /(Component closed|Object|zoid destroyed all components)\n\t \(https:\/\/www.paypal.com\/sdk\/js/, /The method FB.getLoginStatus can no longer be called from http pages/, /The user aborted a request./, ] def configure_vcr VCR.configure do |config| config.cassette_library_dir = File.join(Rails.root, "spec", "support", "fixtures", "vcr_cassettes") config.hook_into :webmock config.ignore_hosts "gumroad-specs.s3.amazonaws.com", "s3.amazonaws.com", "codeclimate.com", "mongo", "redis", "elasticsearch", "minio" config.ignore_hosts "api.knapsackpro.com" config.ignore_hosts "googlechromelabs.github.io" config.ignore_hosts "storage.googleapis.com" config.ignore_localhost = true config.configure_rspec_metadata! config.debug_logger = $stdout if ENV["VCR_DEBUG"] config.default_cassette_options[:record] = BUILDING_ON_CI ? :none : :once config.filter_sensitive_data("<AWS_ACCOUNT_ID>") { GlobalConfig.get("AWS_ACCOUNT_ID") } config.filter_sensitive_data("<AWS_ACCESS_KEY_ID>") { GlobalConfig.get("AWS_ACCESS_KEY_ID") } config.filter_sensitive_data("<STRIPE_PLATFORM_ACCOUNT_ID>") { GlobalConfig.get("STRIPE_PLATFORM_ACCOUNT_ID") } config.filter_sensitive_data("<STRIPE_API_KEY>") { GlobalConfig.get("STRIPE_API_KEY") } config.filter_sensitive_data("<STRIPE_CONNECT_CLIENT_ID>") { GlobalConfig.get("STRIPE_CONNECT_CLIENT_ID") } config.filter_sensitive_data("<PAYPAL_USERNAME>") { GlobalConfig.get("PAYPAL_USERNAME") } config.filter_sensitive_data("<PAYPAL_PASSWORD>") { GlobalConfig.get("PAYPAL_PASSWORD") } config.filter_sensitive_data("<PAYPAL_SIGNATURE>") { GlobalConfig.get("PAYPAL_SIGNATURE") } config.filter_sensitive_data("<STRONGBOX_GENERAL_PASSWORD>") { GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD") } config.filter_sensitive_data("<DROPBOX_API_KEY>") { GlobalConfig.get("DROPBOX_API_KEY") } config.filter_sensitive_data("<SENDGRID_GUMROAD_TRANSACTIONS_API_KEY>") { GlobalConfig.get("SENDGRID_GUMROAD_TRANSACTIONS_API_KEY") } config.filter_sensitive_data("<SENDGRID_GR_CREATORS_API_KEY>") { GlobalConfig.get("SENDGRID_GR_CREATORS_API_KEY") } config.filter_sensitive_data("<SENDGRID_GR_CUSTOMERS_LEVEL_2_API_KEY>") { GlobalConfig.get("SENDGRID_GR_CUSTOMERS_LEVEL_2_API_KEY") } config.filter_sensitive_data("<SENDGRID_GUMROAD_FOLLOWER_CONFIRMATION_API_KEY>") { GlobalConfig.get("SENDGRID_GUMROAD_FOLLOWER_CONFIRMATION_API_KEY") } config.filter_sensitive_data("<EASYPOST_API_KEY>") { GlobalConfig.get("EASYPOST_API_KEY") } config.filter_sensitive_data("<BRAINTREE_API_PRIVATE_KEY>") { GlobalConfig.get("BRAINTREE_API_PRIVATE_KEY") } config.filter_sensitive_data("<BRAINTREE_MERCHANT_ID>") { GlobalConfig.get("BRAINTREE_MERCHANT_ID") } config.filter_sensitive_data("<BRAINTREE_PUBLIC_KEY>") { GlobalConfig.get("BRAINTREE_PUBLIC_KEY") } config.filter_sensitive_data("<BRAINTREE_MERCHANT_ACCOUNT_ID_FOR_SUPPLIERS>") { GlobalConfig.get("BRAINTREE_MERCHANT_ACCOUNT_ID_FOR_SUPPLIERS") } config.filter_sensitive_data("<PAYPAL_CLIENT_ID>") { GlobalConfig.get("PAYPAL_CLIENT_ID") } config.filter_sensitive_data("<PAYPAL_CLIENT_SECRET>") { GlobalConfig.get("PAYPAL_CLIENT_SECRET") } config.filter_sensitive_data("<PAYPAL_MERCHANT_EMAIL>") { GlobalConfig.get("PAYPAL_MERCHANT_EMAIL") } config.filter_sensitive_data("<PAYPAL_PARTNER_CLIENT_ID>") { GlobalConfig.get("PAYPAL_PARTNER_CLIENT_ID") } config.filter_sensitive_data("<PAYPAL_PARTNER_MERCHANT_ID>") { GlobalConfig.get("PAYPAL_PARTNER_MERCHANT_ID") } config.filter_sensitive_data("<PAYPAL_PARTNER_MERCHANT_EMAIL>") { GlobalConfig.get("PAYPAL_PARTNER_MERCHANT_EMAIL") } config.filter_sensitive_data("<PAYPAL_BN_CODE>") { GlobalConfig.get("PAYPAL_BN_CODE") } config.filter_sensitive_data("<VATSTACK_API_KEY>") { GlobalConfig.get("VATSTACK_API_KEY") } config.filter_sensitive_data("<IRAS_API_ID>") { GlobalConfig.get("IRAS_API_ID") } config.filter_sensitive_data("<IRAS_API_SECRET>") { GlobalConfig.get("IRAS_API_SECRET") } config.filter_sensitive_data("<TAXJAR_API_KEY>") { GlobalConfig.get("TAXJAR_API_KEY") } config.filter_sensitive_data("<TAX_ID_PRO_API_KEY>") { GlobalConfig.get("TAX_ID_PRO_API_KEY") } config.filter_sensitive_data("<CIRCLE_API_KEY>") { GlobalConfig.get("CIRCLE_API_KEY") } config.filter_sensitive_data("<OPEN_EXCHANGE_RATES_APP_ID>") { GlobalConfig.get("OPEN_EXCHANGE_RATES_APP_ID") } config.filter_sensitive_data("<UNSPLASH_CLIENT_ID>") { GlobalConfig.get("UNSPLASH_CLIENT_ID") } config.filter_sensitive_data("<DISCORD_BOT_TOKEN>") { GlobalConfig.get("DISCORD_BOT_TOKEN") } config.filter_sensitive_data("<DISCORD_CLIENT_ID>") { GlobalConfig.get("DISCORD_CLIENT_ID") } config.filter_sensitive_data("<ZOOM_CLIENT_ID>") { GlobalConfig.get("ZOOM_CLIENT_ID") } config.filter_sensitive_data("<GCAL_CLIENT_ID>") { GlobalConfig.get("GCAL_CLIENT_ID") } config.filter_sensitive_data("<OPENAI_ACCESS_TOKEN>") { GlobalConfig.get("OPENAI_ACCESS_TOKEN") } config.filter_sensitive_data("<IOS_CONSUMER_APP_APPLE_LOGIN_IDENTIFIER>") { GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_IDENTIFIER") } config.filter_sensitive_data("<IOS_CREATOR_APP_APPLE_LOGIN_TEAM_ID>") { GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_TEAM_ID") } config.filter_sensitive_data("<IOS_CREATOR_APP_APPLE_LOGIN_IDENTIFIER>") { GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_IDENTIFIER") } config.filter_sensitive_data("<GOOGLE_CLIENT_ID>") { GlobalConfig.get("GOOGLE_CLIENT_ID") } config.filter_sensitive_data("<RPUSH_CONSUMER_FCM_FIREBASE_PROJECT_ID>") { GlobalConfig.get("RPUSH_CONSUMER_FCM_FIREBASE_PROJECT_ID") } config.filter_sensitive_data("<SLACK_WEBHOOK_URL>") { GlobalConfig.get("SLACK_WEBHOOK_URL") } config.filter_sensitive_data("<CLOUDFRONT_KEYPAIR_ID>") { GlobalConfig.get("CLOUDFRONT_KEYPAIR_ID") } end end configure_vcr def prepare_mysql ActiveRecord::Base.connection.execute("SET SESSION information_schema_stats_expiry = 0") end RSpec.configure do |config| config.include Capybara::DSL config.include ErrorResponses config.mock_with :rspec config.file_fixture_path = "#{::Rails.root}/spec/support/fixtures" config.infer_base_class_for_anonymous_controllers = false config.infer_spec_type_from_file_location! config.include Devise::Test::ControllerHelpers, type: :controller config.include Devise::Test::ControllerHelpers, type: :helper config.include FactoryBot::Syntax::Methods config.pattern = "**/*_spec.rb" config.raise_errors_for_deprecations! config.use_transactional_fixtures = true config.filter_run_when_matching :focus config.example_status_persistence_file_path = Rails.root.join("tmp", "rspec_status.txt").to_s config.include ActiveSupport::Testing::TimeHelpers if BUILDING_ON_CI # show retry status in spec process config.verbose_retry = true # show exception that triggers a retry if verbose_retry is set to true config.display_try_failure_messages = true config.default_retry_count = 3 end config.before(:suite) do # Disable webmock while cleanup, see also https://github.com/teamcapybara/capybara#gotchas WebMock.allow_net_connect!(net_http_connect_on_start: true) [ Thread.new { prepare_mysql }, Thread.new { ElasticsearchSetup.prepare_test_environment } ].each(&:join) end # Stub SsrfFilter globally to allow localhost/minio in tests # Use `skip_ssrf_stub: true` metadata to opt-out (e.g., for SSRF protection tests) config.before(:each) do |example| unless example.metadata[:skip_ssrf_stub] allow(SsrfFilter).to receive(:get) do |url, **_args| HTTParty.get(url) end end end config.after(:each) do |example| RSpec::Mocks.space.proxy_for(SsrfFilter).reset if example.metadata[:skip_ssrf_stub] end config.before(:suite) do examples = RSpec.world.filtered_examples.values.flatten if examples.any? { |ex| ex.metadata[:type] == :system } begin StripeBalanceEnforcer.ensure_sufficient_balance rescue StandardError => e warn "Stripe balance check failed: #{e.class} #{e.message}" end end end config.before(:suite) do examples = RSpec.world.filtered_examples.values.flatten feature_specs = examples.select { |ex| ex.metadata[:type] == :feature } next if feature_specs.empty? feature_spec_files = feature_specs.map { |ex| ex.metadata[:example_group][:file_path] }.uniq raise <<~ERROR FEATURE SPECS ARE NO LONGER ALLOWED Found #{feature_specs.count} feature spec(s) in #{feature_spec_files.count} file(s): #{feature_spec_files.map { |file| " • #{file}" }.join("\n")} ACTION REQUIRED: Please convert these to system specs by changing: type: :feature -> type: :system ERROR end config.before(:all) do |example| $spec_example_start = Process.clock_gettime(Process::CLOCK_MONOTONIC) print "#{example.class.description}: " end config.after(:all) do spec_example_duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - $spec_example_start puts " [#{spec_example_duration.round(2)}s]" end # Differences between before/after and around: https://relishapp.com/rspec/rspec-core/v/3-0/docs/hooks/around-hooks # tldr: before/after will share state with the example, needed for some plugins config.before(:each) do Sidekiq.redis(&:flushdb) $redis.flushdb %i[ store_discover_searches log_email_events follow_wishlists seller_refund_policy_new_users_enabled paypal_payout_fee disable_braintree_sales ].each do |feature| Feature.activate(feature) end @request&.host = DOMAIN # @request only valid for controller specs. PostSendgridApi.mails.clear end config.after(:each) do |example| capture_state_on_failure(example) Capybara.reset_sessions! WebMock.allow_net_connect! end config.around(:each) do |example| if example.metadata[:sidekiq_inline] Sidekiq::Testing.inline! else Sidekiq::Testing.fake! end example.run end config.around(:each) do |example| if example.metadata[:enforce_product_creation_limit] example.run else Link.bypass_product_creation_limit do example.run end end end config.around(:each, :elasticsearch_wait_for_refresh) do |example| actions = [:index, :update, :update_by_query, :delete] actions.each do |action| Elasticsearch::API::Actions.send(:alias_method, action, :"#{action}_and_wait_for_refresh") end example.run actions.each do |action| Elasticsearch::API::Actions.send(:alias_method, action, :"original_#{action}") end end config.around(:each, :freeze_time) do |example| freeze_time do example.run end end config.around(:each) do |example| config.instance_variable_set(:@curr_file_path, example.metadata[:example_group][:file_path]) Mongoid.purge! options = %w[caching js] # delegate all the before- and after- hooks for these values to metaprogramming "setup" and "teardown" methods, below options.each { |opt| send(:"setup_#{ opt }", example.metadata[opt.to_sym]) } stub_webmock example.run options.each { |opt| send(:"teardown_#{ opt }", example.metadata[opt.to_sym]) } Rails.cache.clear travel_back end config.around(:each, :shipping) do |example| vcr_turned_on do only_matching_vcr_request_from(["easypost", "taxjar"]) do VCR.use_cassette("ShippingScenarios/#{example.description}") do # Debug flaky specs. puts "*" * 100 puts example.full_description puts example.location puts "VCR recording: #{VCR.current_cassette&.recording?}" puts "VCR name: #{VCR.current_cassette&.name}" puts "*" * 100 example.run end end end end config.around(:each, :taxjar) do |example| vcr_turned_on do only_matching_vcr_request_from(["taxjar"]) do VCR.use_cassette("Taxjar/#{example.description}") do example.run end end end end config.after(:each, type: :system, js: true) do JSErrorReporter.instance.report_errors!(self) JSErrorReporter.instance.reset! end # checkout page fetches Braintree client token for PayPal button rendering. # but we don't use paypal in system tests for checkout, so we don't need to generate a real token. config.before(:each, type: :system, js: true) do allow(Braintree::ClientToken).to receive(:generate).and_return("dummy_braintree_client_token") end config.before(:each) do # Needs to be a valid URL that returns 200 OK when accessed externally, otherwise requests to Stripe will error out. allow_any_instance_of(User).to receive(:business_profile_url).and_return("https://vipul.gumroad.com/") end # Subscribe Preview Generation boots up a new webdriver instance and uploads to S3 for each run. # This breaks CI because it collides with Capybara and spams S3, since it runs on User model changes. # The job and associated code is tested separately instead. config.before(:each) do allow_any_instance_of(User).to receive(:generate_subscribe_preview).and_return(true) end config.around(realistic_error_responses: true) do |example| respond_without_detailed_exceptions(&example) end end def ignore_js_error(string_or_regex) JSErrorReporter.instance.add_ignore_error string_or_regex end def capture_state_on_failure(example) return if example.exception.blank? suppress(Capybara::NotSupportedByDriverError) do save_path = example.metadata[:example_group][:location] Capybara.page.save_page("#{save_path}.html") Capybara.page.save_screenshot "#{save_path}.png" end end def find_and_click(selector, options = {}) expect(page).to have_selector(selector, **options) page.find(selector, **options).click end def expect_alert_message(text) expect(page).to have_selector("[role=alert]", text:) end def expect_404_response(response) expect(response).to have_http_status(:not_found) expect(response.parsed_body["success"]).to eq(false) expect(response.parsed_body["error"]).to eq("Not found") end # Around filters for "setup" and "teardown" depending on test/suite options def setup_caching(val = false) ActionController::Base.perform_caching = val end def setup_js(val = false) if val VCR.turn_off! # See also https://github.com/teamcapybara/capybara#gotchas WebMock.allow_net_connect!(net_http_connect_on_start: true) else VCR.turn_on! WebMock.disable_net_connect!(allow_localhost: true, allow: ["api.knapsackpro.com"]) end end def teardown_caching(val = false) ActionController::Base.perform_caching = !val end def teardown_js(val = false) if val WebMock.disable_net_connect!(allow_localhost: true, allow: ["api.knapsackpro.com"]) stub_webmock end end def run_with_log_level(log_level) previous_log_level = Rails.logger.level Rails.logger.level = log_level yield ensure Rails.logger.level = previous_log_level end def vcr_turned_on prev_vcr_on = VCR.turned_on? VCR.turn_on! unless prev_vcr_on begin yield ensure VCR.turn_off! unless prev_vcr_on end end def only_matching_vcr_request_from(hosts) VCR.configure do |c| c.ignore_request do |request| !hosts.any? { |host| request.uri.match?(host) } end end begin yield ensure configure_vcr end end def stub_pwned_password_check @pwned_password_request_stub = WebMock.stub_request(:get, %r{api\.pwnedpasswords\.com/range/.+}) end def stub_webmock WebMock.stub_request(:post, "https://notify.bugsnag.com/") WebMock.stub_request(:post, "https://sessions.bugsnag.com/") WebMock.stub_request(:post, %r{iffy-live\.gumroad\.com/people/buyer_info}) .with(body: "{\"require_zip\": false}", headers: { status: %w[200 OK], content_type: "application/json" }) stub_pwned_password_check end def with_real_pwned_password_check WebMock.remove_request_stub(@pwned_password_request_stub) begin yield ensure stub_pwned_password_check end end RSpec.configure do |config| config.include Devise::Test::IntegrationHelpers, type: :system config.include CapybaraHelpers, type: :system config.include ProductFileListHelpers, type: :system config.include ProductCardHelpers, type: :system config.include ProductRowHelpers, type: :system config.include ProductVariantsHelpers, type: :system config.include PreviewBoxHelpers, type: :system config.include ProductWantThisHelpers, type: :system config.include PayWorkflowHelpers, type: :system config.include CheckoutHelpers, type: :system config.include RichTextEditorHelpers, type: :system config.include DiscoverHelpers, type: :system config.include MockTableHelpers config.include SecureHeadersHelpers, type: :system config.include ElasticsearchHelpers config.include ProductPageViewHelpers config.include SalesRelatedProductsInfosHelpers end RSpec::Sidekiq.configure do |config| config.warn_when_jobs_not_processed_by_sidekiq = false end RSpec::Mocks.configuration.allow_message_expectations_on_nil = true
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/observers/email_delivery_observer_spec.rb
spec/observers/email_delivery_observer_spec.rb
# frozen_string_literal: true require "spec_helper" describe EmailDeliveryObserver do describe ".delivered_email" do let(:message) { instance_double(Mail::Message) } before do allow(EmailDeliveryObserver::HandleEmailEvent).to receive(:perform).with(message).and_return(true) allow(EmailDeliveryObserver::HandleCustomerEmailInfo).to receive(:perform).with(message).and_return(true) end it "calls handlers" do expect(EmailDeliveryObserver::HandleEmailEvent).to receive(:perform).with(message).and_return(true) expect(EmailDeliveryObserver::HandleCustomerEmailInfo).to receive(:perform).with(message).and_return(true) EmailDeliveryObserver.delivered_email(message) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/observers/email_delivery_observer/handle_customer_email_info_spec.rb
spec/observers/email_delivery_observer/handle_customer_email_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe EmailDeliveryObserver::HandleCustomerEmailInfo do let(:purchase) { create(:purchase) } describe ".perform" do RSpec.shared_examples "CustomerMailer.receipt" do describe "for a Purchase" do context "when CustomerEmailInfo record doesn't exist" do it "creates a record and marks as sent" do expect do CustomerMailer.receipt(purchase.id, nil, for_email: true).deliver_now end.to change { CustomerEmailInfo.count }.by(1) email_info = CustomerEmailInfo.last expect(email_info.purchase).to eq(purchase) expect(email_info.email_name).to eq("receipt") expect(email_info.sent_at).to be_present end end context "when CustomerEmailInfo record exists" do let!(:customer_email_info) { create(:customer_email_info, purchase: purchase, email_name: "receipt") } it "finds the record and marks as sent" do expect do CustomerMailer.receipt(purchase.id, nil, for_email: true).deliver_now end.not_to change { CustomerEmailInfo.count } expect(customer_email_info.reload.sent_at).to be_present end end end describe "for a Charge" do let(:charge) { create(:charge, purchases: [purchase]) } let(:order) { charge.order } before do order.purchases << purchase end context "when CustomerEmailInfo record doesn't exist" do it "creates a record and marks as sent" do expect do CustomerMailer.receipt(nil, charge.id, for_email: true).deliver_now end.to change { CustomerEmailInfo.count }.by(1) email_info = CustomerEmailInfo.last expect(email_info.purchase).to be(nil) expect(email_info.email_info_charge.charge_id).to eq(charge.id) expect(email_info.email_name).to eq("receipt") expect(email_info.sent_at).to be_present end end context "when CustomerEmailInfo record exists" do let!(:customer_email_info) do email_info = CustomerEmailInfo.new(email_name: "receipt") email_info.build_email_info_charge(charge_id: charge.id) email_info.save! email_info end it "finds the record and marks as sent" do expect do CustomerMailer.receipt(nil, charge.id, for_email: true).deliver_now end.not_to change { CustomerEmailInfo.count } expect(customer_email_info.reload.sent_at).to be_present end context "when using purchase_id as argument" do it "finds the record and marks as sent" do expect do CustomerMailer.receipt(purchase.id, nil, for_email: true).deliver_now end.not_to change { CustomerEmailInfo.count } expect(customer_email_info.reload.sent_at).to be_present end end end end end RSpec.shared_examples "CustomerMailer.preorder" do let(:preorder) do create(:preorder, preorder_link: create(:preorder_link, link: purchase.link)) end before do purchase.update!(preorder:) end context "when CustomerEmailInfo record doesn't exist" do it "marks creates a record and marks as sent" do expect do CustomerMailer.preorder_receipt(preorder.id).deliver_now end.to change { CustomerEmailInfo.count }.by(1) email_info = CustomerEmailInfo.last expect(email_info.purchase).to eq(purchase) expect(email_info.email_name).to eq("preorder_receipt") expect(email_info.sent_at).to be_present end end context "when CustomerEmailInfo record exists" do let!(:customer_email_info) { create(:customer_email_info, purchase: purchase, email_name: "preorder_receipt") } it "finds the record and marks as sent" do expect do CustomerMailer.preorder_receipt(preorder.id).deliver_now end.not_to change { CustomerEmailInfo.count } expect(customer_email_info.reload.sent_at).to be_present end end end RSpec.shared_examples "mailer method is not supported" do it "doesn't raise and it doesn't create a record" do expect do expect do CustomerMailer.grouped_receipt([purchase.id]).deliver_now end.not_to raise_error end.not_to change { CustomerEmailInfo.count } end end RSpec.shared_examples "mailer class is not supported" do it "doesn't raise and it doesn't create a record" do expect do expect do ContactingCreatorMailer.chargeback_notice(create(:dispute, purchase:).id).deliver_now end.not_to raise_error end.not_to change { CustomerEmailInfo.count } end end context "with SendGrid" do it_behaves_like "CustomerMailer.receipt" it_behaves_like "CustomerMailer.preorder" it_behaves_like "mailer method is not supported" it_behaves_like "mailer class is not supported" context "when the SendGrid header is invalid" do let(:message) { instance_double(Mail::Message) } let(:header) { instance_double(Mail::Header) } let(:smtpapi_header_value) { "invalid" } let(:smtpapi_header_field) { Mail::Field.new(MailerInfo::SENDGRID_X_SMTPAPI_HEADER, smtpapi_header_value) } let(:email_provider_header_field) { Mail::Field.new(MailerInfo.header_name(:email_provider), MailerInfo::EMAIL_PROVIDER_SENDGRID) } before do allow(message).to receive(:header).and_return( { MailerInfo.header_name(:email_provider) => email_provider_header_field, MailerInfo::SENDGRID_X_SMTPAPI_HEADER => smtpapi_header_field, } ) end it "notifies Bugsnag" do expect(Bugsnag).to receive(:notify) do |error| expect(error).to be_a(EmailDeliveryObserver::HandleCustomerEmailInfo::InvalidHeaderError) expect(error.message.to_s).to eq("Failed to parse sendgrid header: unexpected character: 'invalid' at line 1 column 1") expect(JSON.parse(error.bugsnag_meta_data[:debug]).keys).to include(MailerInfo::SENDGRID_X_SMTPAPI_HEADER) end expect do expect do EmailDeliveryObserver::HandleCustomerEmailInfo.perform(message) end.not_to raise_error end.not_to change { CustomerEmailInfo.count } end end end context "with Resend" do before do Feature.activate(:use_resend_for_application_mailer) end it_behaves_like "CustomerMailer.receipt" it_behaves_like "CustomerMailer.preorder" it_behaves_like "mailer method is not supported" it_behaves_like "mailer class is not supported" context "when the Resend header is invalid" do let(:message) { instance_double(Mail::Message) } let(:header) { instance_double(Mail::Header) } let(:header_value) { "invalid" } let(:header_field) { Mail::Field.new(MailerInfo.header_name(:mailer_class), header_value) } let(:email_provider_header_field) { Mail::Field.new(MailerInfo.header_name(:email_provider), MailerInfo::EMAIL_PROVIDER_RESEND) } before do allow(message).to receive(:header).and_return( { MailerInfo.header_name(:email_provider) => email_provider_header_field, MailerInfo.header_name(:mailer_class) => header_field, } ) end it "notifies Bugsnag" do expect(Bugsnag).to receive(:notify) do |error| expect(error).to be_a(EmailDeliveryObserver::HandleCustomerEmailInfo::InvalidHeaderError) expect(error.message.to_s).to eq("Failed to parse resend header: undefined method 'value' for nil") expect(JSON.parse(error.bugsnag_meta_data[:debug]).keys).to include(MailerInfo.header_name(:mailer_class)) end expect do expect do EmailDeliveryObserver::HandleCustomerEmailInfo.perform(message) end.not_to raise_error end.not_to change { CustomerEmailInfo.count } 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/observers/email_delivery_observer/handle_email_event_spec.rb
spec/observers/email_delivery_observer/handle_email_event_spec.rb
# frozen_string_literal: true require "spec_helper" describe EmailDeliveryObserver::HandleEmailEvent do let(:user) { create(:user, email: "user@example.com") } let(:email_digest) { Digest::SHA1.hexdigest(user.email).first(12) } describe ".perform" do it "logs email sent event" do timestamp = Time.current travel_to timestamp do expect do TwoFactorAuthenticationMailer.authentication_token(user.id).deliver_now end.to change { EmailEvent.count }.by(1) record = EmailEvent.find_by(email_digest:) expect(record.sent_emails_count).to eq 1 expect(record.unopened_emails_count).to eq 1 expect(record.last_email_sent_at.to_i).to eq timestamp.to_i expect(record.first_unopened_email_sent_at.to_i).to eq timestamp.to_i end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/jobs/delete_unused_public_files_job_spec.rb
spec/jobs/delete_unused_public_files_job_spec.rb
# frozen_string_literal: true require "spec_helper" describe DeleteUnusedPublicFilesJob do it "deletes public files scheduled for deletion" do public_file = create(:public_file, :with_audio, scheduled_for_deletion_at: 1.day.ago) described_class.new.perform public_file.reload expect(public_file).to be_deleted expect(public_file.file).not_to be_attached end it "does not delete public files not scheduled for deletion" do public_file = create(:public_file, :with_audio) expect(public_file.file).to be_attached described_class.new.perform public_file.reload expect(public_file).not_to be_deleted expect(public_file.file).to be_attached end it "does not delete public files scheduled for future deletion" do public_file = create(:public_file, :with_audio, scheduled_for_deletion_at: 1.day.from_now) expect(public_file.file).to be_attached described_class.new.perform public_file.reload expect(public_file).not_to be_deleted expect(public_file.file).to be_attached end it "only deletes the blob if no other attachments reference it" do public_file1 = create(:public_file, :with_audio, scheduled_for_deletion_at: 1.day.ago) public_file2 = create(:public_file) public_file2.file.attach(public_file1.file.blob) expect(public_file1.file).to be_attached expect(public_file2.file).to be_attached described_class.new.perform public_file1.reload public_file2.reload expect(public_file1).to be_deleted expect(public_file1.file).to be_attached expect(public_file2.file).to be_attached end it "handles transaction rollback if deletion fails" do public_file = create(:public_file, :with_audio, scheduled_for_deletion_at: 1.day.ago) allow_any_instance_of(ActiveStorage::Attached::One).to receive(:purge_later).and_raise(ActiveStorage::FileNotFoundError) expect do described_class.new.perform end.to raise_error(ActiveStorage::FileNotFoundError) public_file.reload expect(public_file).to_not be_deleted expect(public_file.file).to be_attached end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/subdomain_redirector_service_spec.rb
spec/services/subdomain_redirector_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SubdomainRedirectorService do let(:service) { described_class.new } describe "#update" do it "sets the config in redis" do config = "live.gumroad.com=example.com\ntwitter.gumroad.com=twitter.com/gumroad" service.update(config) redis_namespace = Redis::Namespace.new(:subdomain_redirect_namespace, redis: $redis) expect(redis_namespace.get("subdomain_redirects_config")).to eq config end end describe "#redirect_urL_for" do before do config = "live.gumroad.com=example.com\ntwitter.gumroad.com/123=twitter.com/gumroad" service.update(config) end context "when path is empty" do it "finds the correct redirect_url" do request = double("request") allow(request).to receive(:host).and_return("live.gumroad.com") allow(request).to receive(:fullpath).and_return("/") expect(service.redirect_url_for(request)).to eq "example.com" end end context "when path is not empty" do it "finds the correct redirect_url" do request = double("request") allow(request).to receive(:host).and_return("twitter.gumroad.com") allow(request).to receive(:fullpath).and_return("/123") expect(service.redirect_url_for(request)).to eq "twitter.com/gumroad" end end end describe "#hosts_to_redirect" do before do config = "live.gumroad.com=example.com\ntwitter.gumroad.com=twitter.com/gumroad" service.update(config) end it "returns a hash of hosts and redirect locations" do config = "live.gumroad.com=example.com\ntwitter.gumroad.com=twitter.com/gumroad" service.update(config) expect(service.redirects).to eq({ "live.gumroad.com" => "example.com", "twitter.gumroad.com" => "twitter.com/gumroad" }) end it "strips host and location" do config = "live.gumroad.com = example.com" service.update(config) expect(service.redirects).to eq({ "live.gumroad.com" => "example.com" }) end it "splits the config line correctly" do config = "live.gumroad.com=https://gumroad.com/test?hello=world" service.update(config) expect(service.redirects).to eq({ "live.gumroad.com" => "https://gumroad.com/test?hello=world" }) end it "ignores invalid config lines" do config = "abcd\nlive.gumroad.com=example.com" service.update(config) expect(service.redirects).to eq({ "live.gumroad.com" => "example.com" }) end it "ignores protected domains" do stub_const("SubdomainRedirectorService::PROTECTED_HOSTS", ["example.com"]) config = "example.com=gumroad.com\ntwitter.gumroad.com=twitter.com/gumroad" service.update(config) expect(service.redirects).to eq({ "twitter.gumroad.com" => "twitter.com/gumroad" }) end end describe "#redirect_config_as_text" do before do stub_const("SubdomainRedirectorService::PROTECTED_HOSTS", ["example.com"]) config = "example.com=gumroad.com\ntwitter.gumroad.com=twitter.com/gumroad" service.update(config) end it "returns redirect config as text after skipping protected domains" do expect(service.redirect_config_as_text).to eq "twitter.gumroad.com=twitter.com/gumroad" 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_search_service_spec.rb
spec/services/admin_search_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe AdminSearchService do describe "#search_purchases" do it "returns no Purchases if query is invalid" do purchases = AdminSearchService.new.search_purchases(query: "invalidquery") expect(purchases.size).to eq(0) end it "returns purchases matching email, directly and through gifts" do email = "user@example.com" purchase_1 = create(:purchase, email:) purchase_2 = create(:gift, gifter_email: email, gifter_purchase: create(:purchase)).gifter_purchase purchase_3 = create(:gift, giftee_email: email, giftee_purchase: create(:purchase)).giftee_purchase purchases = AdminSearchService.new.search_purchases(query: email) expect(purchases).to include(purchase_1, purchase_2, purchase_3) end it "returns purchase when searching by external_id" do purchase = create(:purchase) other_purchase = create(:purchase) purchases = AdminSearchService.new.search_purchases(query: purchase.external_id) expect(purchases).to eq([purchase]) expect(purchases).not_to include(other_purchase) end it "returns purchase when searching by internal id" do purchase = create(:purchase) other_purchase = create(:purchase) purchases = AdminSearchService.new.search_purchases(query: purchase.id.to_s) expect(purchases).to eq([purchase]) expect(purchases).not_to include(other_purchase) end describe "email parameter" do it "filters purchases by email when provided" do purchase = create(:free_purchase, email: "customer@example.com") other_purchase = create(:free_purchase, email: "other@example.com") purchases = AdminSearchService.new.search_purchases(email: "customer@example.com") expect(purchases).to include(purchase) expect(purchases).not_to include(other_purchase) end it "can use email and query together to find specific purchase" do purchase = create(:free_purchase, email: "customer@example.com") create(:free_purchase, email: "other@example.com") purchases = AdminSearchService.new.search_purchases(query: purchase.external_id, email: "customer@example.com") expect(purchases).to eq([purchase]) end it "returns empty when query matches but email doesn't" do purchase = create(:free_purchase, email: "customer@example.com") purchases = AdminSearchService.new.search_purchases(query: purchase.external_id, email: "wrong@example.com") expect(purchases).to be_empty end end it "returns purchases when searching by email with empty card parameters" do email = "user@example.com" purchase = create(:purchase, email:) purchase.update_column(:stripe_fingerprint, nil) purchases = AdminSearchService.new.search_purchases( query: email, transaction_date: "", last_4: "", card_type: "", price: "", expiry_date: "" ) expect(purchases).to include(purchase) end it "returns purchases for products created by a seller" do seller = create(:user, email: "seller@example.com") purchase = create(:purchase, link: create(:product, user: seller)) create(:purchase) purchases = AdminSearchService.new.search_purchases(creator_email: seller.email) expect(purchases).to eq([purchase]) end it "returns no purchases when creator email is not found" do create(:purchase) purchases = AdminSearchService.new.search_purchases(creator_email: "nonexistent@example.com") expect(purchases.size).to eq(0) end it "returns purchase associated with a license key" do purchase = create(:purchase) license = create(:license, purchase:) create(:purchase) purchases = AdminSearchService.new.search_purchases(license_key: license.serial) expect(purchases).to eq([purchase]) end it "returns no purchases when license key is not found" do create(:purchase) purchases = AdminSearchService.new.search_purchases(license_key: "nonexistent-key") expect(purchases.size).to eq(0) end describe "searching by card" do let(:purchase_visa) do create(:purchase, card_type: "visa", card_visual: "**** **** **** 1234", created_at: Time.zone.local(2019, 1, 17, 1, 2, 3), price_cents: 777, card_expiry_year: 2022, card_expiry_month: 10) end let(:purchase_amex) do create(:purchase, card_type: "amex", card_visual: "**** ****** *7531", created_at: Time.zone.local(2019, 2, 22, 1, 2, 3), price_cents: 1337, card_expiry_year: 2021, card_expiry_month: 7) end context "when transaction_date value is not a date" do it "raises an error" do expect do AdminSearchService.new.search_purchases(transaction_date: "2021-01", card_type: "other") end.to raise_error(AdminSearchService::InvalidDateError) end end it "supports filtering by card_type" do purchases = AdminSearchService.new.search_purchases(card_type: "visa") expect(purchases).to eq [purchase_visa] end it "supports filtering by card_visual" do purchases = AdminSearchService.new.search_purchases(last_4: "7531") expect(purchases).to eq [purchase_amex] end it "supports filtering by expiry date" do purchases = AdminSearchService.new.search_purchases(expiry_date: "7/21") expect(purchases).to eq [purchase_amex] end it "supports filtering by price" do purchases = AdminSearchService.new.search_purchases(price: "7") expect(purchases).to eq [purchase_visa] end it "supports filtering by decimal price" do purchase_decimal = create(:purchase, price_cents: 1999, stripe_fingerprint: "test_fingerprint") purchases = AdminSearchService.new.search_purchases(price: "19.99") expect(purchases).to eq [purchase_decimal] end it "supports filtering by combination of params" do purchases = AdminSearchService.new.search_purchases(card_type: "visa", last_4: "1234", price: "7", transaction_date: "2019-01-17", expiry_date: "10/22") expect(purchases).to eq [purchase_visa] end end describe "searching by ip_address" do let(:ip_v4) { "203.0.113.42" } let(:ip_v6) { "2001:db8::1" } let(:other_ip) { "198.51.100.10" } it "returns purchases matching ip_address" do purchase_from_ip_v4 = create(:purchase, ip_address: ip_v4) purchase_from_ip_v6 = create(:purchase, ip_address: ip_v6) purchases = AdminSearchService.new.search_purchases(query: ip_v4) expect(purchases).to contain_exactly(purchase_from_ip_v4) purchases = AdminSearchService.new.search_purchases(query: ip_v6) expect(purchases).to contain_exactly(purchase_from_ip_v6) purchases = AdminSearchService.new.search_purchases(query: other_ip) expect(purchases).to be_empty end end describe "product_title_query" do let(:product_title_query) { "design" } let!(:product) { create(:product, name: "Graphic Design Course") } let!(:purchase) { create(:purchase, link: product, email: "user@example.com") } let(:query) { "user@example.com" } before do create(:purchase, link: create(:product, name: "Different Product")) end context "when query is set" do it "filters by product title" do purchases = AdminSearchService.new.search_purchases(query:, product_title_query:) expect(purchases).to eq [purchase] end end context "when query is not set" do let(:query) { nil } it "ignores product_title_query" do purchases = AdminSearchService.new.search_purchases(query:, product_title_query:) expect(purchases).to include(purchase) end end end describe "purchase_status" do let!(:successful_purchase) { create(:purchase, purchase_state: "successful", email: "successful@example.com") } let!(:failed_purchase) { create(:purchase, purchase_state: "failed", email: "failed@example.com") } let!(:not_charged_purchase) { create(:purchase, purchase_state: "not_charged", email: "not_charged@example.com") } let!(:chargebacked_purchase) { create(:purchase, chargeback_date: Date.yesterday, email: "chargeback@example.com") } let!(:chargebacked_reversed_purchase) { create(:purchase, chargeback_date: Date.yesterday, chargeback_reversed: true, email: "chargeback_reversed@example.com") } let!(:refunded_purchase) { create(:purchase, stripe_refunded: true, email: "refunded@example.com") } before do create(:purchase, purchase_state: "successful", email: "other@example.com") create(:purchase, purchase_state: "failed", email: "other@example.com") end context "when query is set" do it "filters by successful status" do purchases = AdminSearchService.new.search_purchases(query: successful_purchase.email, purchase_status: "successful") expect(purchases).to contain_exactly(successful_purchase) end it "filters by failed status" do purchases = AdminSearchService.new.search_purchases(query: failed_purchase.email, purchase_status: "failed") expect(purchases).to contain_exactly(failed_purchase) end it "filters by not_charged status" do purchases = AdminSearchService.new.search_purchases(query: not_charged_purchase.email, purchase_status: "not_charged") expect(purchases).to contain_exactly(not_charged_purchase) end it "filters by chargeback status (excluding reversed)" do purchases = AdminSearchService.new.search_purchases(query: chargebacked_purchase.email, purchase_status: "chargeback") expect(purchases).to contain_exactly(chargebacked_purchase) expect(purchases).not_to include(chargebacked_reversed_purchase) end it "filters by refunded status" do purchases = AdminSearchService.new.search_purchases(query: refunded_purchase.email, purchase_status: "refunded") expect(purchases).to contain_exactly(refunded_purchase) end it "ignores invalid purchase_status values" do purchases = AdminSearchService.new.search_purchases(query: successful_purchase.email, purchase_status: "invalid_status") expect(purchases).to contain_exactly(successful_purchase) end it "works with other parameters" do purchases = AdminSearchService.new.search_purchases(query: successful_purchase.email, purchase_status: "successful") expect(purchases).to contain_exactly(successful_purchase) end end context "when query is not set" do let(:query) { nil } it "ignores purchase_status" do purchases = AdminSearchService.new.search_purchases(query:, purchase_status: "successful") expect(purchases).to include(successful_purchase, failed_purchase, not_charged_purchase, chargebacked_purchase, chargebacked_reversed_purchase, refunded_purchase) 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/helper_user_info_service_spec.rb
spec/services/helper_user_info_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe HelperUserInfoService do include Rails.application.routes.url_helpers let(:user) { create(:user, email: "user@example.com") } describe "#customer_info" do let(:service) { described_class.new(email: user.email) } it "retrieves user info" do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(2250) result = service.customer_info expect(result[:name]).to eq(user.name) expect(result[:value]).to eq(2250) expect(result[:actions]).to eq({ "Admin (user)" => "http://app.test.gumroad.com:31337/admin/users/#{user.id}", "Admin (purchases)" => "http://app.test.gumroad.com:31337/admin/search/purchases?query=#{CGI.escape(user.email)}", "Impersonate" => "http://app.test.gumroad.com:31337/admin/helper_actions/impersonate/#{user.external_id}" }) expect(result[:metadata]).to include( "User ID" => user.id, "Account Created" => user.created_at.to_fs(:formatted_date_full_month), "Account Status" => "Active", "Total Earnings Since Joining" => "$22.50" ) end context "value calculation" do let(:product) { create(:product, user:, price_cents: 100_00) } it "returns the higher value between lifetime sales and last-90-day purchases" do # Bought $10.00 of products in the last 90 days. create(:purchase, purchaser: user, price_cents: 10_00, created_at: 95.days.ago) create(:purchase, purchaser: user, price_cents: 10_00, created_at: 1.day.ago) index_model_records(Purchase) expect(service.customer_info[:value]).to eq(10_00) # Sold $100.00 of products, before fees. sale = create(:purchase, link: product, price_cents: 100_00, created_at: 30.days.ago) index_model_records(Purchase) expect(service.customer_info[:value]).to eq(sale.payment_cents) end end context "when user is not found" do let(:service) { described_class.new(email: "inexistent@example.com") } it "returns empty user details and metadata" do result = service.customer_info expect(result[:name]).to be_nil expect(result[:value]).to be_nil expect(result[:actions]).to be_nil expect(result[:metadata]).to eq({}) end end context "with recent purchase" do let(:service) { HelperUserInfoService.new(email: user.email) } it "includes recent purchase info" do product = create(:product) purchase = create(:purchase, purchaser: user, link: product, price_cents: 1_00, created_at: 1.day.ago) result = service.customer_info purchase_info = result[:metadata]["Most Recent Purchase"] expect(purchase_info).to include( "Status" => "Successful", "Product" => product.name, "Price" => purchase.formatted_display_price, "Date" => purchase.created_at.to_fs(:formatted_date_full_month), "Product URL" => product.long_url, "Creator Support Email" => purchase.seller.support_email || purchase.seller.form_email, "Creator Email" => purchase.seller_email, "Receipt URL" => receipt_purchase_url(purchase.external_id, host: DOMAIN, email: purchase.email), "License Key" => purchase.license_key ) end end context "when user has a Stripe Connect account" do it "includes the stripe_connect_account_id in actions" do merchant_account = create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) user_with_stripe = merchant_account.user service = described_class.new(email: user_with_stripe.email) result = service.customer_info expect(result[:actions]["View Stripe account"]).to eq("http://app.test.gumroad.com:31337/admin/helper_actions/stripe_dashboard/#{user_with_stripe.external_id}") end end context "when there's a failed purchase" do it "includes failed purchase info" do product = create(:product) failed_purchase = create(:purchase, purchase_state: "failed", purchaser: user, link: product, price_cents: 1_00, created_at: 1.day.ago) result = described_class.new(email: user.email).customer_info purchase_info = result[:metadata]["Most Recent Purchase"] expect(purchase_info).to include( "Status" => "Failed", "Error" => failed_purchase.formatted_error_code, "Product" => product.name, "Price" => failed_purchase.formatted_display_price, "Date" => failed_purchase.created_at.to_fs(:formatted_date_full_month) ) end end context "when purchase has a refund policy" do it "includes refund policy info" do product = create(:product) purchase = create(:purchase, purchaser: user, link: product, created_at: 1.day.ago) 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 of the refund policy." ) result = described_class.new(email: user.email).customer_info purchase_info = result[:metadata]["Most Recent Purchase"] expect(purchase_info["Refund Policy"]).to eq("This is the fine print of the refund policy.") end end context "when purchase has a license key" do it "includes license key info" do product = create(:product, is_licensed: true) purchase = create(:purchase, purchaser: user, link: product, created_at: 1.day.ago) license = create(:license, purchase: purchase) result = described_class.new(email: user.email).customer_info purchase_info = result[:metadata]["Most Recent Purchase"] expect(purchase_info["License Key"]).to eq(license.serial) end end context "when user has country" do it "includes country in the metadata" do user.update!(country: "United States") result = described_class.new(email: user.email).customer_info expect(result[:metadata]["Country"]).to eq("United States") end end context "when user has no country" do it "does not include country in the metadata" do user.update!(country: nil) result = described_class.new(email: user.email).customer_info expect(result[:metadata]).not_to have_key("Country") end end context "seller comments" do let(:service) { described_class.new(email: user.email) } context "when user has payout notes" do it "includes payout notes from admin" do create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_PAYOUT_NOTE, author_id: GUMROAD_ADMIN_ID, content: "Payout delayed due to verification" ) result = service.customer_info expect(result[:metadata]["Comments"]).to include("Payout Note: Payout delayed due to verification") end it "excludes payout notes not from admin" do other_user = create(:user) create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_PAYOUT_NOTE, author_id: other_user.id, content: "Non-admin payout note" ) result = service.customer_info comments = result[:metadata]["Comments"] || [] expect(comments).not_to include("Payout Note: Non-admin payout note") end end context "when user has risk notes" do it "includes all risk state comment types" do Comment::RISK_STATE_COMMENT_TYPES.each_with_index do |comment_type, index| create(:comment, commentable: user, comment_type: comment_type, content: "Risk note #{index + 1}", created_at: index.minutes.ago ) end result = service.customer_info comments = result[:metadata]["Comments"] || [] Comment::RISK_STATE_COMMENT_TYPES.each_with_index do |_, index| expect(comments).to include("Risk Note: Risk note #{index + 1}") end end it "orders risk notes by creation time" do create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_FLAGGED, content: "Older risk note", created_at: 2.hours.ago ) create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_COUNTRY_CHANGED, content: "Newer risk note", created_at: 1.hour.ago ) result = service.customer_info comments = result[:metadata]["Comments"] || [] older_index = comments.find_index { |comment| comment.include?("Older risk note") } newer_index = comments.find_index { |comment| comment.include?("Newer risk note") } expect(older_index).to be < newer_index end end context "when user has suspension notes" do context "when user is suspended" do let(:user) { create(:tos_user) } it "includes suspension notes" do create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_SUSPENSION_NOTE, content: "Account suspended for policy violation" ) result = service.customer_info expect(result[:metadata]["Comments"]).to include("Suspension Note: Account suspended for policy violation") end end context "when user is not suspended" do before { allow(user).to receive(:suspended?).and_return(false) } it "excludes suspension notes" do create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_SUSPENSION_NOTE, content: "Account suspended for policy violation" ) result = service.customer_info comments = result[:metadata]["Comments"] || [] expect(comments).not_to include("Suspension Note: Account suspended for policy violation") end end end context "when user has other comment types" do it "includes general comments" do create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_COUNTRY_CHANGED, content: "General user comment" ) result = service.customer_info expect(result[:metadata]["Comments"]).to include("Comment: General user comment") end it "includes custom comment types" do create(:comment, commentable: user, comment_type: "custom_type", content: "Custom comment type" ) result = service.customer_info expect(result[:metadata]["Comments"]).to include("Comment: Custom comment type") end end context "when user has multiple comment types" do it "includes all comments in chronological order" do create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_PAYOUT_NOTE, author_id: GUMROAD_ADMIN_ID, content: "Payout note", created_at: 3.hours.ago ) create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_FLAGGED, content: "Risk note", created_at: 2.hours.ago ) create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_COUNTRY_CHANGED, content: "General note", created_at: 1.hour.ago ) result = service.customer_info comments = result[:metadata]["Comments"] || [] expect(comments).to include("Payout Note: Payout note") expect(comments).to include("Risk Note: Risk note") expect(comments).to include("Comment: General note") payout_index = comments.find_index { |comment| comment.include?("Payout Note: Payout note") } risk_index = comments.find_index { |comment| comment.include?("Risk Note: Risk note") } general_index = comments.find_index { |comment| comment.include?("Comment: General note") } expect(payout_index).to be < risk_index expect(risk_index).to be < general_index end end context "when user has no comments" do it "does not include any comment information" do result = service.customer_info expect(result[:metadata]).not_to have_key("Comments") 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/vat_validation_service_spec.rb
spec/services/vat_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe VatValidationService, :vcr do describe "#process" do it "returns false when provided vat is nil" do expect(described_class.new(nil).process).to be(false) end it "returns false when invalid vat is provided" do expect(described_class.new("xxx").process).to be(false) end it "returns true when valid vat is provided" do expect(described_class.new("IE6388047V").process).to be(true) end it "works well with GB numbers" do expect(described_class.new("GB902194939").process).to be(true) end it "falls back to local vat validation when VIES hits timeout/rate limits" do expect_any_instance_of(Valvat).to receive(:exists?).and_raise(Valvat::RateLimitError) expect_any_instance_of(Valvat).to receive(:valid?) described_class.new("IE6388047V").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/discord_api_spec.rb
spec/services/discord_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe DiscordApi do describe "POST oauth_token" do it "makes an oauth authorization request with the given code and redirect uri" do WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL). with( body: { grant_type: "authorization_code", code: "test_code", client_id: DISCORD_CLIENT_ID, client_secret: DISCORD_CLIENT_SECRET, redirect_uri: "test_uri" }, headers: { "Content-Type" => "application/x-www-form-urlencoded" }) discord_api = DiscordApi.new response = discord_api.oauth_token("test_code", "test_uri") expect(response.success?).to eq(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/tra_tin_validation_service_spec.rb
spec/services/tra_tin_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe TraTinValidationService do it "returns true when valid Tanzania TIN is provided" do tin = "12-345678-A" expect(described_class.new(tin).process).to be(true) end it "returns false when nil TIN is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when blank TIN is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when TIN with invalid format is provided" do expect(described_class.new("123-45678-B").process).to be(false) # Wrong first segment length expect(described_class.new("12-34567-A").process).to be(false) # Wrong middle segment length expect(described_class.new("12-345678-1").process).to be(false) # Number instead of letter expect(described_class.new("12345678A").process).to be(false) # Missing hyphens expect(described_class.new("ab-345678-A").process).to be(false) # Letters instead of numbers end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/home_page_link_service_spec.rb
spec/services/home_page_link_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe HomePageLinkService do shared_examples_for "home page link" do |page| describe ".#{page}" do it "returns the full URL of the page" do expect(described_class.public_send(page)).to eq "#{UrlService.root_domain_with_protocol}/#{page}" end end end [:privacy, :terms, :about, :features, :university, :pricing, :affiliates, :prohibited].each do |page| include_examples "home page link", page end describe ".root" do it "returns root domain with protocol" do expect(described_class.root).to eq UrlService.root_domain_with_protocol end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/url_service_spec.rb
spec/services/url_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe UrlService do describe "#domain_with_protocol" do it "returns domain with protocol" do expect(UrlService.domain_with_protocol).to eq "#{PROTOCOL}://#{DOMAIN}" end end describe "#api_domain_with_protocol" do it "returns domain with protocol" do expect(UrlService.api_domain_with_protocol).to eq "#{PROTOCOL}://#{API_DOMAIN}" end end describe "#short_domain_with_protocol" do it "returns short domain with protocol" do expect(UrlService.short_domain_with_protocol).to eq "#{PROTOCOL}://#{SHORT_DOMAIN}" end end describe "#root_domain_with_protocol" do it "returns root_domain with protocol" do expect(UrlService.root_domain_with_protocol).to eq "#{PROTOCOL}://#{ROOT_DOMAIN}" end end describe "#discover_domain_with_protocol" do it "returns path with procotol and domain" do expect(UrlService.discover_domain_with_protocol).to eq "#{PROTOCOL}://#{DISCOVER_DOMAIN}" end end describe "#discover_full_path" do it "returns path with procotol and domain" do expect(UrlService.discover_full_path("/3d")).to eq "#{PROTOCOL}://#{DISCOVER_DOMAIN}/3d" end it "returns path and query with procotol and domain" do expect(UrlService.discover_full_path("/3d", { tags: "tag-1" })).to eq "#{PROTOCOL}://#{DISCOVER_DOMAIN}/3d?tags=tag-1" end end describe "widget_product_link_base_url" do context "when user is not specified" do it "returns url with root domain" do expect(described_class.widget_product_link_base_url).to eq(UrlService.root_domain_with_protocol) end end context "when specified user does not have a username or a custom domain" do let(:user) { create(:user) } it "returns url with root domain" do expect(described_class.widget_product_link_base_url).to eq(UrlService.root_domain_with_protocol) end end context "when specified user does not have a custom domain" do let(:user) { create(:user) } it "returns user's subdomain URL" do expect(described_class.widget_product_link_base_url(seller: user)).to eq(user.subdomain_with_protocol) end end context "when specified user does not have an active custom domain" do let(:user) { create(:user) } let!(:custom_domain) { create(:custom_domain, user:) } it "returns user's subdomain URL" do expect(described_class.widget_product_link_base_url(seller: user)).to eq(user.subdomain_with_protocol) end end context "when specified user has an active custom domain" do let(:user) { create(:user) } let!(:custom_domain) { create(:custom_domain, domain: "www.example.com", user:, state: "verified") } before do custom_domain.set_ssl_certificate_issued_at! end context "when configured custom domain is www-prefixed but the domain pointed to our servers is not www-prefixed" do before do allow(CustomDomainVerificationService) .to receive(:new) .with(domain: custom_domain.domain) .and_return(double(domains_pointed_to_gumroad: ["example.com"])) end it "returns user's subdomain URL" do expect(described_class.widget_product_link_base_url(seller: user)).to eq(user.subdomain_with_protocol) end end context "when configured custom domain matches with the domain pointed to our servers" do before do allow(CustomDomainVerificationService) .to receive(:new) .with(domain: custom_domain.domain) .and_return(double(domains_pointed_to_gumroad: [custom_domain.domain])) end it "returns custom domain with protocol" do expect(described_class.widget_product_link_base_url(seller: user)).to eq("#{PROTOCOL}://#{custom_domain.domain}") end end end end describe "widget_script_base_url" do context "when user is not specified" do it "returns url with root domain" do expect(described_class.widget_script_base_url).to eq(UrlService.root_domain_with_protocol) end end context "when specified user does not have a custom domain" do let(:user) { create(:user) } it "returns url with root domain" do expect(described_class.widget_script_base_url(seller: user)).to eq(UrlService.root_domain_with_protocol) end end context "when specified user does not have an active custom domain" do let(:user) { create(:user) } let!(:custom_domain) { create(:custom_domain, user:) } it "returns url with root domain" do expect(described_class.widget_script_base_url(seller: user)).to eq(UrlService.root_domain_with_protocol) end end context "when specified user has an active custom domain" do let(:user) { create(:user) } let!(:custom_domain) { create(:custom_domain, domain: "www.example.com", user:, state: "verified") } before do custom_domain.set_ssl_certificate_issued_at! end context "when configured custom domain is www-prefixed but the domain pointed to our servers is not www-prefixed" do before do allow(CustomDomainVerificationService) .to receive(:new) .with(domain: custom_domain.domain) .and_return(double(domains_pointed_to_gumroad: ["example.com"])) end it "returns url with root domain" do expect(described_class.widget_script_base_url(seller: user)).to eq(UrlService.root_domain_with_protocol) end end context "when configured custom domain matches with the domain pointed to our servers" do before do allow(CustomDomainVerificationService) .to receive(:new) .with(domain: custom_domain.domain) .and_return(double(domains_pointed_to_gumroad: [custom_domain.domain])) end it "returns custom domain with protocol" do expect(described_class.widget_script_base_url(seller: user)).to eq("#{PROTOCOL}://#{custom_domain.domain}") 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/offer_code_discount_computing_service_spec.rb
spec/services/offer_code_discount_computing_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe OfferCodeDiscountComputingService do let(:seller) { create(:user) } let(:product) { create(:product, user: seller, price_cents: 2000, price_currency_type: "usd") } let(:product2) { create(:product, user: seller, price_cents: 2000, price_currency_type: "usd") } let(:universal_offer_code) { create(:universal_offer_code, user: seller, amount_percentage: 100, amount_cents: nil, currency_type: product.price_currency_type) } let(:offer_code) { create(:offer_code, user: seller, products: [product], amount_percentage: 100, amount_cents: nil, currency_type: product.price_currency_type) } let(:zero_percent_discount_code) { create(:offer_code, user: seller, products: [product], amount_percentage: 0, amount_cents: nil, currency_type: product.price_currency_type) } let(:zero_cents_discount_code) { create(:offer_code, user: seller, products: [product], amount_percentage: nil, amount_cents: 0, currency_type: product.price_currency_type) } let(:products_data) do { product.unique_permalink => { quantity: "3", permalink: product.unique_permalink }, product2.unique_permalink => { quantity: "2", permalink: product2.unique_permalink } } end it "returns invalid error_code in result when offer code is invalid" do result = OfferCodeDiscountComputingService.new("invalid_offer_code", products_data).process expect(result[:error_code]).to eq(:invalid_offer) end it "does not return an invalid error_code in result when offer code amount is 0 cents" do result = OfferCodeDiscountComputingService.new(zero_cents_discount_code.code, products_data).process expect(result[:error_code]).to be_nil end it "does not return an invalid error_code in result when offer code amount is 0%" do result = OfferCodeDiscountComputingService.new(zero_percent_discount_code.code, products_data).process expect(result[:error_code]).to be_nil end it "returns sold_out error_code in result when offer code is sold out" do universal_offer_code.update_attribute(:max_purchase_count, 0) result = OfferCodeDiscountComputingService.new(universal_offer_code.code, products_data).process expect(result[:error_code]).to eq(:sold_out) end it "applies offer code on multiple products when offer code is universal" do result = OfferCodeDiscountComputingService.new(universal_offer_code.code, products_data).process expect(result[:products_data]).to eq( product.unique_permalink => { discount: { type: "percent", percents: universal_offer_code.amount, product_ids: nil, expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, }, product2.unique_permalink => { discount: { type: "percent", percents: universal_offer_code.amount, product_ids: nil, expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, }, ) expect(result[:error_code]).to eq(nil) end it "rejects product with quantity greater than the offer code limit when offer code is universal" do universal_offer_code.update_attribute(:max_purchase_count, 2) result = OfferCodeDiscountComputingService.new(universal_offer_code.code, products_data).process expect(result[:products_data]).to eq( product2.unique_permalink => { discount: { type: "percent", percents: universal_offer_code.amount, product_ids: nil, expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, }, ) end it "applies offer code on single product in bundle when offer code is not universal" do result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:products_data]).to eq( product.unique_permalink => { discount: { type: "percent", percents: offer_code.amount, product_ids: [product.external_id], expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, }, ) expect(result[:error_code]).to eq(nil) end it "includes the expiration date in the result" do offer_code.update!(valid_at: 1.day.ago, expires_at: 1.day.from_now) result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:products_data]).to eq( product.unique_permalink => { discount: { type: "percent", percents: offer_code.amount, product_ids: [product.external_id], expires_at: offer_code.expires_at, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, }, ) expect(result[:error_code]).to eq(nil) end it "includes the minimum quantity in the result" do offer_code.update!(minimum_quantity: 2) result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:products_data]).to eq( product.unique_permalink => { discount: { type: "percent", percents: offer_code.amount, product_ids: [product.external_id], expires_at: offer_code.expires_at, minimum_quantity: 2, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, }, ) expect(result[:error_code]).to eq(nil) end it "includes the duration in the result" do offer_code.update!(duration_in_billing_cycles: 1) result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:products_data]).to eq( product.unique_permalink => { discount: { type: "percent", percents: offer_code.amount, product_ids: [product.external_id], expires_at: offer_code.expires_at, minimum_quantity: nil, duration_in_billing_cycles: 1, minimum_amount_cents: nil, }, }, ) expect(result[:error_code]).to eq(nil) end it "rejects product with quantity greater than the offer code limit when offer code is not universal" do offer_code.update_attribute(:max_purchase_count, 2) result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:products_data]).to eq({}) expect(result[:error_code]).to eq(:insufficient_times_of_use) end context "when offer code is not yet valid" do before do offer_code.update!(valid_at: 1.years.from_now) end it "returns inactive error code" do result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:error_code]).to eq(:inactive) expect(result[:products_data]).to eq({}) end end context "when the user has multiple offer codes with the same name" do let(:shared_code_name) { "MULTIPRODUCT" } let!(:offer_code_for_product1) do create( :offer_code, user: seller, code: shared_code_name, products: [product], amount_percentage: 30, amount_cents: nil, currency_type: product.price_currency_type ) end let!(:offer_code_for_product2) do create( :offer_code, user: seller, code: shared_code_name, products: [product2], amount_percentage: 50, amount_cents: nil, currency_type: product2.price_currency_type ) end it "applies the correct offer code to each product based on product applicability" do result = OfferCodeDiscountComputingService.new(shared_code_name, products_data).process expect(result[:products_data]).to eq( product.unique_permalink => { discount: { product_ids: [product.external_id], **offer_code_for_product1.discount, }, }, product2.unique_permalink => { discount: { product_ids: [product2.external_id], **offer_code_for_product2.discount, }, }, ) expect(result[:error_code]).to be_nil end end context "when the code exists but doesn't apply to this product" do let!(:offer_code_for_product2) do create( :offer_code, user: seller, code: "PRODUCT2", products: [product2], amount_percentage: 30, amount_cents: nil, currency_type: product.price_currency_type ) end it "returns no discount" do result = OfferCodeDiscountComputingService .new(offer_code_for_product2.code, { product.unique_permalink => { quantity: "3", permalink: product.unique_permalink }, }) .process expect(result).to eq(error_code: :invalid_offer, products_data: {}) end end context "when offer code is expired" do before do offer_code.update!(valid_at: 2.years.ago, expires_at: 1.year.ago) end it "returns inactive error code" do result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:error_code]).to eq(:inactive) expect(result[:products_data]).to eq({}) end end context "when an offer code's minimum quantity is unmet" do before do offer_code.update!(minimum_quantity: 5) end it "returns insufficient quantity error code" do result = OfferCodeDiscountComputingService.new(offer_code.code, products_data).process expect(result[:error_code]).to eq(:unmet_minimum_purchase_quantity) expect(result[:products_data]).to eq({}) end end context "when product has cross-sells" do let(:cross_sell_product1) { create(:product, user: seller, price_cents: 3000) } let(:cross_sell_product2) { create(:product, user: seller, price_cents: 4000) } let(:additive_cross_sell_product) { create(:product, user: seller, price_cents: 5000) } let!(:replacement_cross_sell1) do create(:upsell, seller: seller, product: cross_sell_product1, cross_sell: true, replace_selected_products: true, selected_products: [product] ) end let!(:replacement_cross_sell2) do create(:upsell, seller: seller, product: cross_sell_product2, cross_sell: true, replace_selected_products: true, selected_products: [product] ) end let!(:additive_cross_sell) do create(:upsell, seller: seller, product: additive_cross_sell_product, cross_sell: true, replace_selected_products: false, selected_products: [product] ) end context "universal offer code" do let(:universal_offer_code_for_cross_sells) { create(:universal_offer_code, user: seller, amount_percentage: 50, amount_cents: nil, currency_type: "usd") } it "applies discount to main product and all applicable cross-sells" do result = OfferCodeDiscountComputingService.new(universal_offer_code_for_cross_sells.code, products_data).process expect(result[:products_data]).to include( product.unique_permalink => { discount: hash_including( type: "percent", percents: 50 ) }, cross_sell_product1.unique_permalink => { discount: hash_including( type: "percent", percents: 50 ) }, cross_sell_product2.unique_permalink => { discount: hash_including( type: "percent", percents: 50 ) } ) expect(result[:products_data]).to include( additive_cross_sell.product.unique_permalink => { discount: hash_including( type: "percent", percents: 50 ) } ) expect(result[:error_code]).to be_nil end end context "product-specific offer code" do let(:shared_code_name) { "SHAREDCODE" } let!(:offer_for_product) do create( :offer_code, user: seller, code: shared_code_name, products: [product], amount_percentage: 25, amount_cents: nil, currency_type: "usd" ) end let!(:offer_for_cross_sell1) do create( :offer_code, user: seller, code: shared_code_name, products: [cross_sell_product1], amount_percentage: 50, amount_cents: nil, currency_type: "usd" ) end it "applies corresponding offer code to applicable products including cross-sells" do result = OfferCodeDiscountComputingService.new(shared_code_name, products_data).process expect(result[:products_data]).to include( product.unique_permalink => { discount: hash_including( type: "percent", percents: 25 ) }, cross_sell_product1.unique_permalink => { discount: hash_including( type: "percent", percents: 50 ) } ) expect(result[:products_data]).not_to include(cross_sell_product2.unique_permalink) expect(result[:products_data]).not_to include(additive_cross_sell_product.unique_permalink) expect(result[:error_code]).to be_nil end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/purchasing_power_parity_service_spec.rb
spec/services/purchasing_power_parity_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe PurchasingPowerParityService do before do @namespace = Redis::Namespace.new(:ppp, redis: $redis) @service = described_class.new @seller = create(:user) end describe "#get_factor" do before do @namespace.set("FAKE", "0.9876543210") end context "when the country code is `nil`" do it "produces no errors" do expect(@service.get_factor(nil, @seller)).to eq(1) end end context "when the seller has no ppp limit" do it "returns the set factor" do expect(@service.get_factor("FAKE", @seller)).to eq(0.9876543210) end end context "when the seller's minimum ppp factor is lower than the set factor" do before do allow(@seller).to receive(:min_ppp_factor).and_return(0.6) end it "returns the set factor" do expect(@service.get_factor("FAKE", @seller)).to eq(0.9876543210) end end context "when the seller's minimum ppp factor is higher than the corresponding factor" do before do allow(@seller).to receive(:min_ppp_factor).and_return(0.99) end it "returns the seller's minimum ppp factor" do expect(@service.get_factor("FAKE", @seller)).to eq(0.99) end end end describe "#set_factor" do it "sets the factor" do expect { @service.set_factor("FAKE", 0.0123456789) } .to change { @service.get_factor("FAKE", @seller) } .from(1).to(0.0123456789) .and change { @namespace.get("FAKE") } .from(nil).to("0.0123456789") end end describe "#get_all_countries_factors" do before do @seller.update!(purchasing_power_parity_limit: 60) end it "returns a hash of factors for all countries" do @namespace.set("FR", "0.123") @namespace.set("IT", "0.456") @namespace.set("GB", "0.6") result = @service.get_all_countries_factors(@seller) expect(result.keys).to eq(Compliance::Countries.mapping.keys) expect(result.values.all? { |value| value.is_a?(Float) }).to eq(true) expect(result["FR"]).to eq(0.4) expect(result["IT"]).to eq(0.456) expect(result["GB"]).to eq(0.6) expect(result["PL"]).to eq(1.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/pdf_stamping_service_spec.rb
spec/services/pdf_stamping_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe PdfStampingService do describe ".can_stamp_file?" do let(:product_file) { instance_double("ProductFile") } before do allow(PdfStampingService::Stamp).to receive(:can_stamp_file?).and_return(true) end it "calls can_stamp_file? on PdfStampingService::Stamp with the product file" do described_class.can_stamp_file?(product_file: product_file) expect(PdfStampingService::Stamp).to have_received(:can_stamp_file?).with(product_file: product_file) end it "returns the result from PdfStampingService::Stamp.can_stamp_file?" do result = described_class.can_stamp_file?(product_file: product_file) expect(result).to be true end end describe ".stamp_for_purchase!" do let(:purchase) { instance_double("Purchase") } before do allow(PdfStampingService::StampForPurchase).to receive(:perform!).and_return(true) end it "calls perform! on PdfStampingService::StampForPurchase with the purchase" do described_class.stamp_for_purchase!(purchase) expect(PdfStampingService::StampForPurchase).to have_received(:perform!).with(purchase) end it "returns the result from PdfStampingService::StampForPurchase.perform!" do result = described_class.stamp_for_purchase!(purchase) expect(result).to be true end end describe ".cache_key_for_purchase" do it "returns the correct cache key format for a given purchase ID" do purchase_id = 12345 expected_key = "stamp_pdf_for_purchase_job_12345" result = described_class.cache_key_for_purchase(purchase_id) expect(result).to eq(expected_key) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/mailer_attachment_or_link_service_spec.rb
spec/services/mailer_attachment_or_link_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe MailerAttachmentOrLinkService do describe "#perform" do before do @file = fixture_file_upload("test.png") end it "generates URL with given file when size is greater than 10 MB" do allow(@file).to receive(:size).and_return(MailerAttachmentOrLinkService::MAX_FILE_SIZE + 1) result = MailerAttachmentOrLinkService.new(file: @file, extension: "csv").perform expect(result[:file]).to be_nil expect(result[:url]).to match(/#{AWS_S3_ENDPOINT}\/gumroad-specs/o) expect(result[:url]).to match(Regexp.new "#{ExpiringS3FileService::DEFAULT_FILE_EXPIRY.to_i}") end it "returns original file if file size is less than 10 MB" do allow(@file).to receive(:size).and_return(MailerAttachmentOrLinkService::MAX_FILE_SIZE - 1) result = MailerAttachmentOrLinkService.new(file: @file, extension: "csv").perform expect(result[:file]).to eq(@file) expect(result[:url]).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/seller_mobile_analytics_service_spec.rb
spec/services/seller_mobile_analytics_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SellerMobileAnalyticsService do before do @user = create(:user, timezone: "UTC") @product = create(:product, user: @user) end describe "#process" do it "returns the proper purchase data for all time" do valid_purchases = [] travel_to(1.year.ago) do valid_purchases << create(:purchase, link: @product) valid_purchases << create(:purchase, link: @product, is_gift_sender_purchase: true) create(:purchase, link: @product, is_gift_receiver_purchase: true, purchase_state: "gift_receiver_purchase_successful") valid_purchases << create(:purchase, link: @product, chargeback_date: Time.current) valid_purchases << create(:purchase, link: @product, chargeback_date: Time.current, chargeback_reversed: true) refunded_purchase = create(:purchase, link: @product) create(:refund, purchase: create(:purchase, link: @product)) valid_purchases << refunded_purchase end travel_to(2.weeks.ago) do valid_purchases << create(:purchase, link: @product) end valid_purchases << create(:purchase, link: @product) valid_purchases << begin preorder = create(:preorder) purchase = create(:purchase, link: @product, purchase_state: "preorder_concluded_successfully") purchase.update!(preorder:) create(:purchase, link: @product, preorder:) purchase end valid_purchases << begin purchase = create(:purchase, link: @product) purchase.refund_partial_purchase!(1, purchase.seller) purchase.refund_partial_purchase!(2, purchase.seller) purchase end index_model_records(Purchase) result = described_class.new(@user, range: "all").process expected_revenue_in_cents = \ valid_purchases.sum(&:price_cents) - \ valid_purchases.select(&:stripe_partially_refunded?).flat_map(&:refunds).sum(&:amount_cents) - \ valid_purchases.select(&:refunded?).sum(&:price_cents) - \ valid_purchases.select(&:chargedback_not_reversed?).sum(&:price_cents) expect(result[:revenue]).to eq expected_revenue_in_cents expect(result[:formatted_revenue]).to eq Money.new(expected_revenue_in_cents, "USD").format(no_cents_if_whole: true) end it "returns the proper purchase data for the year" do valid_purchases = [] travel_to(Date.today.beginning_of_year - 2.days) do create(:purchase, link: @product) end travel_to(Date.today.beginning_of_year + 2.days) do valid_purchases << create(:purchase, link: @product) end valid_purchases << create(:purchase, link: @product) index_model_records(Purchase) result = described_class.new(@user, range: "year").process expected_revenue_in_cents = valid_purchases.sum(&:price_cents) expect(result[:revenue]).to eq expected_revenue_in_cents expect(result[:formatted_revenue]).to eq Money.new(expected_revenue_in_cents, "USD").format(no_cents_if_whole: true) end it "returns the proper purchase data for current month" do valid_purchases = [] travel_to(1.year.ago) do create(:purchase, link: @product) end travel_to(Date.today.beginning_of_month + 2.days) do valid_purchases << create(:purchase, link: @product) end valid_purchases << create(:purchase, link: @product) index_model_records(Purchase) result = described_class.new(@user, range: "month").process expected_revenue_in_cents = valid_purchases.sum(&:price_cents) expect(result[:revenue]).to eq expected_revenue_in_cents expect(result[:formatted_revenue]).to eq Money.new(expected_revenue_in_cents, "USD").format(no_cents_if_whole: true) end it "returns the proper purchase data for the current week" do valid_purchases = [] travel_to(1.year.ago) do create(:purchase, link: @product) end travel_to(2.weeks.ago) do create(:purchase, link: @product) end travel_to(Date.today.beginning_of_week + 2.days) do valid_purchases << create(:purchase, link: @product) valid_purchases << create(:purchase, link: @product, created_at: 1.day.ago) create(:purchase, link: @product, created_at: 3.days.ago) end index_model_records(Purchase) result = described_class.new(@user, range: "week").process expected_revenue_in_cents = valid_purchases.sum(&:price_cents) expect(result[:revenue]).to eq expected_revenue_in_cents expect(result[:formatted_revenue]).to eq Money.new(expected_revenue_in_cents, "USD").format(no_cents_if_whole: true) end it "returns the proper purchase data for the current day" do valid_purchases = [] travel_to(1.year.ago) do create(:purchase, link: @product) end travel_to(2.weeks.ago) do create(:purchase, link: @product) end valid_purchases << create(:purchase, link: @product) index_model_records(Purchase) result = described_class.new(@user, range: "day").process expected_revenue_in_cents = valid_purchases.sum(&:price_cents) expect(result[:revenue]).to eq expected_revenue_in_cents expect(result[:formatted_revenue]).to eq Money.new(expected_revenue_in_cents, "USD").format(no_cents_if_whole: true) end context "when not requesting optional fields" do it "only returns revenue" do create(:purchase, link: @product) result = described_class.new(@user).process expect(result.keys).to match_array([:revenue, :formatted_revenue]) end end context "when requesting optional fields" do context "when requesting :purchases" do it "returns purchases records as json" do expected_purchases = create_list(:purchase, 2, link: @product) index_model_records(Purchase) result = described_class.new(@user, fields: [:purchases]).process expect(result.keys).to match_array([:revenue, :formatted_revenue, :purchases]) expect(result[:purchases]).to match_array(expected_purchases.as_json(creator_app_api: true)) end it "limits purchases returned to SALES_LIMIT" do stub_const("#{described_class}::SALES_LIMIT", 5) create_list(:purchase, 7, link: @product) index_model_records(Purchase) result = described_class.new(@user, fields: [:purchases]).process expect(result[:purchases].size).to eq 5 end context "with query parameter" do it "passes seller_query to search options when query is provided" do create(:purchase, link: @product, email: "john@example.com", full_name: "John Doe") create(:purchase, link: @product, email: "jane@example.com", full_name: "Jane Smith") index_model_records(Purchase) expect(PurchaseSearchService).to receive(:search).with( hash_including(seller_query: "john") ).and_call_original described_class.new(@user, fields: [:purchases], query: "john").process end it "does not pass seller_query when query is nil" do create(:purchase, link: @product) index_model_records(Purchase) expect(PurchaseSearchService).to receive(:search).with( hash_not_including(:seller_query) ).and_call_original described_class.new(@user, fields: [:purchases], query: nil).process end it "does not pass seller_query when query is empty" do create(:purchase, link: @product) index_model_records(Purchase) expect(PurchaseSearchService).to receive(:search).with( hash_not_including(:seller_query) ).and_call_original described_class.new(@user, fields: [:purchases], query: "").process end it "does not pass seller_query when query is whitespace only" do create(:purchase, link: @product) index_model_records(Purchase) expect(PurchaseSearchService).to receive(:search).with( hash_not_including(:seller_query) ).and_call_original described_class.new(@user, fields: [:purchases], query: " ").process end end end context "when requesting :sales_count" do it "returns the total count of sales" do create_list(:purchase, 2, link: @product) index_model_records(Purchase) result = described_class.new(@user, fields: [:sales_count]).process expect(result.keys).to match_array([:revenue, :formatted_revenue, :sales_count]) expect(result[:sales_count]).to eq(2) end context "with query parameter" do it "does not pass seller_query to search options when only requesting sales_count" do create(:purchase, link: @product) index_model_records(Purchase) expect(PurchaseSearchService).to receive(:search).with( hash_not_including(:seller_query) ).and_call_original described_class.new(@user, fields: [:sales_count], query: "test").process end end end end context "with an invalid range" do it "raises an error" do expect { described_class.new(@user, range: "1d").process }.to raise_error(/Invalid range 1d/) 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/save_content_upsells_service_spec.rb
spec/services/save_content_upsells_service_spec.rb
# frozen_string_literal: true describe SaveContentUpsellsService do let(:seller) { create(:user) } let(:product) { create(:product, user: seller, price_cents: 1000) } let(:variant_category) { create(:variant_category, link: product) } let(:variant) { create(:variant, variant_category:) } describe "#from_html" do let(:service) { described_class.new(seller:, content:, old_content:) } context "when adding a new upsell" do let(:old_content) { "<p>Old content</p>" } let(:content) { %(<p>Content with upsell</p><upsell-card productid="#{product.external_id}" variantid="#{variant.external_id}"></upsell-card>) } it "creates an upsell" do expect { service.from_html }.to change(Upsell, :count).by(1) upsell = Upsell.last expect(upsell.seller).to eq(seller) expect(upsell.product_id).to eq(product.id) expect(upsell.variant_id).to eq(variant.id) expect(upsell.is_content_upsell).to be true expect(upsell.cross_sell).to be true end it "adds id to the upsell card" do result = Nokogiri::HTML.fragment(service.from_html) expect(result.at_css("upsell-card")["id"]).to be_present end context "with discount" do let(:content) do %(<p>Content with upsell</p><upsell-card productid="#{product.external_id}" discount='{"type":"fixed","cents":500}'></upsell-card>) end it "creates an offer code" do expect { service.from_html }.to change(OfferCode, :count).by(1) offer_code = OfferCode.last expect(offer_code.amount_cents).to eq(500) expect(offer_code.amount_percentage).to be_nil expect(offer_code.product_ids).to eq([product.id]) end end end context "when removing an upsell" do let!(:upsell) { create(:upsell, seller:, product:, is_content_upsell: true) } let!(:offer_code) { create(:offer_code, user: seller, product_ids: [product.id]) } let(:old_content) { %(<p>Old content</p><upsell-card id="#{upsell.external_id}"></upsell-card>) } let(:content) { "<p>Content without upsell</p>" } before do upsell.update!(offer_code:) end it "marks upsell and offer code as deleted" do service.from_html expect(upsell.reload.deleted?).to be true expect(offer_code.reload.deleted?).to be true end end end describe "#from_rich_content" do let(:service) { described_class.new(seller:, content:, old_content:) } context "when adding a new upsell" do let(:old_content) { [{ "type" => "paragraph", "content" => "Old content" }] } let(:content) do [ { "type" => "paragraph", "content" => "Content with upsell" }, { "type" => "upsellCard", "attrs" => { "productId" => product.external_id, "variantId" => variant.external_id } } ] end it "creates an upsell" do expect { service.from_rich_content }.to change(Upsell, :count).by(1) upsell = Upsell.last expect(upsell.seller).to eq(seller) expect(upsell.product_id).to eq(product.id) expect(upsell.variant_id).to eq(variant.id) expect(upsell.is_content_upsell).to be true expect(upsell.cross_sell).to be true end it "adds id to the upsell node" do result = service.from_rich_content expect(result.last["attrs"]["id"]).to be_present end context "with discount" do let(:content) do [ { "type" => "paragraph", "content" => "Content with upsell" }, { "type" => "upsellCard", "attrs" => { "productId" => product.external_id, "discount" => { "type" => "percent", "percents" => 20 } } } ] end it "creates an offer code" do service.from_rich_content offer_code = OfferCode.last expect(offer_code.amount_cents).to be_nil expect(offer_code.amount_percentage).to eq(20) expect(offer_code.product_ids).to eq([product.id]) end end end context "when removing an upsell" do let!(:upsell) { create(:upsell, seller:, product:, is_content_upsell: true) } let!(:offer_code) { create(:offer_code, user: seller, product_ids: [product.id]) } let(:old_content) do [ { "type" => "paragraph", "content" => "Old content" }, { "type" => "upsellCard", "attrs" => { "id" => upsell.external_id } } ] end let(:content) { [{ "type" => "paragraph", "content" => "Content without upsell" }] } before do upsell.update!(offer_code:) end it "marks upsell and offer code as deleted" do service.from_rich_content expect(upsell.reload.deleted?).to be true expect(offer_code.reload.deleted?).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/post_sendgrid_api_spec.rb
spec/services/post_sendgrid_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe PostSendgridApi, :freeze_time do include Rails.application.routes.url_helpers before do @seller = create(:named_user) @post = create(:audience_installment, name: "post title", message: "post body", seller: @seller) described_class.mails.clear end def send_emails(**args) = described_class.new(post: @post, **args).send_emails def send_default_email = send_emails(recipients: [{ email: "c1@example.com" }]) def sent_emails = described_class.mails def sent_email = sent_emails["c1@example.com"] def sent_email_content = sent_email[:content] def html_doc(content) = Nokogiri::HTML(content) def body_plaintext(content) = html_doc(content).at_xpath("//body").text.strip describe "Premailer" do before { send_default_email } it "automatically inlines styles" do expect(sent_email_content).to include("<body style=") end end describe "Seller's design settings" do before do @post.seller.seller_profile.update!(highlight_color: "#009a49", font: "Roboto Mono", background_color: "#000000") send_default_email end it "includes them as CSS" do expect(sent_email_content).to include("body {\nbackground-color: #000000; color: #fff; font-family: \"Roboto Mono\", \"ABC Favorit\", monospace;\n}") expect(sent_email_content).to include("body {\nheight: auto; min-height: 100%;\n}") end end describe "preheader text" do before { send_default_email } it "is included at the start of the email" do expect(body_plaintext(sent_email_content)).to start_with("post body") end end describe "call to action button" do before do @post.update!(call_to_action_url: "https://cta.example/", call_to_action_text: "Click here") send_default_email end it "is included when CTA url and CTA text are set" do node = html_doc(sent_email_content).at_xpath(%(//a[@href="https://cta.example/"])) expect(node).to be_present expect(node.text).to eq("Click here") end end describe "'View Content' button" do it "is not included when there are no attachments" do send_default_email expect(sent_email_content).not_to include("View content") end it "is included when there are attachments" do @post.product_files << create(:product_file) url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{url_redirect.download_page_url}"])) expect(node).to be_present expect(node.text).to eq("View content") end end describe "Validations" do it "raises an error when there are too many recipients" do stub_const("#{described_class}::MAX_RECIPIENTS", 2) expect do send_emails(recipients: [{ email: "c1@example.com" }] * 3) end.to raise_error(/too many recipients/i) end it "raises an error when a recipient has no email" do expect do send_emails(recipients: [{ email: "" }]) end.to raise_error(/must have an email/i) end it "raises an error when a post has files but no url_redirect" do @post.product_files << create(:product_file) expect do send_default_email end.to raise_error(/must have a url_redirect/i) end it "raises an error when recipients have inconsistent records" do expect do send_emails(recipients: [{ email: "c1@example.com", purchase: create(:purchase), follower: create(:follower) }]) end.to raise_error(/Recipients can't have .* and\/or .* record/i) expect do send_emails(recipients: [{ email: "c1@example.com", purchase: create(:purchase), affiliate: create(:direct_affiliate) }]) end.to raise_error(/Recipients can't have .* and\/or .* record/i) expect do send_emails(recipients: [{ email: "c1@example.com", follower: create(:follower), affiliate: create(:direct_affiliate) }]) end.to raise_error(/Recipients can't have .* and\/or .* record/i) end end describe "'Reply with a comment' button" do it "is not included when allow_comments=false" do send_default_email expect(sent_email_content).not_to include("Reply with a comment") end it "is not included when allow_comments=true and shown_on_profile=false" do @post.update!(allow_comments: true, shown_on_profile: false) send_default_email expect(sent_email_content).not_to include("Reply with a comment") end it "is included when allow_comments=true and shown_on_profile=true" do @post.update!(allow_comments: true, shown_on_profile: true) send_default_email expected_url = view_post_url( username: @post.user.username, slug: @post.slug, host: UrlService.domain_with_protocol ) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{expected_url}#comments"])) expect(node).to be_present expect(node.text).to eq("Reply with a comment") end end describe "Update reason" do # little text in the footer indicating why the recipient got this email it "is generic when installment_type='seller'" do @post.update!(installment_type: Installment::SELLER_TYPE) send_default_email expect(sent_email_content).to include("You've received this post because you've purchased a product from #{@post.seller.name}.") end context "when installment_type='product' or 'variant'" do before do @product = create(:product, user: @seller) @post.update!(installment_type: Installment::PRODUCT_TYPE, link: @product) end it "mentions when it's due to the subscription being cancelled" do # only workflows @product.update!(is_recurring_billing: true) @post.update!(workflow_trigger: Installment::MEMBER_CANCELLATION_WORKFLOW_TRIGGER) send_default_email expect(sent_email_content).to include("You've received this email because you cancelled your membership to <a href=\"#{@post.link.long_url}\">#{@post.link.name}</a>.") # similar but different link when there's a url_redirect url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) expect(sent_email_content).to include("You've received this email because you cancelled your membership to <a href=\"#{url_redirect.download_page_url}\">#{@post.link.name}</a>.") end it "mentions when it's due to it being an active subscription" do @product.update!(is_recurring_billing: true) send_default_email expect(sent_email_content).to include("You've received this email because you subscribed to <a href=\"#{@post.link.long_url}\">#{@post.link.name}</a>.") # similar but different link when there's a url_redirect url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) expect(sent_email_content).to include("You've received this email because you subscribed to <a href=\"#{url_redirect.download_page_url}\">#{@post.link.name}</a>.") end it "mentions when it's due to it being a purchase" do send_default_email expect(sent_email_content).to include("You've received this email because you've purchased <a href=\"#{@post.link.long_url}\">#{@post.link.name}</a>.") # similar but different link when there's a url_redirect url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) expect(sent_email_content).to include("You've received this email because you've purchased <a href=\"#{url_redirect.download_page_url}\">#{@post.link.name}</a>.") end end end describe "Unsubscribe link" do it "links to purchase unsubscribe page when coming with a purchase" do allow_any_instance_of(Purchase).to receive(:secure_external_id).and_return("sample-secure-id") purchase = create(:purchase, :from_seller, seller: @seller) send_emails(recipients: [{ email: "c1@example.com", purchase: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{unsubscribe_purchase_url(purchase.secure_external_id(scope: "unsubscribe"))}"])) expect(node).to be_present expect(node.text).to eq("Unsubscribe") end it "links to unfollow page when coming with a follower" do follower = create(:follower, user: @seller) send_emails(recipients: [{ email: "c1@example.com", follower: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{cancel_follow_url(follower.external_id)}"])) expect(node).to be_present expect(node.text).to eq("Unsubscribe") end it "links to affiliate unsubscribe page when coming with an affiliate" do affiliate = create(:direct_affiliate, seller: @seller) send_emails(recipients: [{ email: "c1@example.com", affiliate: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{unsubscribe_posts_affiliate_url(affiliate.external_id)}"])) expect(node).to be_present expect(node.text).to eq("Unsubscribe") end end it "sends the correct text / subject / reply-to" do @seller.update!(support_email: "custom@example.com") send_default_email expect(sent_email[:subject]).to include("post title") expect(sent_email[:reply_to]).to include("custom@example.com") expect(sent_email_content).to include("post title") expect(sent_email_content).to include("post body") end it "sets the correct custom_args" do purchase = create(:purchase, :from_seller, seller: @seller) follower = create(:follower, user: @seller) affiliate = create(:direct_affiliate, seller: @seller) send_emails(recipients: [ { email: "c1@example.com", purchase: }, { email: "c2@example.com", follower: }, { email: "c3@example.com", affiliate: }, ]) expect(sent_emails["c1@example.com"][:custom_args]).to eq( "seller_id" => @seller.id.to_s, "purchase_id" => purchase.id.to_s, # the following are required for HandleSendgridEventJob "installment_id" => @post.id.to_s, "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => "[#{purchase.id}, #{@post.id}]", ) expect(sent_emails["c2@example.com"][:custom_args]).to eq( "seller_id" => @seller.id.to_s, "follower_id" => follower.id.to_s, # the following are required for HandleSendgridEventJob "installment_id" => @post.id.to_s, "type" => "CreatorContactingCustomersMailer.follower_installment", "identifier" => "[#{follower.id}, #{@post.id}]", ) expect(sent_emails["c3@example.com"][:custom_args]).to eq( "seller_id" => @seller.id.to_s, "affiliate_id" => affiliate.id.to_s, # the following are required for HandleSendgridEventJob "installment_id" => @post.id.to_s, "type" => "CreatorContactingCustomersMailer.direct_affiliate_installment", "identifier" => "[#{affiliate.id}, #{@post.id}]", ) end it "creates EmailInfo record" do send_emails(recipients: [ { email: "c1@example.com", purchase: create(:purchase) }, { email: "c2@example.com" }, # no purchase for this user, so the email_info record won't be created ]) send_emails(recipients: [{ email: "c1@example.com" }]) expect(EmailInfo.count).to eq(1) expect(EmailInfo.first.attributes).to include( "type" => "CreatorContactingCustomersEmailInfo", "installment_id" => @post.id, "email_name" => "purchase_installment", "state" => "sent", "sent_at" => Time.current, ) end it "records the email events" do expect(EmailEvent).to receive(:log_send_events).with(["c1@example.com"], Time.current).and_call_original send_emails(recipients: [{ email: "c1@example.com" }]) expect(EmailEvent.first!).to have_attributes( "email_digest" => EmailEvent.email_sha_digest("c1@example.com"), "sent_emails_count" => 1, "last_email_sent_at" => Time.current, ) end it "sends push notifications" do purchaser = create(:user, email: "c1@example.com") purchase = create(:purchase, purchaser:) send_emails(recipients: [{ email: "c1@example.com", purchase: }]) expect(PushNotificationWorker.jobs.size).to eq(1) expect(PushNotificationWorker).to have_enqueued_sidekiq_job( purchaser.id, Device::APP_TYPES[:consumer], @post.subject, "By #{@post.seller.name}", { "installment_id" => @post.external_id, "purchase_id" => purchase.external_id }, ).on("low") end it "updates delivery statistics" do blast_1 = create(:post_email_blast, post: @post, delivery_count: 0) send_emails(recipients: [ { email: "c1@example.com" }, { email: "c2@example.com" } ], blast: blast_1) expect(@post.reload.customer_count).to eq(2) expect(blast_1.reload.delivery_count).to eq(2) blast_2 = create(:post_email_blast, post: @post, delivery_count: 0) send_emails(recipients: [ { email: "c3@example.com" } ], blast: blast_2) expect(@post.reload.customer_count).to eq(3) expect(blast_2.reload.delivery_count).to eq(1) end context "when preview email" do before do create(:user, email: "c1@example.com") # test that the push notifications aren't sent send_emails(recipients: [{ email: "c1@example.com" }], preview: true) end it "sends an email" do expect(sent_emails.size).to eq(1) end it "does not record any info" do expect(@post.customer_count).to eq(nil) expect(EmailInfo.count).to eq(0) end it "does not send a push notification" do expect(PushNotificationWorker.jobs.size).to eq(0) end end it "includes a link to Gumroad" do send_default_email node = html_doc(sent_email_content).at_xpath(%(//div[contains(@class, 'footer')]/a[@href="#{root_url}"])) expect(node).to be_present expect(node.text).to include("Powered by") end describe "Cache" do it "prevents the template from being rendered several times for the same post, across multiple calls" do cache = {} expect(ApplicationController.renderer).to receive(:render).twice.and_call_original send_emails(recipients: [ { email: "c1@example.com" }, { email: "c2@example.com" } ], cache:) send_emails(recipients: [ { email: "c3@example.com" }, { email: "c4@example.com" } ], cache:) send_emails( post: create(:post), recipients: [ { email: "c1@example.com" }, { email: "c2@example.com" } ], cache:) 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_duplicator_service_spec.rb
spec/services/product_duplicator_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductDuplicatorService do let(:seller) { create(:user) } let(:s3_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3" } let(:product) do product_params = { user: seller, price_cents: 5000, name: "test product", description: "description for test product", is_recurring_billing: true, subscription_duration: "monthly", is_in_preorder_state: true, custom_permalink: "joker", is_adult: "1" } create(:product, product_params) end let!(:product_refund_policy) { create(:product_refund_policy, product:) } before do product.update!(product_refund_policy_enabled: true) end it "duplicates the product and marks the duplicate product as draft" do file_params = [{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png" }, { external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf" }] product.save_files!(file_params) variant_category = create(:variant_category, title: "sizes", link: product) variant_category2 = create(:variant_category, title: "colors", link: product) variant = create(:variant, variant_category:, name: "small") variant2 = create(:variant, variant_category: variant_category2, name: "red") variant3 = create(:variant, variant_category: variant_category2, name: "blue") sku = create(:sku, link: product, name: "small - red") sku2 = create(:sku, link: product, name: "small - blue") variant.skus << sku << sku2 variant2.skus << sku variant3.skus << sku2 shipping_destination = ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 20, multiple_items_rate_cents: 10) shipping_destination2 = ShippingDestination.new(country_code: Compliance::Countries::DEU.alpha2, one_item_rate_cents: 10, multiple_items_rate_cents: 5) product.shipping_destinations << shipping_destination << shipping_destination2 tags = { one: "digital", two: "comic", three: "joker" } product.save_tags!(tags) offercode = create(:percentage_offer_code, code: "oc1", products: [product], amount_percentage: 50) offercode2 = create(:percentage_offer_code, code: "oc2", products: [product], amount_percentage: 100, amount_cents: nil) offercode3 = create(:offer_code, code: "oc3", products: [product], amount_cents: 200) universal_offer_code = create(:universal_offer_code, code: "uoc1", user: product.user) asset = create(:asset_preview_gif, link: product) asset2 = create(:asset_preview, link: product) preorder_link = create(:preorder_link, link: product, url: s3_url) preorder_link.update_attribute(:release_at, 1.month.from_now.round) tpa_params = [ product: product.unique_permalink, code: "<span>Third party analytics</span>", location: "receipt", ] ThirdPartyAnalytic.save_third_party_analytics(tpa_params, seller) product.save! duplicate_product = ProductDuplicatorService.new(product.id).duplicate do_not_compare = %w[id name unique_permalink custom_permalink draft purchase_disabled_at created_at updated_at] expect(duplicate_product.instance_of?(Link)).to be true expect(duplicate_product.unique_permalink).to_not be(nil) expect(duplicate_product.custom_permalink).to be(nil) expect(duplicate_product.name).to eq "#{product.name} (copy)" expect(duplicate_product.draft).to be(true) expect(duplicate_product.purchase_disabled_at).to_not be(nil) expect(duplicate_product.attributes.except(*do_not_compare)).to eq(product.attributes.except(*do_not_compare)) do_not_compare = %w[id link_id created_at updated_at] expect(duplicate_product.prices.alive.first.attributes.except(*do_not_compare)).to eq(product.prices.alive.first.attributes.except(*do_not_compare)) expect(duplicate_product.product_files.count).to eq(2) expect(duplicate_product.product_files.first.url).to eq(file_params[0][:url]) expect(duplicate_product.product_files.last.url).to eq(file_params[1][:url]) expect(duplicate_product.variant_categories.count).to eq(2) expect(duplicate_product.variant_categories.first.title).to eq(variant_category.title) expect(duplicate_product.variant_categories.last.title).to eq(variant_category2.title) expect(duplicate_product.variant_categories.first.variants.count).to eq(1) expect(duplicate_product.variant_categories.first.variants.first.name).to eq(variant.name) expect(duplicate_product.variant_categories.last.variants.count).to eq(2) expect(duplicate_product.variant_categories.last.variants.first.name).to eq(variant2.name) expect(duplicate_product.variant_categories.last.variants.last.name).to eq(variant3.name) expect(duplicate_product.skus.count).to eq(2) expect(duplicate_product.skus.first.name).to eq(sku.name) expect(duplicate_product.skus.last.name).to eq(sku2.name) expect(duplicate_product.variant_categories.first.variants.first.skus.count).to eq(2) expect(duplicate_product.variant_categories.first.variants.first.skus.first.name).to eq(sku.name) expect(duplicate_product.variant_categories.first.variants.first.skus.last.name).to eq(sku2.name) expect(duplicate_product.variant_categories.last.variants.first.skus.count).to eq(1) expect(duplicate_product.variant_categories.last.variants.first.skus.first.name).to eq(sku.name) expect(duplicate_product.variant_categories.last.variants.last.skus.count).to eq(1) expect(duplicate_product.variant_categories.last.variants.last.skus.first.name).to eq(sku2.name) expect(duplicate_product.shipping_destinations.size).to eq(2) expect(duplicate_product.shipping_destinations.alive.size).to eq(product.shipping_destinations.alive.size) expect(duplicate_product.shipping_destinations.alive.first.country_code).to eq(Product::Shipping::ELSEWHERE) expect(duplicate_product.shipping_destinations.alive.last.country_code).to eq(Compliance::Countries::DEU.alpha2) expect(duplicate_product.product_taggings.size).to eq(tags.size) expect(duplicate_product.tags.size).to eq(tags.size) expect(duplicate_product.tags.first.name).to eq(tags[:one]) expect(duplicate_product.tags.second.name).to eq(tags[:two]) expect(duplicate_product.tags.last.name).to eq(tags[:three]) expect(duplicate_product.offer_codes.size).to eq(3) expect(duplicate_product.product_and_universal_offer_codes.size).to eq(4) all_offer_codes = duplicate_product.product_and_universal_offer_codes expect(all_offer_codes.first.code).to eq(offercode.code) expect(all_offer_codes.first.amount_percentage).to eq(offercode.amount_percentage) expect(all_offer_codes.second.code).to eq(offercode2.code) expect(all_offer_codes.second.amount_percentage).to eq(offercode2.amount_percentage) expect(all_offer_codes.third.code).to eq(offercode3.code) expect(all_offer_codes.third.amount_cents).to eq(offercode3.amount_cents) expect(all_offer_codes.last.code).to eq(universal_offer_code.code) expect(all_offer_codes.last.amount_cents).to eq(universal_offer_code.amount_cents) expect(duplicate_product.asset_previews.count).to eq(2) expect(duplicate_product.asset_previews.first.guid).to eq(asset.guid) expect(duplicate_product.asset_previews.last.guid).to eq(asset2.guid) do_not_compare = %w[id link_id created_at updated_at] expect(duplicate_product.preorder_link.attributes.except(*do_not_compare)).to eq(product.preorder_link.attributes.except(*do_not_compare)) expect(duplicate_product.is_recurring_billing).to be(true) expect(duplicate_product.subscription_duration).to eq("monthly") expect(duplicate_product.third_party_analytics.count).to eq(1) expect(duplicate_product.third_party_analytics.first.analytics_code).to eq("<span>Third party analytics</span>") expect(duplicate_product.is_adult).to be(true) expect(duplicate_product.product_refund_policy_enabled?).to be(true) expect(duplicate_product.product_refund_policy.title).to eq(product.product_refund_policy.title) expect(duplicate_product.product_refund_policy.fine_print).to eq(product.product_refund_policy.fine_print) end it "duplicates the product and marks is_duplicating as false" do product.update!(is_duplicating: true) duplicate_product = ProductDuplicatorService.new(product.id).duplicate expect(duplicate_product.is_duplicating).to be false end it "maintains atomicity and rolls back the transaction if some error occurs in the middle" do duplicate_product = nil allow_any_instance_of(ProductDuplicatorService).to receive(:duplicate_third_party_analytics).and_raise(RuntimeError) expect do duplicate_product = ProductDuplicatorService.new(product.id).duplicate end.to raise_error(RuntimeError) expect(duplicate_product).to be(nil) expect(Link.where(name: "#{product.name} (copy)").count).to eq(0) end it "duplicates released preorder product and sets the new release_at as 1 month from now" do preorder_link = create(:preorder_link, link: product, url: s3_url) preorder_link.update_attribute(:release_at, 1.day.ago.round) duplicate_product = ProductDuplicatorService.new(product.id).duplicate expect(duplicate_product).not_to be(nil) expect(Link.where(name: "#{product.name} (copy)").count).to eq(1) expect(duplicate_product.preorder_link.release_at.to_date).to eq(1.month.from_now.to_date) end it "does not put membership tiers into an invalid state" do product_params = { user: seller, price_cents: 5000, name: "test product", description: "description for test product", is_recurring_billing: true, subscription_duration: "monthly", is_in_preorder_state: true, is_tiered_membership: true } product = create(:product, product_params) product.variant_categories.alive.first.variants.create!(name: "Second") duplicate_product = ProductDuplicatorService.new(product.id).duplicate expect(duplicate_product.is_tiered_membership).to eq true expect(duplicate_product.variant_categories.alive.size).to eq 1 expect(duplicate_product.variant_categories.alive.first.variants.pluck(:name)).to eq ["Untitled", "Second"] end context "duplicating a collab product" do before { create(:collaborator, products: [product]) } it "does not mark a duplicated collab product as a collab" do expect(product.is_collab?).to eq true duplicate_product = ProductDuplicatorService.new(product.id).duplicate expect(duplicate_product.is_collab?).to eq false end end describe "prices" do it "handles products with rental prices" do product.is_recurring_billing = false product.purchase_type = "buy_and_rent" product.save! create(:price, link: product, price_cents: 300, is_rental: true) duplicate_product = ProductDuplicatorService.new(product.id).duplicate expect(duplicate_product.prices.size).to eq 2 expect(duplicate_product.rental_price_cents).to eq 300 expect(duplicate_product.buy_price_cents).to eq 5000 end end describe "asset previews" do it "handles asset preview attachments for images" do asset_preview = AssetPreview.new(link: create(:product)) asset_preview.file.attach(fixture_file_upload("test-small.jpg", "image/jpeg")) asset_preview.save! asset_preview.file.analyze duplicate_product = ProductDuplicatorService.new(asset_preview.link.id).duplicate expect(duplicate_product.asset_previews.count).to eq(1) expect(duplicate_product.asset_previews.first.file.attached?).to eq(true) expect(duplicate_product.asset_previews.first.file.analyzed?).to eq(true) end it "handles asset preview attachments for videos" do asset_preview = AssetPreview.new(link: create(:product)) asset_preview.file.attach(fixture_file_upload("thing.mov", "video/quicktime")) asset_preview.save! asset_preview.file.analyze duplicate_product = ProductDuplicatorService.new(asset_preview.link.id).duplicate expect(duplicate_product.asset_previews.count).to eq(1) expect(duplicate_product.asset_previews.first.file.attached?).to eq(true) expect(duplicate_product.asset_previews.first.file.analyzed?).to eq(true) end it "ignores deleted asset previews" do asset_preview = AssetPreview.new(link: create(:product)) asset_preview.file.attach(fixture_file_upload("test-small.jpg", "image/jpeg")) asset_preview.save! asset_preview.file.analyze asset_preview.mark_deleted duplicate_product = ProductDuplicatorService.new(asset_preview.link.id).duplicate expect(duplicate_product.asset_previews.count).to eq(0) end it "preserves the cover order when duplicating" do product = create(:product) asset_preview1 = AssetPreview.new(link: product) asset_preview1.file.attach(fixture_file_upload("test-small.jpg", "image/jpeg")) asset_preview1.save! asset_preview1.file.analyze asset_preview2 = AssetPreview.new(link: product) asset_preview2.file.attach(fixture_file_upload("smilie.png", "image/png")) asset_preview2.save! asset_preview2.file.analyze asset_preview3 = AssetPreview.new(link: product) asset_preview3.file.attach(fixture_file_upload("thing.mov", "video/quicktime")) asset_preview3.save! asset_preview3.file.analyze product.reorder_previews({ asset_preview1.guid => 2, asset_preview2.guid => 0, asset_preview3.guid => 1 }) duplicate_product = ProductDuplicatorService.new(product.id).duplicate expect(duplicate_product.asset_previews.count).to eq(3) expect(duplicate_product.display_asset_previews.first.file.filename.to_s).to eq("smilie.png") expect(duplicate_product.display_asset_previews.second.file.filename.to_s).to eq("thing.mov") expect(duplicate_product.display_asset_previews.third.file.filename.to_s).to eq("test-small.jpg") end end describe "thumbnail" do it "handles duplication for an image attachment" do thumbnail = Thumbnail.new(product: create(:product)) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png") blob.analyze thumbnail.file.attach(blob) thumbnail.save! duplicate_product = ProductDuplicatorService.new(thumbnail.product.id).duplicate expect(duplicate_product.thumbnail).to_not eq(nil) expect(duplicate_product.thumbnail.file.attached?).to eq(true) expect(duplicate_product.thumbnail.file.analyzed?).to eq(true) end end describe "rich content" do it "duplicates the variant-level rich content ensuring the integrity of the file embeds" do product_file1 = create(:product_file, link: product) product_file2 = create(:readable_document, link: product) product_file3 = create(:listenable_audio, link: product) product_file4 = create(:streamable_video, link: product) category = create(:variant_category, link: product, title: "Versions") version1 = create(:variant, variant_category: category, name: "Version 1") version1.product_files << product_file1 version2 = create(:variant, variant_category: category, name: "Version 2") version2.product_files << product_file2 version2.product_files << product_file3 version2.product_files << product_file4 create(:rich_content, entity: version1, description: [ { "type" => "paragraph", "content" => [{ "text" => "This is Version 1 content", "type" => "text" }] }, { "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => "product-file-1-uid" } } ]) create(:rich_content, entity: version2, description: [ { "type" => "paragraph", "content" => [{ "text" => "This is Version 2 content", "type" => "text" }] }, { "type" => "fileEmbed", "attrs" => { "id" => product_file2.external_id, "uid" => "product-file-2-uid" } }, { "type" => "fileEmbedGroup", "attrs" => { "uid" => "folder-uid", "name" => "Folder" }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => product_file3.external_id, "uid" => "product-file-3-uid" } }, { "type" => "fileEmbed", "attrs" => { "id" => product_file4.external_id, "uid" => "product-file-4-uid" } } ] } ]) duplicate_product = ProductDuplicatorService.new(product.id).duplicate duplicate_product_files = duplicate_product.product_files.alive duplicate_product_file1 = duplicate_product_files.find_by(url: product_file1.url) duplicate_product_file2 = duplicate_product_files.find_by(url: product_file2.url) duplicate_product_file3 = duplicate_product_files.find_by(url: product_file3.url) duplicate_product_file4 = duplicate_product_files.find_by(url: product_file4.url) duplicate_product_version1 = duplicate_product.alive_variants.find_by(name: "Version 1") duplicate_product_version2 = duplicate_product.alive_variants.find_by(name: "Version 2") expect(duplicate_product_files.size).to eq(4) expect(duplicate_product.alive_variants.size).to eq(2) expect(duplicate_product_version1.product_files.alive).to eq([duplicate_product_file1]) expect(duplicate_product_version2.product_files.alive).to eq([duplicate_product_file2, duplicate_product_file3, duplicate_product_file4]) expect(duplicate_product_version1.alive_rich_contents.first.description).to eq( [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "This is Version 1 content" }] }, { "type" => "fileEmbed", "attrs" => { "id" => duplicate_product_file1.external_id, "uid" => "product-file-1-uid" } } ] ) expect(duplicate_product_version2.alive_rich_contents.first.description).to eq( [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "This is Version 2 content" }] }, { "type" => "fileEmbed", "attrs" => { "id" => duplicate_product_file2.external_id, "uid" => "product-file-2-uid" } }, { "type" => "fileEmbedGroup", "attrs" => { "uid" => "folder-uid", "name" => "Folder" }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => duplicate_product_file3.external_id, "uid" => "product-file-3-uid" } }, { "type" => "fileEmbed", "attrs" => { "id" => duplicate_product_file4.external_id, "uid" => "product-file-4-uid" } } ] } ] ) end end describe "public files" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let(:public_file1) { create(:public_file, :with_audio, resource: product) } let(:public_file2) { create(:public_file, :with_audio, resource: product) } let(:description) do <<~HTML <p>Some text</p> <public-file-embed id="#{public_file1.public_id}"></public-file-embed> <p>Hello world!</p> <public-file-embed id="#{public_file2.public_id}"></public-file-embed> <p>More text</p> HTML end before do product.update!(description:) end it "duplicates public files and updates their embed IDs in the description" do duplicate_product = ProductDuplicatorService.new(product.id).duplicate expect(product.reload.description).to eq(description) expect(duplicate_product.public_files.count).to eq(2) duplicated_file1 = duplicate_product.public_files.alive.find_by(display_name: public_file1.display_name) duplicated_file2 = duplicate_product.public_files.alive.find_by(display_name: public_file2.display_name) expect(duplicated_file1.file).to be_attached expect(duplicated_file1.public_id).not_to eq(public_file1.public_id) expect(duplicated_file1.display_name).to eq(public_file1.display_name) expect(duplicated_file1.original_file_name).to eq(public_file1.original_file_name) expect(duplicated_file1.file_type).to eq(public_file1.file_type) expect(duplicated_file1.file_group).to eq(public_file1.file_group) expect(duplicated_file2.file).to be_attached expect(duplicated_file2.public_id).not_to eq(public_file2.public_id) expect(duplicated_file2.display_name).to eq(public_file2.display_name) expect(duplicated_file2.original_file_name).to eq(public_file2.original_file_name) expect(duplicated_file2.file_type).to eq(public_file2.file_type) expect(duplicated_file2.file_group).to eq(public_file2.file_group) expect(duplicate_product.description).to eq(description.gsub(public_file1.public_id, duplicated_file1.public_id).gsub(public_file2.public_id, duplicated_file2.public_id)) end it "removes embeds for non-existent public files" do public_file1.mark_deleted! description_with_invalid_embeds = <<~HTML <p>Some text</p> <public-file-embed id="#{public_file1.public_id}"></public-file-embed> <p>Middle text</p> <public-file-embed id="#{public_file2.public_id}"></public-file-embed> <public-file-embed id="nonexistent"></public-file-embed> <public-file-embed></public-file-embed> <p>More text</p> HTML product.update!(description: description_with_invalid_embeds) duplicate_product = ProductDuplicatorService.new(product.id).duplicate duplicated_file = duplicate_product.public_files.alive.sole expect(duplicated_file.file).to be_attached expect(duplicated_file.file.blob).to eq(public_file2.file.blob) expect(duplicated_file.display_name).to eq(public_file2.display_name) expect(duplicate_product.description.scan(/<public-file-embed/).size).to eq(1) expect(duplicate_product.description).to include("<public-file-embed id=\"#{duplicated_file.public_id}\"></public-file-embed>") 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_service_spec.rb
spec/services/recommended_products_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe RecommendedProductsService do describe ".fetch" do let(:seller) { create(:user) } let!(:sample_product) { create(:product, user: 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") } let!(:product4) { create(:product, name: "Product 4", purchase_disabled_at: Time.current) } let!(:product5) { create(:product, name: "Product 5", deleted_at: Time.current) } let!(:product6) { create(:product, name: "Product 6", banned_at: Time.current) } before do SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product1.id).update!(sales_count: 3) SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product2.id).update!(sales_count: 2) SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product3.id).update!(sales_count: 1) SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product4.id).update!(sales_count: 1) SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product5.id).update!(sales_count: 1) SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product6.id).update!(sales_count: 1) rebuild_srpis_cache allow_any_instance_of(Link).to receive(:recommendable?).and_return(true) end it "returns an ActiveRecord::Relation of products sorted by customer count and excludes non-alive products" do results = described_class.fetch( model: RecommendedProductsService::MODEL_SALES, ids: [sample_product.id], ) expect(results).to be_a(ActiveRecord::Relation) expect(results.to_a).to eq([product1, product2, product3]) end context "when `exclude_ids` is passed" do it "excludes products with the specified IDs" do expect(described_class.fetch( model: RecommendedProductsService::MODEL_SALES, ids: [sample_product.id], exclude_ids: [product1.id], ).to_a).to eq([product2, product3]) end end context "when `user_ids` is passed" do it "only returns products that belong to the specified users" do expect(described_class.fetch( model: RecommendedProductsService::MODEL_SALES, ids: [sample_product.id], user_ids: [seller.id], ).to_a).to eq([product1, product2]) end end context "when `number_of_results` is passed" do it "returns at most the specified number of products" do expect(described_class.fetch( model: RecommendedProductsService::MODEL_SALES, ids: [sample_product.id], number_of_results: 1, ).to_a).to eq([product1]) 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/adult_keyword_detector_spec.rb
spec/services/adult_keyword_detector_spec.rb
# frozen_string_literal: true require "spec_helper" describe AdultKeywordDetector do it "classifies adult text as such" do ["nude2screen", "PussyStuff", "abs punch product", "futa123", "uncensored", "Click here for #HotHentaiComics!"].each do |text| expect(described_class.adult?(text)).to eq(true) end end it "classifies non-adult text as such" do ["squirtle is a Pokémon", "small fuéta", "Yuri Gagarin was a great astronaut", "Tentacle Monster Hat", "ns fw"].each do |text| expect(described_class.adult?(text)).to eq(false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/community_chat_recap_generator_service_spec.rb
spec/services/community_chat_recap_generator_service_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe CommunityChatRecapGeneratorService do let(:seller) { create(:user) } let(:community) { create(:community, seller:) } describe "#process" do context "when recap is already finished" do let(:community_chat_recap) { create(:community_chat_recap, :finished) } it "returns early" do expect(OpenAI::Client).not_to receive(:new) expect do described_class.new(community_chat_recap:).process end.not_to change { community_chat_recap.reload } end end context "when generating daily recap" do let(:recap_run) { create(:community_chat_recap_run, from_date: Date.yesterday.beginning_of_day, to_date: Date.yesterday.end_of_day) } let(:community_chat_recap) { create(:community_chat_recap, community:, community_chat_recap_run: recap_run) } before do [ { user: seller, content: "Welcome to the community!" }, { user: nil, content: "How do I use this feature?" }, { user: seller, content: "Here's how to use it..." }, { user: nil, content: "Thank you for the information!" }, { user: seller, content: "I'm grateful for the help!" }, { user: nil, content: "You're welcome!" }].each.with_index do |message, i| user = message[:user] || create(:user) create(:community_chat_message, community:, user:, content: message[:content], created_at: Date.yesterday.beginning_of_day + (i + 1).hours) end end it "generates a summary from chat messages" do VCR.use_cassette("community_chat_recap_generator/daily_summary") do described_class.new(community_chat_recap: community_chat_recap).process end expect(community_chat_recap.reload).to be_status_finished expect(community_chat_recap.summary).to match(/<ul>.*?<\/ul>/m) expect(community_chat_recap.summary.scan("</li>").count).to eq(4) expect(community_chat_recap.summary).to include("<li>Creator welcomed everyone to the community.</li>") expect(community_chat_recap.summary).to include("<li>A customer asked about using a specific feature.</li>") expect(community_chat_recap.summary).to include("<li>Creator provided detailed instructions on how to use the feature.</li>") expect(community_chat_recap.summary).to include("<li>Two customers expressed their gratitude for the information and help.</li>") expect(community_chat_recap.summarized_message_count).to eq(6) expect(community_chat_recap.input_token_count).to eq(429) expect(community_chat_recap.output_token_count).to eq(67) end it "handles no messages in the given period" do CommunityChatMessage.destroy_all described_class.new(community_chat_recap: community_chat_recap).process expect(community_chat_recap.reload).to be_status_finished expect(community_chat_recap.summary).to be_empty expect(community_chat_recap.summarized_message_count).to eq(0) expect(community_chat_recap.input_token_count).to eq(0) expect(community_chat_recap.output_token_count).to eq(0) end end context "when generating weekly recap" do let(:from_date) { Date.yesterday.beginning_of_day - 6.days } let!(:daily_recap1) { create(:community_chat_recap, :finished, community:, community_chat_recap_run: create(:community_chat_recap_run, from_date: (from_date + 3.day).beginning_of_day, to_date: (from_date + 4.days).end_of_day), summary: "<ul><li>Creator share a new version of the app.</li><li>A customer asked about when the app will be released on Android.</li><li>Creator shared the release date.</li></ul>", summarized_message_count: 12, status: "finished") } let!(:daily_recap2) { create(:community_chat_recap, :finished, community:, community_chat_recap_run: create(:community_chat_recap_run, from_date: (from_date + 5.day).beginning_of_day, to_date: (from_date + 6.days).end_of_day), summary: "<ul><li>Customers discussed about various issues with the product.</li><li>Creator confirmed that the issue is known and will be fixed in the next version.</li></ul>", summarized_message_count: 45, status: "finished") } let(:weekly_recap_run) { create(:community_chat_recap_run, :weekly, from_date:, to_date: (from_date + 6.days).end_of_day) } let(:weekly_recap) { create(:community_chat_recap, community:, community_chat_recap_run: weekly_recap_run) } it "generates a weekly summary from daily recaps" do VCR.use_cassette("community_chat_recap_generator/weekly_summary") do described_class.new(community_chat_recap: weekly_recap).process end expect(weekly_recap.reload).to be_status_finished expect(weekly_recap.summary).to match(/<ul>.*?<\/ul>/m) expect(weekly_recap.summary.scan("</li>").count).to eq(2) expect(weekly_recap.summary).to include("<li>The **new version of the app** was shared by the creator, along with a confirmed **release date** for Android.</li>") expect(weekly_recap.summary).to include("<li>Customers raised concerns regarding various **product issues**, which the creator acknowledged and assured would be addressed in the **next version**.</li>") expect(weekly_recap.summarized_message_count).to eq(57) expect(weekly_recap.input_token_count).to eq(255) expect(weekly_recap.output_token_count).to eq(67) end it "handles no daily recaps in the given period" do daily_recap1.update!(summary: "", summarized_message_count: 0) daily_recap2.update!(summary: "", summarized_message_count: 0) described_class.new(community_chat_recap: weekly_recap).process expect(weekly_recap.reload).to be_status_finished expect(weekly_recap.summary).to be_empty expect(weekly_recap.summarized_message_count).to eq(0) expect(weekly_recap.input_token_count).to eq(0) expect(weekly_recap.output_token_count).to eq(0) end end context "when OpenAI API fails" do let(:community) { create(:community, seller:) } let!(:community_chat_message) { create(:community_chat_message, community:, created_at: Date.yesterday.beginning_of_day + 1.hour) } let(:recap_run) { create(:community_chat_recap_run, from_date: Date.yesterday.beginning_of_day, to_date: Date.yesterday.end_of_day) } let(:community_chat_recap) { create(:community_chat_recap, community:, community_chat_recap_run: recap_run) } before do allow(OpenAI::Client).to receive(:new).and_raise(StandardError.new("API Error")) end it "retries the operation" do expect do expect do described_class.new(community_chat_recap:).process end.to raise_error(StandardError) end.not_to change { community_chat_recap.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/save_utm_link_service_spec.rb
spec/services/save_utm_link_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SaveUtmLinkService do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let(:post) { create(:audience_post, :published, shown_on_profile: true, seller:) } describe "#perform" do context "when 'utm_link' is not provided" do it "creates a UTM link for a product page" do expect do described_class.new( seller:, params: { title: "Test Link", target_resource_id: product.external_id, target_resource_type: "product_page", permalink: "abc12345", utm_source: "facebook", utm_medium: "social", utm_campaign: "summer", utm_term: "sale", utm_content: "banner", ip_address: "192.168.1.1", browser_guid: "1234567890" } ).perform end.to change { seller.utm_links.count }.by(1) utm_link = seller.utm_links.last expect(utm_link).to have_attributes( title: "Test Link", target_resource_type: "product_page", target_resource_id: product.id, permalink: "abc12345", utm_source: "facebook", utm_medium: "social", utm_campaign: "summer", utm_term: "sale", utm_content: "banner", ip_address: "192.168.1.1", browser_guid: "1234567890" ) end it "creates a UTM link for a post page" do expect do described_class.new( seller:, params: { title: "Test Link", target_resource_id: post.external_id, target_resource_type: "post_page", permalink: "abc12345", utm_source: "twitter", utm_medium: "social", utm_campaign: "winter" } ).perform end.to change { seller.utm_links.count }.by(1) utm_link = seller.utm_links.last expect(utm_link).to have_attributes( title: "Test Link", target_resource_type: "post_page", target_resource_id: post.id, permalink: "abc12345", utm_source: "twitter", utm_medium: "social", utm_campaign: "winter", utm_term: nil, utm_content: nil ) end it "creates a UTM link for the profile page" do expect do described_class.new( seller:, params: { title: "Test Link", target_resource_id: nil, target_resource_type: "profile_page", permalink: "abc12345", utm_source: "instagram", utm_medium: "social", utm_campaign: "spring" } ).perform end.to change { seller.utm_links.count }.by(1) utm_link = seller.utm_links.last expect(utm_link).to have_attributes( title: "Test Link", target_resource_type: "profile_page", target_resource_id: nil, permalink: "abc12345", utm_source: "instagram", utm_medium: "social", utm_campaign: "spring" ) end it "creates a UTM link for the subscribe page" do expect do described_class.new( seller:, params: { title: "Test Link", target_resource_type: "subscribe_page", permalink: "abc12345", utm_source: "newsletter", utm_medium: "email", utm_campaign: "subscribe" } ).perform end.to change { seller.utm_links.count }.by(1) utm_link = seller.utm_links.last expect(utm_link).to have_attributes( title: "Test Link", target_resource_type: "subscribe_page", target_resource_id: nil, permalink: "abc12345", utm_source: "newsletter", utm_medium: "email", utm_campaign: "subscribe" ) end it "raises an error if the UTM link fails to save" do expect do described_class.new( seller:, params: { title: "Test Link", target_resource_type: "product_page", target_resource_id: product.external_id, permalink: "abc", utm_source: "facebook", utm_medium: "social", utm_campaign: "summer", } ).perform end.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Permalink is invalid") end end context "when 'utm_link' is provided" do let(:utm_link) { create(:utm_link, seller:, ip_address: "192.168.1.1", browser_guid: "1234567890") } let(:params) do { title: "Updated Title", target_resource_id: product.external_id, target_resource_type: "product_page", permalink: "abc12345", utm_source: "facebook", utm_medium: "social", utm_campaign: "summer", utm_term: "sale", utm_content: "banner", ip_address: "172.0.0.1", browser_guid: "9876543210" } end it "updates only the permitted attributes" do old_permalink = utm_link.permalink described_class.new(seller:, params:, utm_link:).perform utm_link.reload expect(utm_link.title).to eq("Updated Title") expect(utm_link.target_resource_id).to be_nil expect(utm_link.target_resource_type).to eq("profile_page") expect(utm_link.permalink).to eq(old_permalink) expect(utm_link.utm_source).to eq("facebook") expect(utm_link.utm_medium).to eq("social") expect(utm_link.utm_campaign).to eq("summer") expect(utm_link.utm_term).to eq("sale") expect(utm_link.utm_content).to eq("banner") expect(utm_link.ip_address).to eq("192.168.1.1") expect(utm_link.browser_guid).to eq("1234567890") end it "raises an error if the UTM link fails to save" do params[:utm_source] = "a" * 256 expect do described_class.new(seller:, params:, utm_link:).perform end.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Utm source is too long (maximum is 200 characters)") 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/gumroad_daily_analytics_compiler_spec.rb
spec/services/gumroad_daily_analytics_compiler_spec.rb
# frozen_string_literal: true require "spec_helper" describe GumroadDailyAnalyticsCompiler do describe ".compile_gumroad_price_cents" do it "aggregates data for the dates provided" do create :purchase, created_at: Time.utc(2023, 1, 4) create :purchase, created_at: Time.utc(2023, 1, 5) create :purchase, created_at: Time.utc(2023, 1, 6) create :purchase, created_at: Time.utc(2023, 1, 7) create :purchase, created_at: Time.utc(2023, 1, 8) range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 7) value = GumroadDailyAnalyticsCompiler.compile_gumroad_price_cents(between: range) expect(value).to eq(300) end it "aggregates purchase amounts" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300 range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_price_cents(between: range) expect(value).to eq(600) end it "ignores unsuccessful purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, purchase_state: "failed" create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300, purchase_state: "in_progress" range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_price_cents(between: range) expect(value).to eq(100) end it "ignores refunded purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, stripe_refunded: true create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300 range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_price_cents(between: range) expect(value).to eq(400) end end describe ".compile_gumroad_fee_cents" do it "aggregates data for the dates provided" do create :purchase, created_at: Time.utc(2023, 1, 4) create :purchase, created_at: Time.utc(2023, 1, 5) create :purchase, created_at: Time.utc(2023, 1, 6) create :purchase, created_at: Time.utc(2023, 1, 7) create :purchase, created_at: Time.utc(2023, 1, 8) Purchase.update_all("fee_cents = price_cents / 10") # Force fee to be 10% of purchase amount range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 7) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(30) end it "aggregates both purchase fees and service charges" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 # fee_cents: 10 create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 20 Purchase.update_all("fee_cents = price_cents / 10") # Force fee to be 10% of purchase amount range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(30) end context "purchase fees" do it "aggregates purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 # fee_cents: 10 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200 # fee_cents: 20 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300 # fee_cents: 30 Purchase.update_all("fee_cents = price_cents / 10") # Force fee to be 10% of purchase amount range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(60) end it "ignores unsuccessful purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 # fee_cents: 10 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, purchase_state: "failed" # fee_cents: 20 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300, purchase_state: "in_progress" # fee_cents: 30 Purchase.update_all("fee_cents = price_cents / 10") # Force fee to be 10% of purchase amount range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(10) end it "ignores refunded purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 # fee_cents: 10 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, stripe_refunded: true # fee_cents: 20 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300 # fee_cents: 30 Purchase.update_all("fee_cents = price_cents / 10") # Force fee to be 10% of purchase amount range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(40) end end context "service charges" do it "aggregates service charges" do create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 10 create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 20 create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 30 range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(60) end it "ignores failed service charges" do create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 10 create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 20, state: "failed" create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 30 range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(40) end it "ignores refunded service charges" do create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 10 create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 20, charge_processor_refunded: 13 create :service_charge, created_at: Time.utc(2023, 1, 5), charge_cents: 30 range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: range) expect(value).to eq(40) end end end describe ".compile_creators_with_sales" do it "aggregates data for the dates provided" do create :purchase, created_at: Time.utc(2023, 1, 4) create :purchase, created_at: Time.utc(2023, 1, 5) create :purchase, created_at: Time.utc(2023, 1, 6) create :purchase, created_at: Time.utc(2023, 1, 7) create :purchase, created_at: Time.utc(2023, 1, 8) range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 7) value = GumroadDailyAnalyticsCompiler.compile_creators_with_sales(between: range) expect(value).to eq(3) end it "aggregates creators with at least a 1 dollar sale" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 99 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 150 range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_creators_with_sales(between: range) expect(value).to eq(2) end it "does not count the same creator twice" do product = create :product create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100, link: product create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 150, link: product range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_creators_with_sales(between: range) expect(value).to eq(1) end it "ignores suspended creators" do purchase_1 = create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 purchase_2 = create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 purchase_1.seller.update!(user_risk_state: "suspended_for_fraud") purchase_2.seller.update!(user_risk_state: "suspended_for_tos_violation") range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_creators_with_sales(between: range) expect(value).to eq(0) end it "ignores unsuccessful purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, purchase_state: "failed" create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300, purchase_state: "in_progress" range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_creators_with_sales(between: range) expect(value).to eq(1) end it "ignores refunded purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, stripe_refunded: true create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300 range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_creators_with_sales(between: range) expect(value).to eq(2) end end describe ".compile_gumroad_discover_price_cents" do it "aggregates data for the dates provided" do create :purchase, created_at: Time.utc(2023, 1, 4), was_product_recommended: true create :purchase, created_at: Time.utc(2023, 1, 5), was_product_recommended: true create :purchase, created_at: Time.utc(2023, 1, 6), was_product_recommended: true create :purchase, created_at: Time.utc(2023, 1, 7), was_product_recommended: true create :purchase, created_at: Time.utc(2023, 1, 8), was_product_recommended: true range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 7) value = GumroadDailyAnalyticsCompiler.compile_gumroad_discover_price_cents(between: range) expect(value).to eq(300) end it "aggregates discovery purchase amounts" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100, was_product_recommended: true create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200 create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300, was_product_recommended: true range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_discover_price_cents(between: range) expect(value).to eq(400) end it "ignores unsuccessful purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100, was_product_recommended: true create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, was_product_recommended: true, purchase_state: "failed" create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300, was_product_recommended: true, purchase_state: "in_progress" range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_discover_price_cents(between: range) expect(value).to eq(100) end it "ignores refunded purchases" do create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 100, was_product_recommended: true create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 200, was_product_recommended: true, stripe_refunded: true create :purchase, created_at: Time.utc(2023, 1, 5), price_cents: 300, was_product_recommended: true range = Time.utc(2023, 1, 5)..Time.utc(2023, 1, 5) value = GumroadDailyAnalyticsCompiler.compile_gumroad_discover_price_cents(between: range) expect(value).to eq(400) 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_funds_csv_report_service_spec.rb
spec/services/admin_funds_csv_report_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe AdminFundsCsvReportService do describe ".generate" do subject(:csv_report) { described_class.new(@report).generate } context "for funds received report" do before do @report = FundsReceivedReports.funds_received_report(1, 2022) end it "shows all sales and charges split by processor" do parsed_csv = CSV.parse(csv_report) expect(parsed_csv).to eq([ ["Purchases", "PayPal", "total_transaction_count", "0"], ["", "", "total_transaction_cents", "0"], ["", "", "gumroad_tax_cents", "0"], ["", "", "affiliate_credit_cents", "0"], ["", "", "fee_cents", "0"], ["", "Stripe", "total_transaction_count", "0"], ["", "", "total_transaction_cents", "0"], ["", "", "gumroad_tax_cents", "0"], ["", "", "affiliate_credit_cents", "0"], ["", "", "fee_cents", "0"], ]) end end context "for deferred refunds report" do before do @report = DeferredRefundsReports.deferred_refunds_report(1, 2022) end it "shows all sales and charges split by processor" do parsed_csv = CSV.parse(csv_report) expect(parsed_csv).to eq([ ["Purchases", "PayPal", "total_transaction_count", "0"], ["", "", "total_transaction_cents", "0"], ["", "", "gumroad_tax_cents", "0"], ["", "", "affiliate_credit_cents", "0"], ["", "", "fee_cents", "0"], ["", "Stripe", "total_transaction_count", "0"], ["", "", "total_transaction_cents", "0"], ["", "", "gumroad_tax_cents", "0"], ["", "", "affiliate_credit_cents", "0"], ["", "", "fee_cents", "0"], ]) 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/post_resend_api_spec.rb
spec/services/post_resend_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe PostResendApi, :freeze_time do include Rails.application.routes.url_helpers before do @seller = create(:named_user) @post = create(:audience_installment, name: "post title", message: "post body", seller: @seller) described_class.mails.clear end def send_emails(**args) = described_class.new(post: @post, **args).send_emails def send_default_email = send_emails(recipients: [{ email: "c1@example.com" }]) def sent_emails = described_class.mails def sent_email = sent_emails["c1@example.com"] def sent_email_content = sent_email[:content] def html_doc(content) = Nokogiri::HTML(content) def body_plaintext(content) = html_doc(content).at_xpath("//body").text.strip # def body_plaintext(content) = html_doc(content).text.strip describe "Premailer" do before { send_default_email } it "automatically inlines styles" do expect(sent_email_content).to include("<body style=") end end describe "Seller's design settings" do before do @post.seller.seller_profile.update!(highlight_color: "#009a49", font: "Roboto Mono", background_color: "#000000") send_default_email end it "includes them as CSS" do expect(sent_email_content).to include("body {\nbackground-color: #000000; color: #fff; font-family: \"Roboto Mono\", \"ABC Favorit\", monospace;\n}") expect(sent_email_content).to include("body {\nheight: auto; min-height: 100%;\n}") end end describe "preheader text" do before { send_default_email } it "is included at the start of the email" do expect(body_plaintext(sent_email_content)).to start_with("post body") end end describe "call to action button" do before do @post.update!(call_to_action_url: "https://cta.example/", call_to_action_text: "Click here") send_default_email end it "is included when CTA url and CTA text are set" do node = html_doc(sent_email_content).at_xpath(%(//a[@href="https://cta.example/"])) expect(node).to be_present expect(node.text).to eq("Click here") end end describe "'View Content' button" do it "is not included when there are no attachments" do send_default_email expect(sent_email_content).not_to include("View content") end it "is included when there are attachments" do @post.product_files << create(:product_file) url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{url_redirect.download_page_url}"])) expect(node).to be_present expect(node.text).to eq("View content") end end describe "Validations" do it "raises an error when there are too many recipients" do stub_const("#{described_class}::MAX_RECIPIENTS", 2) expect do send_emails(recipients: [{ email: "c1@example.com" }] * 3) end.to raise_error(/too many recipients/i) end it "raises an error when a recipient has no email" do expect do send_emails(recipients: [{ email: "" }]) end.to raise_error(/must have an email/i) end it "raises an error when a post has files but no url_redirect" do @post.product_files << create(:product_file) expect do send_default_email end.to raise_error(/must have a url_redirect/i) end it "raises an error when recipients have inconsistent records" do expect do send_emails(recipients: [{ email: "c1@example.com", purchase: create(:purchase), follower: create(:follower) }]) end.to raise_error(/Recipients can't have .* and\/or .* record/i) expect do send_emails(recipients: [{ email: "c1@example.com", purchase: create(:purchase), affiliate: create(:direct_affiliate) }]) end.to raise_error(/Recipients can't have .* and\/or .* record/i) expect do send_emails(recipients: [{ email: "c1@example.com", follower: create(:follower), affiliate: create(:direct_affiliate) }]) end.to raise_error(/Recipients can't have .* and\/or .* record/i) end end describe "'Reply with a comment' button" do it "is not included when allow_comments=false" do send_default_email expect(sent_email_content).not_to include("Reply with a comment") end it "is not included when allow_comments=true and shown_on_profile=false" do @post.update!(allow_comments: true, shown_on_profile: false) send_default_email expect(sent_email_content).not_to include("Reply with a comment") end it "is included when allow_comments=true and shown_on_profile=true" do @post.update!(allow_comments: true, shown_on_profile: true) send_default_email expected_url = view_post_url( username: @post.user.username, slug: @post.slug, host: UrlService.domain_with_protocol ) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{expected_url}#comments"])) expect(node).to be_present expect(node.text).to eq("Reply with a comment") end end describe "Update reason" do it "is generic when installment_type='seller'" do @post.update!(installment_type: Installment::SELLER_TYPE) send_default_email expect(sent_email_content).to include("You've received this email because you've purchased a product from #{@post.seller.name}.") end context "when installment_type='product' or 'variant'" do before do @product = create(:product, user: @seller) @post.update!(installment_type: Installment::PRODUCT_TYPE, link: @product) end it "mentions when it's due to the subscription being cancelled" do @product.update!(is_recurring_billing: true) @post.update!(workflow_trigger: Installment::MEMBER_CANCELLATION_WORKFLOW_TRIGGER) send_default_email expect(sent_email_content).to include("You've received this email because you cancelled your membership to <a href=\"#{@post.link.long_url}\">#{@post.link.name}</a>.") url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) expect(sent_email_content).to include("You've received this email because you cancelled your membership to <a href=\"#{url_redirect.download_page_url}\">#{@post.link.name}</a>.") end it "mentions when it's due to it being an active subscription" do @product.update!(is_recurring_billing: true) send_default_email expect(sent_email_content).to include("You've received this email because you subscribed to <a href=\"#{@post.link.long_url}\">#{@post.link.name}</a>.") url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) expect(sent_email_content).to include("You've received this email because you subscribed to <a href=\"#{url_redirect.download_page_url}\">#{@post.link.name}</a>.") end it "mentions when it's due to it being a purchase" do send_default_email expect(sent_email_content).to include("You've received this email because you've purchased <a href=\"#{@post.link.long_url}\">#{@post.link.name}</a>.") url_redirect = create(:url_redirect, installment: @post) send_emails(recipients: [{ email: "c1@example.com", url_redirect: }]) expect(sent_email_content).to include("You've received this email because you've purchased <a href=\"#{url_redirect.download_page_url}\">#{@post.link.name}</a>.") end end end describe "Unsubscribe link" do it "links to purchase unsubscribe page when coming with a purchase" do allow_any_instance_of(Purchase).to receive(:secure_external_id).and_return("sample-secure-id") purchase = create(:purchase, :from_seller, seller: @seller) send_emails(recipients: [{ email: "c1@example.com", purchase: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{unsubscribe_purchase_url(purchase.secure_external_id(scope: "unsubscribe"))}"])) expect(node).to be_present expect(node.text).to eq("Unsubscribe") end it "links to unfollow page when coming with a follower" do follower = create(:follower, user: @seller) send_emails(recipients: [{ email: "c1@example.com", follower: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{cancel_follow_url(follower.external_id)}"])) expect(node).to be_present expect(node.text).to eq("Unsubscribe") end it "links to affiliate unsubscribe page when coming with an affiliate" do affiliate = create(:direct_affiliate, seller: @seller) send_emails(recipients: [{ email: "c1@example.com", affiliate: }]) node = html_doc(sent_email_content).at_xpath(%(//a[@href="#{unsubscribe_posts_affiliate_url(affiliate.external_id)}"])) expect(node).to be_present expect(node.text).to eq("Unsubscribe") end end it "sends the correct text / subject / reply-to" do @seller.update!(support_email: "custom@example.com") send_default_email expect(sent_email[:subject]).to include("post title") expect(sent_email[:reply_to]).to include("custom@example.com") expect(sent_email_content).to include("post title") expect(sent_email_content).to include("post body") end it "sets the correct headers" do purchase = create(:purchase, :from_seller, seller: @seller) follower = create(:follower, user: @seller) affiliate = create(:direct_affiliate, seller: @seller) send_emails(recipients: [ { email: "c1@example.com", purchase: }, { email: "c2@example.com", follower: }, { email: "c3@example.com", affiliate: }, ]) purchase_email = sent_emails["c1@example.com"] follower_email = sent_emails["c2@example.com"] affiliate_email = sent_emails["c3@example.com"] # Purchase email headers expect(MailerInfo::Encryption.decrypt(purchase_email[:headers]["X-GUM-Environment"])).to eq(Rails.env) expect(MailerInfo::Encryption.decrypt(purchase_email[:headers]["X-GUM-Mailer-Class"])).to eq("CreatorContactingCustomersMailer") expect(MailerInfo::Encryption.decrypt(purchase_email[:headers]["X-GUM-Mailer-Method"])).to eq("purchase_installment") expect(MailerInfo::Encryption.decrypt(purchase_email[:headers]["X-GUM-Mailer-Args"])).to eq([purchase.id, @post.id].inspect) expect(MailerInfo::Encryption.decrypt(purchase_email[:headers]["X-GUM-Category"])).to eq(["CreatorContactingCustomersMailer", "CreatorContactingCustomersMailer.purchase_installment"].to_json) expect(MailerInfo::Encryption.decrypt(purchase_email[:headers]["X-GUM-Purchase-Id"])).to eq(purchase.id.to_s) expect(MailerInfo::Encryption.decrypt(purchase_email[:headers]["X-GUM-Post-Id"])).to eq(@post.id.to_s) expect(purchase_email[:headers]["X-GUM-Email-Provider"]).to eq(MailerInfo::EMAIL_PROVIDER_RESEND) # Follower email headers expect(MailerInfo::Encryption.decrypt(follower_email[:headers]["X-GUM-Environment"])).to eq(Rails.env) expect(MailerInfo::Encryption.decrypt(follower_email[:headers]["X-GUM-Mailer-Class"])).to eq("CreatorContactingCustomersMailer") expect(MailerInfo::Encryption.decrypt(follower_email[:headers]["X-GUM-Mailer-Method"])).to eq("follower_installment") expect(MailerInfo::Encryption.decrypt(follower_email[:headers]["X-GUM-Mailer-Args"])).to eq([follower.id, @post.id].inspect) expect(MailerInfo::Encryption.decrypt(follower_email[:headers]["X-GUM-Category"])).to eq(["CreatorContactingCustomersMailer", "CreatorContactingCustomersMailer.follower_installment"].to_json) expect(MailerInfo::Encryption.decrypt(follower_email[:headers]["X-GUM-Follower-Id"])).to eq(follower.id.to_s) expect(MailerInfo::Encryption.decrypt(follower_email[:headers]["X-GUM-Post-Id"])).to eq(@post.id.to_s) expect(follower_email[:headers]["X-GUM-Email-Provider"]).to eq(MailerInfo::EMAIL_PROVIDER_RESEND) # Affiliate email headers expect(MailerInfo::Encryption.decrypt(affiliate_email[:headers]["X-GUM-Environment"])).to eq(Rails.env) expect(MailerInfo::Encryption.decrypt(affiliate_email[:headers]["X-GUM-Mailer-Class"])).to eq("CreatorContactingCustomersMailer") expect(MailerInfo::Encryption.decrypt(affiliate_email[:headers]["X-GUM-Mailer-Method"])).to eq("direct_affiliate_installment") expect(MailerInfo::Encryption.decrypt(affiliate_email[:headers]["X-GUM-Mailer-Args"])).to eq([affiliate.id, @post.id].inspect) expect(MailerInfo::Encryption.decrypt(affiliate_email[:headers]["X-GUM-Category"])).to eq(["CreatorContactingCustomersMailer", "CreatorContactingCustomersMailer.direct_affiliate_installment"].to_json) expect(MailerInfo::Encryption.decrypt(affiliate_email[:headers]["X-GUM-Affiliate-Id"])).to eq(affiliate.id.to_s) expect(MailerInfo::Encryption.decrypt(affiliate_email[:headers]["X-GUM-Post-Id"])).to eq(@post.id.to_s) expect(affiliate_email[:headers]["X-GUM-Email-Provider"]).to eq(MailerInfo::EMAIL_PROVIDER_RESEND) end it "creates EmailInfo record" do send_emails(recipients: [ { email: "c1@example.com", purchase: create(:purchase) }, { email: "c2@example.com" }, ]) send_emails(recipients: [{ email: "c1@example.com" }]) expect(EmailInfo.count).to eq(1) expect(EmailInfo.first.attributes).to include( "type" => "CreatorContactingCustomersEmailInfo", "installment_id" => @post.id, "email_name" => "purchase_installment", "state" => "sent", "sent_at" => Time.current, ) end it "records the email events" do expect(EmailEvent).to receive(:log_send_events).with(["c1@example.com"], Time.current).and_call_original send_emails(recipients: [{ email: "c1@example.com" }]) expect(EmailEvent.first!).to have_attributes( "email_digest" => EmailEvent.email_sha_digest("c1@example.com"), "sent_emails_count" => 1, "last_email_sent_at" => Time.current, ) end it "sends push notifications" do purchaser = create(:user, email: "c1@example.com") purchase = create(:purchase, purchaser:) send_emails(recipients: [{ email: "c1@example.com", purchase: }]) expect(PushNotificationWorker.jobs.size).to eq(1) expect(PushNotificationWorker).to have_enqueued_sidekiq_job( purchaser.id, Device::APP_TYPES[:consumer], @post.subject, "By #{@post.seller.name}", { "installment_id" => @post.external_id, "purchase_id" => purchase.external_id }, ).on("low") end it "updates delivery statistics" do blast_1 = create(:post_email_blast, post: @post, delivery_count: 0) send_emails(recipients: [ { email: "c1@example.com" }, { email: "c2@example.com" } ], blast: blast_1) expect(@post.reload.customer_count).to eq(2) expect(blast_1.reload.delivery_count).to eq(2) blast_2 = create(:post_email_blast, post: @post, delivery_count: 0) send_emails(recipients: [ { email: "c3@example.com" } ], blast: blast_2) expect(@post.reload.customer_count).to eq(3) expect(blast_2.reload.delivery_count).to eq(1) end context "when preview email" do before do create(:user, email: "c1@example.com") send_emails(recipients: [{ email: "c1@example.com" }], preview: true) end it "sends an email" do expect(sent_emails.size).to eq(1) end it "does not record any info" do expect(@post.customer_count).to eq(nil) expect(EmailInfo.count).to eq(0) end it "does not send a push notification" do expect(PushNotificationWorker.jobs.size).to eq(0) end end it "includes a link to Gumroad" do send_default_email node = html_doc(sent_email_content).at_xpath(%(//div[contains(@class, 'footer')]/a[@href="#{root_url}"])) expect(node).to be_present expect(node.text).to include("Powered by") end describe "Cache" do it "prevents the template from being rendered several times for the same post, across multiple calls" do cache = {} expect(ApplicationController.renderer).to receive(:render).twice.and_call_original send_emails(recipients: [ { email: "c1@example.com" }, { email: "c2@example.com" } ], cache:) send_emails(recipients: [ { email: "c3@example.com" }, { email: "c4@example.com" } ], cache:) send_emails( post: create(:post), recipients: [ { email: "c1@example.com" }, { email: "c2@example.com" } ], cache:) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/merge_carts_service_spec.rb
spec/services/merge_carts_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe MergeCartsService do describe "#process" do let!(:user) { create(:user) } let(:browser_guid) { SecureRandom.uuid } context "when source cart is nil" do it "updates the details of the target cart" do cart = create(:cart, user:, browser_guid: "old-browser-guid") expect do described_class.new(source_cart: nil, target_cart: cart, user:, browser_guid:).process end.to change { cart.reload.browser_guid }.from("old-browser-guid").to(browser_guid) .and change { cart.email }.from(nil).to(user.email) .and not_change { cart.slice(:user_id, :deleted_at) } .and not_change { Cart.alive.count } end end context "target cart is nil" do it "updates the details of the source cart" do cart = create(:cart, :guest, browser_guid:) expect do expect do described_class.new(source_cart: cart, target_cart: nil, user:, browser_guid:).process end.to change { cart.reload.user_id }.from(nil).to(user.id) end.to_not change { cart.browser_guid } expect(Cart.alive.sole.id).to eq(cart.id) expect(cart.email).to eq(user.email) expect(cart.browser_guid).to eq(browser_guid) end end it "does nothing if the source cart is the same as the target cart" do cart = create(:cart, user:, browser_guid:) expect do expect do described_class.new(source_cart: cart, target_cart: cart, user:, browser_guid:).process end.to_not change { Cart.alive.count } end.to_not change { cart.reload } end it "deletes the source cart when both source and target carts do not have alive cart products" do source_cart = create(:cart, :guest, browser_guid: SecureRandom.uuid, email: "source@example.com") target_cart = create(:cart, :guest, browser_guid:) expect do described_class.new(source_cart:, target_cart:, browser_guid:).process end.to change { Cart.alive.count }.from(2).to(1) expect(Cart.alive.sole.id).to eq(target_cart.id) expect(target_cart.reload.email).to eq("source@example.com") end it "merges the cart products, discount codes and other attributes from source cart to the target cart" do product1 = create(:product) product2 = create(:product) product2_variant = create(:variant, variant_category: create(:variant_category, link: product2)) product3 = create(:product) source_cart = create(:cart, :guest, browser_guid: SecureRandom.uuid, return_url: "https://example.com/source", discount_codes: [{ code: "ABC123", fromUrl: false }, { code: "XYZ789", fromUrl: false }], reject_ppp_discount: true) target_cart = create(:cart, :guest, browser_guid:, discount_codes: [{ code: "DEF456", fromUrl: false }, { code: "ABC123", fromUrl: false }]) create(:cart_product, cart: source_cart, product: product1) create(:cart_product, cart: source_cart, product: product2, option: product2_variant) create(:cart_product, cart: target_cart, product: product3) expect do expect do described_class.new(source_cart:, target_cart:, browser_guid:).process end.to change { Cart.alive.count }.from(2).to(1) end.to change { target_cart.reload.cart_products.count }.from(1).to(3) expect(Cart.alive.sole.id).to eq(target_cart.id) expect(target_cart.return_url).to eq("https://example.com/source") expect(target_cart.discount_codes.map { _1["code"] }).to eq(["DEF456", "ABC123", "XYZ789"]) expect(target_cart.reject_ppp_discount).to be(true) expect(target_cart.alive_cart_products.pluck(:product_id, :option_id)).to eq([[product1.id, nil], [product2.id, product2_variant.id], [product3.id, nil]]) expect(target_cart.browser_guid).to eq(browser_guid) expect(target_cart.email).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/default_abandoned_cart_workflow_generator_service_spec.rb
spec/services/default_abandoned_cart_workflow_generator_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe DefaultAbandonedCartWorkflowGeneratorService do include Rails.application.routes.url_helpers let(:seller) { create(:user) } subject { described_class.new(seller:) } describe "#generate" do context "when seller does not have an abandoned cart workflow" do it "creates a new abandoned cart workflow and publishes it" do expect do subject.generate end.to change { seller.workflows.abandoned_cart_type.published.count }.from(0).to(1) workflow = seller.workflows.abandoned_cart_type.published.sole expect(workflow.name).to eq("Abandoned cart") expect(workflow.bought_products).to be_nil expect(workflow.bought_variants).to be_nil 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="#{checkout_index_url(host: DOMAIN)}" target="_blank" rel="noopener noreferrer nofollow">complete checking out</a>.</p><product-list-placeholder />)) expect(installment.abandoned_cart_type?).to be(true) expect(installment.installment_rule.displayable_time_duration).to eq(24) expect(installment.installment_rule.time_period).to eq("hour") end end context "when seller already has an abandoned cart workflow" do before do create(:workflow, seller:, workflow_type: Workflow::ABANDONED_CART_TYPE, deleted_at: 1.hour.ago) end it "does not create a new abandoned cart workflow" do expect do expect do expect do subject.generate end.to_not change { seller.workflows.abandoned_cart_type.count } end.to_not change { Installment.count } end.to_not change { InstallmentRule.count } end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/cleanup_rpush_device_service_spec.rb
spec/services/cleanup_rpush_device_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe CleanupRpushDeviceService do before do @device_a = create(:device) @device_b = create(:device) @device_c = create(:device) end it "removes device records for the undeliverable token" do apn_feedback = double(device_token: @device_b.token) expect(apn_feedback).to receive(:destroy) expect do CleanupRpushDeviceService.new(apn_feedback).process end.to change { Device.all.count }.from(3).to(2) expect(Device.all.ids).to_not include(@device_b.id) end # Make sure there's no problem in the portion of code we stubbed in the above spec it "works without any errors" do apn_feedback = double(device_token: @device_b.token, destroy: true) expect do CleanupRpushDeviceService.new(apn_feedback).process end.to_not raise_error end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/custom_domain_verification_service_spec.rb
spec/services/custom_domain_verification_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe CustomDomainVerificationService do let(:domain) { "example.com" } subject(:service) { described_class.new(domain:) } describe "#process" do describe "domain CNAME configuration" do let(:domain) { "store.example.com" } context "when there exists a CNAME record pointing to the correct domain" do before do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(domain, Resolv::DNS::Resource::IN::CNAME) .and_return([double(name: "domains-staging.gumroad.com")]) end it "returns success response" do expect(service.process).to eq(true) end end context "when there doesn't exist a CNAME record pointing to the correct domain" do before do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(domain, Resolv::DNS::Resource::IN::CNAME) .and_return([double(name: "wrong-domain.gumroad.com")]) end describe "domain ALIAS configuration" do before do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(CUSTOM_DOMAIN_CNAME, Resolv::DNS::Resource::IN::A) .and_return([double(address: "100.0.0.1"), double(address: "100.0.0.2")]) allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(CUSTOM_DOMAIN_STATIC_IP_HOST, Resolv::DNS::Resource::IN::A) .and_return([double(address: "100.0.0.10"), double(address: "100.0.0.20")]) end context "when the domain is pointed to CUSTOM_DOMAIN_CNAME using ALIAS records" do before do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(domain, Resolv::DNS::Resource::IN::A) .and_return([double(address: "100.0.0.1"), double(address: "100.0.0.2")]) end it "returns success response" do expect(service.process).to eq(true) end end context "when the domain is pointed to CUSTOM_DOMAIN_STATIC_IP_HOST using ALIAS records" do before do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(domain, Resolv::DNS::Resource::IN::A) .and_return([double(address: "100.0.0.20"), double(address: "100.0.0.10")]) end it "returns success response" do expect(service.process).to eq(true) end end context "when the domain is not pointed to either CUSTOM_DOMAIN_CNAME or CUSTOM_DOMAIN_STATIC_IP_HOST using ALIAS records" do before do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(domain, Resolv::DNS::Resource::IN::A) .and_return([double(address: "100.0.0.2")]) end it "returns error response" do expect(service.process).to eq(false) end end end end end context "when the domain is invalid" do let(:domain) { "http://example.com" } it "returns error response" do expect(service.process).to eq(false) end end end describe "#domains_pointed_to_gumroad" do before(:each) do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(anything, Resolv::DNS::Resource::IN::CNAME) .and_return([double(name: CUSTOM_DOMAIN_CNAME)]) end context "when it is a root domain" do it "returns the root domain and the one with www prefix" do expect(service.domains_pointed_to_gumroad).to eq ["example.com", "www.example.com"] end end context "when it's a domain with subdomain'" do let(:domain) { "test.example.com" } it "returns the domain" do expect(service.domains_pointed_to_gumroad).to eq ["test.example.com"] end end end describe "#has_valid_ssl_certificates?" do before(:each) do allow_any_instance_of(Resolv::DNS) .to receive(:getresources) .with(anything, Resolv::DNS::Resource::IN::CNAME) .and_return([double(name: CUSTOM_DOMAIN_CNAME)]) allow(SslCertificates::Base).to receive(:new).and_return(double(ssl_file_path: "path/cert")) s3_double = double("s3") allow(Aws::S3::Resource).to receive(:new).and_return(s3_double) s3_object = double("s3_object") allow(s3_double).to receive(:bucket).and_return(double(object: s3_object)) allow(s3_object).to receive(:exists?).and_return(true) allow(s3_object).to receive(:get).and_return(double(body: double(read: double))) allow(OpenSSL::X509::Certificate).to receive(:new).and_return(double(not_after: 5.days.from_now)) end it "returns true when valid SSL certificates are found for all associated domains" do expect(OpenSSL::X509::Certificate).to receive(:new).twice expect_any_instance_of(Redis::Namespace).to receive(:get).with("ssl_cert_check:example.com") expect_any_instance_of(Redis::Namespace).to receive(:set).with("ssl_cert_check:example.com", true, ex: 10.days) expect_any_instance_of(Redis::Namespace).to receive(:get).with("ssl_cert_check:www.example.com") expect_any_instance_of(Redis::Namespace).to receive(:set).with("ssl_cert_check:www.example.com", true, ex: 10.days) expect(service.has_valid_ssl_certificates?).to eq 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/purchase_search_service_spec.rb
spec/services/purchase_search_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe PurchaseSearchService do describe "#process" do it "can filter by seller" do purchase_1 = create(:purchase) purchase_2 = create(:purchase, link: purchase_1.link) # same seller as purchase_1 seller_1 = purchase_1.seller purchase_3 = create(:purchase) seller_2 = purchase_3.seller create(:purchase) index_model_records(Purchase) expect(get_records(seller: seller_1)).to match_array([purchase_1, purchase_2]) expect(get_records(seller: [seller_1, seller_2.id])).to match_array([purchase_1, purchase_2, purchase_3]) end it "can filter by buyer" do purchase_1 = create(:purchase, purchaser: create(:user)) purchaser_1 = purchase_1.purchaser purchase_2 = create(:purchase, purchaser: purchaser_1) purchase_3 = create(:purchase, purchaser: create(:user)) purchaser_2 = purchase_3.purchaser create(:purchase, purchaser: create(:user)) index_model_records(Purchase) expect(get_records(purchaser: purchaser_1)).to match_array([purchase_1, purchase_2]) expect(get_records(purchaser: [purchaser_1, purchaser_2.id])).to match_array([purchase_1, purchase_2, purchase_3]) end it "can filter by product, and exclude product" do product_1 = create(:product) purchase_1, purchase_2 = create_list(:purchase, 2, link: product_1) product_2 = create(:product) purchase_3 = create(:purchase, link: product_2) index_model_records(Purchase) expect(get_records(product: product_1)).to match_array([purchase_1, purchase_2]) expect(get_records(product: [product_1, product_2.id])).to match_array([purchase_1, purchase_2, purchase_3]) expect(get_records(exclude_product: product_1)).to match_array([purchase_3]) expect(get_records(exclude_product: [product_1, product_2.id])).to match_array([]) end it "can filter by variant, and exclude variant" do product = create(:product) category_1, category_2 = create_list(:variant_category, 2, link: product) variant_1, variant_2, variant_3 = create_list(:variant, 3, variant_category: category_1) variant_4 = create(:variant, variant_category: category_2) purchase_1 = create(:purchase, link: product, variant_attributes: [variant_1]) purchase_2 = create(:purchase, link: product, variant_attributes: [variant_2]) purchase_3 = create(:purchase, link: product, variant_attributes: [variant_3]) purchase_4 = create(:purchase, link: product, variant_attributes: [variant_3, variant_4]) index_model_records(Purchase) expect(get_records(variant: variant_3)).to match_array([purchase_3, purchase_4]) expect(get_records(variant: [variant_2, variant_3, variant_4.id])).to match_array([purchase_2, purchase_3, purchase_4]) expect(get_records(exclude_variant: variant_3)).to match_array([purchase_1, purchase_2]) expect(get_records(exclude_variant: [variant_1, variant_3.id])).to match_array([purchase_2]) end it "can exclude purchasers of a product or a variant" do # Typical usage: # - Seller X needs to see which sales were made to people who didn't buy their product X. # - Seller X needs to see which sales of product X were made to people who didn't buy the variant Y. product_1 = create(:product) variant_category = create(:variant_category, link: product_1) variant_1, variant_2, variant_3 = create_list(:variant, 3, variant_category:) seller = product_1.user product_2, product_3 = create_list(:product, 2, user: seller) customer_1 = create(:user) purchase_1 = create(:purchase, link: product_1, email: customer_1.email, variant_attributes: [variant_1]) _purchase_2 = create(:purchase, link: product_2, email: customer_1.email, purchaser: customer_1) _purchase_3 = create(:purchase, link: product_3, email: customer_1.email, purchaser: customer_1) purchase_4 = create(:purchase, link: product_1, variant_attributes: [variant_2]) index_model_records(Purchase) expect(get_records(seller:, exclude_purchasers_of_product: product_1)).to match_array([]) expect(get_records(seller:, exclude_purchasers_of_product: product_2)).to match_array([purchase_4]) expect(get_records(seller:, exclude_purchasers_of_product: product_3)).to match_array([purchase_4]) expect(get_records(seller:, product: product_1, exclude_purchasers_of_variant: variant_1)).to match_array([purchase_4]) expect(get_records(seller:, product: product_1, exclude_purchasers_of_variant: variant_2)).to match_array([purchase_1]) expect(get_records(seller:, product: product_1, exclude_purchasers_of_variant: variant_3)).to match_array([purchase_1, purchase_4]) end it "can filter by affiliate user" do purchase_1 = create(:purchase) affiliate_credit_1 = create(:affiliate_credit, purchase: purchase_1) purchase_2 = create(:purchase) affiliate_credit_2 = create(:affiliate_credit, purchase: purchase_2) index_model_records(Purchase) expect(get_records(affiliate_user: affiliate_credit_1.affiliate_user)).to match_array([purchase_1]) expect(get_records(affiliate_user: [affiliate_credit_1.affiliate_user, affiliate_credit_2.affiliate_user.id])).to match_array([purchase_1, purchase_2]) end it "can filter by revenue sharing user" do seller_purchase_1 = create(:purchase) seller_purchase_2 = create(:purchase, link: seller_purchase_1.link) user_1 = seller_purchase_1.seller seller_purchase_3 = create(:purchase) user_2 = seller_purchase_3.seller create(:purchase) affiliate_purchase_1 = create(:purchase) create(:affiliate_credit, purchase: affiliate_purchase_1, affiliate_user: user_1) affiliate_purchase_2 = create(:purchase) create(:affiliate_credit, purchase: affiliate_purchase_2, affiliate_user: user_2) create(:affiliate_credit) user_1_purchases = [seller_purchase_1, seller_purchase_2, affiliate_purchase_1] user_2_purchases = [seller_purchase_3, affiliate_purchase_2] index_model_records(Purchase) expect(get_records(revenue_sharing_user: user_1)).to match_array(user_1_purchases) expect(get_records(revenue_sharing_user: user_2)).to match_array(user_2_purchases) expect(get_records(revenue_sharing_user: [user_1, user_2])).to match_array(user_1_purchases + user_2_purchases) end it "can exclude purchases" do purchase_1, purchase_2 = create_list(:purchase, 2) index_model_records(Purchase) expect(get_records(exclude_purchase: purchase_1)).to match_array([purchase_2]) expect(get_records(exclude_purchase: [purchase_1, purchase_2.id])).to match_array([]) end it "can filter by multiple variants and products" do product_1, product_2, product_3 = create_list(:product, 3) category_1 = create(:variant_category, link: product_1) category_2 = create(:variant_category, link: product_2) variant_1, variant_2 = create_list(:variant, 2, variant_category: category_1) variant_3, variant_4 = create_list(:variant, 2, variant_category: category_2) purchase_1 = create(:purchase, link: product_1, variant_attributes: [variant_1]) purchase_2 = create(:purchase, link: product_1, variant_attributes: [variant_2]) purchase_3 = create(:purchase, link: product_2, variant_attributes: [variant_3]) purchase_4 = create(:purchase, link: product_2, variant_attributes: [variant_4]) purchase_5 = create(:purchase, link: product_3) index_model_records(Purchase) expect(get_records(any_products_or_variants: { variants: [variant_1, variant_3] })).to match_array([purchase_1, purchase_3]) expect(get_records(any_products_or_variants: { variants: variant_2, products: [product_3] })).to match_array([purchase_2, purchase_5]) expect(get_records(any_products_or_variants: { variants: variant_4, products: [product_1, product_2] })).to match_array([purchase_1, purchase_2, purchase_3, purchase_4]) end it "can exclude non-original subscription and archived original subscription purchases" do purchase_1 = create(:membership_purchase, created_at: 2.days.ago) _purchase_2 = purchase_1.subscription.charge! purchase_3 = create(:membership_purchase, created_at: 2.days.ago) _purchase_4 = purchase_3.subscription.charge! purchase_5 = create(:purchase) _purchase_6 = create(:membership_purchase, created_at: 3.days.ago, is_archived_original_subscription_purchase: true) index_model_records(Purchase) expect(get_records(exclude_non_original_subscription_purchases: true)).to match_array([purchase_1, purchase_3, purchase_5]) end it "can exclude not_charged purchases that are not free trials" do purchase = create(:free_trial_membership_purchase) create(:purchase, purchase_state: "not_charged") index_model_records(Purchase) expect(get_records(exclude_not_charged_non_free_trial_purchases: true)).to match_array([purchase]) end it "can exclude deactivated subscriptions" do purchase_1 = create(:membership_purchase, created_at: 2.days.ago) purchase_2 = create(:membership_purchase, created_at: 2.days.ago) subscription = purchase_2.subscription subscription.deactivate! index_model_records(Purchase) expect(get_records(exclude_deactivated_subscriptions: true)).to match_array([purchase_1]) end it "can exclude cancelled subscriptions, or pending cancellation" do purchase_1 = create(:membership_purchase) create(:membership_purchase).subscription.update!(cancelled_at: 2.days.ago) create(:membership_purchase).subscription.update!(cancelled_at: 2.days.from_now) index_model_records(Purchase) expect(get_records(exclude_cancelled_or_pending_cancellation_subscriptions: true)).to match_array([purchase_1]) end it "can exclude refunded" do purchase_1 = create(:purchase, stripe_refunded: nil) purchase_2 = create(:purchase, stripe_refunded: false) _purchase_3 = create(:purchase, stripe_refunded: true) index_model_records(Purchase) expect(get_records(exclude_refunded: true)).to match_array([purchase_1, purchase_2]) end it "can exclude refunded-except-subscriptions" do purchase_1 = create(:purchase) _purchase_2 = create(:purchase, stripe_refunded: true) purchase_3 = create(:membership_purchase, stripe_refunded: true) index_model_records(Purchase) expect(get_records(exclude_refunded_except_subscriptions: true)).to match_array([purchase_1, purchase_3]) end it "can exclude unreversed charged back" do purchase_1 = create(:purchase) _purchase_2 = create(:purchase, chargeback_date: Time.current) purchase_3 = create(:purchase, chargeback_date: Time.current, chargeback_reversed: true) index_model_records(Purchase) expect(get_records(exclude_unreversed_chargedback: true)).to match_array([purchase_1, purchase_3]) end it "can exclude purchases from buyers that can't be contacted" do purchase_1 = create(:purchase) _purchase_2 = create(:purchase, can_contact: false) index_model_records(Purchase) expect(get_records(exclude_cant_contact: true)).to match_array([purchase_1]) end it "can exclude gifters or giftees" do purchase_1 = create(:purchase) gift = create(:gift) product = gift.link purchase_2 = create(:purchase, link: product, is_gift_sender_purchase: true) purchase_3 = create(:purchase, link: product, is_gift_receiver_purchase: true) index_model_records(Purchase) expect(get_records(exclude_gifters: true)).to match_array([purchase_1, purchase_3]) expect(get_records(exclude_giftees: true)).to match_array([purchase_1, purchase_2]) end it "can exclude non-successful authorization purchases" do # Without preorder purchase_1 = create(:purchase) purchase_2 = create(:failed_purchase) # With preorder which ended up concluding successfully preorder = create(:preorder) product = preorder.link purchase_3 = create(:purchase, purchase_state: "preorder_concluded_successfully", link: product) purchase_3.update!(preorder:) create(:failed_purchase, link: product, preorder:) # purchase_4 create(:purchase, link: product, preorder:) # purchase_5 # With preorder which didn't conclude yet preorder = create(:preorder) product = preorder.link purchase_6 = create(:preorder_authorization_purchase, link: product) purchase_6.update!(preorder:) create(:failed_purchase, link: product, preorder:) # purchase_7 # With failed preorder preorder = create(:preorder) purchase_8 = create(:purchase, purchase_state: "preorder_authorization_failed", link: preorder.link) purchase_8.update!(preorder:) # With preorder which failed to conclude preorder = create(:preorder) purchase_9 = create(:purchase, purchase_state: "preorder_concluded_unsuccessfully", link: preorder.link) purchase_9.update!(preorder:) index_model_records(Purchase) expect(get_records(exclude_non_successful_preorder_authorizations: true)).to match_array([ purchase_1, purchase_2, purchase_3, purchase_6 ]) end it "can filter by price ranges" do purchase_1 = create(:purchase, price_cents: 0) purchase_2 = create(:purchase, price_cents: 60) purchase_3 = create(:purchase, price_cents: 100) purchase_4 = create(:purchase, price_cents: 101) index_model_records(Purchase) expect(get_records(price_greater_than: 0)).to match_array([purchase_2, purchase_3, purchase_4]) expect(get_records(price_greater_than: 100)).to match_array([purchase_4]) expect(get_records(price_less_than: 0)).to match_array([]) expect(get_records(price_less_than: 100)).to match_array([purchase_1, purchase_2]) expect(get_records(price_greater_than: 40, price_less_than: 100)).to match_array([purchase_2]) end it "can filter by date ranges" do travel_to(Time.current) purchase_1 = create(:purchase, created_at: 15.days.ago) purchase_2 = create(:purchase, created_at: 7.days.ago) purchase_3 = create(:purchase, created_at: 3.days.ago) index_model_records(Purchase) expect(get_records(created_after: 9.days.ago)).to match_array([purchase_2, purchase_3]) expect(get_records(created_after: 1.day.ago)).to match_array([]) expect(get_records(created_before: 20.days.ago)).to match_array([]) expect(get_records(created_before: 9.days.ago)).to match_array([purchase_1]) expect(get_records(created_after: 8.days.ago, created_before: 6.days.ago)).to match_array([purchase_2]) expect(get_records(created_after: purchase_1.created_at)).not_to include(purchase_1) expect(get_records(created_on_or_after: purchase_1.created_at)).to match_array([purchase_1, purchase_2, purchase_3]) expect(get_records(created_before: purchase_1.created_at)).not_to include(purchase_1) expect(get_records(created_on_or_before: purchase_1.created_at)).to eq([purchase_1]) end it "can filter by country" do purchase_1 = create(:physical_purchase) purchase_2 = create(:physical_purchase, country: nil, ip_country: "Mexico") purchase_3 = create(:physical_purchase, country: "South Korea", ip_country: "South Korea") purchase_4 = create(:physical_purchase, country: "Korea, Republic of", ip_country: "South Korea") index_model_records(Purchase) expect(get_records(country: "United States")).to match_array([purchase_1]) expect(get_records(country: "Mexico")).to match_array([purchase_2]) expect(get_records(country: ["South Korea", "Korea, Republic of"])).to match_array([purchase_3, purchase_4]) end it "can filter by email" do purchase_1 = create(:purchase, email: "john@example.com") purchase_2 = create(:purchase, email: "rosalina@example.com") purchase_3 = create(:purchase, email: "john@example.com") index_model_records(Purchase) expect(get_records(email: "john@example.com")).to match_array([purchase_1, purchase_3]) expect(get_records(email: "John@example.com")).to match_array([purchase_1, purchase_3]) expect(get_records(email: "rosalina@example.com")).to match_array([purchase_2]) # Check that we're actually doing an exact match expect(get_records(email: "rosalina@example")).to match_array([]) end it "can filter by state" do purchase_1 = create(:purchase) purchase_2 = create(:test_purchase) _purchase_3 = create(:purchase_in_progress) purchase_4 = create(:purchase, purchase_state: "gift_receiver_purchase_successful") index_model_records(Purchase) expect(get_records(state: "successful")).to match_array([purchase_1]) expect(get_records(state: ["successful", "test_successful"])).to match_array([purchase_1, purchase_2]) expect(get_records(state: ["gift_receiver_purchase_successful"])).to match_array([purchase_4]) end it "can filter by archival state" do purchase_1 = create(:purchase) purchase_2 = create(:purchase, is_archived: true) index_model_records(Purchase) expect(get_records).to match_array([purchase_1, purchase_2]) expect(get_records(archived: true)).to match_array([purchase_2]) expect(get_records(archived: false)).to match_array([purchase_1]) end it "can filter by recommended state" do purchase_1 = create(:purchase) purchase_2 = create(:purchase, was_product_recommended: true) index_model_records(Purchase) expect(get_records).to match_array([purchase_1, purchase_2]) expect(get_records(recommended: true)).to match_array([purchase_2]) expect(get_records(recommended: false)).to match_array([purchase_1]) end it "can filter by is_bundle_product_purchase" do purchase1 = create(:purchase, is_bundle_product_purchase: true) purchase2 = create(:purchase) index_model_records(Purchase) expect(get_records).to match_array([purchase1, purchase2]) expect(get_records(exclude_bundle_product_purchases: true)).to match_array([purchase2]) expect(get_records(exclude_bundle_product_purchases: false)).to match_array([purchase1, purchase2]) end it "can filter by is_commission_completion_purchase" do purchase1 = create(:purchase, is_commission_completion_purchase: true) purchase2 = create(:purchase) index_model_records(Purchase) expect(get_records).to match_array([purchase1, purchase2]) expect(get_records(exclude_commission_completion_purchases: true)).to match_array([purchase2]) expect(get_records(exclude_commission_completion_purchases: false)).to match_array([purchase1, purchase2]) end it "can apply some native ES params" do purchase_1 = create(:purchase, price_cents: 3) _purchase_2 = create(:purchase, price_cents: 1) _purchase_3 = create(:purchase, price_cents: 5) index_model_records(Purchase) response = described_class.new(sort: { price_cents: :asc }, from: 1, size: 1).process expect(response.results.total).to eq(3) expect(response.records.load).to match_array([purchase_1]) end it "supports fulltext/autocomplete search as seller" do purchase_1 = create(:purchase, email: "xavier@loic.com", full_name: "Joelle", card_type: CardType::PAYPAL, card_visual: "xavier@paypal.com") purchase_2 = create(:purchase, email: "rebecca+test@victoria.com", full_name: "Jo Elizabeth") purchase_3 = create(:purchase, email: "rebecca.test@victoria.com", full_name: "Joelle Elizabeth") purchase_4 = create(:purchase, email: "rebecca@victoria.com", full_name: "Joe") purchase_5 = create(:purchase, email: "StevenPaulJobs@apple.com", full_name: "") purchase_6 = create(:purchase, :with_license) index_model_records(Purchase) expect(get_records(seller_query: "xav")).to match_array([purchase_1]) expect(get_records(seller_query: "joel")).to match_array([purchase_1, purchase_3]) expect(get_records(seller_query: "rebecca+test")).to match_array([purchase_2]) expect(get_records(seller_query: "rebecca.test")).to match_array([purchase_3]) expect(get_records(seller_query: "rebecca")).to match_array([purchase_2, purchase_3, purchase_4]) expect(get_records(seller_query: "eliza")).to match_array([purchase_2, purchase_3]) # test support for non-exact search expect(get_records(seller_query: "Joelle Elizabeth")).to match_array([purchase_1, purchase_2, purchase_3]) # test support for exact name search expect(get_records(seller_query: "\"Joelle Elizabeth\"")).to match_array([purchase_3]) # test support for exact search beyond max_ngram expect(get_records(seller_query: "rebecca.test@victoria.com")).to match_array([purchase_3]) # test support for exact email search wth different case expect(get_records(seller_query: "Rebecca.test@victoria.com")).to match_array([purchase_3]) expect(get_records(seller_query: "Xavier@paypal.com")).to match_array([purchase_1]) expect(get_records(seller_query: "StevenPaulJobs@apple.com")).to match_array([purchase_5]) expect(get_records(seller_query: "stevenpauljobs@apple.com")).to match_array([purchase_5]) # test support for email's domain name search expect(get_records(seller_query: "apple.com")).to match_array([purchase_5]) expect(get_records(seller_query: "vic")).to match_array([purchase_2, purchase_3, purchase_4]) # test support to paypal email exact search expect(get_records(seller_query: "xavier@paypal.com")).to match_array([purchase_1]) expect(get_records(seller_query: "paypal.com")).to match_array([]) # test scoring expect(get_records(seller_query: "Joelle Elizabeth")).to eq([purchase_3, purchase_1, purchase_2]) # test support for license key search expect(get_records(seller_query: purchase_6.license.serial)).to match_array([purchase_6]) end it "supports fulltext/autocomplete search as a buyer" do seller_1 = create(:user, name: "Daniel Vassallo") product_1 = create(:product, name: "Everyone Can Build a Twitter Audience", user: seller_1, description: "Last year I left a cushy job at <strong>Amazon</strong> to work for myself.") product_2 = create(:product, name: "Profit and Loss", user: seller_1, description: "I will show you exactly how I'm executing my Portfolio of Small Bets strategy.") seller_2 = create(:user, name: "Wong Fu Productions") product_3 = create(:product, name: "Strangers Never Again", user: seller_2, description: "Josh and Marissa were in love a decade ago, in their early 20s, and since then, life took them in very different directions.") purchase_1 = create(:purchase, link: product_1) purchase_2 = create(:purchase, link: product_2) purchase_3 = create(:purchase, link: product_3) index_model_records(Purchase) # test seller's name expect(get_records(buyer_query: "daniel vassallo")).to match_array([purchase_1, purchase_2]) expect(get_records(buyer_query: "daniel")).to match_array([purchase_1, purchase_2]) expect(get_records(buyer_query: "dan")).to match_array([purchase_1, purchase_2]) expect(get_records(buyer_query: "wong fu")).to match_array([purchase_3]) # test product's name expect(get_records(buyer_query: "profit")).to match_array([purchase_2]) # test product's description expect(get_records(buyer_query: "amazon")).to match_array([purchase_1]) expect(get_records(buyer_query: "amaz")).to match_array([]) # we shouldn't auto-complete description: too large & irrelevant expect(get_records(buyer_query: "small bets")).to match_array([purchase_2]) expect(get_records(buyer_query: "love")).to match_array([purchase_3]) end end describe "#query" do it "is a shortcut to the query part of the request body" do service = described_class.new(seller: 123) expect(service.query).to eq(service.body[:query]) end end describe ".search" do it "is a shortcut to initialization + process" do result_double = double options = { a: 1, b: 2 } instance_double = double(process: result_double) expect(described_class).to receive(:new).with(options).and_return(instance_double) expect(described_class.search(options)).to eq(result_double) end end def get_records(options = {}) service = described_class.new(options) keys_and_values = deep_to_a(service.body.deep_stringify_keys).flatten expect(JSON.load(JSON.dump(keys_and_values))).to eq(keys_and_values) # body values must be JSON safe (no Time, etc.) service.process.records.load end def deep_to_a(hash) hash.map do |v| v.is_a?(Hash) || v.is_a?(Array) ? deep_to_a(v) : v end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/mvn_validation_service_spec.rb
spec/services/mvn_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe MvaValidationService do before do @vatstack_response = { "id" => "5e5a894fa5807929777ad9c7", "active" => true, "company_address" => "Søndre gate 15, 7011 TRONDHEIM", "company_name" => "DANSKE BANK", "company_type" => "NUF", "consultation_number" => nil, "valid" => true, "valid_format" => true, "vat_number" => "977074010", "country_code" => "NO", "query" => "977074010MVA", "type" => "no_vat", "requested" => "2020-02-29T00:00:00.000Z", "created" => "2020-02-29T15:54:55.029Z", "updated" => "2020-02-29T15:54:55.029Z" } end it "returns true when valid mva is provided" do mva_id = "977074010MVA" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "no_vat", "query" => mva_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response) expect(described_class.new(mva_id).process).to be(true) end it "returns false when valid mva is provided, but government services are down" do mva_id = "977074010MVA" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "no_vat", "query" => mva_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response.merge("valid" => nil)) expect(described_class.new(mva_id).process).to be(false) end it "returns false when nil mva is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when blank mva is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when mva with invalid format is provided" do mva_id = "some-invalid-id" query_response = "SOMEINVALIDID" invalid_input_response = { "code" => "INVALID_INPUT", "query" => query_response, "valid" => false, "valid_format" => false } expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "no_vat", "query" => mva_id }, headers: hash_including("X-API-KEY")).and_return(invalid_input_response) expect(described_class.new(mva_id).process).to be(false) end it "returns false when invalid mva is provided" do mva_id = "11111111111" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "no_vat", "query" => mva_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response.merge("valid" => false)) expect(described_class.new(mva_id).process).to be(false) end it "returns false when inactive mva is provided" do mva_id = "12345678901" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "no_vat", "query" => mva_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response.merge("active" => false)) expect(described_class.new(mva_id).process).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/trn_validation_service_spec.rb
spec/services/trn_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe TrnValidationService do it "returns true when valid TRN is provided" do trn_id = "123456789012345" expect(described_class.new(trn_id).process).to be(true) end it "returns false when nil TRN is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when blank TRN is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when TRN with invalid length is provided" do expect(described_class.new("12345").process).to be(false) expect(described_class.new("1234567890123456").process).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/redis_key_spec.rb
spec/services/redis_key_spec.rb
# frozen_string_literal: true require "spec_helper" describe RedisKey do describe ".ai_request_throttle" do it "returns a properly formatted redis key with user id" do user_id = 123 key = described_class.ai_request_throttle(user_id) expect(key).to eq("ai_request_throttle:123") end it "handles string user ids" do user_id = "456" key = described_class.ai_request_throttle(user_id) expect(key).to eq("ai_request_throttle:456") end end describe ".acme_challenge" do it "returns a properly formatted redis key with token" do token = "abc123" key = described_class.acme_challenge(token) expect(key).to eq("acme_challenge:abc123") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/stripe_tax_forms_api_spec.rb
spec/services/stripe_tax_forms_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe StripeTaxFormsApi, vcr: { cassette_name: "StripeTaxFormsApi/tax_forms" } do let(:stripe_account_id) { "acct_1234567890" } let(:form_type) { "us_1099_k" } let(:year) { 2024 } let(:service) { described_class.new(stripe_account_id:, form_type:, year:) } describe "#tax_forms_by_year" do it "returns tax forms grouped by year" do result = service.tax_forms_by_year expect(result.keys).to eq([2024, 2023, 2022, 2021, 2020]) tax_form_2024 = result[2024] expect(tax_form_2024.id).to eq("taxform_1") expect(tax_form_2024.object).to eq("tax.form") expect(tax_form_2024.type).to eq("us_1099_k") expect(tax_form_2024.livemode).to be(true) expect(tax_form_2024.payee.account).to eq("acct_1234567890") expect(tax_form_2024.us_1099_k.reporting_year).to eq(2024) end it "raises error for invalid form type" do invalid_service = described_class.new(stripe_account_id:, form_type: "invalid_type", year:) expect { invalid_service.tax_forms_by_year }.to raise_error(RuntimeError, "Invalid tax form type: invalid_type") end it "returns empty hash on Stripe API error" do allow(Stripe).to receive(:raw_request).and_raise(Stripe::APIConnectionError.new("Connection failed")) expect(Bugsnag).to receive(:notify).with(instance_of(Stripe::APIConnectionError)) result = service.tax_forms_by_year expect(result).to eq({}) end end describe "#download_tax_form" do it "downloads the tax form PDF for the specified year" do allow(HTTParty).to receive(:get).and_yield("PDF content") result = service.download_tax_form expect(result).to be_a(Tempfile) expect(result.path).to include("tax_form_us_1099_k_2024_acct_1234567890") expect(result.path).to end_with(".pdf") expect(HTTParty).to have_received(:get).with( "https://files.stripe.com/v1/tax/forms/taxform_1/pdf", hash_including(headers: hash_including("Authorization" => /Bearer/)) ) result.close result.unlink end it "returns nil when tax form not found for the year" do service_2019 = described_class.new(stripe_account_id:, form_type:, year: 2019) result = service_2019.download_tax_form expect(result).to be_nil end it "returns nil when there is an error" do allow(HTTParty).to receive(:get).and_raise(HTTParty::Error.new("Connection failed")) expect(Bugsnag).to receive(:notify).with(instance_of(HTTParty::Error)) result = service.download_tax_form expect(result).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/product_indexing_service_spec.rb
spec/services/product_indexing_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductIndexingService do before do @product = create(:product) end describe "#perform" do it "can index documents" do # Empty the index for the purpose of this test recreate_model_indices(Link) described_class.perform(product: @product, action: "index") Link.__elasticsearch__.refresh_index! # This would have raised Elasticsearch::Transport::Transport::Errors::NotFound if the document wasn't found expect { EsClient.get(index: Link.index_name, id: @product.id) }.not_to raise_error end it "can update documents" do Link.__elasticsearch__.refresh_index! # Change the name without triggering callbacks for the purpose of this test @product.update_column(:name, "updated name") described_class.perform(product: @product, action: "update", attributes_to_update: ["name"]) Link.__elasticsearch__.refresh_index! expect(EsClient.get(index: Link.index_name, id: @product.id).dig("_source", "name")).to eq("updated name") end it "raises error on failure" do # Empty the index for the purpose of this test recreate_model_indices(Link) expect do described_class.perform(product: @product, action: "update", attributes_to_update: ["name"]) end.to raise_error(Elasticsearch::Transport::Transport::Errors::NotFound) end context "when on_failure = :async" do it "queues a sidekiq job and does not raise an error" do # Empty the index for the purpose of this test recreate_model_indices(Link) expect do described_class.perform(product: @product, action: "update", attributes_to_update: ["name"], on_failure: :async) end.not_to raise_error expect(SendToElasticsearchWorker).to have_enqueued_sidekiq_job(@product.id, "update", ["name"]) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/email_redactor_service_spec.rb
spec/services/email_redactor_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe EmailRedactorService do it "redacts short emails" do expect(EmailRedactorService.redact("foo@bar.baz")).to eq("f*o@b**.baz") end it "redacts 1 char emails" do expect(EmailRedactorService.redact("a@b.co")).to eq("a@b.co") end it "redacts emails with symbols" do expect(EmailRedactorService.redact("a-test+with_symbols@valid-domain.com")).to eq("a*****************s@v***********.com") end it "only keeps the TLD on multi-part TLDs" do expect(EmailRedactorService.redact("john@example.co.uk")).to eq("j**n@e*********.uk") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/firs_tin_validation_service_spec.rb
spec/services/firs_tin_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe FirsTinValidationService do it "returns true when valid FIRS TIN is provided" do firs_tin = "12345678-1234" expect(described_class.new(firs_tin).process).to be(true) end it "returns false when nil FIRS TIN is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when blank FIRS TIN is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when FIRS TIN with invalid format is provided" do expect(described_class.new("123456781234").process).to be(false) expect(described_class.new("12345678-123").process).to be(false) expect(described_class.new("1234567-1234").process).to be(false) expect(described_class.new("abcdefgh-1234").process).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/tax_id_validation_service_spec.rb
spec/services/tax_id_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe TaxIdValidationService, :vcr do let(:tax_id) { "528491" } let(:country_code) { "IS" } it "returns true when a valid tax id is provided" do expect(described_class.new(tax_id, country_code).process).to be(true) end it "returns false when the tax id is nil" do expect(described_class.new(nil, country_code).process).to be(false) end it "returns false when the tax id is empty" do expect(described_class.new("", country_code).process).to be(false) end it "returns false when the country code is nil" do expect(described_class.new(tax_id, nil).process).to be(false) end it "returns false when the country code is empty" do expect(described_class.new(tax_id, "").process).to be(false) end it "returns false when the tax id is not valid" do expect(described_class.new("1234567890", country_code).process).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/black_friday_stats_service_spec.rb
spec/services/black_friday_stats_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe BlackFridayStatsService do describe ".calculate_stats" do it "returns placeholder values with zero counts" do stats = described_class.calculate_stats expect(stats[:active_deals_count]).to eq(0) expect(stats[:revenue_cents]).to eq(0) expect(stats[:average_discount_percentage]).to eq(0) end end describe ".fetch_stats" do before do Rails.cache.clear end after do Rails.cache.clear end it "caches the stats and doesn't recalculate on subsequent calls" do expect(described_class).to receive(:calculate_stats).once.and_call_original first_result = described_class.fetch_stats second_result = described_class.fetch_stats expect(first_result).to eq(second_result) expect(first_result[:active_deals_count]).to eq(0) expect(first_result[:revenue_cents]).to eq(0) expect(first_result[:average_discount_percentage]).to eq(0) end it "uses the correct cache key and expiration" do expect(Rails.cache).to receive(:fetch).with( "black_friday_stats", expires_in: 10.minutes ).and_call_original described_class.fetch_stats end it "stores stats in Rails cache" do described_class.fetch_stats cached_value = Rails.cache.read("black_friday_stats") expect(cached_value).to be_present expect(cached_value[:active_deals_count]).to eq(0) expect(cached_value[:revenue_cents]).to eq(0) expect(cached_value[:average_discount_percentage]).to eq(0) end it "recalculates stats after cache expires" do travel_to Time.current do first_result = described_class.fetch_stats expect(first_result[:active_deals_count]).to eq(0) travel 11.minutes expect(described_class).to receive(:calculate_stats).and_call_original new_result = described_class.fetch_stats expect(new_result[:active_deals_count]).to eq(0) end end it "handles cache deletion and recalculates" do first_result = described_class.fetch_stats expect(first_result[:active_deals_count]).to eq(0) Rails.cache.delete("black_friday_stats") expect(described_class).to receive(:calculate_stats).and_call_original new_result = described_class.fetch_stats expect(new_result[:active_deals_count]).to eq(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/user_custom_domain_request_service_spec.rb
spec/services/user_custom_domain_request_service_spec.rb
# frozen_string_literal: true describe UserCustomDomainRequestService do describe "#valid?" do let(:request) { double("request") } it "returns false when request is from Gumroad domain" do allow(request).to receive(:host).and_return("app.test.gumroad.com") expect(UserCustomDomainRequestService.valid?(request)).to eq(false) end it "returns false when request is from Discover domain" do allow(request).to receive(:host).and_return("test.gumroad.com") expect(UserCustomDomainRequestService.valid?(request)).to eq(false) end it "returns true when request is from a custom domain" do allow(request).to receive(:host).and_return("example.com") expect(UserCustomDomainRequestService.valid?(request)).to eq(true) end it "returns true when request is from Gumroad subdomain" do allow(request).to receive(:host).and_return("example.test.gumroad.com") expect(UserCustomDomainRequestService.valid?(request)).to eq(true) end it "returns false when request is a product custom domain" do create(:custom_domain, user: nil, product: create(:product), domain: "product.com") allow(request).to receive(:host).and_return("product.com") expect(UserCustomDomainRequestService.valid?(request)).to eq(false) end it "returns false when request is a product custom domain with a www prefix" do create(:custom_domain, user: nil, product: create(:product), domain: "product.com") allow(request).to receive(:host).and_return("www.product.com") expect(UserCustomDomainRequestService.valid?(request)).to eq(false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/email_suppression_manager_spec.rb
spec/services/email_suppression_manager_spec.rb
# frozen_string_literal: true require "spec_helper" describe EmailSuppressionManager, :vcr do let(:email) { "sam@example.com" } describe "#unblock_email" do let(:lists) { [:bounces, :spam_reports] } it "scans all lists even if the email is found in one of the lists in between" do allow_any_instance_of(SendGrid::Client).to receive_message_chain(:bounces, :_, :delete, :status_code).and_return(204) lists.each do |list| expect_any_instance_of(SendGrid::Client).to receive_message_chain(list, :_, :delete, :status_code) end described_class.new(email).unblock_email end context "when suppressed email is found in any of the lists" do before do allow_any_instance_of(SendGrid::Client).to receive_message_chain(:spam_reports, :_, :delete, :status_code).and_return(204) end it "returns true" do expect(described_class.new(email).unblock_email).to eq(true) end end context "when suppressed email is not found in any list" do it "returns false" do expect(described_class.new(email).unblock_email).to eq(false) end end end describe "#reason_for_suppression" do it "returns bulleted list of reasons for suppression" do sample_suppression_response = [{ created: 1683811050, email:, reason: "550 5.1.1 Sample reason", status: "5.1.1" }] allow_any_instance_of(SendGrid::Client).to receive_message_chain(:bounces, :_, :get, :parsed_body).and_return(sample_suppression_response) expect(described_class.new(email).reasons_for_suppression).to include(gumroad: [{ list: :bounces, reason: "550 5.1.1 Sample reason" }]) end context "when SendGrid response is not a array of hashes" do it "notifies Bugsnag" do allow_any_instance_of(SendGrid::Client).to receive_message_chain(:bounces, :_, :get, :parsed_body).and_return("sample") expect(Bugsnag).to receive(:notify).at_least(:once) described_class.new(email).reasons_for_suppression 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/tip_options_services_spec.rb
spec/services/tip_options_services_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe TipOptionsService, type: :service do describe ".get_tip_options" do context "when Redis has valid tip options" do before do $redis.set(RedisKey.tip_options, "[10, 20, 30]") end it "returns the parsed tip options" do expect(described_class.get_tip_options).to eq([10, 20, 30]) end end context "when Redis has invalid JSON" do before do $redis.set(RedisKey.tip_options, "invalid_json") end it "returns the default tip options" do expect(described_class.get_tip_options).to eq(TipOptionsService::DEFAULT_TIP_OPTIONS) end end context "when Redis has invalid tip options" do before do $redis.set(RedisKey.tip_options, '[10,"bad",20]') end it "returns the default tip options" do expect(described_class.get_tip_options).to eq(TipOptionsService::DEFAULT_TIP_OPTIONS) end end context "when Redis has no tip options" do it "returns the default tip options" do expect(described_class.get_tip_options).to eq(TipOptionsService::DEFAULT_TIP_OPTIONS) end end end describe ".set_tip_options" do context "when options are valid" do it "sets the tip options in Redis" do described_class.set_tip_options([5, 15, 25]) expect($redis.get(RedisKey.tip_options)).to eq("[5,15,25]") end end context "when options are invalid" do it "raises an ArgumentError" do expect { described_class.set_tip_options("invalid") }.to raise_error(ArgumentError, "Tip options must be an array of integers") end end end describe ".get_default_tip_option" do context "when Redis has a valid default tip option" do before do $redis.set(RedisKey.default_tip_option, "20") end it "returns the default tip option" do expect(described_class.get_default_tip_option).to eq(20) end end context "when Redis has an invalid default tip option" do before do $redis.set(RedisKey.default_tip_option, "invalid") end it "returns the default default tip option" do expect(described_class.get_default_tip_option).to eq(TipOptionsService::DEFAULT_DEFAULT_TIP_OPTION) end end context "when Redis has no default tip option" do it "returns the default default tip option" do expect(described_class.get_default_tip_option).to eq(TipOptionsService::DEFAULT_DEFAULT_TIP_OPTION) end end end describe ".set_default_tip_option" do context "when option is valid" do it "sets the default tip option in Redis" do described_class.set_default_tip_option(10) expect($redis.get(RedisKey.default_tip_option)).to eq("10") end end context "when option is invalid" do it "raises an ArgumentError" do expect { described_class.set_default_tip_option("invalid") }.to raise_error(ArgumentError, "Default tip option must be an integer") 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/notion_api_spec.rb
spec/services/notion_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe NotionApi, :vcr do let(:user) { create(:user, email: "user@example.com") } describe "#get_bot_token" do before do allow(GlobalConfig).to receive(:get).and_return(nil) allow(GlobalConfig).to receive(:get).with("NOTION_OAUTH_CLIENT_ID").and_return("id-1234") allow(GlobalConfig).to receive(:get).with("NOTION_OAUTH_CLIENT_SECRET").and_return("secret-1234") end it "retrieves Notion access token" do result = described_class.new.get_bot_token(code: "03a0066c-f0cf-442c-bcd9-sample", user:) expect(result.parsed_response).to include( "access_token" => "secret_cKEExFXDe4r0JxyDDwdqhO9rpMKJ_SAMPLE", "bot_id" => "e511ea88-8c43-410d-848f-0e2804aab14d", "token_type" => "bearer" ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/gst_validation_service_spec.rb
spec/services/gst_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe GstValidationService do it "returns true when valid a gst id is provided" do gst_id = "T9100001B" success_response = { "returnCode" => "10", "data" => { "gstRegistrationNumber" => "T9100001B", "name" => "GUMROAD, INC.", "RegisteredFrom" => "2020-01-01T00:00:00", "Status" => "Registered", "Remarks" => "Currently registered under Simplified Pay-only Regime" }, "info" => { "fieldInfoList" => [] } } expect(HTTParty).to receive(:post).with("https://apisandbox.iras.gov.sg/iras/sb/GSTListing/SearchGSTRegistered", timeout: 5, body: "{\"clientID\":\"#{IRAS_API_ID}\",\"regID\":\"#{gst_id}\"}", headers: hash_including("X-IBM-Client-Secret")).and_return(success_response) expect(described_class.new(gst_id).process).to be(true) end it "returns false when nil gst id is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when a blank gst id is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when a valid gst id is provided, but IRAS returns a 500" do gst_id = "T9100001B" internal_error_response = { "httpCode" => "500", "httpMessage" => "Internal Server Error", "moreInformation" => "can't come to the phone right now, leave a message" } expect(HTTParty).to receive(:post).with("https://apisandbox.iras.gov.sg/iras/sb/GSTListing/SearchGSTRegistered", timeout: 5, body: "{\"clientID\":\"#{IRAS_API_ID}\",\"regID\":\"#{gst_id}\"}", headers: hash_including("X-IBM-Client-Secret")).and_return(internal_error_response) expect(described_class.new(gst_id).process).to be(false) end it "returns false when IRAS cannot find a match for the provided gst id" do gst_id = "M90379350P" not_found_response = { "returnCode " => "20", "info" => { "fieldInfoList" => [], "message" => "No match data found", "messageCode" => "400033" } } expect(HTTParty).to receive(:post).with("https://apisandbox.iras.gov.sg/iras/sb/GSTListing/SearchGSTRegistered", timeout: 5, body: "{\"clientID\":\"#{IRAS_API_ID}\",\"regID\":\"#{gst_id}\"}", headers: hash_including("X-IBM-Client-Secret")).and_return(not_found_response) expect(described_class.new(gst_id).process).to be(false) end it "returns false when a gst id is provided with an invalid format" do gst_id = "asdf" invalid_input_response = { "returnCode" => "30", "info" => { "fieldInfoList" => [ { "field" => "regId", "message" => "Value is not valid" } ], "message" => "Arguments Error", "messageCode" => "850301" } } expect(HTTParty).to receive(:post).with("https://apisandbox.iras.gov.sg/iras/sb/GSTListing/SearchGSTRegistered", timeout: 5, body: "{\"clientID\":\"#{IRAS_API_ID}\",\"regID\":\"#{gst_id}\"}", headers: hash_including("X-IBM-Client-Secret")).and_return(invalid_input_response) expect(described_class.new(gst_id).process).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/forfeit_balance_service_spec.rb
spec/services/forfeit_balance_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe ForfeitBalanceService do let(:user) { create(:named_user) } let(:merchant_account) { create(:merchant_account, user:, charge_processor_id: StripeChargeProcessor.charge_processor_id) } context "country_change" do before do @service = ForfeitBalanceService.new(user:, reason: :country_change) end describe "#process" do context "when the user doesn't have an unpaid balance" do it "returns nil" do expect(@service.process).to eq(nil) expect(user.reload.comments.last).to eq(nil) end end context "when the user has an unpaid balance" do before do @balance = create(:balance, merchant_account:, user:, amount_cents: 1050) end it "marks the balances as forfeited" do @service.process expect(@balance.reload.state).to eq("forfeited") expect(user.reload.unpaid_balance_cents).to eq(0) end it "adds a comment on the user" do @service.process comment = user.reload.comments.last expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_BALANCE_FORFEITED) expect(comment.content).to eq("Balance of $10.50 has been forfeited. Reason: Country changed. Balance IDs: #{Balance.last.id}") end it "does not add a negative credit" do @service.process expect(user.reload.credits.last).to be nil end end end describe "#balance_amount_cents_to_forfeit" do it "returns the correctly formatted balance" do create(:balance, user:, merchant_account:, amount_cents: 765) expect(@service.balance_amount_cents_to_forfeit).to eq(765) end it "excludes balances held by Gumroad" do create(:balance, user:, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), amount_cents: 765) expect(@service.balance_amount_cents_to_forfeit).to eq(0) end end describe "#balance_amount_formatted" do it "returns the correctly formatted balance" do @balance = create(:balance, user:, merchant_account:, amount_cents: 680) expect(@service.balance_amount_formatted).to eq("$6.80") end end end context "account_closure" do before do @service = ForfeitBalanceService.new(user:, reason: :account_closure) end describe "#process" do context "when the user doesn't have an unpaid balance" do it "returns nil" do expect(@service.process).to eq(nil) expect(user.reload.comments.last).to eq(nil) end end context "when the user has a positive unpaid balance" do before do @balance = create(:balance, user:, amount_cents: 876) end it "marks the balances as forfeited" do @service.process expect(@balance.reload.state).to eq("forfeited") expect(user.reload.unpaid_balance_cents).to eq(0) end it "adds a comment on the user" do @service.process comment = user.reload.comments.last expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_BALANCE_FORFEITED) expect(comment.content).to eq("Balance of $8.76 has been forfeited. Reason: Account closed. Balance IDs: #{Balance.last.id}") end it "does not add a negative credit" do @service.process expect(user.reload.credits.last).to be nil end end context "when the user has a negative unpaid balance" do before do @balance = create(:balance, user:, merchant_account:, amount_cents: -765) end it "doesn't forfeit the balance" do expect(@service.process).to eq(nil) expect(@balance.reload.state).to eq("unpaid") expect(user.reload.comments.last).to eq(nil) end end end describe "#balance_amount_cents_to_forfeit" do it "returns the correct amount" do create(:balance, user:, amount_cents: 850) expect(@service.balance_amount_cents_to_forfeit).to eq(850) end end describe "#balance_amount_formatted" do it "returns the correctly formatted balance" do @balance = create(:balance, user:, amount_cents: 589) expect(@service.balance_amount_formatted).to eq("$5.89") 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/rpush_fcm_app_service_spec.rb
spec/services/rpush_fcm_app_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe RpushFcmAppService do let!(:app_name) { Device::APP_TYPES[:consumer] } describe "#first_or_create!" do before do Rpush::Fcm::App.all.each(&:destroy) Modis.with_connection do |redis| redis.flushdb end end context "when the record exists" do it "returns the record" do app = described_class.new(name: app_name).first_or_create! expect(Rpush::Fcm::App.where(name: app_name).size > 0).to be(true) expect do fetched_app = described_class.new(name: app_name).first_or_create! expect(fetched_app.id).to eq(app.id) end.to_not change { Rpush::Fcm::App.where(name: app_name).size } end end context "when the record does not exist" do it "creates and returns a new record" do expect do app = described_class.new(name: app_name).first_or_create! expect(app.connections).to eq(1) end.to change { Rpush::Fcm::App.where(name: app_name).size }.by(1) end it "creates the Rpush::Fcm::App instance with correct params" do json_key = GlobalConfig.get("RPUSH_CONSUMER_FCM_JSON_KEY") firebase_project_id = GlobalConfig.get("RPUSH_CONSUMER_FCM_FIREBASE_PROJECT_ID") expect(Rpush::Fcm::App).to receive(:new).with( name: app_name, json_key: json_key, firebase_project_id: firebase_project_id, connections: 1 ).and_call_original described_class.new(name: app_name).first_or_create! 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/username_generator_service_spec.rb
spec/services/username_generator_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe UsernameGeneratorService do describe "#username" do let(:user) { build(:user, email: "johnsmith@gmail.com") } let(:username_generator) { described_class.new(user) } it "returns a username generated by OpenAI", :vcr do expect(username_generator.username).to eq "johnsmithy" end it "adds numbers to the end if the username already exists" do existing_username = "johnsmith" create(:user, username: existing_username) expect(username_generator).to receive(:openai_completion).and_return(existing_username).twice generated_username_1 = username_generator.username expect(generated_username_1).to match(/\Ajohnsmith\d\z/) create(:user, username: generated_username_1) generated_username_2 = username_generator.username ends_with_different_number = generated_username_1.last != generated_username_2.last ends_with_two_numbers = generated_username_2 =~ /\Ajohnsmith\d\d\z/ expect(ends_with_different_number || ends_with_two_numbers).to be_truthy end it "uses the user's name when they don't have an email address", :vcr do user = build(:user, email: nil, name: "Alexander Nathaniel Harrison") expect(described_class.new(user).username).to eq "alxnatharrison" end it "doesn't try to generate a username if the user doesn't have a name or email" do user = build(:user, email: nil, name: nil) expect(described_class.new(user).username).to be_nil end context "email contains a \"tricky\" email with common email domain", :vcr do tricky_emails_with_desired_usernames = [ %w[eduat2@hotmail.com eduquest], %w[aholzl@proton.me howlzen], %w[barbo816@outlook.com barbossa], %w[dtcoats@outlook.com coatsy], %w[FuityJuice@mail.com juicyfruit], %w[hanglezco@hotmail.com hanglezco], ] tricky_emails_with_desired_usernames.each do |email, desired_username| it "uses the desired username for #{email}" do user = build(:user, email:, name: nil) expect(described_class.new(user).username).to eq desired_username end end end context "OpenAI returns a username that is invalid" do it "generates a valid username when given a username with only numbers" do expect(username_generator).to receive(:openai_completion).and_return("123") user = build(:user, username: username_generator.username) expect(user.username).to eq "123a" expect(user).to be_valid end it "generates a valid username when given a blank username" do expect(username_generator).to receive(:openai_completion).and_return("") user = build(:user, username: username_generator.username) expect(user.username).to match(/\Aa\d\d\z/) expect(user).to be_valid end it "generates a valid username when given a username with capital letters and invalid characters" do expect(username_generator).to receive(:openai_completion).and_return("John_Smith") user = build(:user, username: username_generator.username) expect(user.username).to eq "johnsmith" expect(user).to be_valid end it "generates a valid username when given a username that is too short" do expect(username_generator).to receive(:openai_completion).and_return("hi") user = build(:user, username: username_generator.username) expect(user.username).to match(/\Ahi\d\z/) expect(user).to be_valid end it "generates a valid username when given a username that is too long" do expect(username_generator).to receive(:openai_completion).and_return("areallyreallylongusername") user = build(:user, username: username_generator.username) expect(user.username).to eq "areallyreallylonguse" expect(user).to be_valid end it "generates a valid username when given a username that is a word from the DENYLIST" do expect(username_generator).to receive(:openai_completion).and_return("about") user = build(:user, username: username_generator.username) expect(user.username).to match(/\Aabout\d\z/) expect(user).to be_valid 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/sitemap_service_spec.rb
spec/services/sitemap_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SitemapService do let(:service) { described_class.new } describe "#generate" do before do @product = create(:product, created_at: Time.current) end it "generates the sitemap" do date = @product.created_at sitemap_file_path = "#{Rails.public_path}/sitemap/products/monthly/#{date.year}/#{date.month}/sitemap.xml.gz" service.generate(date) expect(File.exist?(sitemap_file_path)).to be true end it "deletes /robots.txt sitemap configs cache" do cache_key = "sitemap_configs" redis_namespace = Redis::Namespace.new(:robots_redis_namespace, redis: $redis) redis_namespace.set("sitemap_configs", "[\"https://example.com/robots.txt\"]") service.generate(@product.created_at) expect(redis_namespace.get(cache_key)).to eq 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/payout_users_service_spec.rb
spec/services/payout_users_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe PayoutUsersService, :vcr do let!(:payout_date) { Date.yesterday } let(:user1) { create(:user, should_paypal_payout_be_split: true) } let(:user2) { create(:user) } before do create(:tos_agreement, user: user1) create(:user_compliance_info, user: user1) create(:tos_agreement, user: user2) create(:user_compliance_info, user: user2) end shared_examples_for "PayoutUsersService#process specs" do before do create(:balance, amount_cents: 10_001_00, user: user1, date: payout_date - 3, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) create(:balance, user: user1, date: payout_date - 2, merchant_account: MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) create(:balance, amount_cents: 10_002_00, user: user2, date: payout_date - 3, merchant_account: merchant_account2) create(:balance, user: user2, date: payout_date - 2, merchant_account: merchant_account2) if payout_processor_type == PayoutProcessorType::STRIPE Stripe::Transfer.create(destination: merchant_account2.charge_processor_merchant_id, currency: "usd", amount: user2.unpaid_balance_cents) end end it "marks the balances as processing, alters the users' balances, and creates payments" do service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: [user1.id, user2.id]) expect do expect(service_object).to receive(:create_payments).and_call_original result = service_object.process expect(result.length).to eq(2) expect(result.map(&:id)).to match_array([Payment.last.id, Payment.first.id]) expect(result.map(&:processor).uniq).to eq([payout_processor_type]) end.to change { Payment.count }.by(2) expect(Payment.last.payout_type).to eq(Payouts::PAYOUT_TYPE_STANDARD) expect(Payment.first.payout_type).to eq(Payouts::PAYOUT_TYPE_STANDARD) expect(user1.reload.unpaid_balance_cents).to eq(0) expect(user2.reload.unpaid_balance_cents).to eq(0) expect(user1.balances.reload.pluck(:state).uniq).to eq(["processing"]) expect(user2.balances.reload.pluck(:state).uniq).to eq(["processing"]) end it "works even if the supplied `user_ids` argument is not an array" do service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: user1.id) expect do result = service_object.process expect(result.length).to eq(1) expect(result.first.id).to eq(Payment.last.id) expect(result.first.processor).to eq(payout_processor_type) end.to change { Payment.count }.by(1) expect(user1.reload.unpaid_balance_cents).to eq(0) expect(Payment.last.payout_type).to eq(Payouts::PAYOUT_TYPE_STANDARD) expect(user1.balances.reload.pluck(:state).uniq).to eq(["processing"]) end it "processes payments for all users even if there are exceptions in the process" do # Make processing the first user ID raise an exception allow(User).to receive(:find).and_call_original allow(Payouts).to receive(:create_payment).and_call_original allow(User).to receive(:find).with(user1.id).and_return(user1) allow(Payouts).to receive(:create_payment).with(payout_date.to_s, payout_processor_type, user1, payout_type: Payouts::PAYOUT_TYPE_STANDARD) .and_raise(StandardError) service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: [user1.id, user2.id]) expect do result = service_object.process expect(result.length).to eq(1) expect(result.first.id).to eq(Payment.last.id) expect(result.first.processor).to eq(payout_processor_type) expect(result.first.user_id).to eq(user2.id) end.to change { Payment.count }.by(1) expect(user1.reload.unpaid_balance_cents > 0).to eq(true) expect(user2.reload.unpaid_balance_cents).to eq(0) expect(Payment.last.payout_type).to eq(Payouts::PAYOUT_TYPE_STANDARD) expect(user1.balances.reload.pluck(:state).uniq).to eq(["unpaid"]) expect(user2.balances.reload.pluck(:state).uniq).to eq(["processing"]) end end describe "PayoutUsersService#create_payments" do it "returns array of payments and cross-border payments" do service_object = described_class.new(date_string: payout_date.to_s, processor_type: PayoutProcessorType::STRIPE, user_ids: user1.id) expect(user1.balances).to be_empty payments, cross_border_payments = service_object.create_payments expect(payments).to eq([]) expect(cross_border_payments).to eq([]) create(:balance, amount_cents: 10_00, user: user1, date: payout_date - 2, merchant_account: create(:merchant_account, user: user1)) payments, cross_border_payments = service_object.create_payments expect(payments.pluck(:user_id, :state, :amount_cents)).to eq([[user1.id, "processing", 10_00]]) expect(cross_border_payments).to eq([]) end end context "when the processor_type is 'STRIPE'" do let!(:payout_processor_type) { PayoutProcessorType::STRIPE } let(:merchant_account1) { StripeMerchantAccountManager.create_account(user1.reload, passphrase: "1234") } let(:merchant_account2) { StripeMerchantAccountManager.create_account(user2.reload, passphrase: "1234") } before do create(:ach_account_stripe_succeed, user: user1) create(:ach_account_stripe_succeed, user: user2) stripe_account1 = Stripe::Account.retrieve(merchant_account1.charge_processor_merchant_id) stripe_account2 = Stripe::Account.retrieve(merchant_account2.charge_processor_merchant_id) stripe_account1.refresh until stripe_account1.payouts_enabled? stripe_account2.refresh until stripe_account2.payouts_enabled? end include_examples "PayoutUsersService#process specs" it "does not process cross-border payouts immediately and schedules for 25 hours later" do allow_any_instance_of(UserComplianceInfo).to receive(:legal_entity_country_code).and_return("TH") expect(StripePayoutProcessor).not_to receive(:process_payments) service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: [user1.id, user2.id]) expect do result = service_object.process expect(result.length).to eq(2) expect(result.first.id).to eq(user1.payments.last.id) expect(result.first.processor).to eq(payout_processor_type) expect(result.first.user_id).to eq(user1.id) expect(result.last.id).to eq(user2.payments.last.id) expect(result.last.processor).to eq(payout_processor_type) expect(result.last.user_id).to eq(user2.id) end.to change { Payment.processing.count }.by(2) expect(user1.reload.unpaid_balance_cents).to eq(0) expect(user2.reload.unpaid_balance_cents).to eq(0) expect(user1.balances.reload.pluck(:state).uniq).to eq(["processing"]) expect(user2.balances.reload.pluck(:state).uniq).to eq(["processing"]) expect(ProcessPaymentWorker).to have_enqueued_sidekiq_job(user1.payments.last.id).in(25.hours) expect(ProcessPaymentWorker).to have_enqueued_sidekiq_job(user2.payments.last.id).in(25.hours) end it "marks the balances as processing, alters the users' balances, and creates payments when payout method is instant" do allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(anything).and_return(99_999_00) bal1 = user1.unpaid_balances.where("amount_cents > 1000000").last bal1.update!(amount_cents: 9_989_00, holding_amount_cents: 9_989_00) bal2 = user2.unpaid_balances.where("amount_cents > 1000000").last bal2.update!(amount_cents: 990_00, holding_amount_cents: 990_00) service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: [user1.id, user2.id], payout_type: Payouts::PAYOUT_TYPE_INSTANT) expect do expect(service_object).to receive(:create_payments).and_call_original result = service_object.process expect(result.length).to eq(2) expect(result.map(&:id)).to match_array([Payment.last.id, Payment.first.id]) expect(result.map(&:processor).uniq).to eq([payout_processor_type]) end.to change { Payment.count }.by(2) payment1 = user1.payments.last expect(payment1.payout_type).to eq(Payouts::PAYOUT_TYPE_INSTANT) expect(payment1.state).to eq("processing") expect(payment1.stripe_transfer_id).to match(/po_/) expect(payment1.stripe_connect_account_id).to match(/acct_/) expect(payment1.amount_cents).to eq 970776 expect(payment1.gumroad_fee_cents).to eq 29123 payment2 = user2.payments.last expect(payment2.payout_type).to eq(Payouts::PAYOUT_TYPE_INSTANT) expect(payment2.state).to eq("processing") expect(payment2.stripe_transfer_id).to match(/po_/) expect(payment2.stripe_connect_account_id).to match(/acct_/) expect(payment2.amount_cents).to eq 97087 expect(payment2.gumroad_fee_cents).to eq 2913 expect(user1.reload.unpaid_balance_cents).to eq(0) expect(user2.reload.unpaid_balance_cents).to eq(0) expect(user1.balances.reload.pluck(:state).uniq).to eq(["processing"]) expect(user2.balances.reload.pluck(:state).uniq).to eq(["processing"]) end it "marks the payments as failed if the instant payout amount is more than the limit" do allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(anything).and_return(99_999_00) bal1 = user1.unpaid_balances.where("amount_cents > 1000000").last bal1.update!(amount_cents: 12_000_00, holding_amount_cents: 12_000_00) bal2 = user2.unpaid_balances.where("amount_cents > 1000000").last bal2.update!(amount_cents: 13_000_00, holding_amount_cents: 13_000_00) stripe_account1 = Stripe::Account.retrieve(user1.stripe_account.charge_processor_merchant_id) stripe_account2 = Stripe::Account.retrieve(user2.stripe_account.charge_processor_merchant_id) stripe_account1.refresh until stripe_account1.payouts_enabled? stripe_account2.refresh until stripe_account2.payouts_enabled? Stripe::Transfer.create(destination: merchant_account2.charge_processor_merchant_id, currency: "usd", amount: user2.unpaid_balance_cents) service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: [user1.id, user2.id], payout_type: Payouts::PAYOUT_TYPE_INSTANT) expect do expect(service_object).to receive(:create_payments).and_call_original result = service_object.process expect(result.length).to eq(2) expect(result.map(&:id)).to match_array([Payment.last.id, Payment.first.id]) expect(result.map(&:processor).uniq).to eq([payout_processor_type]) end.to change { Payment.count }.by(2) Payment.last(2).each do |payment| expect(payment.payout_type).to eq(Payouts::PAYOUT_TYPE_INSTANT) expect(payment.state).to eq("failed") end expect(user1.reload.unpaid_balance_cents).to eq(12_010_00) expect(user2.reload.unpaid_balance_cents).to eq(13_010_00) expect(user1.balances.reload.pluck(:state).uniq).to eq(["unpaid"]) expect(user2.balances.reload.pluck(:state).uniq).to eq(["unpaid"]) end it "does not process the payments if the amount is less than the instantly payable unpaid balances amount" do allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(user1).and_return(99_999_00) allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(user2).and_return(800_00) bal1 = user1.unpaid_balances.where("amount_cents > 1000000").last bal1.update!(amount_cents: 900_00, holding_amount_cents: 900_00) bal2 = user2.unpaid_balances.where("amount_cents > 1000000").last bal2.update!(amount_cents: 900_00, holding_amount_cents: 900_00) service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: [user1.id, user2.id], payout_type: Payouts::PAYOUT_TYPE_INSTANT) expect do expect(service_object).to receive(:create_payments).and_call_original result = service_object.process expect(result.length).to eq(1) expect(result.map(&:id)).to match_array([Payment.last.id]) expect(result.map(&:processor).uniq).to eq([payout_processor_type]) end.to change { Payment.count }.by(1) expect(user1.reload.unpaid_balance_cents).to eq(0) expect(user2.reload.unpaid_balance_cents).to eq(910_00) expect(user1.balances.reload.pluck(:state).uniq).to eq(["processing"]) expect(user2.balances.reload.pluck(:state).uniq).to eq(["unpaid"]) end end context "when the processor_type is 'PAYPAL'" do let!(:payout_processor_type) { PayoutProcessorType::PAYPAL } let(:merchant_account1) { MerchantAccount.gumroad(PaypalChargeProcessor::DISPLAY_NAME) } let(:merchant_account2) { merchant_account1 } before do allow(PaypalPayoutProcessor).to receive(:perform_payments) allow(PaypalPayoutProcessor).to receive(:perform_split_payment) end include_examples "PayoutUsersService#process specs" it "processes cross-border payouts immediately" do user1.alive_user_compliance_info.mark_deleted! create(:user_compliance_info, user: user2, country: "Thailand") user2.alive_user_compliance_info.mark_deleted! create(:user_compliance_info, user: user2, country: "Brazil") expect(PaypalPayoutProcessor).to receive(:process_payments) service_object = described_class.new(date_string: payout_date.to_s, processor_type: payout_processor_type, user_ids: [user1.id, user2.id]) expect do result = service_object.process expect(result.length).to eq(2) expect(result.first.id).to eq(user1.payments.last.id) expect(result.first.processor).to eq(payout_processor_type) expect(result.first.user_id).to eq(user1.id) expect(result.first.amount_cents).to eq(9_810_78) expect(result.first.gumroad_fee_cents).to eq(200_22) expect(result.last.id).to eq(user2.payments.last.id) expect(result.last.processor).to eq(payout_processor_type) expect(result.last.user_id).to eq(user2.id) expect(result.last.amount_cents).to eq(10_012_00) expect(result.last.gumroad_fee_cents).to eq(nil) end.to change { Payment.processing.count }.by(2) expect(user1.reload.unpaid_balance_cents).to eq(0) expect(user2.reload.unpaid_balance_cents).to eq(0) expect(user1.balances.reload.pluck(:state).uniq).to eq(["processing"]) expect(user2.balances.reload.pluck(:state).uniq).to eq(["processing"]) expect(ProcessPaymentWorker.jobs.size).to eq(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/safe_redirect_path_service_spec.rb
spec/services/safe_redirect_path_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe "SafeRedirectPathService" do before do @request = OpenStruct.new(host: "test.gumroad.com") end let(:service) { SafeRedirectPathService.new(@path, @request) } describe "#process" do context "when path has a subdomain host" do before do @path = "https://username.test.gumroad.com:31337/123" stub_const("ROOT_DOMAIN", "test.gumroad.com") end context "when subdomain host is allowed" do it "returns path" do expect(service.process).to eq @path end end context "when subdomain host is not allowed" do let(:service) { SafeRedirectPathService.new(@path, @request, allow_subdomain_host: false) } it "returns relative path" do expect(service.process).to eq "/123" end end end context "when hosts of request and path are same" do it "returns path" do @request = OpenStruct.new(host: "test2.gumroad.com") @path = "https://test2.gumroad.com/123" expect(service.process).to eq @path end end context "when path is a relative path" do it "returns path" do @path = "/test3" expect(service.process).to eq @path end end context "when safety conditions aren't met" do it "returns parsed path" do @path = "http://example.com/test?a=b" expect(service.process).to eq "/test?a=b" end end context "when path is an escaped external url" do it "clears the parsed path" do @path = "////evil.org" expect(service.process).to eq "/evil.org" end it "decodes the parsed path" do @path = "///%2Fevil.org" expect(service.process).to eq "/evil.org" end end context "when domain contains regex special characters" do before do stub_const("ROOT_DOMAIN", "gumroad.com") end it "does not match malicious domains that try to exploit unescaped dots" do @path = "https://attacker.gumroadXcom/malicious" expect(service.process).to eq "/malicious" end it "correctly matches legitimate subdomains" do @path = "https://user.gumroad.com/legitimate" expect(service.process).to eq @path end end context "when there is only a query parameter" do it "does not prepend unnecessary forward slash" do @path = "?query=param" expect(service.process).to eq "?query=param" 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/post_email_api_spec.rb
spec/services/post_email_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe PostEmailApi do let(:seller) { create(:named_user) } let(:post) { create(:audience_installment, seller: seller) } let(:recipients) do 10.times.map { |i| { email: "recipient#{i}@gumroad-example.com" } } end let(:args) { { post: post, recipients: recipients } } describe ".process" do context "when the feature flag is active" do before do allow(Feature).to receive(:inactive?).with(:use_resend_for_post_emails, seller).and_return(false) # Email via Resend for the first 4 recipients, SendGrid for the rest allow(MailerInfo::Router).to receive(:determine_email_provider) do |domain| @call_count ||= 0 @call_count += 1 @call_count <= 4 ? MailerInfo::EMAIL_PROVIDER_RESEND : MailerInfo::EMAIL_PROVIDER_SENDGRID end end it "splits recipients between Resend and SendGrid" do resend_recipients = recipients[0..3] sendgrid_recipients = recipients[4..9] expect(PostResendApi).to receive(:process).with(args.merge(recipients: resend_recipients)) expect(PostSendgridApi).to receive(:process).with(args.merge(recipients: sendgrid_recipients)) PostEmailApi.process(**args) end it "routes non-ASCII emails through SendGrid" do # Set to resend to test the fallback allow(MailerInfo::Router).to receive(:determine_email_provider).and_return(MailerInfo::EMAIL_PROVIDER_RESEND) non_ascii_recipients = [{ email: "récipient@gumroad-example.com" }] non_ascii_args = { post: post, recipients: non_ascii_recipients } expect(PostSendgridApi).to receive(:process).with(non_ascii_args) expect(PostResendApi).not_to receive(:process) PostEmailApi.process(**non_ascii_args) end it "routes emails with local parts exceeding 64 characters through SendGrid" do # Set to resend to test the fallback allow(MailerInfo::Router).to receive(:determine_email_provider).and_return(MailerInfo::EMAIL_PROVIDER_RESEND) # Create an email with local part longer than 64 characters long_local_part = "a" * 65 # 65 characters long_email_recipient = [{ email: "#{long_local_part}@gumroad-example.com" }] long_email_args = { post: post, recipients: long_email_recipient } expect(PostSendgridApi).to receive(:process).with(long_email_args) expect(PostResendApi).not_to receive(:process) PostEmailApi.process(**long_email_args) end it "routes emails with special characters through SendGrid" do # Set to resend to test the fallback allow(MailerInfo::Router).to receive(:determine_email_provider).and_return(MailerInfo::EMAIL_PROVIDER_RESEND) # Test with various special characters that should be rejected by the regex special_char_emails = [ { email: "recipient!@gumroad-example.com" }, # exclamation mark { email: "recipient*@gumroad-example.com" }, # asterisk { email: "recipient=@gumroad-example.com" }, # equals sign { email: "recipient$@gumroad-example.com" }, # dollar sign { email: "recipient{@gumroad-example.com" }, # curly brace { email: "recipient-name@gumroad-example.com" } # hyphen ] special_char_emails.each do |email_recipient| special_char_args = { post: post, recipients: [email_recipient] } expect(PostSendgridApi).to receive(:process).with(special_char_args) expect(PostResendApi).not_to receive(:process) PostEmailApi.process(**special_char_args) end end it "routes emails with formatting issues through SendGrid" do # Set to resend to test the fallback allow(MailerInfo::Router).to receive(:determine_email_provider).and_return(MailerInfo::EMAIL_PROVIDER_RESEND) # Test various email formatting issues invalid_format_emails = [ { email: "" }, # blank email { email: nil }, # nil email { email: "userexample.com" }, # missing @ symbol { email: "user@example@domain.com" }, # multiple @ symbols { email: "@gumroad-example.com" }, # blank local part { email: "user@" }, # blank domain part { email: "user@gumroad-example" }, # domain without period { email: "user@.gumroad-example.com" }, # domain starting with period { email: "user@gumroad-example.com." } # domain ending with period ] invalid_format_emails.each do |email_recipient| invalid_format_args = { post: post, recipients: [email_recipient] } expect(PostSendgridApi).to receive(:process).with(invalid_format_args) expect(PostResendApi).not_to receive(:process) PostEmailApi.process(**invalid_format_args) end end it "routes emails from excluded domains through SendGrid" do # Set to resend to test the fallback allow(MailerInfo::Router).to receive(:determine_email_provider).and_return(MailerInfo::EMAIL_PROVIDER_RESEND) # Test with emails from excluded domains excluded_domains = ["example.com", "example.org", "example.net", "test.com"] excluded_domain_emails = excluded_domains.map do |domain| { email: "user@#{domain}" } end excluded_domain_emails.each do |email_recipient| excluded_domain_args = { post: post, recipients: [email_recipient] } expect(PostSendgridApi).to receive(:process).with(excluded_domain_args) expect(PostResendApi).not_to receive(:process) PostEmailApi.process(**excluded_domain_args) end end it "routes emails exceeding maximum length through SendGrid" do # Set to resend to test the fallback allow(MailerInfo::Router).to receive(:determine_email_provider).and_return(MailerInfo::EMAIL_PROVIDER_RESEND) # Test email with total length exceeding 254 characters long_domain = "gumroad-example.com" long_local_part = "a" * 245 # Makes total email length > 254 characters long_email_args = { post: post, recipients: [{ email: "#{long_local_part}@#{long_domain}" }] } expect(PostSendgridApi).to receive(:process).with(long_email_args) expect(PostResendApi).not_to receive(:process) PostEmailApi.process(**long_email_args) end it "routes valid emails through Resend when determined by the router" do # Valid email with only permitted special characters valid_recipient = { email: "user.name+tag@gumroad-example.com" } valid_args = { post: post, recipients: [valid_recipient] } # Configure router to choose Resend allow(MailerInfo::Router).to receive(:determine_email_provider) .with(MailerInfo::DeliveryMethod::DOMAIN_CREATORS) .and_return(MailerInfo::EMAIL_PROVIDER_RESEND) expect(PostResendApi).to receive(:process).with(valid_args) expect(PostSendgridApi).not_to receive(:process) PostEmailApi.process(**valid_args) end it "routes valid emails through SendGrid when determined by the router" do # Valid email with only permitted special characters valid_recipient = { email: "user_name_123@gumroad-example.com" } valid_args = { post: post, recipients: [valid_recipient] } # Configure router to choose SendGrid allow(MailerInfo::Router).to receive(:determine_email_provider) .with(MailerInfo::DeliveryMethod::DOMAIN_CREATORS) .and_return(MailerInfo::EMAIL_PROVIDER_SENDGRID) expect(PostSendgridApi).to receive(:process).with(valid_args) expect(PostResendApi).not_to receive(:process) PostEmailApi.process(**valid_args) end end context "when the feature flag is inactive" do before do allow(Feature).to receive(:inactive?).with(:use_resend_for_post_emails, seller).and_return(true) end it "sends all emails through SendGrid" do expect(PostSendgridApi).to receive(:process).with(args) PostEmailApi.process(**args) end end end describe ".max_recipients" do context "when the feature flag is active" do it "returns the Resend max recipients" do allow(Feature).to receive(:active?).with(:use_resend_for_post_emails).and_return(true) expect(PostEmailApi.max_recipients).to eq(PostResendApi::MAX_RECIPIENTS) end end context "when the feature flag is inactive" do it "returns the SendGrid max recipients" do allow(Feature).to receive(:active?).with(:use_resend_for_post_emails).and_return(false) expect(PostEmailApi.max_recipients).to eq(PostSendgridApi::MAX_RECIPIENTS) 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/update_user_country_spec.rb
spec/services/update_user_country_spec.rb
# frozen_string_literal: true require "spec_helper" describe UpdateUserCountry do before do @user = create(:named_user) create(:ach_account_stripe_succeed, user: @user) create(:ach_account, user: @user) create(:user_compliance_info, user: @user) create(:merchant_account, user: @user, charge_processor_id: StripeChargeProcessor.charge_processor_id) end describe "#process" do it "deletes the old compliance info and creates a new one" do old_compliance_info = @user.alive_user_compliance_info UpdateUserCountry.new(new_country_code: "GB", user: @user).process expect(old_compliance_info.reload.deleted?).to eq(true) end it "deletes the old stripe account" do old_stripe_account = @user.stripe_account UpdateUserCountry.new(new_country_code: "GB", user: @user).process expect(old_stripe_account.reload.deleted?).to eq(true) end it "marks all pending compliance info requests as provided" do create(:user_compliance_info_request, user: @user, field_needed: UserComplianceInfoFields::Individual::TAX_ID) create(:user_compliance_info_request, user: @user, field_needed: UserComplianceInfoFields::Individual::STRIPE_IDENTITY_DOCUMENT_ID) create(:user_compliance_info_request, user: @user, field_needed: UserComplianceInfoFields::Business::STRIPE_COMPANY_DOCUMENT_ID) expect(@user.user_compliance_info_requests.provided.count).to eq(0) expect(@user.user_compliance_info_requests.requested.count).to eq(3) UpdateUserCountry.new(new_country_code: "GB", user: @user).process expect(@user.user_compliance_info_requests.provided.count).to eq(3) expect(@user.user_compliance_info_requests.requested.count).to eq(0) end it "deletes the old bank account" do old_bank_account = @user.active_bank_account UpdateUserCountry.new(new_country_code: "GB", user: @user).process expect(old_bank_account.reload.deleted?).to eq(true) end it "adds country changed comment" do UpdateUserCountry.new(new_country_code: "GB", user: @user).process comment = @user.reload.comments.last expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_COUNTRY_CHANGED) expect(comment.content).to eq("Country changed from US to GB") end context "when old and new country are not Stripe-supported countries" do it "retains PayPal payment address" do payment_address = @user.payment_address allow(@user).to receive(:native_payouts_supported?).and_return(false) UpdateUserCountry.new(new_country_code: "GB", user: @user).process expect(@user.reload.payment_address).to eq(payment_address) end end context "when user has balance" do before do stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id) # For negative credits @merchant_account = create(:merchant_account, user: @user) create(:balance, merchant_account: @merchant_account, user: @user, amount_cents: 1000, state: "unpaid") end it "marks balances as forfeited" do UpdateUserCountry.new(new_country_code: "GB", user: @user).process expect(@user.reload.balances.last.state).to eq("forfeited") expect(@user.reload.balances.last.merchant_account).to eq(@merchant_account) end it "adds comment on the user" do UpdateUserCountry.new(new_country_code: "GB", user: @user).process comment = @user.reload.comments.last expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_BALANCE_FORFEITED) expect(comment.content).to eq("Balance of $10 has been forfeited. Reason: Country changed. Balance IDs: #{Balance.last.id}") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/recommended_wishlists_service_spec.rb
spec/services/recommended_wishlists_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe RecommendedWishlistsService do describe ".fetch" do let!(:wishlists) do 5.times.map { |i| create(:wishlist, name: "Recommendable #{i}", recent_follower_count: i, recommendable: true) } end let(:recommended_products) { create_list(:product, 4) } let(:taxonomy) { Taxonomy.last } before do wishlists.each { create(:wishlist_product, wishlist: _1) } end it "returns wishlists ordered by recent_follower_count when no additional params are provided" do result = described_class.fetch(limit: 4, current_seller: nil) expect(result.count).to eq(4) expect(result).to eq(wishlists.last(4).reverse) end it "excludes wishlists owned by the current seller" do result = described_class.fetch(limit: 4, current_seller: wishlists.last.user) expect(result).to eq(wishlists.first(4).reverse) end it "prioritizes wishlists with recommended products" do wishlists.first(4).each.with_index do |wishlist, i| create(:wishlist_product, wishlist: wishlist, product: recommended_products[i]) end result = described_class.fetch(limit: 4, current_seller: nil, curated_product_ids: recommended_products.pluck(:id)) expect(result).to eq(wishlists.first(4).reverse) end it "returns nothing if there are no product matches" do result = described_class.fetch(limit: 4, current_seller: nil, curated_product_ids: [create(:product).id]) expect(result).to be_empty end it "fills remaining slots with non-matching wishlists if not enough matches" do create(:wishlist_product, wishlist: wishlists.first, product: recommended_products.second) result = described_class.fetch(limit: 4, current_seller: nil, curated_product_ids: recommended_products.pluck(:id)) expect(result).to eq([wishlists.first, *wishlists.last(3).reverse]) end it "filters wishlists by taxonomy_id" do taxonomy_product = create(:product, taxonomy: taxonomy) taxonomy_wishlist = create(:wishlist, name: "Taxonomy wishlist", recommendable: true) create(:wishlist_product, wishlist: taxonomy_wishlist, product: taxonomy_product) result = described_class.fetch(limit: 4, current_seller: nil, taxonomy_id: taxonomy.id) expect(result).to eq([taxonomy_wishlist]) end it "returns nothing if there are no taxonomy matches" do result = described_class.fetch(limit: 4, current_seller: nil, taxonomy_id: create(:taxonomy).id) expect(result).to be_empty end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/robots_service_spec.rb
spec/services/robots_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe RobotsService do before do @redis_namespace = Redis::Namespace.new(:robots_redis_namespace, redis: $redis) @sitemap_config = "Sitemap: https://test-public-files.gumroad.com/products/sitemap.xml" @user_agent_rules = ["User-agent: *", "Disallow: /purchases/"] end describe "#sitemap_configs" do before do s3_double = double(:s3_double) response_double = double(:list_objects_response) allow(Aws::S3::Client).to receive(:new).and_return(s3_double) allow(s3_double).to receive(:list_objects).times.and_return([response_double]) allow(response_double).to receive(:contents).and_return([OpenStruct.new(key: "products/sitemap.xml")]) end it "generates sitemap configs" do expect(described_class.new.sitemap_configs).to eq [@sitemap_config] expect(@redis_namespace.get("sitemap_configs")).to eq [@sitemap_config].to_json end it "doesn't generate sitemaps configs when cache exists" do expect_any_instance_of(RobotsService).to receive(:generate_sitemap_configs).once 2.times do RobotsService.new.sitemap_configs end end end describe "#user_agent_rules" do it "returns the user agent rules" do expect(described_class.new.user_agent_rules).to eq @user_agent_rules end end describe "#expire_sitemap_configs_cache" do before do @redis_namespace.set("sitemap_configs", @sitemap_config) end it "expires sitemap_configs cache" do described_class.new.expire_sitemap_configs_cache expect(@redis_namespace.get("sitemap_configs")).to eq 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/save_installment_service_spec.rb
spec/services/save_installment_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SaveInstallmentService do let(:seller) { create(:user) } let(:installment) { nil } let(:product) { create(:product, user: seller) } let(:params) do ActionController::Parameters.new( installment: { affiliate_products: nil, allow_comments: true, bought_from: "United States", bought_products: [product.unique_permalink], bought_variants: [], created_after: "2024-01-01", created_before: "2024-01-31", files: [{ external_id: SecureRandom.uuid, stream_only: false, subtitles: [], url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/some-url.txt" }], installment_type: "product", link_id: product.unique_permalink, message: "<p>Hello, world!</p>", name: "Hello", not_bought_products: [], not_bought_variants: [], paid_less_than_cents: 2000, paid_more_than_cents: 1000, send_emails: true, shown_on_profile: true, }, publish: false, send_preview_email: false, to_be_published_at: nil, variant_external_id: nil, shown_in_profile_sections: [], ) end let(:preview_email_recipient) { seller } 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 shared_examples_for "updates profile posts sections" do it "updates profile posts sections based on 'shown_in_profile_sections' param" do section1 = create(:seller_profile_posts_section, seller:, shown_posts: [2000, 3000]) section2 = create(:seller_profile_posts_section, seller:, shown_posts: []) section3 = create(:seller_profile_posts_section, seller:, shown_posts: [2000, 3000]) if installment.present? section1.update!(shown_posts: [installment.id, 2000, 3000]) end service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { shown_in_profile_sections: [section2.external_id, section3.external_id] }), preview_email_recipient:) service.process expect(section1.reload.shown_posts).to eq([2000, 3000]) expect(section2.reload.shown_posts).to eq([Installment.last.id]) expect(section3.reload.shown_posts).to eq([2000, 3000, Installment.last.id]) end end context "when installment is nil" do it "creates a product-type installment" do service = described_class.new(seller:, installment:, params:, preview_email_recipient:) expect do service.process end.to change { Installment.count }.by(1) expect(service.error).to be_nil installment = Installment.last expect(service.installment).to eq(installment) expect(installment.seller).to eq(seller) expect(installment.name).to eq("Hello") expect(installment.product_type?).to be(true) expect(installment.link).to eq(product) expect(installment.bought_from).to eq("United States") expect(installment.bought_products).to eq([product.unique_permalink]) expect(installment.bought_variants).to be_nil expect(installment.created_after.to_date).to eq(Date.parse("2024-01-01")) expect(installment.created_before.to_date).to eq(Date.parse("2024-01-31")) expect(installment.paid_less_than_cents).to eq(2000) expect(installment.paid_more_than_cents).to eq(1000) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.published?).to be(false) expect(installment.product_files.sole.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/some-url.txt") end it "creates a variant-type installment" do variant = create(:variant, variant_category: create(:variant_category, link: product)) service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { installment_type: "variant", bought_variants: [variant.external_id], bought_products: [] }, variant_external_id: variant.external_id), preview_email_recipient:) service.process expect(service.error).to be_nil installment = service.installment expect(installment.variant_type?).to be(true) expect(installment.bought_variants).to eq([variant.external_id]) expect(installment.bought_products).to be_nil expect(installment.link).to eq(product) expect(installment.base_variant).to eq(variant) end it "creates a seller-type installment" do product2 = create(:product, user: seller) service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { installment_type: "seller", link_id: nil, bought_products: [product.unique_permalink, product2.unique_permalink] }), preview_email_recipient:) service.process expect(service.error).to be_nil installment = service.installment expect(installment.seller_type?).to be(true) expect(installment.bought_products).to eq([product.unique_permalink, product2.unique_permalink]) end it "creates an audience-type installment" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { installment_type: "audience", link_id: nil, bought_products: nil, not_bought_products: [product.unique_permalink] }), preview_email_recipient:) service.process expect(service.error).to be_nil installment = service.installment expect(installment.audience_type?).to be(true) expect(installment.bought_products).to be_nil expect(installment.not_bought_products).to eq([product.unique_permalink]) end it "creates a follower-type installment" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { installment_type: "follower", link_id: nil }), preview_email_recipient:) service.process expect(service.error).to be_nil installment = service.installment expect(installment.follower_type?).to be(true) expect(installment.bought_products).to eq([product.unique_permalink]) end it "creates a affiliate-type installment" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { installment_type: "affiliate", link_id: nil, affiliate_products: [product.unique_permalink], bought_products: nil }), preview_email_recipient:) service.process expect(service.error).to be_nil installment = service.installment expect(installment.affiliate_type?).to be(true) expect(installment.bought_products).to be_nil expect(installment.affiliate_products).to eq([product.unique_permalink]) end it "creates and publishes the installment" do service = described_class.new(seller:, installment:, params: params.merge(publish: true), preview_email_recipient:) service.process expect(service.error).to be_nil expect(service.installment.published?).to be(true) expect(SendPostBlastEmailsJob).to have_enqueued_sidekiq_job(PostEmailBlast.last.id) end it "publishes the installment but does not send emails" do service = described_class.new(seller:, installment:, params: params.deep_merge(publish: true, installment: { send_emails: false }), preview_email_recipient:) service.process expect(service.error).to be_nil expect(service.installment.published?).to be(true) expect(SendPostBlastEmailsJob.jobs).to be_empty end it "creates and sends a preview email" do allow(PostSendgridApi).to receive(:process).and_call_original service = described_class.new(seller:, installment:, params: params.merge(send_preview_email: true), preview_email_recipient:) service.process expect(service.error).to be_nil expect(service.installment.published?).to be(false) expect(PostSendgridApi).to have_received(:process).with( post: service.installment, recipients: [{ email: seller.email, url_redirect: service.installment.url_redirects.sole, }], preview: true, ) end it "sends a preview email to the impersonated user" do gumroad_admin = create(:admin_user) expect_any_instance_of(Installment).to receive(:send_preview_email).with(gumroad_admin) service = described_class.new(seller:, installment:, params: params.merge(send_preview_email: true), preview_email_recipient: gumroad_admin) service.process end it "returns an error while previewing an email if the logged-in user has uncofirmed email" do seller.update_attribute(:unconfirmed_email, "john@example.com") expect(PostSendgridApi).to_not receive(:process) service = described_class.new(seller:, installment:, params: params.merge(send_preview_email: true), preview_email_recipient:) expect do service.process end.to_not change { Installment.count } expect(service.error).to eq("You have to confirm your email address before you can do that.") end it "creates and schedules the installment" do freeze_time do service = described_class.new(seller:, installment:, params: params.merge(to_be_published_at: 1.day.from_now.to_s), preview_email_recipient:) expect do service.process end.to change { Installment.count }.by(1) .and change { InstallmentRule.count }.by(1) expect(service.error).to be_nil expect(service.installment.published?).to be(false) expect(service.installment.ready_to_publish?).to be(true) expect(PublishScheduledPostJob).to have_enqueued_sidekiq_job(service.installment.id, 1).at(1.day.from_now) end end it "returns an error if the schedule date is in past" do service = described_class.new(seller:, installment:, params: params.merge(to_be_published_at: 1.day.ago.to_s), preview_email_recipient:) expect do service.process end.to not_change { Installment.count } .and not_change { InstallmentRule.count } expect(service.error).to eq("Please select a date and time in the future.") end it "returns an error if no channel is provided" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { send_emails: nil, shown_on_profile: nil }), preview_email_recipient:) expect do service.process end.to_not change { Installment.count } expect(service.error).to eq("Please set at least one channel for your update.") end it "returns an error if paid more than is greater than paid less than" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { paid_more_than_cents: 5000 }), preview_email_recipient:) expect do service.process end.to_not change { Installment.count } expect(service.error).to eq("Please enter valid paid more than and paid less than values.") end it "returns an error if bought after date is after bought before date" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { created_after: "2024-01-31", created_before: "2024-01-01" }), preview_email_recipient:) expect do service.process end.to_not change { Installment.count } expect(service.error).to eq("Please enter valid before and after dates.") end it "returns an error if the message is missing" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { message: nil }), preview_email_recipient:) expect do service.process end.to_not change { Installment.count } expect(service.error).to eq("Please include a message as part of the update.") end it "invokes SaveContentUpsellsService with correct arguments" do expect(SaveContentUpsellsService).to receive(:new).with(seller:, content: "<p>Hello, world!</p>", old_content: nil).and_call_original service = described_class.new(seller:, installment:, params:, preview_email_recipient:) service.process end include_examples "updates profile posts sections" end context "when installment is present" do let(:installment) { create(:installment, seller:, installment_type: "seller") } it "updates the installment" do service = described_class.new(seller:, installment:, params:, preview_email_recipient:) expect do service.process end.to change { installment.reload.installment_type }.to("product") expect(service.error).to be_nil expect(installment.name).to eq("Hello") expect(installment.message).to eq("<p>Hello, world!</p>") expect(installment.link).to eq(product) expect(installment.seller).to eq(seller) expect(installment.bought_products).to eq([product.unique_permalink]) expect(installment.bought_variants).to be_nil expect(installment.bought_from).to eq("United States") expect(installment.paid_less_than_cents).to eq(2000) expect(installment.paid_more_than_cents).to eq(1000) expect(installment.created_after.to_date).to eq(Date.parse("2024-01-01")) expect(installment.created_before.to_date).to eq(Date.parse("2024-01-31")) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.published?).to be(false) expect(installment.product_files.sole.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/some-url.txt") end it "marks the old file as deleted" do installment.product_files.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/old-url.txt") service = described_class.new(seller:, installment:, params:, preview_email_recipient:) expect do service.process end.to change { installment.reload.product_files.count }.from(1).to(2) expect(installment.product_files.alive.sole.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/some-url.txt") expect(service.error).to be_nil end it "removes the existing files" do installment.product_files.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/old-url.txt") service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { files: [] }), preview_email_recipient:) expect do service.process end.to change { installment.reload.product_files.alive.count }.from(1).to(0) expect(service.error).to be_nil end it "updates and publishes the installment" do service = described_class.new(seller:, installment:, params: params.deep_merge(publish: true), preview_email_recipient:) expect do service.process end.to change { installment.reload.published? }.from(false).to(true) expect(service.error).to be_nil expect(SendPostBlastEmailsJob).to have_enqueued_sidekiq_job(PostEmailBlast.last.id) expect(installment.name).to eq("Hello") end it "returns an error while publishing an installment if the seller is not eligible to send emails" do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE - 1) service = described_class.new(seller:, installment:, params: params.deep_merge(publish: true), preview_email_recipient:) expect do service.process end.to_not change { installment.reload.published? } expect(service.error).to eq("You are not eligible to publish or schedule emails. Please ensure you have made at least $100 in sales and received a payout.") expect(SendPostBlastEmailsJob.jobs).to be_empty end it "updates and publishes the installment but does not send emails" do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE - 1) service = described_class.new(seller:, installment:, params: params.deep_merge(publish: true, installment: { send_emails: false }), preview_email_recipient:) expect do service.process end.to change { installment.reload.published? }.from(false).to(true) expect(service.error).to be_nil expect(installment.reload.published?).to be(true) expect(SendPostBlastEmailsJob.jobs).to be_empty expect(installment.name).to eq("Hello") end it "allows updating only certain attributes for a published installment" do freeze_time do installment.update!(published_at: 10.days.ago, shown_on_profile: false, send_emails: true, allow_comments: false) service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { published_at: 2.days.ago.to_date.to_s, send_emails: false }), preview_email_recipient:) expect do service.process puts service.error end.to change { installment.reload.published_at }.from(10.days.ago).to(2.days.ago.to_date) .and change { installment.name }.to("Hello") .and change { installment.message }.to("<p>Hello, world!</p>") .and change { installment.shown_on_profile }.from(false).to(true) .and change { installment.send_emails }.from(true).to(false) .and change { installment.allow_comments }.from(false).to(true) .and not_change { installment.installment_type } .and not_change { installment.bought_products } .and not_change { installment.bought_variants } .and not_change { installment.bought_from } .and not_change { installment.paid_less_than_cents } .and not_change { installment.paid_more_than_cents } .and not_change { installment.created_after } .and not_change { installment.created_before } expect(service.error).to be_nil end end it "does not allow updating 'send_emails' if it has been published and already blasted" do create(:blast, post: installment) installment.update!(published_at: 10.days.ago, send_emails: true) service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { send_emails: false }), preview_email_recipient:) expect do service.process end.to_not change { installment.reload.send_emails } expect(service.error).to be_nil end it "updates the installment but do not change the publish date if it is unchanged for a published installment" do installment.update!(published_at: 10.days.ago) service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { published_at: 10.days.ago.to_date.to_s }), preview_email_recipient:) expect do service.process end.to_not change { installment.reload.published_at } expect(service.error).to be_nil expect(installment.reload.published?).to be(true) expect(installment.name).to eq("Hello") end it "does not allow a future publish date for an already published installment" do installment.update!(published_at: 1.day.ago) service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { published_at: 1.day.from_now.to_date.to_s }), preview_email_recipient:) expect do service.process end.to_not change { installment.reload.published_at } expect(service.error).to eq("Please enter a publish date in the past.") expect(installment.name).to_not eq("Hello") end it "updates the installment and sends a preview email" do allow(PostSendgridApi).to receive(:process).and_call_original service = described_class.new(seller:, installment:, params: params.deep_merge(send_preview_email: true), preview_email_recipient:) service.process expect(service.error).to be_nil expect(installment.reload.published?).to be(false) expect(installment.name).to eq("Hello") expect(PostSendgridApi).to have_received(:process).with( post: installment, recipients: [{ email: preview_email_recipient.email, url_redirect: installment.url_redirects.sole, }], preview: true, ) end it "returns an error while previewing an email if the logged-in user has uncofirmed email" do seller.update_attribute(:unconfirmed_email, "john@example.com") expect(PostSendgridApi).to_not receive(:process) service = described_class.new(seller:, installment:, params: params.deep_merge(send_preview_email: true), preview_email_recipient:) expect do service.process end.to_not change { installment.reload } expect(service.error).to eq("You have to confirm your email address before you can do that.") end it "updates the installment and schedules the installment" do freeze_time do service = described_class.new(seller:, installment:, params: params.merge(to_be_published_at: 1.day.from_now.to_s), preview_email_recipient:) expect do service.process end.to change { InstallmentRule.count }.by(1) expect(service.error).to be_nil expect(installment.reload.published?).to be(false) expect(installment.ready_to_publish?).to be(true) expect(PublishScheduledPostJob).to have_enqueued_sidekiq_job(installment.id, 1).at(1.day.from_now) end end it "returns an error while scheduling an installment if the seller is not eligible to send emails" do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE - 1) service = described_class.new(seller:, installment:, params: params.merge(to_be_published_at: 1.day.from_now.to_s), preview_email_recipient:) expect do service.process end.to_not change { installment.reload } expect(service.error).to eq("You are not eligible to publish or schedule emails. Please ensure you have made at least $100 in sales and received a payout.") expect(PublishScheduledPostJob.jobs).to be_empty end it "updates the installment and changes the existing schedule time of an already scheduled installment" do freeze_time do installment_rule = create(:installment_rule, installment:, to_be_published_at: 1.day.from_now) service = described_class.new(seller:, installment:, params: params.merge(to_be_published_at: 15.day.from_now.to_s), preview_email_recipient:) expect do service.process end.to change { installment_rule.reload.to_be_published_at }.from(1.day.from_now).to(15.days.from_now) expect(service.error).to be_nil expect(installment.reload.name).to eq("Hello") expect(installment.published?).to be(false) expect(installment.ready_to_publish?).to be(true) expect(PublishScheduledPostJob).to have_enqueued_sidekiq_job(installment.id, 2).at(15.days.from_now) end end it "returns an error if the schedule date is in past" do service = described_class.new(seller:, installment:, params: params.merge(to_be_published_at: 1.day.ago.to_s), preview_email_recipient:) expect do service.process end.to_not change { installment.reload } expect(service.error).to eq("Please select a date and time in the future.") end it "returns an error while scheduling if the seller has not confirmed their email address" do seller.update!(confirmed_at: nil) service = described_class.new(seller:, installment:, params: params.merge(to_be_published_at: 1.day.from_now.to_s), preview_email_recipient:) expect do service.process end.to_not change { installment.reload } expect(service.error).to eq("You have to confirm your email address before you can do that.") end it "returns an error if paid more than is greater than paid less than" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { paid_more_than_cents: 5000 }), preview_email_recipient:) expect do service.process end.to_not change { installment.reload } expect(service.error).to eq("Please enter valid paid more than and paid less than values.") end it "returns an error if bought after date is after bought before date" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { created_after: "2024-01-31", created_before: "2024-01-01" }), preview_email_recipient:) expect do service.process end.to_not change { installment.reload } expect(service.error).to eq("Please enter valid before and after dates.") end it "returns an error if the message is missing" do service = described_class.new(seller:, installment:, params: params.deep_merge(installment: { message: nil }), preview_email_recipient:) expect do service.process end.to_not change { installment.reload } expect(service.error).to eq("Please include a message as part of the update.") end include_examples "updates profile posts sections" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/kra_pin_validation_service_spec.rb
spec/services/kra_pin_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe KraPinValidationService do it "returns true when valid KRA PIN is provided" do kra_pin = "A123456789P" expect(described_class.new(kra_pin).process).to be(true) end it "returns false when nil KRA PIN is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when blank KRA PIN is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when KRA PIN with invalid format is provided" do expect(described_class.new("123456789").process).to be(false) expect(described_class.new("A12345678PP").process).to be(false) expect(described_class.new("123456789P").process).to be(false) expect(described_class.new("A123456789").process).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/balances_by_product_service_spec.rb
spec/services/balances_by_product_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe BalancesByProductService do include CollabProductHelper describe "#process" do let(:user) { create(:user) } before do (0...5).each do |i| product = create(:product, user:, name: "product #{i}", purchase_disabled_at: i == 4 ? Time.current : nil) (0...10).each do |j| purchase = create :purchase, link: product, seller: user, purchase_state: :successful, price_cents: 1000 + 200 * i + 100 * j, tax_cents: 5 * i + 7 * j, created_at: j.days.ago if j == 2 flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, 200) purchase.refund_purchase!(flow_of_funds, user.id) elsif j == 3 flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, purchase.total_transaction_cents) purchase.refund_purchase!(flow_of_funds, user.id) elsif j == 4 purchase.update!(chargeback_date: 4.days.ago) end end end @collab_stats = setup_collab_purchases_for(user) index_model_records(Purchase) end it "doesn't error if product is deleted" do user.links.first.delete balances = described_class.new(user).process expect(balances.size).to eq(5) end it "doesn't list products with no sales" do product = create(:product, user:) balances = described_class.new(user).process product_ids = balances.map { |balance| balance["link_id"] } expect(product_ids).not_to eq(product.id) end it "has expected values" do balances = described_class.new(user).process expect(balances[0]).to include("name" => "collab product", "gross" => @collab_stats[:gross], "fees" => @collab_stats[:fees], "taxes" => 0, "refunds" => @collab_stats[:refunds], "chargebacks" => @collab_stats[:chargebacks], "net" => @collab_stats[:net]) expect(balances[1]).to include("name" => "product 4", "gross" => 22500, "fees" => 2955, "taxes" => 423, "refunds" => 2300, "chargebacks" => 2200, "net" => 14622) expect(balances[2]).to include("name" => "product 3", "gross" => 20500, "fees" => 2748, "taxes" => 383, "refunds" => 2100, "chargebacks" => 2000, "net" => 13269) expect(balances[3]).to include("name" => "product 2", "gross" => 18500, "fees" => 2541, "taxes" => 343, "refunds" => 1900, "chargebacks" => 1800, "net" => 11916) expect(balances[4]).to include("name" => "product 1", "gross" => 16500, "fees" => 2332, "taxes" => 304, "refunds" => 1700, "chargebacks" => 1600, "net" => 10564) expect(balances[5]).to include("name" => "product 0", "gross" => 14500, "fees" => 2123, "taxes" => 264, "refunds" => 1500, "chargebacks" => 1400, "net" => 9213) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/circle_api_spec.rb
spec/services/circle_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe CircleApi, :vcr, :without_circle_rate_limit do let(:communities_list) do [ { "id" => 3512, "name" => "Gumroad", "slug" => "gumroad", "icon_url" => "https://d2y5h3osumboay.cloudfront.net/o4431o822um5prcmyefm7pc9fhht", "logo_url" => "https://d2y5h3osumboay.cloudfront.net/jwp8ec5m46vtdw05eki9fd38ga7zJ5Hj6yK1", "owner_id" => 200455, "is_private" => false, "space_ids" => [ 24914, 24916, 24918, 24919, 25148, 25159, 27096, 32841, 42109, 42111, 42112, 76381, 77110, 97329, 97374, 97376, 97377, 97378, 98660, 98664, 105741, 105742, 116356, 116357, 132358, 132553, 132554, 132556, 132557, 132559, 132560, 132561, 132562, 132563, 132565, 132566, 132567, 132568, 132569, 132571, 132573, 132574, 132575, 134985, 139900, 140195, 142769, 142937 ], "last_visited_by_current_user" => true, "default_existing_member_space_id" => 0, "root_url" => "community.gumroad.com", "display_on_switcher" => true, "prefs" => { "has_posts" => true, "has_spaces" => true, "has_topics" => true, "brand_color" => "#00959A", "has_seen_widget" => true, "has_invited_member" => true, "has_completed_onboarding" => true } } ] end let(:space_groups_list) do [ { "id" => 8015, "name" => "Community", "is_hidden_from_non_members" => false, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ "77110", "24914", "32841", "132358", "25159", "97329", "76381", 76381, 77110, 134985, 32841, 132358, 24914, 97329, 140195 ], "created_at" => "2020-10-17T00:52:17.905Z", "updated_at" => "2021-08-06T00:34:52.373Z", "automatically_add_members_to_new_spaces" => false, "add_members_to_space_group_on_space_join" => false, "slug" => "community", "hide_non_member_spaces_from_sidebar" => false }, { "id" => 8017, "name" => "14 Day Product", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ "25148", "27096", "24918", "25157", "24916", "24919", "27095", 24918, 27096, 25148, 24916, 24919 ], "created_at" => "2020-10-17T00:56:17.325Z", "updated_at" => "2021-04-27T08:42:23.214Z", "automatically_add_members_to_new_spaces" => true, "add_members_to_space_group_on_space_join" => true, "slug" => "14dayproduct", "hide_non_member_spaces_from_sidebar" => true }, { "id" => 13237, "name" => "Sale Every Day", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ 42109, 42111, 42112 ], "created_at" => "2020-12-14T22:04:07.505Z", "updated_at" => "2021-04-27T08:35:31.274Z", "automatically_add_members_to_new_spaces" => true, "add_members_to_space_group_on_space_join" => true, "slug" => "sale-every-day", "hide_non_member_spaces_from_sidebar" => true }, { "id" => 30973, "name" => "Milestones", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ "97352", "97340", "97343", "97346", "97348", "97349", "97351", 132571, 132573, 132574, 132575 ], "created_at" => "2021-04-27T08:47:11.647Z", "updated_at" => "2021-07-20T12:12:13.635Z", "automatically_add_members_to_new_spaces" => false, "add_members_to_space_group_on_space_join" => false, "slug" => "milestones", "hide_non_member_spaces_from_sidebar" => true }, { "id" => 30981, "name" => "Discover", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ "97378", "132568", "97374", "132569", "97377", "132553", "132554", "132556", "132557", "132559", "132560", "132561", "132562", "132563", "97376", "132565", "132566", "132567", 132553, 97374, 132557, 132556 ], "created_at" => "2021-04-27T10:34:48.095Z", "updated_at" => "2021-08-03T12:08:58.889Z", "automatically_add_members_to_new_spaces" => false, "add_members_to_space_group_on_space_join" => false, "slug" => "discover", "hide_non_member_spaces_from_sidebar" => false }, { "id" => 31336, "name" => "5 Day Email List Course", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ 98660, 98664 ], "created_at" => "2021-04-29T12:11:01.995Z", "updated_at" => "2021-04-29T12:22:48.465Z", "automatically_add_members_to_new_spaces" => true, "add_members_to_space_group_on_space_join" => true, "slug" => "5-day-email-list-course", "hide_non_member_spaces_from_sidebar" => false }, { "id" => 33545, "name" => "Grow Your Audience Challenge", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ 105741, 105742 ], "created_at" => "2021-05-15T13:19:57.081Z", "updated_at" => "2021-05-15T13:22:10.587Z", "automatically_add_members_to_new_spaces" => true, "add_members_to_space_group_on_space_join" => true, "slug" => "grow-your-audience-challenge", "hide_non_member_spaces_from_sidebar" => false }, { "id" => 36700, "name" => "Sale Every Day Course", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ 116356, 116357 ], "created_at" => "2021-06-08T17:14:16.451Z", "updated_at" => "2021-06-08T17:15:48.861Z", "automatically_add_members_to_new_spaces" => true, "add_members_to_space_group_on_space_join" => true, "slug" => "sale-every-day-course", "hide_non_member_spaces_from_sidebar" => false }, { "id" => 43576, "name" => "Tests", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ 139900, 142937 ], "created_at" => "2021-08-05T13:14:01.390Z", "updated_at" => "2021-08-12T20:33:12.085Z", "automatically_add_members_to_new_spaces" => false, "add_members_to_space_group_on_space_join" => false, "slug" => "tests", "hide_non_member_spaces_from_sidebar" => false }, { "id" => 44429, "name" => "Drafts", "is_hidden_from_non_members" => true, "allow_members_to_create_spaces" => false, "community_id" => 3512, "space_order_array" => [ 142769 ], "created_at" => "2021-08-12T11:37:10.752Z", "updated_at" => "2021-08-12T11:37:37.829Z", "automatically_add_members_to_new_spaces" => false, "add_members_to_space_group_on_space_join" => false, "slug" => "drafts", "hide_non_member_spaces_from_sidebar" => false } ] end let(:test_community_id) { 3512 } let(:test_space_group_id) { 43576 } let(:test_member_email) { "circle_test_email@gumroad.com" } before do @circle_api_handle = CircleApi.new(GlobalConfig.get("CIRCLE_API_KEY")) end describe "GET communities" do it "returns communities for a valid api_key" do response = @circle_api_handle.get_communities expect(response.parsed_response).to eq(communities_list) end it "fails if invalid api_key is passed" do circle_api_handle = CircleApi.new("invalid_api_key") response = circle_api_handle.get_communities expect(response.parsed_response).to eq({ "status" => "unauthorized", "message" => "Your account could not be authenticated." }) end end describe "GET space_groups" do it "returns space_groups for a valid api_key and community_id" do response = @circle_api_handle.get_space_groups(test_community_id) expect(response.parsed_response).to eq(space_groups_list) end it "fails if invalid api_key is passed" do circle_api_handle = CircleApi.new("invalid_api_key") response = circle_api_handle.get_space_groups(test_community_id) expect(response.parsed_response).to eq({ "status" => "unauthorized", "message" => "Your account could not be authenticated." }) end end describe "POST community_members" do it "adds a new member" do response = @circle_api_handle.add_member(test_community_id, test_space_group_id, test_member_email) expect(response.parsed_response["success"]).to eq(true) expect(response.parsed_response["message"]).to eq("This user has been added to the community and has been added to the spaces / space groups specified.") expect(response.parsed_response["user"]["email"]).to eq("circle_test_email@gumroad.com") end it "is successful if member already exists" do @circle_api_handle.add_member(test_community_id, test_space_group_id, test_member_email) response = @circle_api_handle.add_member(test_community_id, test_space_group_id, test_member_email) expect(response.parsed_response["success"]).to eq(true) expect(response.parsed_response["message"]).to eq("This user is already a member of this community and has been added to the spaces / space groups specified.") expect(response.parsed_response["user"]["email"]).to eq("circle_test_email@gumroad.com") end it "fails if invalid api_key is passed" do circle_api_handle = CircleApi.new("invalid_api_key") response = circle_api_handle.add_member(test_community_id, test_space_group_id, test_member_email) expect(response.parsed_response).to eq({ "status" => "unauthorized", "message" => "Your account could not be authenticated." }) end it "fails if invalid member email is passed" do response = @circle_api_handle.add_member(test_community_id, test_space_group_id, "invalid_email") expect(response.parsed_response["success"]).to eq(false) expect(response.parsed_response["errors"]).to eq("Email is invalid") end end describe "DELETE community_members" do before do @circle_api_handle.add_member(test_community_id, test_space_group_id, test_member_email) end it "deletes an existing member" do response = @circle_api_handle.remove_member(test_community_id, test_member_email) expect(response.parsed_response["success"]).to eq(true) expect(response.parsed_response["message"]).to eq("This user has been removed from the community.") end it "fails if invalid api_key is passed" do circle_api_handle = CircleApi.new("invalid_api_key") response = circle_api_handle.remove_member(test_community_id, test_member_email) expect(response.parsed_response).to eq({ "status" => "unauthorized", "message" => "Your account could not be authenticated." }) end it "fails if member does not exist" do response = @circle_api_handle.remove_member(test_community_id, "not_circle_member@gmail.com") expect(response.parsed_response["success"]).to eq(true) expect(response.parsed_response["message"]).to eq("This user could not be removed. Please ensure that the user and community specified exists, and that the user is a member of the community.") end it "fails if invalid member email is passed" do response = @circle_api_handle.remove_member(test_community_id, "invalid_email") expect(response.parsed_response["success"]).to eq(true) expect(response.parsed_response["message"]).to eq("This user could not be removed. Please ensure that the user and community specified exists, and that the user is a member of the community.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/expiring_s3_file_service_spec.rb
spec/services/expiring_s3_file_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe ExpiringS3FileService do describe "#perform" do before do @file = fixture_file_upload("test.png") stub_const("S3_BUCKET", "gumroad-specs") end it "generates URL with given data and default values" do result = ExpiringS3FileService.new(file: @file, extension: "pdf").perform expect(result).to match(/#{AWS_S3_ENDPOINT}\/gumroad-specs\/File/o) expect(result).to match(/pdf/) expect(result).to match(Regexp.new "#{ExpiringS3FileService::DEFAULT_FILE_EXPIRY.to_i}") end it "generates URL with given filename" do result = ExpiringS3FileService.new(file: @file, filename: "test.pdf").perform expect(result).to match(/#{AWS_S3_ENDPOINT}\/gumroad-specs\/test.pdf/o) end it "generates URL with given path, prefix, extension, expiry" do result = ExpiringS3FileService.new(file: @file, prefix: "prefix", extension: "txt", path: "folder", expiry: 1.hour).perform expect(result).to match( /#{AWS_S3_ENDPOINT}\/gumroad-specs\/folder\/prefix_.*txt.*3600/o ) end it "generates presigned URL with the 'response-content-disposition' query parameter set to 'attachment'" do presigned_url = ExpiringS3FileService.new(file: @file, filename: "sales.csv").perform expect(presigned_url).to match(/response-content-disposition=attachment/) end context "when specified without the filename and without the extension" do it "raises an error" do expect { ExpiringS3FileService.new(file: @file).perform } .to raise_error(ArgumentError, "Either filename or extension is required") end end context "when specified without the file object" do it "raises an error" do expect { ExpiringS3FileService.new.perform } .to raise_error(ArgumentError, "missing keyword: :file") end end context "when specified with the extension but no filename" do it "uploads file with the content type inferred from the file's extension" do allow_any_instance_of(Aws::S3::Object) .to receive(:upload_file).with(@file, content_type: "text/csv") ExpiringS3FileService.new(file: @file, extension: "csv").perform end end context "when specified with the filename but no extension" do it "uploads file with the content type inferred from the file's name" do allow_any_instance_of(Aws::S3::Object) .to receive(:upload_file).with(@file, content_type: "application/pdf") ExpiringS3FileService.new(file: @file, filename: "sales.pdf").perform end end context "when specified with the both filename and extension" do it "uploads file with the content type inferred from the file's name" do allow_any_instance_of(Aws::S3::Object) .to receive(:upload_file).with(@file, content_type: "application/pdf") ExpiringS3FileService.new(file: @file, filename: "sales.pdf", extension: "csv").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/secure_encrypt_service_spec.rb
spec/services/secure_encrypt_service_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe SecureEncryptService do let(:key) { SecureRandom.random_bytes(32) } let(:text) { "this is a secret message" } before do allow(GlobalConfig).to receive(:get).with("SECURE_ENCRYPT_KEY").and_return(key) # Reset memoized encryptor described_class.instance_variable_set(:@encryptor, nil) end describe ".encrypt" do it "encrypts text" do encrypted_text = described_class.encrypt(text) expect(encrypted_text).not_to be_blank expect(encrypted_text).not_to eq(text) end end describe ".decrypt" do let(:encrypted_text) { described_class.encrypt(text) } it "decrypts text" do expect(described_class.decrypt(encrypted_text)).to eq(text) end it "returns nil for tampered text" do tampered_text = encrypted_text + "tamper" expect(described_class.decrypt(tampered_text)).to be_nil end it "returns nil for a different key" do encrypted_with_first_key = described_class.encrypt(text) different_key = SecureRandom.random_bytes(32) allow(GlobalConfig).to receive(:get).with("SECURE_ENCRYPT_KEY").and_return(different_key) described_class.instance_variable_set(:@encryptor, nil) expect(described_class.decrypt(encrypted_with_first_key)).to be_nil end end describe ".verify" do let(:encrypted_text) { described_class.encrypt(text) } it "returns true for correct text" do expect(described_class.verify(encrypted_text, text)).to be true end it "returns false for incorrect text" do expect(described_class.verify(encrypted_text, "wrong message")).to be false end it "returns false for tampered encrypted text" do tampered_text = encrypted_text + "tamper" expect(described_class.verify(tampered_text, text)).to be false end it "returns false for nil user input" do expect(described_class.verify(encrypted_text, nil)).to be false end end context "with key configuration errors" do before do described_class.instance_variable_set(:@encryptor, nil) end it "raises MissingKeyError if key is not set" do allow(GlobalConfig).to receive(:get).with("SECURE_ENCRYPT_KEY").and_return(nil) expect { described_class.encrypt(text) }.to raise_error(SecureEncryptService::MissingKeyError, "SECURE_ENCRYPT_KEY is not set.") end it "raises InvalidKeyError if key is not 32 bytes" do allow(GlobalConfig).to receive(:get).with("SECURE_ENCRYPT_KEY").and_return("short_key") expect { described_class.encrypt(text) }.to raise_error(SecureEncryptService::InvalidKeyError, "SECURE_ENCRYPT_KEY must be 32 bytes for aes-256-gcm.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/installment_search_service_spec.rb
spec/services/installment_search_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe InstallmentSearchService do describe "#process" do it "can filter by seller" do product_1 = create(:product) installment_1 = create(:installment, link: product_1) installment_2 = create(:installment, link: product_1) creator_1 = product_1.user product_2 = create(:product) installment_3 = create(:installment, link: product_2) creator_2 = product_2.user create(:installment) index_model_records(Installment) expect(get_records(seller: creator_1)).to match_array([installment_1, installment_2]) expect(get_records(seller: [creator_1, creator_2])).to match_array([installment_1, installment_2, installment_3]) end it "can exclude deleted posts" do installment_1 = create(:installment) installment_2 = create(:installment, deleted_at: Time.current) index_model_records(Installment) expect(get_records(exclude_deleted: false)).to match_array([installment_1, installment_2]) expect(get_records(exclude_deleted: true)).to match_array([installment_1]) end it "filters by type to only include the specified posts" do installment_1 = create(:installment) installment_2 = create(:scheduled_installment) installment_3 = create(:published_installment) index_model_records(Installment) expect(get_records(type: nil)).to match_array([installment_1, installment_2, installment_3]) expect(get_records(type: "draft")).to match_array([installment_1]) expect(get_records(type: "scheduled")).to match_array([installment_2]) expect(get_records(type: "published")).to match_array([installment_3]) end it "can exclude workflow posts" do workflow = create(:workflow) workflow_installment = create(:installment, workflow:) installment = create(:installment) index_model_records(Installment) expect(get_records(exclude_workflow_installments: false)).to match_array([workflow_installment, installment]) expect(get_records(exclude_workflow_installments: true)).to match_array([installment]) end it "can apply some native ES params" do installment = create(:installment) create(:installment, created_at: 1.day.ago) index_model_records(Installment) response = described_class.new(sort: { created_at: :asc }, from: 1, size: 1).process expect(response.results.total).to eq(2) expect(response.records.load).to match_array([installment]) end it "supports fulltext/autocomplete search" do installment_1 = create(:installment, name: "The Gumroad Journey Beginning", message: "<p>Lorem ipsum dolor</p>") installment_2 = create(:installment, name: "My First Sale Went Live!", message: "<p>Lor ipsum dolor</p>") installment_3 = create(:installment, name: "Reached 100 followers!", message: "<p>Lorem dol</p>") installment_4 = create(:installment, name: "Reached 1000 followers!", message: "<p>Lo dolor</p>") index_model_records(Installment) expect(get_records(q: "gum")).to match_array([installment_1]) expect(get_records(q: "ipsum")).to match_array([installment_1, installment_2]) expect(get_records(q: "followers")).to match_array([installment_3, installment_4]) expect(get_records(q: "live")).to match_array([installment_2]) expect(get_records(q: "dolor")).to match_array([installment_1, installment_2, installment_4]) # test support for exact search beyond max_ngram expect(get_records(q: "The Gumroad Journey Beginning")).to match_array([installment_1]) # test support for exact title search wth different case expect(get_records(q: "the gumroad journey beginning")).to match_array([installment_1]) # test scoring expect(get_records(q: "Lo dolor")).to eq([installment_4, installment_1, installment_2]) end end describe ".search" do it "is a shortcut to initialization + process" do result_double = double options = { a: 1, b: 2 } instance_double = double(process: result_double) expect(described_class).to receive(:new).with(options).and_return(instance_double) expect(described_class.search(options)).to eq(result_double) end end def get_records(options) described_class.new(options).process.records.load end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/qst_validation_service_spec.rb
spec/services/qst_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe QstValidationService, :vcr do let(:qst_id) { "1002092821TQ0001" } it "returns true when a valid qst id is provided" do expect(described_class.new(qst_id).process).to be(true) end it "returns false when the qst id is nil" do expect(described_class.new(nil).process).to be(false) end it "returns false when the qst id is empty" do expect(described_class.new("").process).to be(false) end it "returns false when the format of the qst id is invalid" do expect(described_class.new("NR00005576").process).to be(false) end it "returns false when the qst id is not a registration number" do expect(described_class.new(qst_id.gsub("0001", "0002")).process).to be(false) end it "returns false when the qst id registration has been revoked or cancelled" do revoked_result = { "Resultat" => { "StatutSousDossierUsager" => "A", # This would be "R" if the QST ID represents a valid registration "DescriptionStatut" => "Regulier", "DateStatut" => "1992-07-01T00:00:00", "NomEntreprise" => "APPLE CANADA INC.", "RaisonSociale" => nil }, "OperationReussie" => true, "MessagesFonctionnels" => [], "MessagesInformatifs" => [] } revoked_response = instance_double(HTTParty::Response, code: 200, parsed_response: revoked_result) expect(HTTParty).to receive(:get).with("https://svcnab2b.revenuquebec.ca/2019/02/ValidationTVQ/#{qst_id}", timeout: 5).and_return(revoked_response) expect(described_class.new(qst_id).process).to be(false) end it "handles QST IDs that need encoding" do expect(described_class.new("needs encoding").process).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/rpush_apns_app_service_spec.rb
spec/services/rpush_apns_app_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe RpushApnsAppService do let!(:app_name) { Device::APP_TYPES[:creator] } describe "#first_or_create!" do before do Rpush::Apns2::App.all.each(&:destroy) end context "when the record exists" do it "returns the record" do app = described_class.new(name: app_name).first_or_create! expect(Rpush::Apns2::App.where(name: app_name).size > 0).to be(true) expect do fetched_app = described_class.new(name: app_name).first_or_create! expect(fetched_app.id).to eq(app.id) end.to_not change { Rpush::Apns2::App.where(name: app_name).size } end end context "when the record does not exist" do it "creates and returns a new record" do expect do app = described_class.new(name: app_name).first_or_create! expect(app.environment).to eq("development") expect(app.certificate).to be_present expect(app.connections).to eq(1) end.to change { Rpush::Apns2::App.where(name: app_name).size }.by(1) end it "creates an app with environment production when the Rails environment is staging and returns it" do allow(Rails.env).to receive(:staging?).and_return(true) expect do app = described_class.new(name: app_name).first_or_create! expect(app.environment).to eq("production") end.to change { Rpush::Apns2::App.where(name: app_name).size }.by(1) end it "creates an app with environment production when the Rails environment is production and returns it" do allow(Rails.env).to receive(:production?).and_return(true) expect do app = described_class.new(name: app_name).first_or_create! expect(app.environment).to eq("production") end.to change { Rpush::Apns2::App.where(name: app_name).size }.by(1) end end end describe "#creator_app?" do it "returns correct app type" do expect(described_class.new(name: Device::APP_TYPES[:creator]).send(:creator_app?)).to be(true) expect(described_class.new(name: Device::APP_TYPES[:consumer]).send(:creator_app?)).to be(false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/user_balance_stats_service_spec.rb
spec/services/user_balance_stats_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe UserBalanceStatsService do let(:user) { create(:user) } let(:instance) { described_class.new(user:) } let(:example_values) { { foo: "bar", nested: { key1: { key2: "value2" } }, records: [{ id: 1, name: "first" }, { id: 2, name: "second" }] } } describe "#generate" do # We're not actually testing the values generated here. # The values and intended final behavior is tested in spec/requests/balance_pages_spec.rb it "returns a hash" do now = Time.zone.local(2020, 1, 1) travel_to(now) generated = instance.send(:generate) expect(generated).to be_a(Hash) expect(generated.fetch(:generated_at)).to eq(now) end end describe "#fetch" do let(:fetched) { instance.fetch } context "when value should be retrieved from the cache" do before do expect(instance).to receive(:should_use_cache?).and_return(true) end after do expect(UpdateUserBalanceStatsCacheWorker).to have_enqueued_sidekiq_job(user.id) end context "when cached value exists" do it "returns cached value" do $redis.setex(instance.send(:cache_key), 48.hours.to_i, example_values.to_json) expect(instance).not_to receive(:generate) expect(fetched).to eq(example_values) end end context "when cached value does not exist" do it "returns generated value" do expect(instance).to receive(:generate).and_return(example_values) expect(fetched).to eq(example_values) end end end context "when value should not be retrieved from the cache" do before do expect(instance).to receive(:should_use_cache?).and_return(false) end it "returns generated value" do expect(instance).to receive(:generate).and_return(example_values) expect(fetched).to eq(example_values) end end it "returns a hash" do user = create(:user) now = Time.zone.local(2020, 1, 1) travel_to(now) generated = described_class.new(user:).send(:generate) expect(generated).to be_a(Hash) expect(generated.keys).to match_array( [:generated_at, :next_payout_period_data, :processing_payout_periods_data, :overview, :payout_period_data, :payments, :is_paginating] ) expect(generated.fetch(:generated_at)).to eq(now) end describe "next_payout_period_data" do let(:user) { create(:compliant_user, unpaid_balance_cents: 10_01) } before do create(:merchant_account, user:) create(:ach_account, user:, stripe_bank_account_id: "ba_bankaccountid") create(:user_compliance_info, user:) end let(:generated) { described_class.new(user:).send(:generate) } context "when there is no standard payout processing" do it "returns the next payout period data" do expect(generated.fetch(:next_payout_period_data)).not_to eq(nil) end end context "when an instant payout is processing" do before do create( :payment, user:, processor: "STRIPE", processor_fee_cents: 10, stripe_transfer_id: "tr_1234", stripe_connect_account_id: "acct_1234", json_data: { type: Payouts::PAYOUT_TYPE_INSTANT } ) end it "returns the next payout period data" do expect(generated.fetch(:next_payout_period_data)).not_to eq(nil) end end context "when a standard payout is processing" do before do create( :payment, user:, processor: "STRIPE", processor_fee_cents: 10, stripe_transfer_id: "tr_1234", stripe_connect_account_id: "acct_1234", json_data: { type: Payouts::PAYOUT_TYPE_STANDARD } ) end it "returns the next payout period data as nil" do expect(generated.fetch(:next_payout_period_data)).to eq(nil) end end end describe "processing_payout_periods_data" do let(:user) { create(:compliant_user, unpaid_balance_cents: 10_01) } before do create(:merchant_account, user:) create(:ach_account, user:, stripe_bank_account_id: "ba_bankaccountid") create(:user_compliance_info, user:) end let(:generated) { described_class.new(user:).send(:generate) } context "when there are no processing payouts" do it "returns an empty array" do expect(generated.fetch(:processing_payout_periods_data)).to eq([]) end end context "when there are multiple processing payouts" do before do create(:payment, user:, processor: "STRIPE", processor_fee_cents: 10, stripe_transfer_id: "tr_1234", stripe_connect_account_id: "acct_1234", json_data: { payout_type: Payouts::PAYOUT_TYPE_INSTANT }) create(:payment, user:, processor: "STRIPE", processor_fee_cents: 10, stripe_transfer_id: "tr_1235", stripe_connect_account_id: "acct_1235", json_data: { payout_type: Payouts::PAYOUT_TYPE_STANDARD }) end it "returns the processing payout period data" do processing_payout_periods_data = generated.fetch(:processing_payout_periods_data) expect(processing_payout_periods_data.size).to eq(2) expect(processing_payout_periods_data.map { _1.fetch(:type) }).to match_array([Payouts::PAYOUT_TYPE_INSTANT, Payouts::PAYOUT_TYPE_STANDARD]) end end end end describe "#should_use_cache?" do context "when user is large seller" do before do stub_const("#{described_class}::DEFAULT_SALES_CACHING_THRESHOLD", 100) user.current_sign_in_at = 1.day.ago user.save! expect(described_class).to receive(:cacheable_users).and_call_original end context "with sales count below threshold" do it "returns false" do create(:large_seller, user:, sales_count: 50) expect(instance.send(:should_use_cache?)).to eq(false) end end context "with sales count above threshold" do it "returns true" do create(:large_seller, user:, sales_count: 200) expect(instance.send(:should_use_cache?)).to eq(true) end end end context "when user is not a large seller" do it "returns false" do expect(instance.send(:should_use_cache?)).to eq(false) end end end describe "#write_cache" do it "writes generated values" do expect(instance.send(:read_cache)).to eq(nil) expect(instance).to receive(:generate).and_return(example_values) instance.write_cache expect(instance.send(:read_cache)).to eq(example_values) end end describe "#read_cache" do it "reads cached values" do expect(instance.send(:read_cache)).to eq(nil) expect(instance).to receive(:generate).and_return(example_values) instance.write_cache expect(instance.send(:read_cache)).to eq(example_values) end end describe ".cacheable_users" do it "returns correct list of users" do user_1 = create(:large_seller, sales_count: 200, user: build(:user, current_sign_in_at: 10.days.ago)).user user_2 = create(:large_seller, sales_count: 200, user: build(:user, current_sign_in_at: 3.days.ago)).user user_3 = create(:large_seller, sales_count: 50, user: build(:user, current_sign_in_at: 10.days.ago)).user user_4 = create(:large_seller, sales_count: 50, user: build(:user, current_sign_in_at: 3.days.ago)).user # With default values stub_const("#{described_class}::DEFAULT_SALES_CACHING_THRESHOLD", 100) expect(described_class.cacheable_users).to match_array([user_1, user_2]) # With custom redis set values $redis.set(RedisKey.balance_stats_sales_caching_threshold, 40) expect(described_class.cacheable_users).to match_array([user_1, user_2, user_3, user_4]) $redis.sadd(RedisKey.balance_stats_users_excluded_from_caching, [user_1.id, user_3.id]) expect(described_class.cacheable_users).to match_array([user_2, user_4]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/google_calendar_api_spec.rb
spec/services/google_calendar_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe GoogleCalendarApi do describe "POST oauth_token" do it "makes an oauth authorization request with the given code and redirect uri" do WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token"). with( body: { grant_type: "authorization_code", code: "test_code", redirect_uri: "test_uri", client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"), client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"), }) response = GoogleCalendarApi.new.oauth_token("test_code", "test_uri") expect(response.success?).to eq(true) end end describe "GET user_info" do it "requests user info with the given token" do WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/oauth2/v2/userinfo").with(query: { access_token: "test_access_token" }) response = GoogleCalendarApi.new.user_info("test_access_token") expect(response.success?).to eq(true) end end describe "GET calendar_list" do it "requests calendar_list with the given token" do WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/calendar/v3/users/me/calendarList").with(headers: { "Authorization" => "Bearer test_access_token" }) response = GoogleCalendarApi.new.calendar_list("test_access_token") expect(response.success?).to eq(true) end end describe "POST disconnect" do it "requests disconnect with the given token" do WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/revoke").with(query: { token: "test_access_token" }) response = GoogleCalendarApi.new.disconnect("test_access_token") expect(response.success?).to eq(true) end end describe "POST refresh_token" do it "requests refresh_token with the given token" do WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token"). with( body: { grant_type: "refresh_token", refresh_token: "test_refresh_token", client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"), client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"), }) response = GoogleCalendarApi.new.refresh_token("test_refresh_token") expect(response.success?).to eq(true) end end describe "POST insert_event" do it "inserts an event with the given parameters" do calendar_id = "primary" event = { summary: "Test Event", start: { dateTime: "2023-05-01T09:00:00-07:00" }, end: { dateTime: "2023-05-01T10:00:00-07:00" } } access_token = "test_access_token" WebMock.stub_request(:post, "#{GoogleCalendarApi.base_uri}/calendar/v3/calendars/#{calendar_id}/events") .with( headers: { "Authorization" => "Bearer #{access_token}" }, body: event.to_json ) .to_return(status: 200, body: "", headers: {}) response = GoogleCalendarApi.new.insert_event(calendar_id, event, access_token: access_token) expect(response.success?).to eq(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/zoom_api_spec.rb
spec/services/zoom_api_spec.rb
# frozen_string_literal: true require "spec_helper" describe ZoomApi do let(:oauth_request_header) do client_id = GlobalConfig.get("ZOOM_CLIENT_ID") client_secret = GlobalConfig.get("ZOOM_CLIENT_SECRET") token = Base64.strict_encode64("#{client_id}:#{client_secret}") { "Authorization" => "Basic #{token}", "Content-Type" => "application/x-www-form-urlencoded" } end describe "POST oauth_token" do it "makes an oauth authorization request with the given code and redirect uri" do WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL). with( body: { grant_type: "authorization_code", code: "test_code", redirect_uri: "test_uri" }, headers: oauth_request_header) response = ZoomApi.new.oauth_token("test_code", "test_uri") expect(response.success?).to eq(true) end end describe "GET user_info" do it "requests user information with the given user token" do WebMock.stub_request(:get, "#{ZoomApi.base_uri}/users/me").with(headers: { "Authorization" => "Bearer test_token" }) response = ZoomApi.new.user_info("test_token") expect(response.success?).to eq(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/oman_vat_number_validation_service_spec.rb
spec/services/oman_vat_number_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe OmanVatNumberValidationService do it "returns true when valid VAT number is provided" do vat_number = "OM1234567890" expect(described_class.new(vat_number).process).to be(true) end it "returns false when nil VAT number is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when blank VAT number is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when VAT number with invalid format is provided" do expect(described_class.new("OM123456").process).to be(false) expect(described_class.new("ON1234567890").process).to be(false) expect(described_class.new("om1234567890").process).to be(false) expect(described_class.new("1234567890").process).to be(false) expect(described_class.new("OMABCDEFGHIJ").process).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/save_public_files_service_spec.rb
spec/services/save_public_files_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SavePublicFilesService do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let!(:public_file1) { create(:public_file, :with_audio, resource: product, display_name: "Audio 1") } let!(:public_file2) { create(:public_file, :with_audio, resource: product, display_name: "Audio 2") } let(:content) do <<~HTML <p>Some text</p> <public-file-embed id="#{public_file1.public_id}"></public-file-embed> <p>Hello world!</p> <public-file-embed id="#{public_file2.public_id}"></public-file-embed> <p>More text</p> HTML end describe "#process" do it "updates existing files and returns cleaned content" do files_params = [ { "id" => public_file1.public_id, "name" => "Updated Audio 1", "status" => { "type" => "saved" } }, { "id" => public_file2.public_id, "name" => "", "status" => { "type" => "saved" } }, { "id" => "blob:http://example.com/audio.mp3", "name" => "Audio 3", "status" => { "type" => "uploading" } } ] service = described_class.new(resource: product, files_params:, content:) result = service.process expect(public_file1.reload.attributes.values_at("display_name", "scheduled_for_deletion_at")).to eq(["Updated Audio 1", nil]) expect(public_file2.reload.attributes.values_at("display_name", "scheduled_for_deletion_at")).to eq(["Untitled", nil]) expect(product.public_files.alive.count).to eq(2) expect(result).to eq(content) end it "schedules unused files for deletion" do unused_file = create(:public_file, :with_audio, resource: product) files_params = [ { "id" => public_file1.public_id, "name" => "Audio 1", "status" => { "type" => "saved" } } ] service = described_class.new(resource: product, files_params:, content:) service.process expect(product.public_files.alive.count).to eq(3) expect(unused_file.reload.scheduled_for_deletion_at).to be_within(5.seconds).of(10.days.from_now) expect(public_file1.reload.scheduled_for_deletion_at).to be_nil expect(public_file2.reload.scheduled_for_deletion_at).to be_within(5.seconds).of(10.days.from_now) end it "removes invalid file embeds from content" do content_with_invalid_embeds = <<~HTML <p>Some text</p> <public-file-embed id="#{public_file1.public_id}"></public-file-embed> <p>Middle text</p> <public-file-embed id="nonexistent"></public-file-embed> <public-file-embed></public-file-embed> <p>More text</p> HTML files_params = [ { "id" => public_file1.public_id, "name" => "Audio 1", "status" => { "type" => "saved" } }, { "id" => public_file2.public_id, "name" => "Audio 2", "status" => { "type" => "saved" } }, ] service = described_class.new(resource: product, files_params:, content: content_with_invalid_embeds) result = service.process expect(result).to eq(<<~HTML <p>Some text</p> <public-file-embed id="#{public_file1.public_id}"></public-file-embed> <p>Middle text</p> <p>More text</p> HTML ) expect(product.public_files.alive.count).to eq(2) expect(public_file1.reload.scheduled_for_deletion_at).to be_nil expect(public_file2.reload.scheduled_for_deletion_at).to be_within(5.seconds).of(10.days.from_now) end it "handles empty files_params" do service = described_class.new(resource: product, files_params: nil, content:) result = service.process expect(result).to eq(<<~HTML <p>Some text</p> <p>Hello world!</p> <p>More text</p> HTML ) expect(public_file1.reload.scheduled_for_deletion_at).to be_present expect(public_file2.reload.scheduled_for_deletion_at).to be_present end it "handles empty content" do files_params = [ { "id" => public_file1.public_id, "status" => { "type" => "saved" } } ] service = described_class.new(resource: product, files_params:, content: nil) result = service.process expect(result).to eq("") expect(public_file1.reload.scheduled_for_deletion_at).to be_present expect(public_file2.reload.scheduled_for_deletion_at).to be_present end it "rolls back on error" do files_params = [ { "id" => public_file1.public_id, "name" => "Updated Audio 1", "status" => { "type" => "saved" } } ] service = described_class.new(resource: product, files_params:, content:) allow_any_instance_of(PublicFile).to receive(:save!).and_raise(ActiveRecord::RecordInvalid.new) expect do service.process end.to raise_error(ActiveRecord::RecordInvalid) expect(public_file1.reload.display_name).to eq("Audio 1") expect(public_file1.reload.scheduled_for_deletion_at).to be_nil expect(public_file2.reload.scheduled_for_deletion_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/abn_validation_service_spec.rb
spec/services/abn_validation_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe AbnValidationService do before do @vatstack_response = { "active" => true, "company_address" => "NSW 2020", "company_name" => "KANGAROO AIRWAYS LIMITED", "company_type" => "PUB", "consultation_number" => nil, "country_code" => "AU", "created" => "2022-02-13T16:09:08.189Z", "external_id" => nil, "id" => "62092d24a1f0d913207815ce", "query" => "51824753556", "requested" => "2022-02-13T16:09:08.186Z", "type" => "au_gst", "updated" => "2022-02-13T16:09:08.189Z", "valid" => true, "valid_format" => true, "vat_number" => "51824753556" } end it "returns true when valid abn is provided" do abn_id = "51824753556" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "au_gst", "query" => abn_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response) expect(described_class.new(abn_id).process).to be(true) end it "returns false when valid abn is provided, but government services are down" do abn_id = "51824753556" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "au_gst", "query" => abn_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response.merge("valid" => nil)) expect(described_class.new(abn_id).process).to be(false) end it "returns false when nil abn is provided" do expect(described_class.new(nil).process).to be(false) end it "returns false when blank abn is provided" do expect(described_class.new(" ").process).to be(false) end it "returns false when abn with invalid format is provided" do abn_id = "some-invalid-id" query_response = "SOMEINVALIDID" invalid_input_response = { "code" => "INVALID_INPUT", "query" => query_response, "valid" => false, "valid_format" => false } expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "au_gst", "query" => abn_id }, headers: hash_including("X-API-KEY")).and_return(invalid_input_response) expect(described_class.new(abn_id).process).to be(false) end it "returns false when invalid abn is provided" do abn_id = "11111111111" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "au_gst", "query" => abn_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response.merge("valid" => false)) expect(described_class.new(abn_id).process).to be(false) end it "returns false when inactive abn is provided" do abn_id = "12345678901" expect(HTTParty).to receive(:post).with("https://api.vatstack.com/v1/validations", timeout: 5, body: { "type" => "au_gst", "query" => abn_id }, headers: hash_including("X-API-KEY")).and_return(@vatstack_response.merge("active" => false)) expect(described_class.new(abn_id).process).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/instant_payouts_service_spec.rb
spec/services/instant_payouts_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe InstantPayoutsService, :vcr do let(:seller) { create(:compliant_user) } before do create(:tos_agreement, user: seller) create(:user_compliance_info, user: seller) create_list(:payment_completed, 4, user: seller) end describe "#perform" do context "with stripe account" do before do create(:ach_account_stripe_succeed, user: seller) merchant_account = StripeMerchantAccountManager.create_account(seller.reload, passphrase: "1234") @merchant_account = merchant_account @stripe_account = Stripe::Account.retrieve(merchant_account.charge_processor_merchant_id) @stripe_account.refresh until @stripe_account.payouts_enabled? end context "when seller has a balance within the instant payout range" do before do Stripe::Transfer.create(destination: @stripe_account.id, currency: "usd", amount: 1000_00) create(:balance, amount_cents: 1000_00, holding_amount_cents: 1000_00, user: seller, date: Date.yesterday, merchant_account: @merchant_account) end it "creates and processes an instant payout" do expect do result = described_class.new(seller).perform expect(result[:success]).to be true end.to change { Payment.count }.by(1) payment = Payment.last expect(payment.payout_type).to eq(Payouts::PAYOUT_TYPE_INSTANT) expect(payment.processor).to eq(PayoutProcessorType::STRIPE) expect(payment.user_id).to eq(seller.id) expect(payment.state).to eq("processing") expect(payment.stripe_transfer_id).to match(/po_/) expect(payment.stripe_connect_account_id).to match(/acct_/) end end context "when the seller has balances that exceed the maximum instant payout amount" do let!(:balance1) { create(:balance, amount_cents: 6000_00, holding_amount_cents: 6000_00, user: seller, date: 7.days.ago, merchant_account: @merchant_account) } let!(:balance2) { create(:balance, amount_cents: 3999_00, holding_amount_cents: 3999_00, user: seller, date: 6.days.ago, merchant_account: @merchant_account) } let!(:balance3) { create(:balance, amount_cents: 5100_00, holding_amount_cents: 5100_00, user: seller, date: 5.days.ago, merchant_account: @merchant_account) } let!(:balance4) { create(:balance, amount_cents: 5000_00, holding_amount_cents: 5000_00, user: seller, date: 4.days.ago, merchant_account: @merchant_account) } let!(:balance5) { create(:balance, amount_cents: 3500_00, holding_amount_cents: 3500_00, user: seller, date: 3.days.ago, merchant_account: @merchant_account) } let!(:balance6) { create(:balance, amount_cents: 3000_00, holding_amount_cents: 3000_00, user: seller, date: 2.days.ago, merchant_account: @merchant_account) } let!(:balance7) { create(:balance, amount_cents: 3000_00, holding_amount_cents: 3000_00, user: seller, date: 1.day.ago, merchant_account: @merchant_account) } before do Stripe::Transfer.create(destination: @stripe_account.id, currency: "usd", amount: 29_599_00) end it "creates and processes multiple instant payouts" do expect do result = described_class.new(seller).perform expect(result[:success]).to be true end.to change { Payment.count }.by(4) payments = Payment.last(4) expect(payments[0].amount_cents).to eq(9_707_76) expect(payments[0].balances).to match_array([balance1, balance2]) expect(payments[1].amount_cents).to eq(4_951_45) expect(payments[1].balances).to match_array([balance3]) expect(payments[2].amount_cents).to eq(8_252_42) expect(payments[2].balances).to match_array([balance4, balance5]) expect(payments[3].amount_cents).to eq(5_825_24) expect(payments[3].balances).to match_array([balance6, balance7]) payments.each do |payment| expect(payment.payout_type).to eq(Payouts::PAYOUT_TYPE_INSTANT) expect(payment.processor).to eq(PayoutProcessorType::STRIPE) expect(payment.user_id).to eq(seller.id) expect(payment.state).to eq("processing") expect(payment.stripe_transfer_id).to match(/po_/) expect(payment.stripe_connect_account_id).to match(/acct_/) end end end context "when seller has a balance less than $10" do before do create(:balance, amount_cents: 500, holding_amount_cents: 500, user: seller, date: Date.yesterday, merchant_account: @merchant_account) Stripe::Transfer.create(destination: @stripe_account.id, currency: "usd", amount: 5_00) end it "returns error message" do expect do result = described_class.new(seller).perform expect(result).to eq( success: false, error: "You need at least $10 in your balance to request an instant payout." ) end.not_to change { Payment.count } end end context "when seller has a balance greater than $10,000" do before do create(:balance, amount_cents: 11_000_00, holding_amount_cents: 11_000_00, user: seller, date: Date.yesterday, merchant_account: @merchant_account) Stripe::Transfer.create(destination: @stripe_account.id, currency: "usd", amount: 11_000_00) end it "returns error message" do expect do result = described_class.new(seller).perform expect(result).to eq( success: false, error: "Your balance exceeds the maximum instant payout amount. Please contact support for assistance." ) end.not_to change { Payment.count } end end end context "when seller is not eligible for instant payouts" do before do allow(seller).to receive(:eligible_for_instant_payouts?).and_return(false) end it "returns error message" do expect do result = described_class.new(seller).perform expect(result).to eq( success: false, error: "Your account is not eligible for instant payouts at this time." ) end.not_to change { Payment.count } end end context "when seller has no stripe account" do it "returns an error" do expect do result = described_class.new(seller).perform expect(result).to eq( success: false, error: "Your account is not eligible for instant payouts at this time." ) end.not_to change { Payment.count } end end context "when seller is not compliant" do before do seller.update!(user_risk_state: "not_reviewed") end it "returns error message" do expect(seller.eligible_for_instant_payouts?).to be false expect do result = described_class.new(seller).perform expect(result).to eq( success: false, error: "Your account is not eligible for instant payouts at this time." ) end.not_to change { Payment.count } end end context "when the payout fails" do let(:payment) { build(:payment_failed) } before do allow_any_instance_of(User).to receive(:eligible_for_instant_payouts?).and_return(true) allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).and_return(1000_00) allow_any_instance_of(User).to receive(:instant_payouts_supported?).and_return(true) create(:balance, holding_amount_cents: 1000_00, user: seller, date: Date.yesterday) allow(Payouts).to receive(:create_payment).and_return([payment, []]) allow(StripePayoutProcessor).to receive(:process_payments) end it "returns an error" do result = described_class.new(seller).perform expect(result).to eq(success: false, error: "Failed to process instant payout") 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/save_files_service_spec.rb
spec/services/save_files_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SaveFilesService do before do @product = create(:product) end subject(:service) { described_class } describe ".perform" do context "when params is empty" do it "does not raise an error" do service.perform(@product, {}) end end it "updates files" do file_1 = create(:product_file, link: @product, description: "pencil", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png") file_2 = create(:product_file, link: @product, description: "manual", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf") @product.product_files << file_1 @product.product_files << file_2 service.perform(@product, { files: [{ external_id: file_2.external_id, url: file_2.url, display_name: "new manual", description: "new manual description", position: 2 }, { external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/book.pdf", display_name: "new book", description: "new book description", position: 1 }, { external_id: SecureRandom.uuid, url: "https://www.gumroad.com", display_name: "new link", description: "new link description", extension: "URL", position: 0 }] }) expect(@product.product_files.count).to eq(4) expect(@product.product_files.alive.count).to eq(3) manual_file = @product.product_files.alive[0].reload expect(manual_file.display_name).to eq("new manual") expect(manual_file.description).to eq("new manual description") expect(manual_file.position).to eq(2) book_file = @product.product_files.alive[1].reload expect(book_file.url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/book.pdf") expect(book_file.unique_url_identifier).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/book.pdf") expect(book_file.display_name).to eq("new book") expect(book_file.description).to eq("new book description") expect(book_file.position).to eq(1) link_file = @product.product_files.alive[2].reload expect(link_file.url).to eq("https://www.gumroad.com") expect(link_file.unique_url_identifier).to eq("https://www.gumroad.com") expect(link_file.display_name).to eq("new link") expect(link_file.description).to eq("new link description") expect(link_file.external_link?).to eq(true) expect(link_file.position).to eq(0) pencil_file = @product.product_files[0].reload expect(pencil_file.deleted?).to eq(true) end it "updates subtitles" do @product.product_files << create(:streamable_video) @product.product_files << create(:listenable_audio) @product.product_files << create(:non_streamable_video) @product.product_files << create(:readable_document) video_1 = @product.product_files.first video_2 = @product.product_files.third video_1.subtitle_files << create(:subtitle_file) video_2.subtitle_files << create(:subtitle_file) video_2.subtitle_files << create(:subtitle_file) service.perform(@product, { files: [{ external_id: @product.product_files.first.external_id, url: @product.product_files.first.url, subtitle_files: [{ "url" => "https://newurl1.srt", "language" => "new-language1" }] }, { external_id: @product.product_files.second.external_id, url: @product.product_files.second.url }, { external_id: @product.product_files.third.external_id, url: @product.product_files.third.url, subtitle_files: [{ "url" => "https://newurl2.srt", "language" => "new-language2" }] }, { external_id: @product.product_files.fourth.external_id, url: @product.product_files.fourth.url }, ] }) expect(@product.product_files.count).to eq(4) video_1_subtitles = video_1.subtitle_files.reload.alive expect(video_1_subtitles.count).to eq(1) expect(video_1_subtitles.first.url).to eq("https://newurl1.srt") expect(video_1_subtitles.first.language).to eq("new-language1") video_2_subtitles = video_2.subtitle_files.reload.alive expect(video_2_subtitles.count).to eq(1) expect(video_2_subtitles.first.url).to eq("https://newurl2.srt") expect(video_2_subtitles.first.language).to eq("new-language2") end it "supports `files` param as an array" do installment = create(:installment, workflow: create(:workflow)) file1 = create(:product_file, installment:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png") file2 = create(:product_file, installment:, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf") service.perform(installment, { files: [ { external_id: file1.external_id, url: file2.url, position: 1, stream_only: false, subtitle_files: [], }, { external_id: file2.external_id, url: file2.url, position: 2, stream_only: false, subtitle_files: [], }, ] }) expect(installment.product_files.alive.count).to eq(2) expect(installment.product_files.pluck(:id, :position, :url)).to match_array([[file1.id, 1, file2.url], [file2.id, 2, file2.url]]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/subscribe_preview_generator_service_spec.rb
spec/services/subscribe_preview_generator_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe SubscribePreviewGeneratorService, type: :system, js: true do describe "#generate_pngs" do before do @user1 = create(:user, name: "User 1", username: "user1") @user2 = create(:user, name: "User 2", username: "user2") visit user_subscribe_preview_path(@user1.username) # Needed to boot the server end it "generates a png correctly" do images = described_class.generate_pngs([@user1, @user2]) expect(images.first).to start_with("\x89PNG".b) expect(images.second).to start_with("\x89PNG".b) end it "always quits the webdriver on success" do expect_any_instance_of(Selenium::WebDriver::Driver).to receive(:quit) described_class.generate_pngs([@user1]) end it "always quits the webdriver on error" do error = "FAILURE" expect_any_instance_of(Selenium::WebDriver::Driver).to receive(:quit) allow_any_instance_of(Selenium::WebDriver::Driver).to receive(:screenshot_as).and_raise(error) expect { described_class.generate_pngs([@user2]) }.to raise_error(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/ai/product_details_generator_service_spec.rb
spec/services/ai/product_details_generator_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Ai::ProductDetailsGeneratorService, :vcr do let(:current_seller) { create(:user) } let(:service) { described_class.new(current_seller:) } describe "#generate_product_details" do let(:prompt) { "Create a coding tutorial ebook about Ruby on Rails for $29.99" } context "with valid prompt" do it "generates product details successfully" do result = service.generate_product_details(prompt:) expect(result).to include( :name, :description, :summary, :native_type, :number_of_content_pages, :price, :duration_in_seconds ) expect(result[:name]).to eq("Ruby on Rails Coding Tutorial") expect(result[:description]).to eq("<p>Unlock the power of web development with our comprehensive <strong>Ruby on Rails Coding Tutorial</strong>. This ebook is designed for both beginners and experienced developers looking to enhance their skills in Ruby on Rails.</p><ul><li><strong>Learn the Basics:</strong> Understand the fundamental concepts of Ruby and Rails.</li><li><strong>Build Real Applications:</strong> Follow step-by-step instructions to create your own web applications.</li><li><strong>Advanced Techniques:</strong> Explore advanced features and best practices to optimize your projects.</li><li><strong>Hands-On Projects:</strong> Engage in practical projects to solidify your learning.</li></ul><p>Whether you're starting from scratch or looking to refine your skills, this ebook is your ultimate guide to mastering Ruby on Rails! 🚀</p>") expect(result[:summary]).to eq("A comprehensive ebook that teaches you Ruby on Rails, from basics to advanced techniques, with hands-on projects.") expect(result[:native_type]).to eq("ebook") expect(result[:number_of_content_pages]).to eq(4) expect(result[:price]).to eq(29.99) expect(result[:price_frequency_in_months]).to be_nil expect(result[:currency_code]).to eq("usd") expect(result[:duration_in_seconds]).to be_a(Numeric) end it "includes price frequency for membership products" do membership_prompt = "Create a quarterly membership for Ruby on Rails developers for $19/month" result = service.generate_product_details(prompt: membership_prompt) expect(result[:price_frequency_in_months]).to eq(3) end end context "with different currency code" do it "returns price in seller's currency" do result = service.generate_product_details(prompt: "Create a coding tutorial ebook about Ruby on Rails for 19.99 yen") expect(result[:price]).to eq(19.99) expect(result[:currency_code]).to eq("jpy") end end context "with blank prompt" do it "raises an error" do expect { service.generate_product_details(prompt: "") } .to raise_error(described_class::InvalidPromptError, "Prompt cannot be blank") end end context "when OpenAI returns invalid JSON" do before do allow_any_instance_of(OpenAI::Client).to receive(:chat).and_return( "choices" => [{ "message" => { "content" => "invalid json response" } }] ) end it "raises an error and retries" do expect { service.generate_product_details(prompt:) } .to raise_error(described_class::MaxRetriesExceededError) end end end describe "#generate_cover_image" do let(:product_name) { "Joy of Programming in Ruby" } context "with valid product name" do it "generates cover image successfully" do result = service.generate_cover_image(product_name:) expect(result[:image_data]).to be_a(String) expect(result[:duration_in_seconds]).to be_a(Numeric) end end context "when OpenAI image generation fails" do before do allow_any_instance_of(OpenAI::Client).to receive(:images).and_return(double(generate: { "data" => [] })) end it "raises an error and retries" do expect { service.generate_cover_image(product_name:) } .to raise_error(described_class::MaxRetriesExceededError) end end end describe "#generate_rich_content_pages" do let(:product_info) do { name: "Joy of Programming in Ruby", description: "<p>Learn Ruby from the ground up</p>", native_type: "ebook", number_of_content_pages: 2 } end context "with valid product info" do it "generates rich content pages successfully" do result = service.generate_rich_content_pages(product_info) expect(result[:pages].size).to eq(2) expect(result[:pages].first["title"]).to eq("Introduction to Ruby") expect(result[:pages].first["content"]).to eq([{ "type" => "heading", "attrs" => { "level" => 2 }, "content" => [{ "type" => "text", "text" => "What is Ruby?" }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ruby is a dynamic, open-source programming language that is known for its simplicity and productivity. It was created by Yukihiro Matsumoto in the mid-1990s and has since gained immense popularity among developers." }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "One of the key features of Ruby is its elegant syntax that is easy to read and write. This makes it an ideal choice for beginners who are just starting their programming journey." }] }, { "type" => "heading", "attrs" => { "level" => 3 }, "content" => [{ "type" => "text", "text" => "Why Learn Ruby?" }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Learning Ruby opens up a world of opportunities, especially in web development. Ruby on Rails, a popular web application framework, is built on Ruby and is widely used by many startups and established companies." }] }, { "type" => "bulletList", "content" => [{ "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Easy to learn for beginners." }] }] }, { "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Strong community support." }] }] }, { "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Versatile for various applications." }] }] }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "In this section, we will cover the foundational concepts of Ruby, including variables, data types, and control structures." }] }]) expect(result[:pages].last["title"]).to eq("Getting Started with Ruby") expect(result[:pages].last["content"]).to eq([ { "type" => "heading", "attrs" => { "level" => 2 }, "content" => [{ "type" => "text", "text" => "Setting Up Your Environment" }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Before diving into programming, you need to set up your development environment. This involves installing Ruby and a code editor." }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "You can download Ruby from the official website, and we recommend using Visual Studio Code as your code editor due to its rich features and extensions." }] }, { "type" => "heading", "attrs" => { "level" => 3 }, "content" => [{ "type" => "text", "text" => "Writing Your First Ruby Program" }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Once your environment is set up, you can create your first Ruby program. Open your code editor, create a new file named 'hello.rb', and write the following code:" }] }, { "type" => "codeBlock", "content" => [{ "type" => "text", "text" => "puts 'Hello, World!'" }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Save the file and run it in your terminal using the command `ruby hello.rb`. You should see 'Hello, World!' printed on the screen." }] }, { "type" => "heading", "attrs" => { "level" => 3 }, "content" => [{ "type" => "text", "text" => "Next Steps" }] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "In the following chapters, we will explore more advanced topics such as object-oriented programming, error handling, and building web applications using Ruby on Rails." }] }]) expect(result[:duration_in_seconds]).to be_a(Numeric) end end context "when OpenAI returns malformed JSON with type colon syntax" do before do malformed_response = { "pages" => [ { "title" => "Chapter 1", "content" => [ { "type: " => "paragraph", "content" => [{ "type" => "text", "text" => "Content" }] } ] } ] } allow_any_instance_of(OpenAI::Client).to receive(:chat).and_return( "choices" => [{ "message" => { "content" => JSON.generate(malformed_response).gsub('"type"', '"type: "') } }] ) end it "cleans up the JSON and parses successfully" do result = service.generate_rich_content_pages(product_info) expect(result[:pages]).to be_an(Array) expect(result[:pages].first["content"].first["type"]).to eq("paragraph") 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/push_notification_service/ios_spec.rb
spec/services/push_notification_service/ios_spec.rb
# frozen_string_literal: true require "spec_helper" describe PushNotificationService::Ios do describe "creator app" do it "creates an APNS notification" do app = double("apns_app") allow(PushNotificationService::Ios).to receive(:creator_app).and_return(app) device_token = "ABC" title = "Test" body = "Body" notification = double("apns_notification") expect(Rpush::Apns2::Notification).to receive(:new).with({ app:, device_token:, alert: { "title" => title, "body" => body }, sound: "chaching.wav", data: { headers: { "apns-topic": "com.GRD.iOSCreator" } } }).and_return(notification) expect(notification).to receive(:save!) PushNotificationService::Ios.new(device_token:, title:, body:, app_type: Device::APP_TYPES[:creator], sound: Device::NOTIFICATION_SOUNDS[:sale]).process end end describe "consumer app" do context "when notification sound is passed" do it "creates an APNS notification" do app = double("apns_app") allow(PushNotificationService::Ios).to receive(:consumer_app).and_return(app) device_token = "ABC" title = "Test" body = "Body" notification = double("apns_notification") expect(Rpush::Apns2::Notification).to receive(:new).with({ app:, device_token:, alert: { "title" => title, "body" => body }, sound: "chaching.wav", data: { headers: { "apns-topic": "com.GRD.Gumroad" } } }).and_return(notification) expect(notification).to receive(:save!) PushNotificationService::Ios.new(device_token:, title:, body:, app_type: Device::APP_TYPES[:consumer], sound: Device::NOTIFICATION_SOUNDS[:sale]).process end end context "when notification sound is not passed" do it "creates an APNS notification" do app = double("apns_app") allow(PushNotificationService::Ios).to receive(:consumer_app).and_return(app) device_token = "ABC" title = "Test" body = "Body" notification = double("apns_notification") expect(Rpush::Apns2::Notification).to receive(:new).with({ app:, device_token:, alert: { "title" => title, "body" => body }, data: { headers: { "apns-topic": "com.GRD.Gumroad" } } }).and_return(notification) expect(notification).to receive(:save!) PushNotificationService::Ios.new(device_token:, title:, body:, app_type: Device::APP_TYPES[:consumer]).process end end context "empty body" do it "sets proper alert message" do app = double("apns_app") allow(PushNotificationService::Ios).to receive(:consumer_app).and_return(app) device_token = "ABC" title = "Test" notification = double("apns_notification") expect(Rpush::Apns2::Notification).to receive(:new).with({ app:, device_token:, alert: title, data: { headers: { "apns-topic": "com.GRD.Gumroad" } } }).and_return(notification) expect(notification).to receive(:save!) PushNotificationService::Ios.new(device_token:, title:, body: nil, app_type: Device::APP_TYPES[:consumer]).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/push_notification_service/android_spec.rb
spec/services/push_notification_service/android_spec.rb
# frozen_string_literal: true require "spec_helper" describe PushNotificationService::Android do before do Feature.activate(:send_notifications_to_android_devices) end describe "consumer app" do context "when notification sound is passed" do it "creates a FCM notification with sound" do app = double("fcm_app") allow(PushNotificationService::Android).to receive(:consumer_app).and_return(app) device_token = "ABC" title = "Test" body = "Test body" sound = Device::NOTIFICATION_SOUNDS[:sale] notification = double("fcm_notification") expect(Rpush::Fcm::Notification).to receive(:new).and_return(notification) expect(notification).to receive(:app=).with(app) expect(notification).to receive(:alert=).with(title) expect(notification).to receive(:device_token=).with(device_token) expect(notification).to receive(:content_available=).with(true) expect(notification).to receive(:sound=).with(sound) expect(notification).to receive(:notification=).with({ title: title, body: body, icon: "notification_icon", channel_id: "Purchases" }) expect(notification).to receive(:data=).with({ message: title }) expect(notification).to receive(:save!) PushNotificationService::Android.new(device_token: device_token, title: title, body: body, app_type: Device::APP_TYPES[:consumer], sound: sound).process end end context "when notification sound is not passed" do it "creates a FCM notification without sound" do app = double("fcm_app") allow(PushNotificationService::Android).to receive(:consumer_app).and_return(app) device_token = "ABC" title = "Test" body = "Test body" notification = double("fcm_notification") expect(Rpush::Fcm::Notification).to receive(:new).and_return(notification) expect(notification).to receive(:app=).with(app) expect(notification).to receive(:alert=).with(title) expect(notification).to receive(:device_token=).with(device_token) expect(notification).to receive(:content_available=).with(true) expect(notification).to receive(:notification=).with({ title: title, body: body, icon: "notification_icon" }) expect(notification).to receive(:data=).with({ message: title }) expect(notification).to receive(:save!) PushNotificationService::Android.new(device_token: device_token, title: title, body: body, app_type: Device::APP_TYPES[:consumer]).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/handle_email_event_info/for_receipt_email_spec.rb
spec/services/handle_email_event_info/for_receipt_email_spec.rb
# frozen_string_literal: true describe HandleEmailEventInfo::ForReceiptEmail do let!(:preorder) { create(:preorder) } let(:purchase) { create(:purchase) } def handler_class_for(email_provider) case email_provider when :sendgrid then HandleSendgridEventJob when :resend then HandleResendEventJob end end describe ".perform" do RSpec.shared_examples "handles bounced event type" do |email_provider| context "when CustomerEmailInfo doesn't exist" do it "creates a new email info and mark it as bounced" do travel_to(Time.current) do handler_class_for(email_provider).new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(CustomerEmailInfo.last.state).to eq "bounced" expect(CustomerEmailInfo.last.email_name).to eq mailer_method end end context "when CustomerEmailInfo exists" do let!(:email_info) { create(:customer_email_info, email_name: mailer_method, purchase:) } it "marks it as bounced and deletes the follower" do travel_to(Time.current) do handler_class_for(email_provider).new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(email_info.reload.state).to eq "bounced" expect(follower.reload).to be_deleted end end end RSpec.shared_examples "handles delivered event type" do |email_provider| context "when CustomerEmailInfo doesn't exist" do it "creates a new email info and mark it as delivered" do travel_to(Time.current) do handler_class_for(email_provider).new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(CustomerEmailInfo.last.state).to eq "delivered" if email_provider == :resend expect(CustomerEmailInfo.last.delivered_at.change(usec: 0)).to eq(Time.zone.parse(params["data"]["created_at"]).change(usec: 0)) else expect(CustomerEmailInfo.last.delivered_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end end end context "when CustomerEmailInfo exists" do let!(:email_info) { create(:customer_email_info, email_name: mailer_method, purchase:) } it "marks it as delivered" do travel_to(Time.current) do handler_class_for(email_provider).new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(email_info.reload.state).to eq "delivered" if email_provider == :resend expect(email_info.reload.delivered_at.change(usec: 0)).to eq(Time.zone.parse(params["data"]["created_at"]).change(usec: 0)) else expect(email_info.reload.delivered_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end end end end RSpec.shared_examples "handles open event type" do |email_provider| context "when CustomerEmailInfo doesn't exist" do it "creates a new email info and mark it as opened" do travel_to(Time.current) do handler_class_for(email_provider).new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(CustomerEmailInfo.last.state).to eq "opened" if email_provider == :resend expect(CustomerEmailInfo.last.opened_at.change(usec: 0)).to eq(Time.zone.parse(params["data"]["created_at"]).change(usec: 0)) else expect(CustomerEmailInfo.last.opened_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end end end context "when CustomerEmailInfo exists" do let!(:email_info) { create(:customer_email_info, email_name: mailer_method, purchase:) } it "marks it as opened" do travel_to(Time.current) do handler_class_for(email_provider).new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(email_info.reload.state).to eq "opened" if email_provider == :resend expect(email_info.reload.opened_at.change(usec: 0)).to eq(Time.zone.parse(params["data"]["created_at"]).change(usec: 0)) else expect(email_info.reload.opened_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end end end end RSpec.shared_examples "handles spamreport event type" do |email_provider| context "when CustomerEmailInfo doesn't exist" do it "unsubscribes the buyer of the purchase" do another_product = create(:product, user: purchase.seller) another_purchase = create(:purchase, link: another_product, email: purchase.email) if email_provider == :resend expect do handler_class_for(email_provider).new.perform(params) end.not_to change { [purchase.reload.can_contact, another_purchase.reload.can_contact] } else expect do handler_class_for(email_provider).new.perform(params) end.to change { [purchase.reload.can_contact, another_purchase.reload.can_contact] }.from([true, true]).to([false, false]) end end end context "when CustomerEmailInfo exists" do let!(:email_info) { create(:customer_email_info, email_name: mailer_method, purchase:) } it "unsubscribes the buyer of the purchase and cancels the follower" do follower&.destroy follower = create(:active_follower, email: purchase.email, followed_id: purchase.seller_id) another_product = create(:product, user: purchase.seller) another_purchase = create(:purchase, link: another_product, email: purchase.email) if email_provider == :resend expect do handler_class_for(email_provider).new.perform(params) end.not_to change { [purchase.reload.can_contact, another_purchase.reload.can_contact, follower.reload.alive?] } else expect do handler_class_for(email_provider).new.perform(params) end.to change { [purchase.reload.can_contact, another_purchase.reload.can_contact, follower.reload.alive?] }.from([true, true, true]).to([false, false, false]) end end end end [EmailEventInfo::RECEIPT_MAILER_METHOD, EmailEventInfo::PREORDER_RECEIPT_MAILER_METHOD].each do |mailer_method| describe "#{mailer_method} method" do let(:mailer_method) { mailer_method } let(:mailer_args) do if mailer_method == EmailEventInfo::RECEIPT_MAILER_METHOD "[#{purchase.id}]" else "[#{preorder.id}]" end end before do preorder.purchases << purchase if mailer_method == EmailEventInfo::PREORDER_RECEIPT_MAILER_METHOD end context "with SendGrid" do let!(:follower) { create(:active_follower, email: purchase.email, followed_id: purchase.seller_id) } context "with type and identifier unique args" do let(:params) do { "_json" => [{ "event" => event_type, "type" => "CustomerMailer.#{mailer_method}", "identifier" => mailer_args }] } end context "with bounce event" do let(:event_type) { EmailEventInfo::EVENTS[:bounced][MailerInfo::EMAIL_PROVIDER_SENDGRID] } it_behaves_like "handles bounced event type", :sendgrid end context "with delivered event" do let(:event_type) { EmailEventInfo::EVENTS[:delivered][MailerInfo::EMAIL_PROVIDER_SENDGRID] } before { params["_json"].first["timestamp"] = 1.day.ago.to_i } it_behaves_like "handles delivered event type", :sendgrid end context "with open event" do let(:event_type) { EmailEventInfo::EVENTS[:opened][MailerInfo::EMAIL_PROVIDER_SENDGRID] } before { params["_json"].first["timestamp"] = 1.hour.ago.to_i } it_behaves_like "handles open event type", :sendgrid end context "with spamreport event" do let(:event_type) { EmailEventInfo::EVENTS[:complained][MailerInfo::EMAIL_PROVIDER_SENDGRID] } before { params["_json"].first["timestamp"] = 1.hour.ago.to_i } it_behaves_like "handles spamreport event type", :sendgrid end end context "with records as individual unique args" do let(:params) do { "_json" => [{ "event" => event_type, "mailer_class" => "CustomerMailer", "mailer_method" => mailer_method, "mailer_args" => mailer_args, "purchase_id" => purchase.id.to_s, }] } end context "with bounce event" do let(:event_type) { EmailEventInfo::EVENTS[:bounced][MailerInfo::EMAIL_PROVIDER_SENDGRID] } it_behaves_like "handles bounced event type", :sendgrid end context "with delivered event" do let(:event_type) { EmailEventInfo::EVENTS[:delivered][MailerInfo::EMAIL_PROVIDER_SENDGRID] } before { params["_json"].first["timestamp"] = 1.day.ago.to_i } it_behaves_like "handles delivered event type", :sendgrid end context "with open event" do let(:event_type) { EmailEventInfo::EVENTS[:opened][MailerInfo::EMAIL_PROVIDER_SENDGRID] } before { params["_json"].first["timestamp"] = 1.day.ago.to_i } it_behaves_like "handles open event type", :sendgrid end context "with spamreport event" do let(:event_type) { EmailEventInfo::EVENTS[:complained][MailerInfo::EMAIL_PROVIDER_SENDGRID] } before { params["_json"].first["timestamp"] = 1.hour.ago.to_i } it_behaves_like "handles spamreport event type", :sendgrid end end end context "with Resend" do let!(:follower) { create(:active_follower, email: purchase.email, followed_id: purchase.seller_id) } let(:params) do { "data" => { "created_at" => "2025-01-02 00:14:11.140106+00", "to" => ["customer@example.com"], "headers" => [ { "name" => MailerInfo.header_name(:mailer_class), "value" => MailerInfo.encrypt("CustomerMailer") }, { "name" => MailerInfo.header_name(:mailer_method), "value" => MailerInfo.encrypt(mailer_method) }, { "name" => MailerInfo.header_name(:mailer_args), "value" => MailerInfo.encrypt(mailer_args) }, { "name" => MailerInfo.header_name(:purchase_id), "value" => MailerInfo.encrypt(purchase.id.to_s) } ], }, "type" => event_type } end context "with bounce event" do let(:event_type) { EmailEventInfo::EVENTS[:bounced][MailerInfo::EMAIL_PROVIDER_RESEND] } it_behaves_like "handles bounced event type", :resend end context "with delivered event" do let(:event_type) { EmailEventInfo::EVENTS[:delivered][MailerInfo::EMAIL_PROVIDER_RESEND] } it_behaves_like "handles delivered event type", :resend end context "with open event" do let(:event_type) { EmailEventInfo::EVENTS[:opened][MailerInfo::EMAIL_PROVIDER_RESEND] } it_behaves_like "handles open event type", :resend end context "with spamreport event" do let(:event_type) { EmailEventInfo::EVENTS[:complained][MailerInfo::EMAIL_PROVIDER_RESEND] } it_behaves_like "handles spamreport event type", :resend end end end end describe "receipt - for a Charge", :vcr do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } let(:order) { charge.order } let!(:follower) { create(:active_follower, email: purchase.email, followed_id: purchase.seller_id) } before do order.purchases << purchase end context "with SendGrid" do let(:params) do { "_json" => [{ "event" => "bounce", "mailer_class" => "CustomerMailer", "mailer_method" => "receipt", "mailer_args" => "[nil,#{charge.id}]", "charge_id" => charge.id.to_s, }] } end context "when CustomerEmailInfo doesn't exist" do it "creates a new email info and marks it as bounced" do travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 email_info = CustomerEmailInfo.last expect(email_info.state).to eq "bounced" expect(email_info.email_name).to eq "receipt" expect(email_info.charge_id).to eq charge.id end end context "when CustomerEmailInfo exists" do let!(:email_info) do create( :customer_email_info, purchase_id: nil, email_name: "receipt", email_info_charge_attributes: { charge_id: charge.id } ) end it "marks it as bounced and deletes the follower" do travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(email_info.reload.state).to eq "bounced" expect(follower.reload).to be_deleted end end end context "with Resend" do let(:params) do { "data" => { "created_at" => "2025-01-02 00:14:11.140106+00", "to" => ["customer@example.com"], "headers" => [ { "name" => MailerInfo.header_name(:mailer_class), "value" => MailerInfo.encrypt("CustomerMailer") }, { "name" => MailerInfo.header_name(:mailer_method), "value" => MailerInfo.encrypt("receipt") }, { "name" => MailerInfo.header_name(:mailer_args), "value" => MailerInfo.encrypt("[nil,#{charge.id}]") }, { "name" => MailerInfo.header_name(:charge_id), "value" => MailerInfo.encrypt(charge.id.to_s) } ], }, "type" => EmailEventInfo::EVENTS[:bounced][MailerInfo::EMAIL_PROVIDER_RESEND] } end context "when CustomerEmailInfo doesn't exist" do it "creates a new email info and marks it as bounced" do travel_to(Time.current) do HandleResendEventJob.new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 email_info = CustomerEmailInfo.last expect(email_info.state).to eq "bounced" expect(email_info.email_name).to eq "receipt" expect(email_info.charge_id).to eq charge.id end end context "when CustomerEmailInfo exists" do let!(:email_info) do create( :customer_email_info, purchase_id: nil, email_name: "receipt", email_info_charge_attributes: { charge_id: charge.id } ) end it "marks it as bounced and deletes the follower" do travel_to(Time.current) do HandleResendEventJob.new.perform(params) end expect(CustomerEmailInfo.count).to eq 1 expect(email_info.reload.state).to eq "bounced" expect(follower.reload).to be_deleted end end end end describe "refund" do before do expect(CreatorContactingCustomersEmailInfo.count).to eq 0 end let(:params) do { "_json" => [{ "event" => "bounce", "type" => "CustomerMailer.refund", "identifier" => "[#{purchase.id}]" }] } end it "does not create a new email info" do travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CustomerEmailInfo.count).to eq 0 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/handle_email_event_info/for_abandoned_cart_email_spec.rb
spec/services/handle_email_event_info/for_abandoned_cart_email_spec.rb
# frozen_string_literal: true describe HandleEmailEventInfo::ForAbandonedCartEmail do let!(:abandoned_cart_workflow1) { create(:abandoned_cart_workflow) } let(:abandoned_cart_workflow_installment1) { abandoned_cart_workflow1.alive_installments.sole } let!(:abandoned_cart_workflow2) { create(:abandoned_cart_workflow) } let(:abandoned_cart_workflow_installment2) { abandoned_cart_workflow2.alive_installments.sole } let!(:abandoned_cart_workflow3) { create(:abandoned_cart_workflow) } let(:abandoned_cart_workflow_installment3) { abandoned_cart_workflow3.alive_installments.sole } let(:mailer_args_with_multiple_workflow_ids) { "[4, {\"#{abandoned_cart_workflow1.id}\"=>[31, 57, 60], \"#{abandoned_cart_workflow3.id}\"=>[22, 57, 60]}]" } let(:mailer_args_with_single_workflow_id) { "[4, {\"#{abandoned_cart_workflow1.id}\"=>[31, 57, 60]}]" } def handler_class_for(email_provider) case email_provider when :sendgrid then HandleSendgridEventJob when :resend then HandleResendEventJob end end describe ".perform" do RSpec.shared_examples "tracks a delivered event" do |email_provider| it "tracks a delivered event" do expect do handler_class_for(email_provider).new.perform(params) end.to change { abandoned_cart_workflow_installment1.reload.customer_count }.from(nil).to(1) .and change { abandoned_cart_workflow_installment3.reload.customer_count }.from(nil).to(1) expect(abandoned_cart_workflow_installment2.reload.customer_count).to be_nil end end RSpec.shared_examples "handles opened events" do |email_provider| it "tracks an open event" do now = Time.current travel_to(now) do handler_class_for(email_provider).new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq(2) CreatorEmailOpenEvent.each.with_index do |open_event, i| expect(open_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(open_event.mailer_args).to eq(mailer_args_with_multiple_workflow_ids) expect(open_event.installment_id).to eq([abandoned_cart_workflow_installment1.id, abandoned_cart_workflow_installment3.id][i]) expect(open_event.open_timestamps.sole.to_i).to eq(now.to_i) expect(open_event.open_count).to eq(1) end end it "sets cache for open event" do handler_class_for(email_provider).new.perform(params) expect(Rails.cache.read("unique_open_count_for_installment_#{abandoned_cart_workflow_installment1.id}")).to eq(1) expect(Rails.cache.read("unique_open_count_for_installment_#{abandoned_cart_workflow_installment2.id}")).to be_nil expect(Rails.cache.read("unique_open_count_for_installment_#{abandoned_cart_workflow_installment3.id}")).to eq(1) end it "tracks an open event and update it if there are 2 identical open events" do now = Time.current travel_to(now) do handler_class_for(email_provider).new.perform(params) end travel_to(now + 1.minute) do handler_class_for(email_provider).new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq(2) CreatorEmailOpenEvent.each.with_index do |open_event, i| expect(open_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(open_event.mailer_args).to eq(mailer_args_with_multiple_workflow_ids) expect(open_event.installment_id).to eq([abandoned_cart_workflow_installment1.id, abandoned_cart_workflow_installment3.id][i]) expect(open_event.open_timestamps.count).to eq(2) expect(open_event.open_timestamps.first.to_i).to eq(now.to_i) expect(open_event.open_timestamps.last.to_i).to eq((now + 1.minute).to_i) expect(open_event.open_count).to eq(2) end end end RSpec.shared_examples "handles click events" do |email_provider| it "tracks a click event with email click summary" do now = Time.current travel_to(now) do handler_class_for(email_provider).new.perform(params1) end installments = [abandoned_cart_workflow_installment1.id, abandoned_cart_workflow_installment3.id] expect(CreatorEmailClickSummary.count).to eq(2) CreatorEmailClickSummary.each.with_index do |summary, i| expect(summary.total_unique_clicks).to eq(1) expect(summary.installment_id).to eq(installments[i]) expect(summary.urls).to eq("https://www&#46;gumroad&#46;com/checkout" => 1) end expect(CreatorEmailClickEvent.count).to eq(2) CreatorEmailClickEvent.each.with_index do |click_event, i| expect(click_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(click_event.mailer_args).to eq(mailer_args_with_multiple_workflow_ids) expect(click_event.installment_id).to eq(installments[i]) expect(click_event.click_url).to eq "https://www&#46;gumroad&#46;com/checkout" expect(click_event.click_timestamps.sole.to_i).to eq(now.to_i) expect(click_event.click_count).to eq(1) end end it "sets cache on click event" do handler_class_for(email_provider).new.perform(params1) [abandoned_cart_workflow_installment1.id, abandoned_cart_workflow_installment3.id].each do |installment_id| expect(Rails.cache.read("unique_click_count_for_installment_#{installment_id}")).to eq(1) # It should also cache unique_open_count expect(Rails.cache.read("unique_open_count_for_installment_#{installment_id}")).to eq(1) end expect(Rails.cache.read("unique_click_count_for_installment_#{abandoned_cart_workflow_installment2.id}")).to be_nil expect(Rails.cache.read("unique_open_count_for_installment_#{abandoned_cart_workflow_installment2.id}")).to be_nil end it "tracks multiple click events and only one email click summary record for different URLs for an installment" do now = Time.current travel_to(now) do handler_class_for(email_provider).new.perform(params1) end travel_to(now + 1.minute) do handler_class_for(email_provider).new.perform(params2) end installments = [abandoned_cart_workflow_installment1.id, abandoned_cart_workflow_installment3.id] expect(CreatorEmailClickSummary.count).to eq(2) CreatorEmailClickSummary.each.with_index do |summary, i| expect(summary.total_unique_clicks).to eq(1) expect(summary.installment_id).to eq(installments[i]) expect(summary.urls).to eq( "https://www&#46;gumroad&#46;com/checkout" => 1, "https://seller&#46;gumroad&#46;com/l/abc" => 1 ) end expect(CreatorEmailClickEvent.count).to eq(4) expect(CreatorEmailClickEvent.where(installment_id: abandoned_cart_workflow_installment2.id).count).to eq(0) CreatorEmailClickEvent.order(created_at: :asc).each_slice(2).with_index do |click_events, i| click_events.each.with_index do |click_event, j| expect(click_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(click_event.mailer_args).to eq(mailer_args_with_multiple_workflow_ids) expect(click_event.installment_id).to eq(installments[j]) expect(click_event.click_url).to eq(["https://www&#46;gumroad&#46;com/checkout", "https://seller&#46;gumroad&#46;com/l/abc"][i]) expect(click_event.click_timestamps.sole.to_i).to eq([now, now + 1.minute][i].to_i) expect(click_event.click_count).to eq(1) end end end it "records a single email click summary for duplicate click events and updates the timestamps for the tracked click event" do now = Time.current travel_to(now) do handler_class_for(email_provider).new.perform(params1) end travel_to(now + 1.minute) do handler_class_for(email_provider).new.perform(params1) end installments = [abandoned_cart_workflow_installment1.id, abandoned_cart_workflow_installment3.id] expect(CreatorEmailClickSummary.count).to eq(2) CreatorEmailClickSummary.each.with_index do |summary, i| expect(summary.total_unique_clicks).to eq(1) expect(summary.installment_id).to eq(installments[i]) expect(summary.urls).to eq("https://www&#46;gumroad&#46;com/checkout" => 1) end expect(CreatorEmailClickEvent.count).to eq(2) CreatorEmailClickEvent.each.with_index do |click_event, i| expect(click_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(click_event.mailer_args).to eq(mailer_args_with_multiple_workflow_ids) expect(click_event.installment_id).to eq(installments[i]) expect(click_event.click_url).to eq("https://www&#46;gumroad&#46;com/checkout") expect(click_event.click_timestamps.sole.to_i).to eq(now.to_i) end end end RSpec.shared_examples "records an open event while tracking a click event when a corresponding open event does not exist yet" do |email_provider| it "records an open event while tracking a click event when a corresponding open event does not exist yet" do now = Time.current travel_to(now) do handler_class_for(email_provider).new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq(1) open_event = CreatorEmailOpenEvent.last expect(open_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(open_event.mailer_args).to eq(mailer_args_with_single_workflow_id) expect(open_event.installment_id).to eq(abandoned_cart_workflow_installment1.id) expect(open_event.open_timestamps.count).to eq(1) expect(open_event.open_timestamps.last.to_i).to eq(now.to_i) end end context "with SendGrid" do let(:params) do { "_json" => [ { "event" => event_type, "mailer_class" => "CustomerMailer", "mailer_method" => "abandoned_cart", "mailer_args" => mailer_args_with_multiple_workflow_ids } ] } end context "with delivered event" do let(:event_type) { EmailEventInfo::EVENTS[:delivered][MailerInfo::EMAIL_PROVIDER_SENDGRID] } it_behaves_like "tracks a delivered event", :sendgrid end context "with opened event" do let(:event_type) { EmailEventInfo::EVENTS[:opened][MailerInfo::EMAIL_PROVIDER_SENDGRID] } it_behaves_like "handles opened events", :sendgrid end context "with clicked event" do let(:event_type) { EmailEventInfo::EVENTS[:clicked][MailerInfo::EMAIL_PROVIDER_SENDGRID] } let(:params1) { params.deep_merge("_json" => [params["_json"].first.merge("url" => "https://www&#46;gumroad&#46;com/checkout")]) } let(:params2) { params.deep_merge("_json" => [params["_json"].first.merge("url" => "https://seller&#46;gumroad&#46;com/l/abc")]) } it_behaves_like "handles click events", :sendgrid context "with mailer_args with single workflow_id" do before do params["_json"] = [params["_json"].first.merge("mailer_args" => mailer_args_with_single_workflow_id, "url" => "https://www&#46;gumroad&#46;com/checkout")] end it_behaves_like "records an open event while tracking a click event when a corresponding open event does not exist yet", :sendgrid end it "handles the second event in the params array even if the first one is malformed" do now = Time.current params = { "_json" => [{ "event" => "click" }, { "event" => "click", "mailer_class" => "CustomerMailer", "mailer_method" => "abandoned_cart", "mailer_args" => mailer_args_with_multiple_workflow_ids, "url" => "https://www&#46;gumroad&#46;com/checkout" }] } travel_to(now) do handler_class_for(:sendgrid).new.perform(params) end installments = [abandoned_cart_workflow_installment1.id, abandoned_cart_workflow_installment3.id] expect(CreatorEmailClickSummary.count).to eq(2) CreatorEmailClickSummary.each.with_index do |summary, i| expect(summary.total_unique_clicks).to eq(1) expect(summary.installment_id).to eq(installments[i]) expect(summary.urls).to eq("https://www&#46;gumroad&#46;com/checkout" => 1) end expect(CreatorEmailClickEvent.count).to eq(2) CreatorEmailClickEvent.each.with_index do |click_event, i| expect(click_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(click_event.mailer_args).to eq(mailer_args_with_multiple_workflow_ids) expect(click_event.installment_id).to eq(installments[i]) expect(click_event.click_url).to eq("https://www&#46;gumroad&#46;com/checkout") expect(click_event.click_timestamps.sole.to_i).to eq(now.to_i) expect(click_event.click_count).to eq(1) end end end it "does not record an open event while recording a click event when a corresponding open event already exists" do now = Time.current params = { "_json" => [ { "event" => "open", "mailer_class" => "CustomerMailer", "mailer_method" => "abandoned_cart", "mailer_args" => mailer_args_with_single_workflow_id }, { "event" => "click", "mailer_class" => "CustomerMailer", "mailer_method" => "abandoned_cart", "mailer_args" => mailer_args_with_single_workflow_id, "url" => "https://www&#46;gumroad&#46;com/checkout" } ] } travel_to(now) do handler_class_for(:sendgrid).new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq(1) open_event = CreatorEmailOpenEvent.last expect(open_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(open_event.mailer_args).to eq(mailer_args_with_single_workflow_id) expect(open_event.installment_id).to eq(abandoned_cart_workflow_installment1.id) expect(open_event.open_timestamps.sole.to_i).to eq(now.to_i) expect(CreatorEmailClickSummary.count).to eq(1) summary = CreatorEmailClickSummary.last expect(summary.total_unique_clicks).to eq(1) expect(summary.installment_id).to eq(abandoned_cart_workflow_installment1.id) expect(summary.urls).to eq("https://www&#46;gumroad&#46;com/checkout" => 1) expect(CreatorEmailClickEvent.count).to eq(1) click_event = CreatorEmailClickEvent.last expect(click_event.mailer_method).to eq("CustomerMailer.abandoned_cart") expect(click_event.mailer_args).to eq(mailer_args_with_single_workflow_id) expect(click_event.installment_id).to eq(abandoned_cart_workflow_installment1.id) expect(click_event.click_url).to eq("https://www&#46;gumroad&#46;com/checkout") expect(click_event.click_timestamps.count).to eq(1) expect(click_event.click_timestamps.sole.to_i).to eq(now.to_i) expect(click_event.click_count).to eq(1) end end context "with Resend" do let(:params) do { "data" => { "created_at" => "2025-01-02 00:14:11.140106+00", "to" => ["customer@example.com"], "headers" => [ { "name" => MailerInfo.header_name(:mailer_class), "value" => MailerInfo.encrypt("CustomerMailer") }, { "name" => MailerInfo.header_name(:mailer_method), "value" => MailerInfo.encrypt("abandoned_cart") }, { "name" => MailerInfo.header_name(:mailer_args), "value" => MailerInfo.encrypt(mailer_args_with_multiple_workflow_ids) }, { "name" => MailerInfo.header_name(:workflow_ids), "value" => MailerInfo.encrypt([abandoned_cart_workflow1.id, abandoned_cart_workflow3.id].to_json) } ], }, "type" => event_type } end context "with delivered event" do let(:event_type) { EmailEventInfo::EVENTS[:delivered][MailerInfo::EMAIL_PROVIDER_RESEND] } it_behaves_like "tracks a delivered event", :resend end context "with opened event" do let(:event_type) { EmailEventInfo::EVENTS[:opened][MailerInfo::EMAIL_PROVIDER_RESEND] } it_behaves_like "handles opened events", :resend end context "with clicked event" do let(:event_type) { EmailEventInfo::EVENTS[:clicked][MailerInfo::EMAIL_PROVIDER_RESEND] } # "click": { # "ipAddress": "99.199.137.97", # "link": "https://app.gumroad.dev/d/d12705ba11d9a4d81776638601b911bd", # "timestamp": "2025-01-02T04:22:05.080Z", # "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" # }, let(:params1) { params.deep_merge("data" => { "click" => { "link" => "https://www&#46;gumroad&#46;com/checkout" } }) } let(:params2) { params.deep_merge("data" => { "click" => { "link" => "https://seller&#46;gumroad&#46;com/l/abc" } }) } it_behaves_like "handles click events", :resend context "with mailer_args with single workflow_id" do before do params["data"]["click"] = { "link" => "https://www&#46;gumroad&#46;com/checkout" } params["data"]["headers"].find { |header| header["name"] == MailerInfo.header_name(:workflow_ids) }["value"] = MailerInfo.encrypt([abandoned_cart_workflow1.id].to_json) params["data"]["headers"].find { |header| header["name"] == MailerInfo.header_name(:mailer_args) }["value"] = MailerInfo.encrypt(mailer_args_with_single_workflow_id) end it_behaves_like "records an open event while tracking a click event when a corresponding open event does not exist yet", :resend 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/handle_email_event_info/for_installment_email_spec.rb
spec/services/handle_email_event_info/for_installment_email_spec.rb
# frozen_string_literal: true describe HandleEmailEventInfo::ForInstallmentEmail do before do @installment = create(:installment) @purchase = create(:purchase) @identifier = "[#{@purchase.id}, #{@installment.id}]" end describe ".perform" do it "creates a new CreatorEmailOpenEvent object" do now = Time.current params = { "_json" => [{ "event" => "open", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq 1 open_event = CreatorEmailOpenEvent.last expect(open_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(open_event.mailer_args).to eq @identifier expect(open_event.installment_id).to eq @installment.id expect(open_event.open_timestamps.count).to eq 1 expect(open_event.open_timestamps.last.to_i).to eq now.to_i expect(open_event.open_count).to eq 1 end it "sets cache for open event" do params = { "_json" => [{ "event" => "open", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }] } HandleSendgridEventJob.new.perform(params) unique_open_count = Rails.cache.read("unique_open_count_for_installment_#{@installment.id}") expect(unique_open_count).to eq 1 end it "creates a new CreatorEmailOpenEvent object and then update it if there are 2 identical open events" do now = Time.current params = { "_json" => [{ "event" => "open", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end travel_to(now + 1.minute) do HandleSendgridEventJob.new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq 1 open_event = CreatorEmailOpenEvent.last expect(open_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(open_event.mailer_args).to eq @identifier expect(open_event.installment_id).to eq @installment.id expect(open_event.open_timestamps.count).to eq 2 expect(open_event.open_timestamps.first.to_i).to eq now.to_i expect(open_event.open_timestamps.last.to_i).to eq((now + 1.minute).to_i) expect(open_event.open_count).to eq 2 end it "creates a new CreatorEmailClickSummary object and a new CreatorEmailClickEvent object" do now = Time.current params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end expect(CreatorEmailClickSummary.count).to eq 1 summary = CreatorEmailClickSummary.last expect(summary.total_unique_clicks).to eq 1 expect(summary.installment_id).to eq @installment.id url_hash = { "https://www&#46;gumroad&#46;com" => 1 } expect(summary.urls).to eq url_hash expect(CreatorEmailClickEvent.count).to eq 1 click_event = CreatorEmailClickEvent.last expect(click_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(click_event.mailer_args).to eq @identifier expect(click_event.installment_id).to eq @installment.id expect(click_event.click_url).to eq "https://www&#46;gumroad&#46;com" expect(click_event.click_timestamps.count).to eq 1 expect(click_event.click_timestamps.last.to_i).to eq now.to_i expect(click_event.click_count).to eq 1 end it "sets cache on click event" do params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } HandleSendgridEventJob.new.perform(params) unique_click_count = Rails.cache.read("unique_click_count_for_installment_#{@installment.id}") expect(unique_click_count).to eq 1 # It should also cache unique_open_count unique_open_count = Rails.cache.read("unique_open_count_for_installment_#{@installment.id}") expect(unique_open_count).to eq 1 end it "creates 1 new CreatorEmailClickSummary and 2 CreatorEmailClickEvent objects for different URLs, \ but not update unique clicks if same identifier" do now = Time.current params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end params2 = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;google&#46;com" }] } travel_to(now + 1.minute) do HandleSendgridEventJob.new.perform(params2) end expect(CreatorEmailClickSummary.count).to eq 1 summary = CreatorEmailClickSummary.last expect(summary.total_unique_clicks).to eq 1 expect(summary.installment_id).to eq @installment.id url_hash = { "https://www&#46;gumroad&#46;com" => 1, "https://www&#46;google&#46;com" => 1 } expect(summary.urls).to eq url_hash expect(CreatorEmailClickEvent.count).to eq 2 click_event = CreatorEmailClickEvent.order_by(created_at: :asc).last expect(click_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(click_event.mailer_args).to eq @identifier expect(click_event.installment_id).to eq @installment.id expect(click_event.click_url).to eq "https://www&#46;google&#46;com" expect(click_event.click_timestamps.count).to eq 1 expect(click_event.click_timestamps.last.to_i).to eq((now + 1.minute).to_i) expect(click_event.click_count).to eq 1 end it "does not modify CreatorEmailClickSummary if it sees two duplicate events, \ but should update the timestamps for the CreatorEmailClickEvent object" do now = Time.current params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end travel_to(now + 1.minute) do HandleSendgridEventJob.new.perform(params) end expect(CreatorEmailClickSummary.count).to eq 1 summary = CreatorEmailClickSummary.last expect(summary.total_unique_clicks).to eq 1 expect(summary.installment_id).to eq @installment.id url_hash = { "https://www&#46;gumroad&#46;com" => 1 } expect(summary.urls).to eq url_hash expect(CreatorEmailClickEvent.count).to eq 1 click_event = CreatorEmailClickEvent.last expect(click_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(click_event.mailer_args).to eq @identifier expect(click_event.installment_id).to eq @installment.id expect(click_event.click_url).to eq "https://www&#46;gumroad&#46;com" expect(click_event.click_timestamps.first.to_i).to eq now.to_i end it "registers two unique clicks for two different users clicking the same url for the same installment" do now = Time.current params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end purchase2 = create(:purchase) params2 = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => "[#{purchase2.id}, #{@installment.id}]", "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now + 1.minute) do HandleSendgridEventJob.new.perform(params2) end expect(CreatorEmailClickSummary.count).to eq 1 summary = CreatorEmailClickSummary.last expect(summary.total_unique_clicks).to eq 2 expect(summary.installment_id).to eq @installment.id url_hash = { "https://www&#46;gumroad&#46;com" => 2 } expect(summary.urls).to eq url_hash expect(CreatorEmailClickEvent.count).to eq 2 click_event = CreatorEmailClickEvent.order_by(created_at: :asc).last expect(click_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(click_event.mailer_args).to eq "[#{purchase2.id}, #{@installment.id}]" expect(click_event.installment_id).to eq @installment.id expect(click_event.click_url).to eq "https://www&#46;gumroad&#46;com" expect(click_event.click_timestamps.count).to eq 1 expect(click_event.click_timestamps.first.to_i).to eq((now + 1.minute).to_i) expect(click_event.click_count).to eq 1 end it "handles the second event in the params array even if the first one is malformed" do now = Time.current params = { "_json" => [{ "event" => "click" }, { "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end expect(CreatorEmailClickSummary.count).to eq 1 summary = CreatorEmailClickSummary.last expect(summary.total_unique_clicks).to eq 1 expect(summary.installment_id).to eq @installment.id url_hash = { "https://www&#46;gumroad&#46;com" => 1 } expect(summary.urls).to eq url_hash expect(CreatorEmailClickEvent.count).to eq 1 click_event = CreatorEmailClickEvent.last expect(click_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(click_event.mailer_args).to eq @identifier expect(click_event.installment_id).to eq @installment.id expect(click_event.click_url).to eq "https://www&#46;gumroad&#46;com" expect(click_event.click_timestamps.count).to eq 1 expect(click_event.click_timestamps.first.to_i).to eq now.to_i expect(click_event.click_count).to eq 1 end it "creates a corresponding open event if a click event is logged but \ an open event does not yet exist for a particular installment / recipient pair" do now = Time.current params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq 1 open_event = CreatorEmailOpenEvent.last expect(open_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(open_event.mailer_args).to eq @identifier expect(open_event.installment_id).to eq @installment.id expect(open_event.open_timestamps.count).to eq 1 expect(open_event.open_timestamps.last.to_i).to eq now.to_i end it "does not create a corresponding open event if a click event is logged if an open event already exists" do now = Time.current params = { "_json" => [{ "event" => "open", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }, { "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "https://www&#46;gumroad&#46;com" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end expect(CreatorEmailOpenEvent.count).to eq 1 open_event = CreatorEmailOpenEvent.last expect(open_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(open_event.mailer_args).to eq @identifier expect(open_event.installment_id).to eq @installment.id expect(open_event.open_timestamps.count).to eq 1 expect(open_event.open_timestamps.last.to_i).to eq now.to_i expect(CreatorEmailClickSummary.count).to eq 1 summary = CreatorEmailClickSummary.last expect(summary.total_unique_clicks).to eq 1 expect(summary.installment_id).to eq @installment.id url_hash = { "https://www&#46;gumroad&#46;com" => 1 } expect(summary.urls).to eq url_hash expect(CreatorEmailClickEvent.count).to eq 1 click_event = CreatorEmailClickEvent.last expect(click_event.mailer_method).to eq "CreatorContactingCustomersMailer.purchase_installment" expect(click_event.mailer_args).to eq @identifier expect(click_event.installment_id).to eq @installment.id expect(click_event.click_url).to eq "https://www&#46;gumroad&#46;com" expect(click_event.click_timestamps.count).to eq 1 expect(click_event.click_timestamps.first.to_i).to eq now.to_i expect(click_event.click_count).to eq 1 end it "replaces the url for an attachment link with 'Attached Files'" do now = Time.current params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "#{DOMAIN}/d/fdd185111c9808abfb6029a3c2e4e96e" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end click_event = CreatorEmailClickEvent.last expect(click_event.click_url).to eq "view_attachments_url" end it "does not create an event for unsubscribes" do now = Time.current params = { "_json" => [{ "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "#{DOMAIN}#{Rails.application.routes.url_helpers.unsubscribe_purchase_path('CTE53CxbKFW_VLa0BZ9-iA==')}" }, { "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "#{DOMAIN}#{Rails.application.routes.url_helpers.unsubscribe_imported_customer_path('_CTE53CxbKVLa0BZ9-iA==')}" }, { "event" => "click", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "url" => "#{DOMAIN}#{Rails.application.routes.url_helpers.cancel_follow_path('-CTE53CxbKVLa0BZ9-iA==')}" }] } travel_to(now) do HandleSendgridEventJob.new.perform(params) end click_event = CreatorEmailClickEvent.last expect(click_event).to eq nil end describe "cancel follower" do before do @non_existent_purchase_id = 999_999_999 end it "cancels the follower on bounce event" do follower = create(:active_follower, email: "test@example.com", followed_id: @installment.seller_id) params = { "_json" => [{ "event" => "bounce", "type" => "bounce", "email" => "test@example.com", "identifier" => "[#{@non_existent_purchase_id}, #{@installment.id}]", "installment_id" => @installment.id }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(follower.reload).to be_deleted end it "cancels the follower on spamreport event" do follower = create(:active_follower, email: "test@example.com", followed_id: @installment.seller_id) params = { "_json" => [{ "event" => "spamreport", "type" => "spamreport", "email" => "test@example.com", "identifier" => "[#{@non_existent_purchase_id}, #{@installment.id}]", "installment_id" => @installment.id }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(follower.reload).to be_deleted end end describe "email info" do describe "purchase installment" do describe "existing email info" do before do @email_info = create(:creator_contacting_customers_email_info, installment: @installment, purchase: @purchase) end it "marks it as bounced and cancel the follower" do follower = create(:active_follower, email: @purchase.email, followed_id: @purchase.seller_id) params = { "_json" => [{ "event" => "bounce", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(@email_info.reload.state).to eq "bounced" expect(follower.reload).to be_deleted end it "marks it as delivered" do params = { "_json" => [{ "event" => "delivered", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "timestamp" => 1.day.ago.to_i }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(@email_info.reload.state).to eq "delivered" expect(@email_info.reload.delivered_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end it "marks it as opened" do params = { "_json" => [{ "event" => "open", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "timestamp" => 1.hour.ago.to_i }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(@email_info.reload.state).to eq "opened" expect(@email_info.reload.opened_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end it "unsubscribes the buyer of the purchase and cancels the follower when the event type is 'spamreport'" do follower = create(:active_follower, email: @purchase.email, followed_id: @purchase.seller_id) another_product = create(:product, user: @purchase.seller) another_purchase = create(:purchase, link: another_product, email: @purchase.email) params = { "_json" => [{ "event" => "spamreport", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }] } expect do HandleSendgridEventJob.new.perform(params) end.to change { [@purchase.reload.can_contact, another_purchase.reload.can_contact, follower.reload.alive?] }.from([true, true, true]).to([false, false, false]) end it "does not unsubscribe the buyer when the event type is 'spamreport' from Resend" do follower = create(:active_follower, email: @purchase.email, followed_id: @purchase.seller_id) another_product = create(:product, user: @purchase.seller) another_purchase = create(:purchase, link: another_product, email: @purchase.email) params = { "data" => { "created_at" => "2025-01-02 00:14:11.140106+00", "to" => [@purchase.email], "headers" => [ { "name" => MailerInfo.header_name(:mailer_class), "value" => MailerInfo.encrypt("CreatorContactingCustomersMailer") }, { "name" => MailerInfo.header_name(:mailer_method), "value" => MailerInfo.encrypt("purchase_installment") }, { "name" => MailerInfo.header_name(:mailer_args), "value" => MailerInfo.encrypt(@identifier) }, { "name" => MailerInfo.header_name(:purchase_id), "value" => MailerInfo.encrypt(@purchase.id.to_s) }, { "name" => MailerInfo.header_name(:post_id), "value" => MailerInfo.encrypt(@installment.id.to_s) } ], }, "type" => EmailEventInfo::EVENTS[:complained][MailerInfo::EMAIL_PROVIDER_RESEND] } expect do HandleResendEventJob.new.perform(params) end.not_to change { [@purchase.reload.can_contact, another_purchase.reload.can_contact, follower.reload.alive?] } end end describe "creating new email info" do it "creates a new email info and mark it as bounced" do expect(CreatorContactingCustomersEmailInfo.count).to eq 0 params = { "_json" => [{ "event" => "bounce", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(CreatorContactingCustomersEmailInfo.last.state).to eq "bounced" expect(CreatorContactingCustomersEmailInfo.last.email_name).to eq "purchase_installment" end it "creates a new email info and mark it as delivered" do expect(CreatorContactingCustomersEmailInfo.count).to eq 0 params = { "_json" => [{ "event" => "delivered", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "timestamp" => 1.day.ago.to_i }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(CreatorContactingCustomersEmailInfo.last.state).to eq "delivered" expect(CreatorContactingCustomersEmailInfo.last.delivered_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end it "creates a new email info and mark it as opened" do expect(CreatorContactingCustomersEmailInfo.count).to eq 0 params = { "_json" => [{ "event" => "open", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id, "timestamp" => 1.hour.ago.to_i }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(CreatorContactingCustomersEmailInfo.last.state).to eq "opened" expect(CreatorContactingCustomersEmailInfo.last.opened_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end it "unsubscribes the buyer of the purchase when the event type is 'spamreport'" do another_product = create(:product, user: @purchase.seller) another_purchase = create(:purchase, link: another_product, email: @purchase.email) params = { "_json" => [{ "event" => "spamreport", "type" => "CreatorContactingCustomersMailer.purchase_installment", "identifier" => @identifier, "installment_id" => @installment.id }] } expect do HandleSendgridEventJob.new.perform(params) end.to change { [@purchase.reload.can_contact, another_purchase.reload.can_contact] }.from([true, true]).to([false, false]) end end end describe "subscription installment" do before do @subscription = create(:subscription) @purchase.update_attribute(:subscription_id, @subscription.id) @purchase.update_attribute(:is_original_subscription_purchase, true) end describe "existing email info" do before do @email_info = create(:creator_contacting_customers_email_info, installment: @installment, purchase: @purchase) end it "marks it as opened" do params = { "_json" => [{ "event" => "open", "type" => "CreatorContactingCustomersMailer.subscription_installment", "identifier" => "[#{@subscription.id}, #{@installment.id}]", "installment_id" => @installment.id, "timestamp" => 1.hour.ago.to_i }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(@email_info.reload.state).to eq "opened" expect(@email_info.reload.opened_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end end describe "creating new email info" do it "creates a new email info and mark it as bounced" do expect(CreatorContactingCustomersEmailInfo.count).to eq 0 params = { "_json" => [{ "event" => "bounce", "type" => "CreatorContactingCustomersMailer.subscription_installment", "identifier" => "[#{@subscription.id}, #{@installment.id}]", "installment_id" => @installment.id }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(CreatorContactingCustomersEmailInfo.last.state).to eq "bounced" expect(CreatorContactingCustomersEmailInfo.last.email_name).to eq "subscription_installment" end it "creates a new email info and mark it as delivered" do expect(CreatorContactingCustomersEmailInfo.count).to eq 0 params = { "_json" => [{ "event" => "delivered", "type" => "CreatorContactingCustomersMailer.subscription_installment", "identifier" => "[#{@subscription.id}, #{@installment.id}]", "installment_id" => @installment.id, "timestamp" => 1.day.ago.to_i }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 1 expect(CreatorContactingCustomersEmailInfo.last.state).to eq "delivered" expect(CreatorContactingCustomersEmailInfo.last.delivered_at).to eq(Time.zone.at(params["_json"].first["timestamp"])) end end end describe "follower installment" do it "does not create a new email info" do expect(CreatorContactingCustomersEmailInfo.count).to eq 0 params = { "_json" => [{ "event" => "delivered", "type" => "CreatorContactingCustomersMailer.follower_installment", "identifier" => "[5, #{@installment.id}]", "installment_id" => @installment.id }] } travel_to(Time.current) do HandleSendgridEventJob.new.perform(params) end expect(CreatorContactingCustomersEmailInfo.count).to eq 0 end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/integrations/circle_integration_service_spec.rb
spec/services/integrations/circle_integration_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Integrations::CircleIntegrationService, :without_circle_rate_limit do let(:community_id) { 3512 } let(:space_group_id) { 43576 } let(:email) { "test_circle_integration@gumroad.com" } before do @user = create(:user, email:) @integration = create(:circle_integration, community_id:, space_group_id:) end describe "standalone product" do before do @product = create(:product, active_integrations: [@integration]) @purchase = create(:purchase, link: @product, email:) @purchase_without_integration = create(:purchase, email:) end describe "#activate" do it "adds member to the community specified in the integration" do expect_any_instance_of(CircleApi).to receive(:add_member).with(community_id, space_group_id, email) Integrations::CircleIntegrationService.new.activate(@purchase) end it "does nothing if integration does not exist" do expect_any_instance_of(CircleApi).to_not receive(:add_member) Integrations::CircleIntegrationService.new.activate(@purchase_without_integration) end end describe "#deactivate" do it "removes member from the community specified in the integration" do expect_any_instance_of(CircleApi).to receive(:remove_member).with(community_id, email) Integrations::CircleIntegrationService.new.deactivate(@purchase) end it "does nothing if integration does not exist" do expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.deactivate(@purchase_without_integration) end it "does nothing if deactivation is disabled" do @integration.update!(keep_inactive_members: true) expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.deactivate(@purchase) end end end describe "product with variants" do before do @product_with_digital_versions = create(:product_with_digital_versions, active_integrations: [@integration]) @version_category = @product_with_digital_versions.variant_categories.first @version_category.variants[1].active_integrations << @integration @purchase_with_integration = create(:purchase, link: @product_with_digital_versions, email:, variant_attributes: [@version_category.variants[1]]) @purchase_without_integration = create(:purchase, link: @product_with_digital_versions, email:, variant_attributes: [@version_category.variants[0]]) @purchase_without_variant = create(:purchase, link: @product_with_digital_versions, email:) end describe "#activate" do it "adds member to the community if variant has integration" do expect_any_instance_of(CircleApi).to receive(:add_member).with(community_id, space_group_id, email) Integrations::CircleIntegrationService.new.activate(@purchase_with_integration) end it "adds member to the community if product has integration and purchase does not have a variant specified" do expect_any_instance_of(CircleApi).to receive(:add_member).with(community_id, space_group_id, email) Integrations::CircleIntegrationService.new.activate(@purchase_without_variant) end it "does nothing if variant does not have integration" do expect_any_instance_of(CircleApi).to_not receive(:add_member) Integrations::CircleIntegrationService.new.activate(@purchase_without_integration) end end describe "#deactivate" do it "removes member from the community if variant has integration" do expect_any_instance_of(CircleApi).to receive(:remove_member).with(community_id, email) Integrations::CircleIntegrationService.new.deactivate(@purchase_with_integration) end it "does nothing if variant does not have integration" do expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.deactivate(@purchase_without_integration) end it "does nothing if deactivation is disabled" do @integration.update!(keep_inactive_members: true) expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.deactivate(@purchase_with_integration) end it "removes member from the community if product has integration and purchase does not have a variant specified" do expect_any_instance_of(CircleApi).to receive(:remove_member).with(community_id, email) Integrations::CircleIntegrationService.new.deactivate(@purchase_without_variant) end end end describe "membership product" do before do @membership_product = create(:membership_product_with_preset_tiered_pricing, active_integrations: [@integration]) @membership_product.tiers[1].active_integrations << @integration @purchase_with_integration = create(:membership_purchase, link: @membership_product, email:, variant_attributes: [@membership_product.tiers[1]], purchase_sales_tax_info: PurchaseSalesTaxInfo.create(business_vat_id: 0)) @purchase_without_integration = create(:membership_purchase, link: @membership_product, email:, variant_attributes: [@membership_product.tiers[0]], purchase_sales_tax_info: PurchaseSalesTaxInfo.create(business_vat_id: 0)) end describe "#activate" do it "adds member to the community if tier has integration" do expect_any_instance_of(CircleApi).to receive(:add_member).with(community_id, space_group_id, email) Integrations::CircleIntegrationService.new.activate(@purchase_with_integration) end it "does nothing if tier does not have integration" do expect_any_instance_of(CircleApi).to_not receive(:add_member) Integrations::CircleIntegrationService.new.activate(@purchase_without_integration) end end describe "#deactivate" do it "removes member from the community if tier has integration" do expect_any_instance_of(CircleApi).to receive(:remove_member).with(community_id, email) Integrations::CircleIntegrationService.new.deactivate(@purchase_with_integration) end it "does nothing if tier does not have integration" do expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.deactivate(@purchase_without_integration) end it "does nothing if deactivation is disabled" do @integration.update!(keep_inactive_members: true) expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.deactivate(@purchase_with_integration) end end describe "#update_on_tier_change" do before do @subscription_with_integration = @purchase_with_integration.subscription @subscription_without_integration = @purchase_without_integration.subscription end it "activates integration if new tier has integration and old tier did not" do @subscription_without_integration.update_current_plan!( new_variants: [@membership_product.tiers[1]], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) @subscription_without_integration.reload expect_any_instance_of(CircleApi).to receive(:add_member).with(community_id, space_group_id, email) expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.update_on_tier_change(@subscription_without_integration) end it "deactivates integration if old tier had integration and new tier does not" do @subscription_with_integration.update_current_plan!( new_variants: [@membership_product.tiers[0]], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) @subscription_with_integration.reload expect_any_instance_of(CircleApi).to receive(:remove_member).with(community_id, email) expect_any_instance_of(CircleApi).to_not receive(:add_member) Integrations::CircleIntegrationService.new.update_on_tier_change(@subscription_with_integration) end it "does nothing if old tier had integration and new tier does not but deactivation is disabled" do @integration.update!(keep_inactive_members: true) @subscription_with_integration.update_current_plan!( new_variants: [@membership_product.tiers[0]], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) @subscription_with_integration.reload expect_any_instance_of(CircleApi).to_not receive(:remove_member) expect_any_instance_of(CircleApi).to_not receive(:add_member) Integrations::CircleIntegrationService.new.update_on_tier_change(@subscription_with_integration) end it "does nothing if new and old tier have integration" do tier_3 = create(:variant, variant_category: @membership_product.tier_category, name: "Tier 3", active_integrations: [@integration]) @subscription_with_integration.update_current_plan!( new_variants: [tier_3], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) @subscription_with_integration.reload expect_any_instance_of(CircleApi).to_not receive(:add_member) expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.update_on_tier_change(@subscription_with_integration) end it "does nothing if new and old tier do not have integration" do tier_3 = create(:variant, variant_category: @membership_product.tier_category, name: "Tier 3") @subscription_without_integration.update_current_plan!( new_variants: [tier_3], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) @subscription_without_integration.reload expect_any_instance_of(CircleApi).to_not receive(:add_member) expect_any_instance_of(CircleApi).to_not receive(:remove_member) Integrations::CircleIntegrationService.new.update_on_tier_change(@subscription_without_integration) 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/integrations/base_integration_service_spec.rb
spec/services/integrations/base_integration_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Integrations::BaseIntegrationService do it "raises runtime error on direct instantiation" do expect { Integrations::BaseIntegrationService.new }.to raise_error(RuntimeError, "Integrations::BaseIntegrationService should not be instantiated. Instantiate child classes instead.") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/integrations/discord_integration_service_spec.rb
spec/services/integrations/discord_integration_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Integrations::DiscordIntegrationService do let(:integration) { create(:discord_integration) } let(:server_id) { integration.server_id } let(:user_id) { "694641779777077339" } let(:regular_user_role_id) { "111111111111111111" } let(:gumroad_bot_role_id) { "222222222222222222" } let(:power_user_role_id) { "333333333333333333" } let(:new_role_id) { "999999999999999999" } let(:admin_user_role_id) { "444444444444444444" } let(:resolve_member_response) do OpenStruct.new( body: { "avatar" => nil, "communication_disabled_until" => nil, "flags" => 0, "joined_at" => "2024-03-01T04:38:49.939000+00:00", "nick" => nil, "pending" => false, "premium_since" => nil, "roles" => [], # This will be empty for members with the default @everyone role "unusual_dm_activity_until" => nil, "user" => { "id" => user_id, "username" => "tkidd0", "avatar" => "4a2e3c2f51d11aad2d4c6e586bce9a7d", "discriminator" => "0", "public_flags" => 0, "premium_type" => 0, "flags" => 0, "banner" => nil, "accent_color" => nil, "global_name" => "tkidd9", "avatar_decoration_data" => nil, "banner_color" => nil }, "mute" => false, "deaf" => false }.to_json ) end let(:gumroad_resolve_member_response) do OpenStruct.new( body: { "avatar" => nil, "communication_disabled_until" => nil, "flags" => 0, "joined_at" => "2024-03-09T00:23:46.555000+00:00", "nick" => nil, "pending" => false, "premium_since" => nil, "roles" => [gumroad_bot_role_id], "unusual_dm_activity_until" => nil, "user" => { "id" => DISCORD_GUMROAD_BOT_ID, "username" => "Gumroad", "avatar" => nil, "discriminator" => "1956", "public_flags" => 65536, "premium_type" => 0, "flags" => 65536, "bot" => true, "banner" => nil, "accent_color" => nil, "global_name" => nil, "avatar_decoration_data" => nil, "banner_color" => nil }, "mute" => false, "deaf" => false }.to_json ) end let(:roles_response) do OpenStruct.new( body: [ { "id" => "000000000000000000", "name" => "@everyone", "description" => nil, "permissions" => "533235326373441", "position" => 0, "color" => 0, "hoist" => false, "managed" => false, "mentionable" => false, "icon" => nil, "unicode_emoji" => nil, "flags" => 0 }, { "id" => power_user_role_id, "name" => "Power User Role", "description" => nil, "permissions" => "1071698660928", "position" => 3, "color" => 3447003, "hoist" => true, "managed" => false, "mentionable" => false, "icon" => nil, "unicode_emoji" => nil, "flags" => 0 }, { "id" => new_role_id, "name" => "New Role at same position as Power User Role", "description" => nil, "permissions" => "1071698660928", # When a Discord Role is created, it could receive the same position as another role. # Positions become unique again if an Admin reorders the Roles in the Discord interface. # Weird. https://github.com/discord/discord-api-docs/issues/1778 "position" => 3, "color" => 3447003, "hoist" => true, "managed" => false, "mentionable" => false, "icon" => nil, "unicode_emoji" => nil, "flags" => 0 }, { "id" => admin_user_role_id, "name" => "Admin User Role", "description" => nil, "permissions" => "1071698660928", "position" => 4, "color" => 3447003, "hoist" => true, "managed" => false, "mentionable" => false, "icon" => nil, "unicode_emoji" => nil, "flags" => 0 }, { "id" => regular_user_role_id, "name" => "Regular User Role", "description" => nil, "permissions" => "1071698660928", "position" => 1, "color" => 3447003, "hoist" => true, "managed" => false, "mentionable" => false, "icon" => nil, "unicode_emoji" => nil, "flags" => 0 }, { "id" => gumroad_bot_role_id, "name" => "Gumroad", "description" => nil, "permissions" => "268435459", "position" => 2, "color" => 0, "hoist" => false, "managed" => true, "mentionable" => false, "icon" => nil, "unicode_emoji" => nil, "tags" => { "bot_id" => DISCORD_GUMROAD_BOT_ID }, # This tag will appear for the Role managed by the Gumroad bot. "flags" => 0 } ].to_json ) end describe "standalone product" do describe "#deactivate" do it "removes member from the server specified in the integration" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id) Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) expect(discord_purchase_integration.reload.deleted?).to eq(true) end it "does nothing if integration is not enabled" do purchase_without_integration = create(:purchase) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_without_integration) end it "does nothing if purchase does not have an activated integration" do purchase_with_integration = create(:purchase, link: create(:product, active_integrations: [integration])) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_with_integration) end it "does nothing if deactivation is disabled" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) integration.update!(keep_inactive_members: true) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) expect(discord_purchase_integration.reload.deleted?).to eq(false) end it "sends an email to the creator when the Gumroad bot role is lower than the member's highest role" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) resolve_member_response.body = JSON.parse(resolve_member_response.body).merge("roles" => [admin_user_role_id]).to_json expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id).and_raise(Discordrb::Errors::NoPermission) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, user_id).and_return(resolve_member_response) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, DISCORD_GUMROAD_BOT_ID).and_return(gumroad_resolve_member_response) expect_any_instance_of(DiscordApi).to receive(:roles).with(server_id).and_return(roles_response) expect(ContactingCreatorMailer).to receive(:unremovable_discord_member).and_call_original Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) end it "sends an email to the creator when the Gumroad bot role is lower than the member's highest of multiple roles" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) resolve_member_response.body = JSON.parse(resolve_member_response.body).merge("roles" => [regular_user_role_id, admin_user_role_id]).to_json expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id).and_raise(Discordrb::Errors::NoPermission) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, user_id).and_return(resolve_member_response) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, DISCORD_GUMROAD_BOT_ID).and_return(gumroad_resolve_member_response) expect_any_instance_of(DiscordApi).to receive(:roles).with(server_id).and_return(roles_response) expect(ContactingCreatorMailer).to receive(:unremovable_discord_member).and_call_original Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) end it "sends an email to the creator when the Gumoroad bot role is equal to the member's highest role" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) resolve_member_response.body = JSON.parse(resolve_member_response.body).merge("roles" => [new_role_id]).to_json gumroad_resolve_member_response.body = JSON.parse(resolve_member_response.body).merge("roles" => [gumroad_bot_role_id, power_user_role_id]).to_json expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id).and_raise(Discordrb::Errors::NoPermission) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, user_id).and_return(resolve_member_response) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, DISCORD_GUMROAD_BOT_ID).and_return(gumroad_resolve_member_response) expect_any_instance_of(DiscordApi).to receive(:roles).with(server_id).and_return(roles_response) expect(ContactingCreatorMailer).to receive(:unremovable_discord_member).and_call_original Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) end it "propagates the NoPermission error if it is raised when the Gumroad bot role removes a member with the default @everyone role" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id).and_raise(Discordrb::Errors::NoPermission) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, user_id).and_return(resolve_member_response) expect do Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) end.to raise_error(Discordrb::Errors::NoPermission) end it "propagates the NoPermission error if it is raised when the Gumroad bot role is higher than the member's highest role" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) resolve_member_response.body = JSON.parse(resolve_member_response.body).merge("roles" => [regular_user_role_id]).to_json expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id).and_raise(Discordrb::Errors::NoPermission) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, user_id).and_return(resolve_member_response) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, DISCORD_GUMROAD_BOT_ID).and_return(gumroad_resolve_member_response) expect_any_instance_of(DiscordApi).to receive(:roles).with(server_id).and_return(roles_response) expect do Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) end.to raise_error(Discordrb::Errors::NoPermission) end it "propagates the NoPermission error if it is raised when the Gumroad bot is assigned a role higher than the member's highest role" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) resolve_member_response.body = JSON.parse(resolve_member_response.body).merge("roles" => [power_user_role_id]).to_json gumroad_resolve_member_response.body = JSON.parse(resolve_member_response.body).merge("roles" => [gumroad_bot_role_id, admin_user_role_id]).to_json expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id).and_raise(Discordrb::Errors::NoPermission) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, user_id).and_return(resolve_member_response) allow_any_instance_of(DiscordApi).to receive(:resolve_member).with(server_id, DISCORD_GUMROAD_BOT_ID).and_return(gumroad_resolve_member_response) expect_any_instance_of(DiscordApi).to receive(:roles).with(server_id).and_return(roles_response) expect do Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) end.to raise_error(Discordrb::Errors::NoPermission) end it "marks the purchase integration as deleted when the Discord server is deleted" do discord_purchase_integration = create(:discord_purchase_integration, integration:, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id).and_raise(Discordrb::Errors::UnknownServer, "unknown server") Integrations::DiscordIntegrationService.new.deactivate(discord_purchase_integration.purchase) expect(discord_purchase_integration.reload.deleted?).to eq(true) end end end describe "product with variants" do let(:product_with_digital_versions) { create(:product_with_digital_versions, active_integrations: [integration]) } let(:variant_with_integration) do version_category = product_with_digital_versions.variant_categories.first variant = version_category.variants[1] variant.active_integrations << integration variant end let(:variant_without_integration) { product_with_digital_versions.variant_categories.first.variants[0] } describe "#deactivate" do it "removes member from the server if variant has integration" do purchase_with_integration = create(:purchase, link: product_with_digital_versions, variant_attributes: [variant_with_integration]) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_with_integration, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id) Integrations::DiscordIntegrationService.new.deactivate(purchase_with_integration) expect(purchase_integration.reload.deleted?).to eq(true) end it "does nothing if variant does not have integration enabled" do purchase_without_integration = create(:purchase, link: product_with_digital_versions, variant_attributes: [variant_without_integration]) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_without_integration) end it "does nothing if purchase does not have an activated integration" do purchase_with_integration = create(:purchase, link: product_with_digital_versions, variant_attributes: [variant_with_integration]) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_with_integration) end it "does nothing if deactivation is disabled" do integration.update!(keep_inactive_members: true) purchase_with_integration = create(:purchase, link: product_with_digital_versions, variant_attributes: [variant_with_integration]) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_with_integration, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_with_integration) expect(purchase_integration.reload.deleted?).to eq(false) end it "removes member from the server if product has integration and purchase does not have a variant specified" do purchase_without_variant = create(:purchase, link: product_with_digital_versions) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_without_variant, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id) Integrations::DiscordIntegrationService.new.deactivate(purchase_without_variant) expect(purchase_integration.reload.deleted?).to eq(true) end end end describe "membership product" do let(:membership_product) { create(:membership_product_with_preset_tiered_pricing, active_integrations: [integration]) } let(:tier_with_integration) do tier = membership_product.tiers[1] tier.active_integrations << integration tier end let(:tier_without_integration) { membership_product.tiers[0] } describe "#deactivate" do it "removes member from the server if tier has integration" do purchase_with_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_with_integration]) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_with_integration, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id) Integrations::DiscordIntegrationService.new.deactivate(purchase_with_integration) expect(purchase_integration.reload.deleted?).to eq(true) end it "does nothing if tier does not have integration enabled" do purchase_without_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_without_integration]) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_without_integration) end it "does nothing if purchase does not have an activated integration" do purchase_with_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_with_integration]) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_with_integration) end it "does nothing if deactivation is disabled" do integration.update!(keep_inactive_members: true) purchase_with_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_with_integration]) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_with_integration, discord_user_id: user_id) expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.deactivate(purchase_with_integration) expect(purchase_integration.reload.deleted?).to eq(false) end end describe "#update_on_tier_change" do it "does nothing if new tier has integration and old tier did not" do purchase_without_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_without_integration]) subscription_without_integration = purchase_without_integration.subscription subscription_without_integration.update_current_plan!( new_variants: [tier_with_integration], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) subscription_without_integration.reload expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.update_on_tier_change(subscription_without_integration) end it "deactivates integration if old tier had integration and new tier does not" do purchase_with_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_with_integration]) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_with_integration, discord_user_id: user_id) subscription_with_integration = purchase_with_integration.subscription subscription_with_integration.update_current_plan!( new_variants: [tier_without_integration], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) subscription_with_integration.reload expect_any_instance_of(DiscordApi).to receive(:remove_member).with(server_id, user_id) Integrations::DiscordIntegrationService.new.update_on_tier_change(subscription_with_integration) expect(purchase_integration.reload.deleted?).to eq(true) end it "does nothing if old tier had integration and new tier does not but the integration was not activated" do purchase_with_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_with_integration]) subscription_with_integration = purchase_with_integration.subscription subscription_with_integration.update_current_plan!( new_variants: [tier_without_integration], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) subscription_with_integration.reload expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.update_on_tier_change(subscription_with_integration) end it "does nothing if old tier had integration and new tier does not but deactivation is disabled" do purchase_with_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_with_integration]) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_with_integration, discord_user_id: user_id) subscription_with_integration = purchase_with_integration.subscription integration.update!(keep_inactive_members: true) subscription_with_integration.update_current_plan!( new_variants: [tier_without_integration], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) subscription_with_integration.reload expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.update_on_tier_change(subscription_with_integration) expect(purchase_integration.reload.deleted?).to eq(false) end it "does nothing if new and old tier have integration" do purchase_with_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_with_integration]) purchase_integration = create(:purchase_integration, integration:, purchase: purchase_with_integration, discord_user_id: user_id) tier_3 = create(:variant, variant_category: membership_product.tier_category, name: "Tier 3", active_integrations: [integration]) subscription_with_integration = purchase_with_integration.subscription subscription_with_integration.update_current_plan!( new_variants: [tier_3], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) subscription_with_integration.reload expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.update_on_tier_change(subscription_with_integration) expect(purchase_integration.reload.deleted?).to eq(false) end it "does nothing if new and old tier do not have integration" do purchase_without_integration = create(:membership_purchase, link: membership_product, variant_attributes: [tier_without_integration]) tier_3 = create(:variant, variant_category: membership_product.tier_category, name: "Tier 3") subscription_without_integration = purchase_without_integration.subscription subscription_without_integration.update_current_plan!( new_variants: [tier_3], new_price: create(:price), perceived_price_cents: 0, is_applying_plan_change: true, ) subscription_without_integration.reload expect_any_instance_of(DiscordApi).to_not receive(:remove_member) Integrations::DiscordIntegrationService.new.update_on_tier_change(subscription_without_integration) 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/exports/audience_export_service_spec.rb
spec/services/exports/audience_export_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Exports::AudienceExportService do describe "#perform" do let!(:user) { create(:user) } let!(:follower) { create(:active_follower, email: "follower@gumroad.com", user: user, created_at: 1.day.ago) } let(:product) { create(:product, user: user, name: "Product 1", price_cents: 100) } let!(:customer) { create(:purchase, seller: user, link: product, created_at: 2.days.ago) } let(:affiliate_user) { create(:affiliate_user, created_at: 4.days.ago) } let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller: user, created_at: 3.days.ago) } let!(:product_affiliate) { create(:product_affiliate, product:, affiliate: direct_affiliate, affiliate_basis_points: 10_00) } subject { described_class.new(user, options) } context "when options has followers" do let(:options) { { followers: true } } it "generates csv with followers" do rows = CSV.parse(subject.perform.tempfile.read) expect(rows.size).to eq(2) headers, data_row = rows.first, rows.second expect(headers).to eq(described_class::FIELDS) expect(data_row.first).to eq(follower.email) expect(data_row.second).to eq(follower.created_at.to_s) end end context "when options has customers" do let(:options) { { customers: true } } it "generates csv with customers" do rows = CSV.parse(subject.perform.tempfile.read) expect(rows.size).to eq(2) headers, data_row = rows.first, rows.second expect(headers).to eq(described_class::FIELDS) expect(data_row.first).to eq(customer.email) expect(data_row.second).to eq(customer.created_at.to_s) end end context "when options has affiliates" do let(:options) { { affiliates: true } } it "generates csv with customers" do rows = CSV.parse(subject.perform.tempfile.read) expect(rows.size).to eq(2) headers, data_row = rows.first, rows.second expect(headers).to eq(described_class::FIELDS) expect(data_row.first).to eq(affiliate_user.email) expect(data_row.second).to eq(direct_affiliate.created_at.to_s) end end context "when options has all audience types" do let(:options) { { followers: true, customers: true, affiliates: true } } it "generates csv with all audience types" do rows = CSV.parse(subject.perform.tempfile.read) expect(rows.size).to eq(4) headers = rows.first expect(headers).to eq(described_class::FIELDS) expect(rows[1].first).to eq(follower.email) expect(rows[1].second).to eq(follower.created_at.to_s) expect(rows[2].first).to eq(customer.email) expect(rows[2].second).to eq(customer.created_at.to_s) expect(rows[3].first).to eq(affiliate_user.email) expect(rows[3].second).to eq(direct_affiliate.created_at.to_s) end end context "when user is both a follower and a customer" do let(:options) { { followers: true, customers: true } } let!(:follower_customer) { create(:active_follower, email: customer.email, user:, created_at: 1000.day.ago) } it "generates csv with unique entries with minimum created_at" do rows = CSV.parse(subject.perform.tempfile.read) expect(rows.size).to eq(3) headers = rows.first expect(headers).to eq(described_class::FIELDS) expect(rows[1].first).to eq(follower.email) expect(rows[1].second).to eq(follower.created_at.to_s) expect(rows[2].first).to eq(follower_customer.email) expect(rows[2].second).to eq(follower_customer.created_at.to_s) end end context "when no options are provided" do let(:options) { {} } it "raises an ArgumentError" do expect { described_class.new(user, {}) }.to raise_error(ArgumentError, "At least one audience type (followers, customers, or affiliates) must be selected") 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/exports/purchase_export_service_spec.rb
spec/services/exports/purchase_export_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Exports::PurchaseExportService do describe "#perform" do before do @seller = create(:user) @product = create(:product, user: @seller, price_cents: 100_00) @purchase = create(:purchase, link: @product, street_address: "Søéad", full_name: "Кочергина Дарья", ip_address: "216.38.135.1") end it "uses the purchaser name if full_name is blank" do row = last_data_row expect(field_value(row, "Buyer Name")).to eq("Кочергина Дарья") @purchase.update!(purchaser: create(:named_user), full_name: nil) row = last_data_row expect(field_value(row, "Buyer Name")).to eq("Gumbot") end it "includes the partial refund amount" do refunding_user = create(:user) @purchase.fee_cents = 31 @purchase.save! @purchase.refund_partial_purchase!(2301, refunding_user.id) @purchase.refund_partial_purchase!(3347, refunding_user.id) row = last_data_row expect(field_value(row, "Refunded?")).to eq("1") expect(field_value(row, "Partial Refund ($)")).to eq("56.48") expect(field_value(row, "Fully Refunded?")).to eq("0") end it "shows that the purchase has been fully refunded when multiple partial refunds have got it to that state" do refunding_user = create(:user) @purchase.fee_cents = 31 @purchase.save! @purchase.refund_partial_purchase!(2301, refunding_user.id) @purchase.refund_partial_purchase!(3347, refunding_user.id) @purchase.refund_partial_purchase!(4352, refunding_user.id) row = last_data_row expect(field_value(row, "Refunded?")).to eq("1") expect(field_value(row, "Partial Refund ($)")).to eq("0.0") expect(field_value(row, "Fully Refunded?")).to eq("1") end it "sets 'Disputed' and 'Dispute Won' to '1' when appropriate" do @purchase.fee_cents = 31 @purchase.chargeback_date = @purchase.created_at + 1.minute @purchase.chargeback_reversed = true @purchase.save! row = last_data_row expect(field_value(row, "Disputed?")).to eq("1") expect(field_value(row, "Dispute Won?")).to eq("1") end it "transliterates information" do row = last_data_row expect(field_value(row, "Buyer Name")).to eq("Кочергина Дарья") expect(field_value(row, "Street Address")).to eq("Soead") end it "includes the variant price cents", :vcr do @product = create(:product, price_cents: 100, user: @seller) @category = create(:variant_category, title: "sizes", link: @product) @variant = create(:variant, name: "small", price_difference_cents: 350, variant_category: @category) @purchase = build(:purchase, link: @product, chargeable: build(:chargeable), perceived_price_cents: 450, save_card: false) @purchase.variant_attributes << @variant @purchase.process! row = last_data_row expect(field_value(row, "Item Price ($)")).to eq("1.0") expect(field_value(totals_row, "Item Price ($)")).to eq("101.0") expect(field_value(row, "Variants Price ($)")).to eq("3.5") expect(field_value(totals_row, "Variants Price ($)")).to eq("3.5") end it "includes product rating" do create(:product_review, purchase: @purchase, rating: 5, message: "This is a great product!") expect(field_value(last_data_row, "Rating")).to eq("5") expect(field_value(last_data_row, "Review")).to eq("This is a great product!") end it "includes product rating posted by the giftee" do @purchase.update!(is_gift_sender_purchase: true) giftee_purchase = create(:purchase, :gift_receiver, link: @product) create(:gift, link: @product, gifter_purchase: @purchase, giftee_purchase:) create(:product_review, purchase: giftee_purchase, rating: 5) expect(field_value(last_data_row, "Rating")).to eq("5") end it "includes the purchase external id" do expect(field_value(last_data_row, "Purchase ID")).to eq(Purchase.last.external_id.to_s) end it "includes the sku", :vcr do @product = create(:product, price_range: "$1", skus_enabled: true, user: @seller) @category1 = create(:variant_category, title: "Size", link: @product) @variant1 = create(:variant, variant_category: @category1, name: "Small") @category2 = create(:variant_category, title: "Color", link: @product) @variant2 = create(:variant, variant_category: @category2, name: "Red") Product::SkusUpdaterService.new(product: @product).perform @purchase = build(:purchase, link: @product, chargeable: build(:chargeable), perceived_price_cents: 100, save_card: false, price_range: 1) @purchase.variant_attributes << Sku.last @purchase.process! expect(field_value(last_data_row, "SKU ID")).to eq(Sku.last.external_id.to_s) end it "shows the custom sku", :vcr do @product = create(:product, price_range: "$1", skus_enabled: true, user: @seller) @category1 = create(:variant_category, title: "Size", link: @product) @variant1 = create(:variant, variant_category: @category1, name: "Small") @category2 = create(:variant_category, title: "Color", link: @product) @variant2 = create(:variant, variant_category: @category2, name: "Red") Product::SkusUpdaterService.new(product: @product).perform Sku.last.update_attribute(:custom_sku, "ABC123_Sm_Re") @purchase = build(:purchase, link: @product, chargeable: build(:chargeable), perceived_price_cents: 100, save_card: false, price_range: 1) @purchase.variant_attributes << Sku.last @purchase.process! expect(field_value(last_data_row, "SKU ID")).to eq("ABC123_Sm_Re") end describe "subscriptions" do before do @product = create(:subscription_product, user: @seller, price_cents: 10_00) @subscription = create(:subscription, link: @product) @purchase = create(:purchase, link: @product, subscription: @subscription, is_original_subscription_purchase: true) end it "marks recurring charges" do row = last_data_row expect(field_value(row, "Recurring Charge?")).to eq("0") expect(field_value(row, "Recurrence")).to eq("monthly") expect(field_value(row, "Subscription End Date")).to eq(nil) create(:purchase, link: @product, subscription: @subscription) expect(field_value(last_data_row, "Recurring Charge?")).to eq("1") end it "marks free trial purchases" do @purchase.update!(purchase_state: "not_charged", is_free_trial_purchase: true) row = last_data_row expect(field_value(row, "Free trial purchase?")).to eq("1") end it "includes when the subscription was terminated" do @subscription.update_attribute(:cancelled_at, 1.day.ago) row = last_data_row expect(field_value(row, "Recurring Charge?")).to eq("0") expect(field_value(row, "Recurrence")).to eq("monthly") expect(field_value(row, "Subscription End Date")).to eq(@subscription.cancelled_at.to_date.to_s) end end describe "preorders" do before do @product = create(:product, is_in_preorder_state: true, user: @seller, price_cents: 10_00) @preorder_link = create(:preorder_link, link: @product, release_at: 2.days.from_now) @authorization_purchase = create(:purchase, link: @product, is_preorder_authorization: true) end it "marks preorder authorizations" do row = last_data_row expect(field_value(row, "Purchase Date")).to eq(@authorization_purchase.created_at.to_date.to_s) expect(field_value(row, "Purchase Time (UTC timezone)")).to eq(@authorization_purchase.created_at.to_time.to_s) expect(field_value(row, "Pre-order authorization?")).to eq("1") end it "includes the preorder authorization date-time", :vcr do preorder_auth_time = 2.days.ago travel_to(preorder_auth_time) do authorization_purchase = build(:purchase, link: @product, chargeable: build(:chargeable), purchase_state: "in_progress", is_preorder_authorization: true) @preorder = @preorder_link.build_preorder(authorization_purchase) @preorder.authorize! @preorder.mark_authorization_successful! end @preorder_link.update!(release_at: 2.days.from_now) @product.update_attribute(:is_in_preorder_state, false) @preorder.charge! charge_purchase = @preorder.purchases.last row = last_data_row expect(field_value(row, "Purchase Email")).to eq(charge_purchase.email) expect(field_value(row, "Purchase Date")).to eq(charge_purchase.created_at.to_date.to_s) expect(field_value(row, "Purchase Time (UTC timezone)")).to eq(charge_purchase.created_at.to_time.to_s) expect(field_value(row, "Pre-order authorization time (UTC timezone)")).to eq(preorder_auth_time.to_time.to_s) end end it "includes the offer code" do @purchase.update!(offer_code: create(:offer_code, products: [@product], code: "sxsw", amount_cents: 100)) expect(field_value(last_data_row, "Discount Code")).to eq("sxsw") end describe "sales tax" do before do @purchase.fee_cents = 31 end it "displays (blank) when purchase is not taxable" do @purchase.was_purchase_taxable = false @purchase.save! row = last_data_row expect(field_value(row, "Subtotal ($)")).to eq("100.0") expect(field_value(row, "Taxes ($)")).to eq("0.0") expect(field_value(row, "Tax Type")).to eq("") expect(field_value(row, "Shipping ($)")).to eq("0.0") expect(field_value(row, "Sale Price ($)")).to eq("100.0") expect(field_value(row, "Fees ($)")).to eq("0.31") expect(field_value(row, "Net Total ($)")).to eq("99.69") expect(field_value(row, "Tax Included in Price?")).to eq(nil) end it "displays 0 for 'Is Tax Included in Price ?' when tax was excluded from purchase price" do @purchase.was_purchase_taxable = true @purchase.was_tax_excluded_from_price = true @purchase.tax_cents = 1_10 @purchase.save! row = last_data_row expect(field_value(row, "Subtotal ($)")).to eq("98.9") expect(field_value(row, "Taxes ($)")).to eq("1.1") expect(field_value(row, "Shipping ($)")).to eq("0.0") expect(field_value(row, "Sale Price ($)")).to eq("100.0") expect(field_value(row, "Fees ($)")).to eq("0.31") expect(field_value(row, "Net Total ($)")).to eq("99.69") expect(field_value(row, "Tax Included in Price?")).to eq("0") end it "displays 1 for 'Is Tax Included in Price ?' when tax was not excluded from purchase price" do @purchase.was_purchase_taxable = true @purchase.was_tax_excluded_from_price = false @purchase.tax_cents = 1_10 @purchase.save! row = last_data_row expect(field_value(row, "Subtotal ($)")).to eq("98.9") expect(field_value(row, "Taxes ($)")).to eq("1.1") expect(field_value(row, "Shipping ($)")).to eq("0.0") expect(field_value(row, "Sale Price ($)")).to eq("100.0") expect(field_value(row, "Fees ($)")).to eq("0.31") expect(field_value(row, "Net Total ($)")).to eq("99.69") expect(field_value(row, "Tax Included in Price?")).to eq("1") end it "has subtotal that does not include the sales tax" do @purchase.was_purchase_taxable = true @purchase.was_tax_excluded_from_price = true @purchase.tax_cents = 1_10 @purchase.save! row = last_data_row expect(field_value(row, "Subtotal ($)")).to eq("98.9") expect(field_value(totals_row, "Subtotal ($)")).to eq("98.9") expect(field_value(row, "Taxes ($)")).to eq("1.1") expect(field_value(totals_row, "Taxes ($)")).to eq("1.1") expect(field_value(row, "Shipping ($)")).to eq("0.0") expect(field_value(totals_row, "Shipping ($)")).to eq("0.0") expect(field_value(row, "Sale Price ($)")).to eq("100.0") expect(field_value(totals_row, "Sale Price ($)")).to eq("100.0") expect(field_value(row, "Fees ($)")).to eq("0.31") expect(field_value(totals_row, "Fees ($)")).to eq("0.31") expect(field_value(row, "Net Total ($)")).to eq("99.69") expect(field_value(totals_row, "Net Total ($)")).to eq("99.69") expect(field_value(row, "Tax Included in Price?")).to eq("0") end it "has subtotal that does not include the tax collected by Gumroad" do @purchase.was_purchase_taxable = true @purchase.was_tax_excluded_from_price = true @purchase.gumroad_tax_cents = 1_80 @purchase.save! row = last_data_row expect(field_value(row, "Subtotal ($)")).to eq("100.0") expect(field_value(totals_row, "Subtotal ($)")).to eq("100.0") expect(field_value(row, "Taxes ($)")).to eq("1.8") expect(field_value(totals_row, "Taxes ($)")).to eq("1.8") expect(field_value(row, "Shipping ($)")).to eq("0.0") expect(field_value(totals_row, "Shipping ($)")).to eq("0.0") expect(field_value(row, "Sale Price ($)")).to eq("100.0") expect(field_value(totals_row, "Sale Price ($)")).to eq("100.0") expect(field_value(row, "Fees ($)")).to eq("0.31") expect(field_value(totals_row, "Fees ($)")).to eq("0.31") expect(field_value(row, "Net Total ($)")).to eq("99.69") expect(field_value(totals_row, "Net Total ($)")).to eq("99.69") expect(field_value(row, "Tax Included in Price?")).to eq("0") end describe "tax type" do tax_type_test_cases = [ { country: "IT", rate: 0.22, excluded: nil, expected_type: "VAT" }, { country: "AU", rate: 0.10, excluded: nil, expected_type: "GST" }, { country: "SG", rate: 0.07, excluded: nil, expected_type: "GST" }, { country: "US", rate: 0.085, excluded: true, expected_type: "Sales tax" }, { country: "US", rate: 0.085, excluded: false, expected_type: "Sales tax" }, { country: nil, rate: nil, excluded: true, expected_type: "Sales tax" }, ] tax_type_test_cases.each do |test_case| country = test_case[:country] rate = test_case[:rate] excluded = test_case[:excluded] expected_type = test_case[:expected_type] context "when country is #{country.inspect}, rate is #{rate.inspect}, and excluded is #{excluded.inspect}" do before do @purchase.update!( was_purchase_taxable: true, was_tax_excluded_from_price: excluded, tax_cents: 100, zip_tax_rate: country && create(:zip_tax_rate, country:, combined_rate: rate) ) end it "returns #{expected_type}" do expect(field_value(last_data_row, "Tax Type")).to eq(expected_type) end end end end end it "includes the affiliate information" do @affiliate_user = create(:affiliate_user) @seller = create(:affiliate_user, username: "momoney") @product = create(:product, user: @seller) @direct_affiliate = create(:direct_affiliate, affiliate_user: @affiliate_user, seller: @seller, affiliate_basis_points: 3000, products: [@product]) @purchase = create(:purchase_in_progress, seller: @seller, link: @product, purchase_state: "in_progress", affiliate: @direct_affiliate) @purchase.process! @purchase.update_balance_and_mark_successful! row = last_data_row expect(field_value(row, "Affiliate")).to eq(@affiliate_user.form_email) expect(field_value(row, "Affiliate commission ($)")).to eq("0.02") end it "includes the discover information" do @purchase.update!(was_product_recommended: true) expect(field_value(last_data_row, "Discover?")).to eq("1") end it "includes the full country name when purchase doesn't have shipping details" do create(:purchase, email: "test@gumroad.com", link: @product, zip_code: 94_103, state: "CA", country: "United States") create(:purchase, email: "test@gumroad.com", link: @product, ip_address: "199.241.200.176") rows = CSV.parse(generate_csv) expect(field_value(rows[1], "Country")).to eq("United States") expect(field_value(rows[2], "Country")).to eq("United States") expect(field_value(rows[3], "Country")).to eq("United States") end it "includes buyers email if buyer has an account" do @purchase.update!(email: "some@email.com", purchaser: create(:user, email: "some.other@email.com")) row = last_data_row expect(field_value(row, "Purchase Email")).to eq("some@email.com") expect(field_value(row, "Buyer Email")).to eq("some.other@email.com") end it "includes payment type" do @purchase.update!(card_type: "paypal") expect(field_value(last_data_row, "Payment Type")).to eq("PayPal") @purchase.update!(card_type: "mastercard") expect(field_value(last_data_row, "Payment Type")).to eq("Card") @purchase.update!(card_type: nil) expect(field_value(last_data_row, "Payment Type")).to eq(nil) end it "includes PayPal fields only for PayPal marketplace sales" do @purchase.update!( card_type: "mastercard", processor_fee_cents: 12, processor_fee_cents_currency: "eur" ) expect(field_value(last_data_row, "PayPal Transaction ID")).to be_nil expect(field_value(last_data_row, "PayPal Fee Amount")).to be_nil expect(field_value(last_data_row, "PayPal Fee Currency")).to be_nil @purchase.update!(card_type: "paypal") expect(field_value(last_data_row, "PayPal Transaction ID")).to be_nil expect(field_value(last_data_row, "PayPal Fee Amount")).to be_nil expect(field_value(totals_row, "PayPal Fee Amount")).to eq("0.0") expect(field_value(last_data_row, "PayPal Fee Currency")).to be_nil @purchase.update!(card_type: "paypal", paypal_order_id: "someOrderId", stripe_transaction_id: "PayPalTx123") expect(field_value(last_data_row, "PayPal Transaction ID")).to eq("PayPalTx123") expect(field_value(last_data_row, "PayPal Fee Amount")).to eq("0.12") expect(field_value(totals_row, "PayPal Fee Amount")).to eq("0.12") expect(field_value(last_data_row, "PayPal Fee Currency")).to eq("eur") end it "includes PayPal fields with fee amount in USD" do @purchase.update!( card_type: "mastercard", processor_fee_cents: 13, processor_fee_cents_currency: "usd" ) @purchase.update!(card_type: "paypal", paypal_order_id: "someOrderId", stripe_transaction_id: "PayPalTx123") expect(field_value(last_data_row, "PayPal Transaction ID")).to eq("PayPalTx123") expect(field_value(last_data_row, "PayPal Fee Amount")).to eq("0.13") expect(field_value(last_data_row, "PayPal Fee Currency")).to eq("usd") end it "includes PayPal fields with fee amount in GBP" do @purchase.update!( card_type: "mastercard", processor_fee_cents: 14, processor_fee_cents_currency: "gbp" ) @purchase.update!(card_type: "paypal", paypal_order_id: "someOrderId", stripe_transaction_id: "PayPalTx123") expect(field_value(last_data_row, "PayPal Transaction ID")).to eq("PayPalTx123") expect(field_value(last_data_row, "PayPal Fee Amount")).to eq("0.14") expect(field_value(last_data_row, "PayPal Fee Currency")).to eq("gbp") end it "includes Stripe fields only for Stripe Connect sales", :vcr do expect(field_value(last_data_row, "Stripe Transaction ID")).to be_nil expect(field_value(last_data_row, "Stripe Fee Amount")).to be_nil expect(field_value(last_data_row, "Stripe Fee Currency")).to be_nil @purchase.update!( merchant_account_id: create(:merchant_account_paypal).id, paypal_order_id: "someOrderId", processor_fee_cents: 12, processor_fee_cents_currency: "eur", stripe_transaction_id: "PayPalTx123" ) expect(field_value(last_data_row, "Stripe Transaction ID")).to be_nil expect(field_value(last_data_row, "Stripe Fee Amount")).to be_nil expect(field_value(last_data_row, "Stripe Fee Currency")).to be_nil @purchase.update!( merchant_account_id: create(:merchant_account_stripe).id, processor_fee_cents: 12, processor_fee_cents_currency: "eur", stripe_transaction_id: "ch_12345" ) expect(field_value(last_data_row, "Stripe Transaction ID")).to be_nil expect(field_value(last_data_row, "Stripe Fee Amount")).to be_nil expect(field_value(last_data_row, "Stripe Fee Currency")).to be_nil @purchase.update!( merchant_account_id: create(:merchant_account_stripe_connect).id, processor_fee_cents: 12, processor_fee_cents_currency: "eur", stripe_transaction_id: "ch_12345" ) expect(field_value(last_data_row, "Stripe Transaction ID")).to eq("ch_12345") expect(field_value(last_data_row, "Stripe Fee Amount")).to eq("0.12") expect(field_value(totals_row, "Stripe Fee Amount")).to eq("0.12") expect(field_value(last_data_row, "Stripe Fee Currency")).to eq("eur") end it "includes a field indicating if the purchase was purchasing power parity discounted" do expect(field_value(last_data_row, "Purchasing Power Parity Discounted?")).to eq("0") @purchase.update!(is_purchasing_power_parity_discounted: true) expect(field_value(last_data_row, "Purchasing Power Parity Discounted?")).to eq("1") end it "includes a field indicating if the purchase was upsold" do expect(field_value(last_data_row, "Upsold?")).to eq("0") create(:upsell_purchase, purchase: @purchase, upsell: create(:upsell, seller: @seller, product: @product, cross_sell: true)) expect(field_value(last_data_row, "Upsold?")).to eq("1") end it "generates csv with default purchase fields and extra purchase fields" do # We name a field "Order number" to check that a custom field can have the same name as a default field name create(:purchase_custom_field, name: "Age", value: "30", purchase: @purchase) create(:purchase_custom_field, name: "Order Number", value: "O123", purchase: @purchase) # We check that the custom fields of the represented products are present, even if the purchases don't set them @product.custom_fields << [create(:custom_field, name: "Age"), create(:custom_field, name: "Size")] csv = generate_csv rows = CSV.parse(csv) headers, row = rows.first, rows[rows.size - 2] expect(headers).to eq(described_class::PURCHASE_FIELDS + ["Age", "Order Number", "Size"]) expect(headers).to include("Tax Type") expect(headers.count("Order Number")).to eq(2) native_field_index = headers.index("Order Number") expect(row.fetch(native_field_index)).to eq(@purchase.external_id_numeric.to_s) custom_field_index = headers.rindex("Order Number") expect(row.fetch(custom_field_index)).to eq("O123") expect(row.fetch(headers.index("Age"))).to eq("30") expect(row.fetch(headers.index("Size"))).to eq(nil) end it "raises error if a value is not JSON safe (type other than String, Number, Array, Hash, Boolean, NilClass)" do expect { generate_csv }.not_to raise_error allow_any_instance_of(Purchase).to receive(:license_key).and_return(Time.now.utc) expect { generate_csv }.to raise_error(StandardError, /not JSON safe/) allow_any_instance_of(Purchase).to receive(:license_key).and_return(Time.zone.now) expect { generate_csv }.to raise_error(StandardError, /not JSON safe/) allow_any_instance_of(Purchase).to receive(:license_key).and_return(Date.today) expect { generate_csv }.to raise_error(StandardError, /not JSON safe/) end it "shows whether the license key is enabled (not disabled)" do expect(field_value(last_data_row, "License Key Enabled?")).to eq(nil) @product.update!(is_licensed: true) @purchase.create_license! expect(field_value(last_data_row, "License Key Enabled?")).to eq("1") @purchase.license.disable! expect(field_value(last_data_row, "License Key Enabled?")).to eq("0") end it "includes licence key" do @product.update!(is_licensed: true) @purchase.create_license! expect(@purchase.license_key).to be_present expect(field_value(last_data_row, "License Key")).to eq(@purchase.license_key) end it "includes licence key belonging to the giftee" do @product.update!(is_licensed: true) @purchase.update!(is_gift_sender_purchase: true) giftee_purchase = create(:purchase, :gift_receiver, link: @product) create(:gift, link: @product, gifter_purchase: @purchase, giftee_purchase:) giftee_purchase.create_license! expect(@purchase.license_key).to be_blank expect(giftee_purchase.license_key).to be_present expect(field_value(last_data_row, "License Key")).to eq(giftee_purchase.license_key) end it "includes license key activation count" do @product.update!(is_licensed: true) @purchase.create_license! expect(field_value(last_data_row, "License Key Activation Count")).to eq("0") @purchase.license.update!(uses: 5) expect(field_value(last_data_row, "License Key Activation Count")).to eq("5") end it "includes license key activation count for giftee" do @product.update!(is_licensed: true) @purchase.update!(is_gift_sender_purchase: true) giftee_purchase = create(:purchase, :gift_receiver, link: @product) create(:gift, link: @product, gifter_purchase: @purchase, giftee_purchase:) giftee_purchase.create_license! giftee_purchase.license.update!(uses: 3) expect(field_value(last_data_row, "License Key Activation Count")).to eq("3") end it "shows nil for license key activation count when no license exists" do expect(field_value(last_data_row, "License Key Activation Count")).to be_nil end it "shows whether the purchase is associated to a sent abandoned cart email" do expect(field_value(last_data_row, "Sent Abandoned Cart Email?")).to eq("0") cart = create(:cart, order: create(:order, purchases: [@purchase])) create(:sent_abandoned_cart_email, cart:) # for a different seller's product expect(field_value(last_data_row, "Sent Abandoned Cart Email?")).to eq("0") workflow = create(:abandoned_cart_workflow, seller: @seller) create(:sent_abandoned_cart_email, cart:, installment: workflow.installments.sole) expect(field_value(last_data_row, "Sent Abandoned Cart Email?")).to eq("1") end it "includes access revoked status" do expect(field_value(last_data_row, "Access Revoked?")).to eq("0") @purchase.update!(is_access_revoked: true) expect(field_value(last_data_row, "Access Revoked?")).to eq("1") end context "when the purchase has a tip" do before do create(:tip, purchase: @purchase, value_usd_cents: 100, created_at: 2.minutes.ago) create(:tip, purchase: create(:purchase, link: @product, seller: @seller), value_usd_cents: 450, created_at: 1.minute.ago) end it "includes the tip amount in USD" do expect(field_value(last_data_row, "Tip ($)")).to eq("4.5") expect(field_value(totals_row, "Tip ($)")).to eq("5.5") end end context "when the purchase has no tip" do it "shows 0 for the tip amount" do expect(field_value(last_data_row, "Tip ($)")).to eq("0.0") expect(field_value(totals_row, "Tip ($)")).to eq("0.0") end end describe "UTM parameters" do context "when the purchase was not driven by a UTM link" do it "includes blank values for UTM parameters" do expect(field_value(last_data_row, "UTM Source")).to be_nil expect(field_value(last_data_row, "UTM Medium")).to be_nil expect(field_value(last_data_row, "UTM Campaign")).to be_nil expect(field_value(last_data_row, "UTM Term")).to be_nil expect(field_value(last_data_row, "UTM Content")).to be_nil end end context "when the purchase was driven by a UTM link" do it "includes the UTM parameters" do utm_link = create(:utm_link, utm_source: "twitter", utm_medium: "social", utm_campaign: "campaign", utm_term: "gumroad", utm_content: "hello-world") create(:utm_link_driven_sale, utm_link:, purchase: @purchase) expect(field_value(last_data_row, "UTM Source")).to eq("twitter") expect(field_value(last_data_row, "UTM Medium")).to eq("social") expect(field_value(last_data_row, "UTM Campaign")).to eq("campaign") expect(field_value(last_data_row, "UTM Term")).to eq("gumroad") expect(field_value(last_data_row, "UTM Content")).to eq("hello-world") end end end end def field_index(name) described_class::PURCHASE_FIELDS.index(name) end def field_value(row, name) row.fetch(field_index(name)) end def generate_csv(purchases = @seller.sales.where(purchase_state: Purchase::NON_GIFT_SUCCESS_STATES)) described_class.new(purchases).perform.read end def last_data_row rows = CSV.parse(generate_csv) rows[rows.size - 2] # last row has totals end def totals_row rows = CSV.parse(generate_csv) rows.last end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/exports/affiliate_export_service_spec.rb
spec/services/exports/affiliate_export_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Exports::AffiliateExportService do describe "#perform" do before do @product = create(:product, price_cents: 10_00, name: "Product 1") @seller = @product.user @affiliate_user = create(:affiliate_user, email: "affiliate@gumroad.com", name: "Affiliate 1") @direct_affiliate = create(:direct_affiliate, affiliate_user: @affiliate_user, seller: @seller, affiliate_basis_points: 1000, products: [@product]) @purchase = create(:purchase_in_progress, seller: @seller, link: @product, affiliate: @direct_affiliate) @purchase.process! @purchase.update_balance_and_mark_successful! create(:direct_affiliate, seller: @seller).mark_deleted! @service = described_class.new(@seller) @service.perform end it "generates affiliates CSV tempfile with proper data" do rows = CSV.parse(@service.tempfile.read) expect(rows.size).to eq(3) headers, data_row, totals_row = rows.first, rows.second, rows.last expect(headers).to match_array described_class::AFFILIATE_FIELDS expect(field_value(data_row, "Affiliate ID")).to eq(@direct_affiliate.external_id_numeric.to_s) expect(field_value(data_row, "Name")).to eq("Affiliate 1") expect(totals_row[0]).to eq("Totals") expect(field_value(data_row, "Email")).to eq("affiliate@gumroad.com") expect(field_value(data_row, "Fee")).to eq("10 %") expect(field_value(data_row, "Sales ($)")).to eq("10.00") expect(field_value(totals_row, "Sales ($)")).to eq("10.0") expect(field_value(data_row, "Products")).to eq('["Product 1"]') expect(field_value(data_row, "Referral URL")).to eq(@direct_affiliate.referral_url) expect(field_value(data_row, "Destination URL")).to eq(@direct_affiliate.destination_url) expect(field_value(data_row, "Created At")).to eq(@direct_affiliate.created_at.in_time_zone(@direct_affiliate.affiliate_user.timezone).to_date.to_s) end it "sets a filename" do expect(@service.filename).to match(/Affiliates-#{@seller.username}_.*\.csv/) end end describe ".export" do before do @seller = create(:user) create(:direct_affiliate, seller: @seller) create(:direct_affiliate, seller: @seller).mark_deleted! end it "returns performed service when the affiliates count is below the threshold" do stub_const("#{described_class}::SYNCHRONOUS_EXPORT_THRESHOLD", 2) result = described_class.export(seller: @seller) expect(result).to be_a(described_class) expect(result.filename).to be_a(String) expect(result.tempfile).to be_a(Tempfile) end it "enqueues job and returns false when the affiliates count is above the threshold" do stub_const("#{described_class}::SYNCHRONOUS_EXPORT_THRESHOLD", 0) recipient = create(:user) result = described_class.export(seller: @seller, recipient:) expect(result).to eq(false) expect(Exports::AffiliateExportWorker).to have_enqueued_sidekiq_job(@seller.id, recipient.id) end end def field_index(name) described_class::AFFILIATE_FIELDS.index(name) end def field_value(row, name) row.fetch(field_index(name)) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/exports/payouts/csv_spec.rb
spec/services/exports/payouts/csv_spec.rb
# frozen_string_literal: true require "spec_helper" describe Exports::Payouts::Csv, :vcr do describe "perform" do let!(:now) { Time.current } let!(:payout_date) { 1.week.ago } let(:payout_processor_type) { PayoutProcessorType::PAYPAL } before do @seller = create :named_user @another_seller = create :named_user @direct_affiliate = create :direct_affiliate, affiliate_user: @seller, seller: @another_seller base_past_date = 1.month.ago allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil) travel_to(base_past_date) do @product = create :product, user: @seller, name: "Hunting Capybaras For Fun And Profit", price_cents: 1000 @affiliate_product = create :product, user: @another_seller, name: "Some Affiliate Product", price_cents: 1000 end travel_to(base_past_date - 2.days) do @purchase_to_chargeback = create_purchase price_cents: 1000, seller: @seller, link: @product event = OpenStruct.new(created_at: 1.day.ago, extras: {}, flow_of_funds: FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @purchase_to_chargeback.total_transaction_cents)) allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil) @purchase_to_chargeback.handle_event_dispute_formalized!(event) end travel_to(base_past_date) do @regular_purchase = create_purchase price_cents: 1000, seller: @seller, link: @product @paypal_purchase = create_purchase price_cents: 1000, seller: @seller, link: @product, charge_processor_id: PaypalChargeProcessor.charge_processor_id, chargeable: create(:native_paypal_chargeable), merchant_account: create(:merchant_account_paypal, user: @seller, charge_processor_merchant_id: "CJS32DZ7NDN5L", country: "GB", currency: "gbp") @paypal_purchase.update!(affiliate_credit_cents: 200) @purchase_with_tax = create_purchase price_cents: 1000, seller: @seller, link: @product, tax_cents: 200 @purchase_with_gumroad_tax = create_purchase price_cents: 1000, seller: @seller, link: @product, gumroad_tax_cents: 180 @purchase_with_affiliate_1 = create_purchase price_cents: 1000, seller: @another_seller, link: @affiliate_product, affiliate: @direct_affiliate @purchase_to_refund = create_purchase price_cents: 1000, seller: @seller, link: @product @user_credit = Credit.create_for_credit!(user: @seller, amount_cents: 1000, crediting_user: create(:user)) end travel_to(base_past_date + 1.day) do @purchase_to_refund.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @purchase_to_refund.total_transaction_cents), @seller) @purchase_to_refund.reload end travel_to(base_past_date) do @purchase_to_refund_partially = create(:purchase_in_progress, price_cents: 1000, seller: @seller, link: @product, chargeable: create(:chargeable)) @purchase_to_refund_partially.process! @purchase_to_refund_partially.update_balance_and_mark_successful! end travel_to(base_past_date + 1.day) do @purchase_to_refund_partially.refund_and_save!(@seller.id, amount_cents: 350) @purchase_to_refund_partially.reload end travel_to(base_past_date) do @purchase_to_refund_from_years_ago = create_purchase price_cents: 1000, seller: @seller, link: @product end travel_to(base_past_date + 1.day) do @purchase_to_refund_from_years_ago.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @purchase_to_refund.total_transaction_cents), @seller) @purchase_to_refund_from_years_ago.refunds.first.balance_transactions.destroy_all @purchase_to_refund_from_years_ago.reload end travel_to(base_past_date) do bt = BalanceTransaction::Amount.new( currency: @regular_purchase.link.price_currency_type, gross_cents: @regular_purchase.payment_cents, net_cents: @regular_purchase.payment_cents) @credit_for_dispute_won = Credit.create_for_dispute_won!(user: @seller, merchant_account: MerchantAccount.gumroad(PaypalChargeProcessor::DISPLAY_NAME), dispute: create(:dispute, purchase: @regular_purchase), chargedback_purchase: @regular_purchase, balance_transaction_issued_amount: bt, balance_transaction_holding_amount: bt) end @payout = create_payout(payout_date, payout_processor_type, @seller) end it "shows all activity related to the payout" do csv = Exports::Payouts::Csv.new(payment_id: @payout.id).perform parsed_csv = CSV.parse(csv) expected = [ Exports::Payouts::Csv::HEADERS, ["Chargeback", @purchase_to_chargeback.chargeback_date.to_date.to_s, @purchase_to_chargeback.external_id, @purchase_to_chargeback.link.name, @purchase_to_chargeback.full_name, @purchase_to_chargeback.purchaser_email_or_email, "-0.0", "-0.0", "-10.0", "-2.09", "-7.91"], ["Sale", @purchase_to_chargeback.succeeded_at.to_date.to_s, @purchase_to_chargeback.external_id, @purchase_to_chargeback.link.name, @purchase_to_chargeback.full_name, @purchase_to_chargeback.purchaser_email_or_email, "0.0", "0.0", "10.0", "2.09", "7.91"], ["Credit", @user_credit.balance.date.to_s, "", "", "", "", "", "", "10.0", "", "10.0"], ["Sale", @regular_purchase.succeeded_at.to_date.to_s, @regular_purchase.external_id, @regular_purchase.link.name, @regular_purchase.full_name, @regular_purchase.purchaser_email_or_email, "0.0", "0.0", "10.0", "2.09", "7.91"], ["Sale", @purchase_with_tax.succeeded_at.to_date.to_s, @purchase_with_tax.external_id, @purchase_with_tax.link.name, @purchase_with_tax.full_name, @purchase_with_tax.purchaser_email_or_email, "2.0", "0.0", "10.0", "2.09", "7.91"], ["Sale", @purchase_with_gumroad_tax.succeeded_at.to_date.to_s, @purchase_with_gumroad_tax.external_id, @purchase_with_gumroad_tax.link.name, @purchase_with_gumroad_tax.full_name, @purchase_with_gumroad_tax.purchaser_email_or_email, "1.8", "0.0", "10.0", "2.09", "7.91"], ["Sale", @purchase_to_refund.succeeded_at.to_date.to_s, @purchase_to_refund.external_id, @purchase_to_refund.link.name, @purchase_to_refund.full_name, @purchase_to_refund.purchaser_email_or_email, "0.0", "0.0", "10.0", "2.09", "7.91"], ["Sale", @purchase_to_refund_partially.succeeded_at.to_date.to_s, @purchase_to_refund_partially.external_id, @purchase_to_refund_partially.link.name, @purchase_to_refund_partially.full_name, @purchase_to_refund_partially.purchaser_email_or_email, "0.0", "0.0", "10.0", "2.09", "7.91"], ["Sale", @purchase_to_refund_from_years_ago.succeeded_at.to_date.to_s, @purchase_to_refund_from_years_ago.external_id, @purchase_to_refund_from_years_ago.link.name, @purchase_to_refund_from_years_ago.full_name, @purchase_to_refund_from_years_ago.purchaser_email_or_email, "0.0", "0.0", "10.0", "2.09", "7.91"], ["Affiliate Credit", @purchase_with_tax.succeeded_at.to_date.to_s, "", "", "", "", "", "", "0.23", "", "0.23"], ["Credit", @credit_for_dispute_won.balance.date.to_s, @regular_purchase.external_id, "", "", "", "", "", "7.91", "", "7.91"], ["Sale", @paypal_purchase.succeeded_at.to_date.to_s, @paypal_purchase.external_id, @paypal_purchase.link.name, @paypal_purchase.full_name, @paypal_purchase.purchaser_email_or_email, "0.0", "0.0", "10.0", "1.5", "8.5"], ["PayPal Connect Affiliate Fees", @paypal_purchase.succeeded_at.to_date.to_s, "", "", "", "", "", "", "-2.0", "", "-2.0"], ["Full Refund", (@purchase_to_refund.succeeded_at + 1.day).to_date.to_s, @purchase_to_refund.external_id, @purchase_to_refund.link.name, @purchase_to_refund.full_name, @purchase_to_refund.purchaser_email_or_email, "-0.0", "-0.0", "-10.0", "-1.5", "-8.5"], ["Partial Refund", (@purchase_to_refund_partially.succeeded_at + 1.day).to_date.to_s, @purchase_to_refund_partially.external_id, @purchase_to_refund_partially.link.name, @purchase_to_refund_partially.full_name, @purchase_to_refund_partially.purchaser_email_or_email, "-0.0", "-0.0", "-3.5", "-0.55", "-2.95"], ["Full Refund", (@purchase_to_refund_from_years_ago.succeeded_at + 1.day).to_date.to_s, @purchase_to_refund_from_years_ago.external_id, @purchase_to_refund_from_years_ago.link.name, @purchase_to_refund_from_years_ago.full_name, @purchase_to_refund_from_years_ago.purchaser_email_or_email, "-0.0", "-0.0", "-10.0", "-1.5", "-8.5"], ["PayPal Payouts", @payout.payout_period_end_date.to_s, "", "", "", "", "", "", "-6.5", "", "-6.5"], ["Payout Fee", @payout.payout_period_end_date.to_s, "", "", "", "", "", "", "", "0.92", "-0.92"], ["Totals", nil, nil, nil, nil, nil, "3.8", "0.0", "56.14", "11.41", "44.73"] ] expect(parsed_csv).to eq(expected) end describe "Technical Adjustment entries" do it "does not add entry for non-usd payment currency" do @payout.amount_cents = @payout.amount_cents + 100 @payout.currency = Currency::GBP @payout.save! csv = Exports::Payouts::Csv.new(payment_id: @payout.id).perform parsed_csv = CSV.parse(csv) expect(parsed_csv).not_to include(["Technical Adjustment", @payout.payout_period_end_date.to_s, "", "", "", "", "", "", "", "", "1.0"]) end it "add entry for usd payment currency" do @payout.amount_cents = @payout.amount_cents + 100 @payout.save! csv = Exports::Payouts::Csv.new(payment_id: @payout.id).perform parsed_csv = CSV.parse(csv) expect(parsed_csv).to include(["Technical Adjustment", @payout.payout_period_end_date.to_s, "", "", "", "", "", "", "", "", "1.0"]) end end end describe "affiliate fees from Stripe Connect sales" do it "correctly adds the affiliate fee entries from Stripe Connect sales" do seller = create :user direct_affiliate = create(:direct_affiliate, affiliate_user: create(:user), seller:) stripe_connect_account = create(:merchant_account_stripe_connect, user: seller, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d") travel_to(1.month.ago) do affiliate_product = create :product, user: seller, name: "Some Affiliate Product", price_cents: 15000 create_purchase price_cents: 1000, seller:, link: affiliate_product create_purchase price_cents: 1000, seller:, link: affiliate_product, affiliate: direct_affiliate, merchant_account: stripe_connect_account end regular_purchase = Purchase.where.not(merchant_account_id: stripe_connect_account.id).last stripe_connect_purchase = Purchase.where(merchant_account_id: stripe_connect_account.id).last travel_to(10.days.ago) do stripe_connect_purchase.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, 7500), seller.id) end payout = create_payout(1.week.ago, PayoutProcessorType::PAYPAL, seller) csv = Exports::Payouts::Csv.new(payment_id: payout.id).perform parsed_csv = CSV.parse(csv) expect(parsed_csv).to match_array [ Exports::Payouts::Csv::HEADERS, ["Sale", regular_purchase.succeeded_at.to_date.to_s, regular_purchase.external_id, regular_purchase.link.name, regular_purchase.full_name, regular_purchase.purchaser_email_or_email, "0.0", "0.0", "150.0", "20.15", "129.85"], ["Sale", stripe_connect_purchase.succeeded_at.to_date.to_s, stripe_connect_purchase.external_id, stripe_connect_purchase.link.name, stripe_connect_purchase.full_name, stripe_connect_purchase.purchaser_email_or_email, "0.0", "0.0", "150.0", "15.5", "134.5"], ["Stripe Connect Affiliate Fees", stripe_connect_purchase.succeeded_at.to_date.to_s, "", "", "", "", "", "", "-4.03", "", "-4.03"], ["Stripe Connect Refund", 10.days.ago.to_date.to_s, stripe_connect_purchase.external_id, stripe_connect_purchase.link.name, stripe_connect_purchase.full_name, stripe_connect_purchase.purchaser_email_or_email, "-0.0", "-0.0", "-75.0", "7.75", "-67.25"], ["Stripe Connect Affiliate Fees", 10.days.ago.to_date.to_s, "", "", "", "", "", "", "2.02", "", "2.02"], ["Stripe Connect Payouts", payout.payout_period_end_date.to_date.to_s, "", "", "", "", "", "", "-65.24", "", "-65.24"], ["Payout Fee", payout.payout_period_end_date.to_s, "", "", "", "", "", "", "", "2.6", "-2.6"], ["Totals", nil, nil, nil, nil, nil, "0.0", "0.0", "157.75", "46.0", "127.25"] ] end end describe "affiliate credits involving several balances" do let!(:now) { Time.current } let!(:payout_date) { 1.week.ago } let(:payout_processor_type) { PayoutProcessorType::PAYPAL } before do @seller = create :user @another_seller = create :user @direct_affiliate = create :direct_affiliate, affiliate_user: @seller, seller: @another_seller travel_to(1.month.ago) do @affiliate_product = create :product, user: @another_seller, name: "Some Affiliate Product", price_cents: 1000 @affiliate_product_2 = create :product, user: @another_seller, name: "Some Affiliate Product", price_cents: 15000 end travel_to(1.month.ago + 1.day) do @from_previous_payout = create_purchase price_cents: 1000, seller: @another_seller, link: @affiliate_product, affiliate: @direct_affiliate end travel_to(1.month.ago + 2.day) do create_payout(Time.current, payout_processor_type, @seller) end travel_to(1.month.ago + 9.day) do @from_this_payout = create_purchase price_cents: 15000, seller: @another_seller, link: @affiliate_product_2, affiliate: @direct_affiliate @from_previous_payout.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, @from_previous_payout.total_transaction_cents), @seller) @from_previous_payout.reload end travel_to(1.month.ago + 18.day) do @payout = create_payout(payout_date, payout_processor_type, @seller) end end it "takes refunded credit into account, even if actual credit happened in a different payout" do csv = Exports::Payouts::Csv.new(payment_id: @payout.id).perform parsed_csv = CSV.parse(csv) # +3.96 for from_this_payout credit # -0.30 for from_previous_payout refund expect(parsed_csv).to eq [ Exports::Payouts::Csv::HEADERS, ["Affiliate Credit", @from_this_payout.succeeded_at.to_date.to_s, "", "", "", "", "", "", "3.66", "", "3.66"], ["Payout Fee", @payout.payout_period_end_date.to_s, "", "", "", "", "", "", "", "0.08", "-0.08"], ["Totals", nil, nil, nil, nil, nil, "0.0", "0.0", "3.66", "0.08", "3.58"] ] end end def create_payout(payout_date, processor_type, user) payment, _ = Payouts.create_payment(payout_date, processor_type, user) payment.update(correlation_id: "12345") payment.txn_id = 123 payment.mark_completed! payment end def create_purchase(**attrs) purchase = create :purchase, **attrs, card_type: CardType::PAYPAL, purchase_state: "in_progress" purchase.process! purchase.update_balance_and_mark_successful! if attrs[:tax_cents] purchase.tax_cents = attrs[:tax_cents] purchase.save end if attrs[:gumroad_tax_cents] purchase.gumroad_tax_cents = attrs[:gumroad_tax_cents] purchase.save end purchase end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/exports/payouts/annual_spec.rb
spec/services/exports/payouts/annual_spec.rb
# frozen_string_literal: true require "spec_helper" describe Exports::Payouts::Annual, :vcr do include PaymentsHelper describe "perform" do let!(:year) { 2019 } before do @user = create(:user) date_for_year = Date.new(year) amount_cents = 1500 (0..11).each do |month| created_at_date = date_for_year + month.months payment = create(:payment_completed, user: @user, amount_cents:, payout_period_end_date: created_at_date, created_at: created_at_date) purchase = create(:purchase, seller: @user, 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, link: create(:product, user: @user)) payment.amount_cents = purchase.payment_cents payment.save! create(:purchase, seller: @user, price_cents: amount_cents, total_transaction_cents: amount_cents, charge_processor_id: PaypalChargeProcessor.charge_processor_id, created_at: created_at_date, succeeded_at: created_at_date, link: create(:product, user: @user)) end end it "shows all activity related to the yearly payout" do date_for_year = Date.new(year) data = Exports::Payouts::Annual.new(user: @user, year:).perform parsed_csv = CSV.parse(data[:csv_file].read) expect(parsed_csv).to include(Exports::Payouts::Csv::HEADERS) @user.sales.where("created_at BETWEEN ? AND ?", date_for_year.beginning_of_year, date_for_year.at_end_of_year).each do |sale| expect(parsed_csv).to include(sale_summary(sale)) end expect(parsed_csv.last).to eq(["Totals", nil, nil, nil, nil, nil, "0.0", "0.0", "212.88", "65.76", "147.12"]) end it "returns total_amount from the yearly payout" do date_for_year = Date.new(year) data = Exports::Payouts::Annual.new(user: @user, year:).perform amount = (data[:total_amount] * 100.0).round expect(amount).to eq(@user.sales.where("created_at BETWEEN ? AND ?", date_for_year.beginning_of_year, date_for_year.at_end_of_year).sum("price_cents - fee_cents")) end it "returns no data if no payments exist" do data = Exports::Payouts::Annual.new(user: create(:user), year:).perform expect(data[:csv_file]).to be_nil end it "returns no data on failed payments" do date_for_year = Date.new(year) payment_data = create_payment_with_purchase(@user, date_for_year, :payment_failed) data = Exports::Payouts::Annual.new(user: @user, year:).perform parsed_csv = CSV.parse(data[:csv_file].read) expect(parsed_csv).not_to include(sale_summary(payment_data[:purchase])) end it "does not return sales falling on days not in given year" do payment_data = create_payment_with_purchase(@user, Date.new(year) - 3.days) data = Exports::Payouts::Annual.new(user: @user, year:).perform parsed_csv = CSV.parse(data[:csv_file].read) expect(parsed_csv).to_not include(sale_summary(payment_data[:purchase])) end end private def sale_summary(sale) CSV.parse([ "Sale", sale.succeeded_at.to_date.to_s, sale.external_id, sale.link.name, sale.full_name, sale.purchaser_email_or_email, sale.tax_dollars, sale.shipping_dollars, sale.price_dollars, sale.fee_dollars, sale.net_total, ].to_csv).first end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/exports/tax_summary/payable_spec.rb
spec/services/exports/tax_summary/payable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Exports::TaxSummary::Payable, :vcr do include PaymentsHelper describe "perform" do let!(:year) { 2019 } before do date_in_year = Date.new(year) @user = create(:user) @compliance_info = create(:user_compliance_info, user: @user) @merchant_account_stripe = create(:merchant_account_stripe, user: @user) create(:tos_agreement, user: @user) @payments = {} @payments[date_in_year] = create_payment_with_purchase(@user, date_in_year)[:payment] 11.downto(1).each do |i| @payments[date_in_year + i.months] = create_payment_with_purchase(@user, date_in_year + i.months)[:payment] end end it "generates total transactions count" do csv = Exports::TaxSummary::Payable.new(user: @user, year:).perform parsed_csv = CSV.parse(csv) expect(parsed_csv[1][24]).to eq "12" end it "generates total transactions amount" do csv = Exports::TaxSummary::Payable.new(user: @user, year:).perform parsed_csv = CSV.parse(csv) total_amount = @payments.values.collect(&:amount_cents).sum(0) / 100.0 expect(parsed_csv[1][21]).to eq(total_amount.to_s) end it "creates monthly breakdown with transaction amount" do csv = Exports::TaxSummary::Payable.new(user: @user, year:).perform parsed_csv = CSV.parse(csv) expect(parsed_csv[1][26..37].sort).to eq @payments.values.collect { |payment| (payment.amount_cents / 100.0).to_s }.sort end it "adds compliance and other user related fields" do csv = Exports::TaxSummary::Payable.new(user: @user, year:).perform parsed_csv = CSV.parse(csv) row = parsed_csv[1] expect(row[1]).to eq(@user.external_id) expect(row[2]).to eq(@merchant_account_stripe.charge_processor_merchant_id) expect(row[3..6]).to eq([@compliance_info.first_and_last_name, @compliance_info.first_name, @compliance_info.last_name, @compliance_info.legal_entity_name]) expect(row[7]).to eq(@user.email) expect(row[8..13]).to eq([@compliance_info.legal_entity_street_address, nil, @compliance_info.legal_entity_city, @compliance_info.legal_entity_state_code, @compliance_info.legal_entity_zip_code, @compliance_info.legal_entity_country_code,]) expect(row[14]).to eq(@compliance_info.legal_entity_payable_business_type) expect(row[17]).to eq "EPF Other" expect(row[18]).to eq "Third Party Network" expect(row[19]).to eq "Gumroad" expect(row[20]).to eq "(650) 204-3486" end it "adds tax id if user is an individual" do csv = Exports::TaxSummary::Payable.new(user: @user, year:).perform parsed_csv = CSV.parse(csv) row = parsed_csv[1] expect(row[15]).to eq(@compliance_info.individual_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))) end context "when user is a business" do before do @user.user_compliance_infos.delete_all @compliance_info = create(:user_compliance_info_business, user: @user) end it "adds individual tax id and business tax id if user is a business" do csv = Exports::TaxSummary::Payable.new(user: @user, year:).perform parsed_csv = CSV.parse(csv) row = parsed_csv[1] expect(row[15]).to eq(@compliance_info.individual_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))) expect(row[16]).to eq(@compliance_info.business_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))) end end it "returns no data if no payments exist" do csv = Exports::TaxSummary::Payable.new(user: create(:user), year:).perform expect(csv).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/exports/tax_summary/annual_spec.rb
spec/services/exports/tax_summary/annual_spec.rb
# frozen_string_literal: true require "spec_helper" describe Exports::TaxSummary::Annual, :vcr do include PaymentsHelper describe "perform" do let!(:year) { 2019 } before do date_in_year = Date.new(year) @user = create(:user) @compliance_info = create(:user_compliance_info, user: @user) @merchant_account_stripe = create(:merchant_account_stripe, user: @user) create(:tos_agreement, user: @user) @payments = {} @payments[date_in_year] = create_payment_with_purchase(@user, date_in_year)[:payment] 11.downto(1).each do |i| @payments[date_in_year + i.months] = create_payment_with_purchase(@user, date_in_year + i.months)[:payment] end # To simulate the exports stub_const("User::Taxation::MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING", 10) end it "does not export for non compliant users" do UserComplianceInfo.delete_all csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| csv_data = CSV.parse f.read expect(csv_data).to be_empty end end it "does not export for non-us users" do @compliance_info.destroy @compliance_info = create(:user_compliance_info, user: @user, country: Compliance::Countries::GBR.common_name) csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| csv_data = CSV.parse f.read expect(csv_data).to be_empty end end it "does not export for invalid compliance country users" do UserComplianceInfo.delete_all @compliance_info = create(:user_compliance_info, user: @user) UserComplianceInfo.update_all(country: "Aland Islands") csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| csv_data = CSV.parse f.read expect(csv_data).to be_empty end end it "does not export users without min sales amount" do stub_const("User::Taxation::MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING", 100_000) csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| csv_data = CSV.parse f.read expect(csv_data).to be_empty end end it "generates total transactions amount" do csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| parsed_csv = CSV.parse f.read total_amount = @payments.values.collect(&:amount_cents).sum(0) / 100.0 expect(parsed_csv[1][21]).to eq(total_amount.to_s) end end it "creates monthly breakdown with transaction amount" do csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| parsed_csv = CSV.parse f.read expect(parsed_csv[1][26..37].sort).to eq @payments.values.collect { |payment| (payment.amount_cents / 100.0).to_s }.sort end end it "returns compliance and other user related fields" do csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| parsed_csv = CSV.parse f.read row = parsed_csv[1] expect(row[1]).to eq(@user.external_id) expect(row[2]).to eq(@merchant_account_stripe.charge_processor_merchant_id) expect(row[3..6]).to eq([@compliance_info.first_and_last_name, @compliance_info.first_name, @compliance_info.last_name, @compliance_info.legal_entity_name]) expect(row[7]).to eq(@user.email) expect(row[8..13]).to eq([@compliance_info.legal_entity_street_address, nil, @compliance_info.legal_entity_city, @compliance_info.legal_entity_state_code, @compliance_info.legal_entity_zip_code, @compliance_info.legal_entity_country_code,]) expect(row[14]).to eq(@compliance_info.legal_entity_payable_business_type) expect(row[17]).to eq "EPF Other" expect(row[18]).to eq "Third Party Network" expect(row[19]).to eq "Gumroad" expect(row[20]).to eq "(650) 204-3486" end end it "adds tax id if user is an individual" do csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| parsed_csv = CSV.parse f.read row = parsed_csv[1] expect(row[15]).to eq(@compliance_info.individual_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))) end end it "adds business tax id if user is a business" do @user.user_compliance_infos.delete_all @compliance_info = create(:user_compliance_info_business, user: @user) csv_url = described_class.new(year:).perform URI.open(csv_url) do |f| parsed_csv = CSV.parse f.read row = parsed_csv[1] expect(row[16]).to eq(@compliance_info.business_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))) 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/product/compute_call_availabilities_service_spec.rb
spec/services/product/compute_call_availabilities_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::ComputeCallAvailabilitiesService, :freeze_time do let(:seller) { create(:user, :eligible_for_service_products) } let(:call_product) { create(:call_product, user: seller) } let(:call_limitation_info) { call_product.call_limitation_info } let(:service) { described_class.new(call_product) } before do travel_to(Time.utc(2015, 4, 1)) end def create_call_availability(start_time:, end_time:) create(:call_availability, call: call_product, start_time:, end_time:) end def create_sold_call(start_time:, end_time:) create(:call_purchase, link: call_product, call: create(:call, start_time:, end_time:)) end context "when product is not a call product" do let(:coffee_product) { create(:coffee_product) } it "returns an empty array" do expect(service.perform).to eq([]) end end it "excludes availabilities from the past" do call_limitation_info.update!(minimum_notice_in_minutes: 0) create_call_availability(start_time: 10.hours.ago, end_time: 1.hour.from_now) create_call_availability(start_time: 1.hour.from_now, end_time: 2.hours.from_now) expect(service.perform).to contain_exactly({ start_time: Time.current, end_time: 2.hours.from_now }) end it "excludes availabilities that are within the minimum notice period" do call_limitation_info.update!(minimum_notice_in_minutes: 1.hour.in_minutes) create_call_availability(start_time: 10.hours.ago, end_time: 2.hours.from_now) expect(service.perform).to contain_exactly({ start_time: 1.hour.from_now, end_time: 2.hours.from_now }) end it "excludes availabiltiies on days that exceed the maximum call limit for the seller's timezone" do # Explicitly simulate three different timezones to ensure calculations are correct. # For ease of understanding, everything is setup in the seller's timezone, and then converted to other timezones # as needed. seller_timezone = Time.find_zone("Pacific Time (US & Canada)") buyer_timezone = Time.find_zone("Eastern Time (US & Canada)") system_timezone = Time.find_zone("UTC") seller.update!(timezone: seller_timezone.name) call_limitation_info.update!(maximum_calls_per_day: 1, minimum_notice_in_minutes: 0) travel_to(seller_timezone.local(2015, 4, 1, 12)) available_from_apr_1_to_apr_6 = create_call_availability( start_time: seller_timezone.local(2015, 4, 1, 12), end_time: seller_timezone.local(2015, 4, 6, 12) ) create_sold_call( start_time: seller_timezone.local(2015, 4, 2, 12).in_time_zone(buyer_timezone), end_time: seller_timezone.local(2015, 4, 2, 13).in_time_zone(buyer_timezone) ) create_sold_call( start_time: seller_timezone.local(2015, 4, 3, 12).in_time_zone(buyer_timezone), end_time: seller_timezone.local(2015, 4, 3, 13).in_time_zone(buyer_timezone) ) sold_apr_5_to_apr_6 = create_sold_call( start_time: seller_timezone.local(2015, 4, 5, 12).in_time_zone(buyer_timezone), end_time: seller_timezone.local(2015, 4, 6, 1).in_time_zone(buyer_timezone) ) availabilities = Time.use_zone(system_timezone) { service.perform } expect(availabilities).to contain_exactly( { start_time: available_from_apr_1_to_apr_6.start_time, # Apr 2nd has already scheduled the maximum number of calls, thus available till the end of Apr 1st. end_time: seller_timezone.local(2015, 4, 1).end_of_day }, { # Apr 3rd has already scheduled the maximum number of calls, thus available from the beginning of Apr 4th. start_time: seller_timezone.local(2015, 4, 4).beginning_of_day, # Apr 5th has already scheduled the maximum number of calls, thus available till the end of Apr 4th. end_time: seller_timezone.local(2015, 4, 4).end_of_day }, { # The call that spans from Apr 5th to 6th does not count towards limit for Apr 6th, thus available from Apr 6th. start_time: sold_apr_5_to_apr_6.call.end_time, end_time: available_from_apr_1_to_apr_6.end_time } ) end it "excludes availabilities that are sold" do # Ensure overlapping availabilities are not double counted. create_call_availability(start_time: 10.hours.from_now, end_time: 16.hours.from_now) create_call_availability(start_time: 10.hours.from_now, end_time: 16.hours.from_now) create_sold_call(start_time: 9.hours.from_now, end_time: 11.hours.from_now) create_sold_call(start_time: 14.hours.from_now, end_time: 15.hours.from_now) expect(service.perform).to contain_exactly( { start_time: 11.hours.from_now, end_time: 14.hours.from_now }, { start_time: 15.hours.from_now, end_time: 16.hours.from_now } ) end it "includes availabilities that are sold but no longer take up availabilities" do create_call_availability(start_time: 10.hours.from_now, end_time: 16.hours.from_now) create( :call_purchase, :refunded, link: call_product, call: create(:call, start_time: 10.hours.from_now, end_time: 11.hours.from_now) ) create( :call_purchase, purchase_state: "failed", link: call_product, call: create(:call, start_time: 11.hours.from_now, end_time: 12.hours.from_now) ) expect(service.perform).to contain_exactly({ start_time: 10.hours.from_now, end_time: 16.hours.from_now }) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/product/save_post_purchase_custom_fields_service_spec.rb
spec/services/product/save_post_purchase_custom_fields_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::SavePostPurchaseCustomFieldsService do describe "#perform" do let(:product) { create(:product_with_digital_versions, has_same_rich_content_for_all_variants: true) } let!(:long_answer) { create(:custom_field, seller: product.user, products: [product], field_type: CustomField::TYPE_LONG_TEXT, is_post_purchase: true) } let!(:short_answer) { create(:custom_field, seller: product.user, products: [product], field_type: CustomField::TYPE_TEXT, is_post_purchase: true) } let!(:non_post_purchase) { create(:custom_field, seller: product.user, products: [product], field_type: CustomField::TYPE_TEXT) } let!(:rich_content) do create( :product_rich_content, entity: product, description: [ { "type" => RichContent::LONG_ANSWER_NODE_TYPE, "attrs" => { "id" => long_answer.external_id, "label" => "Long answer" } }, { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "label" => "New short answer" }, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => non_post_purchase.external_id, "label" => "Non post purchase short answer" }, } ] ) end it "syncs post-purchase custom fields with rich content nodes" do expect do described_class.new(product.reload).perform end.to change { CustomField.exists?(short_answer.id) }.from(true).to(false) .and change { long_answer.reload.name }.from("Custom field").to("Long answer") .and not_change { non_post_purchase.reload.name } file_upload = product.custom_fields.find_by(field_type: CustomField::TYPE_FILE) expect(file_upload.seller).to eq(product.user) expect(file_upload.products).to eq([product]) expect(file_upload.is_post_purchase).to eq(true) new_short_answer = product.custom_fields.where(field_type: CustomField::TYPE_TEXT).second_to_last expect(new_short_answer.seller).to eq(product.user) expect(new_short_answer.products).to eq([product]) expect(new_short_answer.name).to eq("New short answer") expect(new_short_answer.is_post_purchase).to eq(true) other_new_short_answer = product.custom_fields.where(field_type: CustomField::TYPE_TEXT).last expect(other_new_short_answer.seller).to eq(product.user) expect(other_new_short_answer.products).to eq([product]) expect(other_new_short_answer.name).to eq("Non post purchase short answer") expect(other_new_short_answer.is_post_purchase).to eq(true) expect(rich_content.reload.description).to eq( [ { "type" => RichContent::LONG_ANSWER_NODE_TYPE, "attrs" => { "id" => long_answer.external_id, "label" => "Long answer" } }, { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, "attrs" => { "id" => file_upload.external_id } }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "label" => "New short answer", "id" => new_short_answer.external_id, }, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => other_new_short_answer.external_id, "label" => "Non post purchase short answer" }, } ] ) end context "product has different content for each variant" do let!(:rich_content1) do create( :rich_content, entity: product.alive_variants.first, description: [ { "type" => RichContent::LONG_ANSWER_NODE_TYPE, "attrs" => { "id" => long_answer.external_id, "label" => "Long answer 1" } }, { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "label" => "New short answer 1" }, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => non_post_purchase.external_id, "label" => "Non post purchase short answer 1" }, } ] ) end let!(:rich_content2) do create( :rich_content, entity: product.alive_variants.second, description: [ { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "label" => "New short answer 2" }, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => non_post_purchase.external_id, "label" => "Non post purchase short answer 2" }, } ] ) end before { product.update!(has_same_rich_content_for_all_variants: false) } it "syncs post-purchase custom fields with rich content nodes for all variants" do expect do described_class.new(product.reload).perform end.to change { CustomField.exists?(short_answer.id) }.from(true).to(false) .and change { long_answer.reload.name }.from("Custom field").to("Long answer 1") .and not_change { non_post_purchase.reload.name } file_upload1 = product.custom_fields.where(field_type: CustomField::TYPE_FILE).first expect(file_upload1.seller).to eq(product.user) expect(file_upload1.products).to eq([product]) expect(file_upload1.is_post_purchase).to eq(true) new_short_answer1 = product.custom_fields.where(field_type: CustomField::TYPE_TEXT).find_by(name: "New short answer 1") expect(new_short_answer1.seller).to eq(product.user) expect(new_short_answer1.products).to eq([product]) expect(new_short_answer1.is_post_purchase).to eq(true) other_new_short_answer1 = product.custom_fields.where(field_type: CustomField::TYPE_TEXT).find_by(name: "Non post purchase short answer 1") expect(other_new_short_answer1.seller).to eq(product.user) expect(other_new_short_answer1.products).to eq([product]) expect(other_new_short_answer1.is_post_purchase).to eq(true) expect(rich_content1.reload.description).to eq( [ { "type" => RichContent::LONG_ANSWER_NODE_TYPE, "attrs" => { "id" => long_answer.external_id, "label" => "Long answer 1" } }, { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, "attrs" => { "id" => file_upload1.external_id } }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "label" => "New short answer 1", "id" => new_short_answer1.external_id, }, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => other_new_short_answer1.external_id, "label" => "Non post purchase short answer 1" }, } ] ) file_upload2 = product.custom_fields.where(field_type: CustomField::TYPE_FILE).second expect(file_upload2.seller).to eq(product.user) expect(file_upload2.products).to eq([product]) expect(file_upload2.is_post_purchase).to eq(true) new_short_answer2 = product.custom_fields.where(field_type: CustomField::TYPE_TEXT).find_by(name: "New short answer 2") expect(new_short_answer2.seller).to eq(product.user) expect(new_short_answer2.products).to eq([product]) expect(new_short_answer2.is_post_purchase).to eq(true) other_new_short_answer2 = product.custom_fields.where(field_type: CustomField::TYPE_TEXT).find_by(name: "Non post purchase short answer 2") expect(other_new_short_answer2.seller).to eq(product.user) expect(other_new_short_answer2.products).to eq([product]) expect(other_new_short_answer2.is_post_purchase).to eq(true) expect(rich_content2.reload.description).to eq( [ { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, "attrs" => { "id" => file_upload2.external_id } }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "label" => "New short answer 2", "id" => new_short_answer2.external_id, }, }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => other_new_short_answer2.external_id, "label" => "Non post purchase short answer 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/services/product/skus_updater_service_spec.rb
spec/services/product/skus_updater_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::SkusUpdaterService do describe ".perform" do before do @product = create(:physical_product, skus_enabled: true) @category1 = create(:variant_category, title: "Size", link: @product) @variant1 = create(:variant, variant_category: @category1, name: "Small") @category2 = create(:variant_category, title: "Color", link: @product) @variant2 = create(:variant, variant_category: @category2, name: "Red") end subject { Product::SkusUpdaterService.new(product: @product) } it "creates the proper skus" do subject.perform expect(Sku.count).to eq 2 expect(Sku.not_is_default_sku.count).to eq 1 expect(Sku.not_is_default_sku.last.name).to eq "Small - Red" expect(Sku.not_is_default_sku.last.variants).to eq [@variant1, @variant2] expect(Sku.not_is_default_sku.last.link).to eq @product end it "creates the proper skus" do variant1_1 = create(:variant, variant_category: @category1, name: "Large") variant2_2 = create(:variant, variant_category: @category2, name: "Blue") subject.perform expect(Sku.count).to eq 5 expect(Sku.not_is_default_sku.count).to eq 4 skus = Sku.not_is_default_sku expect(skus.map(&:link)).to all eq(@product) expect(skus[0].name).to eq "Small - Red" expect(skus[0].variants).to match_array [@variant1, @variant2] expect(skus[1].name).to eq "Small - Blue" expect(skus[1].variants).to match_array [@variant1, variant2_2] expect(skus[2].name).to eq "Large - Red" expect(skus[2].variants).to match_array [variant1_1, @variant2] expect(skus[3].name).to eq "Large - Blue" expect(skus[3].variants).to match_array [variant1_1, variant2_2] end it "renames the existing sku if the variant name has changed" do subject.perform sku = Sku.last @variant1.update!(name: "S") subject.perform expect(Sku.count).to eq 2 expect(Sku.not_is_default_sku.count).to eq 1 expect(Sku.not_is_default_sku.last.name).to eq "S - Red" expect(Sku.not_is_default_sku.last.variants).to eq [@variant1, @variant2] expect(Sku.not_is_default_sku.last.id).to eq sku.id end it "removes the old skus and creates new ones if a new category has been added" do subject.perform old_sku = Sku.last @category2 = create(:variant_category, title: "Pattern", link: @product) @variant2 = create(:variant, variant_category: @category2, name: "Plaid") subject.perform expect(Sku.count).to eq 3 expect(Sku.not_is_default_sku.count).to eq 2 expect(Sku.not_is_default_sku.last.name).to eq "Small - Red - Plaid" expect(old_sku.reload.deleted_at.present?).to be(true) end it "deletes the skus if there are no variant categories left" do subject.perform @category1.mark_deleted @category2.mark_deleted subject.perform expect(Sku.count).to eq 2 expect(Sku.not_is_default_sku.count).to eq 1 expect(Sku.not_is_default_sku.last.deleted_at.present?).to be(true) end it "does not delete the default sku" do subject.perform @category1.mark_deleted @category2.mark_deleted subject.perform expect(Sku.alive.count).to eq 1 expect(Sku.alive.is_default_sku.count).to eq 1 expect(Sku.alive.not_is_default_sku.count).to eq 0 end it "sets the price and quantity properly on existing skus" do variant1_1 = create(:variant, variant_category: @category1, name: "Large") variant2_2 = create(:variant, variant_category: @category2, name: "Blue") subject.perform expect(Sku.count).to eq 5 expect(Sku.not_is_default_sku.count).to eq 4 skus = Sku.not_is_default_sku expect(skus[0].name).to eq "Small - Red" expect(skus[0].variants).to eq [@variant1, @variant2] expect(skus[1].name).to eq "Small - Blue" expect(skus[1].variants).to eq [@variant1, variant2_2] expect(skus[2].name).to eq "Large - Red" expect(skus[2].variants).to eq [variant1_1, @variant2] expect(skus[3].name).to eq "Large - Blue" expect(skus[3].variants).to eq [variant1_1, variant2_2] skus_params = [ { price_difference: "1", max_purchase_count: "2", id: skus[0].external_id }, { price_difference: "3", max_purchase_count: "4", id: skus[1].external_id }, { price_difference: "5", max_purchase_count: "6", id: skus[2].external_id }, { price_difference: "7", max_purchase_count: "8", id: skus[3].external_id } ] Product::SkusUpdaterService.new(product: @product, skus_params:).perform skus = Sku.not_is_default_sku expect(skus[0].price_difference_cents).to eq 100 expect(skus[0].max_purchase_count).to eq 2 expect(skus[1].price_difference_cents).to eq 300 expect(skus[1].max_purchase_count).to eq 4 expect(skus[2].price_difference_cents).to eq 500 expect(skus[2].max_purchase_count).to eq 6 expect(skus[3].price_difference_cents).to eq 700 expect(skus[3].max_purchase_count).to eq 8 end context "invalid SKU id in params" do it "raises an error" do subject.perform skus = Sku.not_is_default_sku skus_params = [ { price_difference: "1", max_purchase_count: "2", id: skus[0].external_id }, { price_difference: "3", max_purchase_count: "4", id: "not_a_valid_sku" }, ] expect do Product::SkusUpdaterService.new(product: @product, skus_params:).perform end.to raise_error(Link::LinkInvalid) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/services/product/save_integrations_service_spec.rb
spec/services/product/save_integrations_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::SaveIntegrationsService do let(:product) { create(:product) } def get_integration_class(integration_name) case integration_name when "circle" CircleIntegration when "discord" DiscordIntegration when "zoom" ZoomIntegration when "google_calendar" GoogleCalendarIntegration else raise "Unknown integration: #{integration_name}" end end describe ".perform" do shared_examples "manages integrations" do it "adds a new integration" do expect do described_class.perform(product, { integration_name => new_integration_params }) end.to change { Integration.count }.by(1) .and change { ProductIntegration.count }.by(1) product_integration = ProductIntegration.last integration = Integration.last expect(product_integration.integration).to eq(integration) expect(product_integration.product).to eq(product) expect(integration.type).to eq(Integration.type_for(integration_name)) new_integration_params.each do |key, value| expect(integration.send(key)).to eq(value) end end it "modifies an existing integration" do product.active_integrations << create("#{integration_name}_integration".to_sym) expect do described_class.perform(product, { integration_name => modified_integration_params }) end.to change { Integration.count }.by(0) .and change { ProductIntegration.count }.by(0) product_integration = ProductIntegration.last integration = Integration.last expect(product_integration.integration).to eq(integration) expect(product_integration.product).to eq(product) expect(integration.type).to eq(Integration.type_for(integration_name)) modified_integration_params.each do |key, value| expect(integration.send(key)).to eq(value) end end it "calls disconnect if integration is removed" do product.active_integrations << create("#{integration_name}_integration".to_sym) expect_any_instance_of(get_integration_class(integration_name)).to receive(:disconnect!).and_return(true) expect do described_class.perform(product, {}) end.to change { product.active_integrations.count }.by(-1) expect(product.live_product_integrations.pluck(:integration_id)).to match_array [] end it "does not call disconnect if integration is removed but the same integration is present on another product by same user" do integration_1 = create("#{integration_name}_integration".to_sym) integration_2 = create("#{integration_name}_integration".to_sym) product.active_integrations << integration_1 product_2 = create(:product, user: product.user, active_integrations: [integration_2]) if integration_1.same_connection?(integration_2) expect_any_instance_of(get_integration_class(integration_name)).to_not receive(:disconnect!) end expect do described_class.perform(product, {}) end.to change { product.active_integrations.count }.by(-1) expect(product.live_product_integrations.pluck(:integration_id)).to match_array [] expect(product_2.live_product_integrations.pluck(:integration_id)).to match_array [integration_2.id] end end describe "circle integration" do let(:integration_name) { "circle" } let(:new_integration_params) { { "api_key" => GlobalConfig.get("CIRCLE_API_KEY"), "community_id" => "0", "space_group_id" => "0", "keep_inactive_members" => false } } let(:modified_integration_params) { { "api_key" => "modified_api_key", "community_id" => "1", "space_group_id" => "1", "keep_inactive_members" => true } } it_behaves_like "manages integrations" end describe "discord integration" do let(:server_id) { "0" } let(:integration_name) { "discord" } let(:new_integration_params) { { "server_id" => server_id, "server_name" => "Gaming", "username" => "gumbot", "keep_inactive_members" => false } } let(:modified_integration_params) { { "server_id" => "1", "server_name" => "Tech", "username" => "techuser", "keep_inactive_members" => true } } it_behaves_like "manages integrations" describe "disconnection" do let(:request_header) { { "Authorization" => "Bot #{DISCORD_BOT_TOKEN}" } } let!(:discord_integration) do integration = create(:discord_integration, server_id:) product.active_integrations << integration integration end it "removes bot from server if server id is valid" do WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/users/@me/guilds/#{server_id}"). with(headers: request_header). to_return(status: 204) expect do described_class.perform(product, {}) end.to change { product.active_integrations.count }.by(-1) expect(product.live_product_integrations.pluck(:integration_id)).to match_array [] end it "fails if bot is not added to server" do WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/users/@me/guilds/#{server_id}"). with(headers: request_header). to_return(status: 404, body: { code: Discordrb::Errors::UnknownMember.code }.to_json) expect do described_class.perform(product, {}) end.to change { product.active_integrations.count }.by(0) .and raise_error(Link::LinkInvalid) expect(product.live_product_integrations.pluck(:integration_id)).to match_array [discord_integration].map(&:id) end end end describe "zoom integration" do let(:integration_name) { "zoom" } let(:new_integration_params) { { "user_id" => "0", "email" => "test@zoom.com", "access_token" => "test_access_token", "refresh_token" => "test_refresh_token" } } let(:modified_integration_params) { { "user_id" => "1", "email" => "test2@zoom.com", "access_token" => "test_access_token", "refresh_token" => "test_refresh_token" } } it_behaves_like "manages integrations" end describe "google calendar integration" do let(:integration_name) { "google_calendar" } let(:new_integration_params) { { "calendar_id" => "0", "calendar_summary" => "Holidays", "access_token" => "test_access_token", "refresh_token" => "test_refresh_token", "email" => "hi@gmail.com" } } let(:modified_integration_params) { { "calendar_id" => "1", "calendar_summary" => "Meetings", "access_token" => "test_access_token", "refresh_token" => "test_refresh_token", "email" => "hi@gmail.com" } } it_behaves_like "manages integrations" describe "disconnection" do let!(:google_calendar_integration) do integration = create(:google_calendar_integration) product.active_integrations << integration integration end it "succeeds if the gumroad app is successfully disconnected from google account" do WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/revoke"). with(query: { token: google_calendar_integration.access_token }).to_return(status: 200) expect do described_class.perform(product, {}) end.to change { product.active_integrations.count }.by(-1) expect(product.live_product_integrations.pluck(:integration_id)).to match_array [] end it "fails if disconnecting the gumroad app from google fails" do WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/revoke"). with(query: { token: google_calendar_integration.access_token }).to_return(status: 404) expect do described_class.perform(product, {}) end.to change { product.active_integrations.count }.by(0) .and raise_error(Link::LinkInvalid) expect(product.live_product_integrations.pluck(:integration_id)).to match_array [google_calendar_integration.id] 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/product/bulk_update_support_email_service_spec.rb
spec/services/product/bulk_update_support_email_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::BulkUpdateSupportEmailService do let(:user) { create(:user) } let!(:product1) { create(:product, user:, support_email: "old1@example.com") } let!(:product2) { create(:product, user:, support_email: "old2@example.com") } let!(:product3) { create(:product, user:, support_email: "old3@example.com") } let(:other_user_product) { create(:product, support_email: "other@example.com") } before { Feature.activate_user(:product_level_support_emails, user) } describe "#perform" do it "updates products support emails according to entries" do entries = [ { email: "new1+2@example.com", product_ids: [product1.external_id, product2.external_id] }, { email: "new3@example.com", product_ids: [product3.external_id] } ] service = described_class.new(user, entries) expect { service.perform } .to change { product1.reload.support_email }.to("new1+2@example.com") .and change { product2.reload.support_email }.to("new1+2@example.com") .and change { product3.reload.support_email }.to("new3@example.com") end it "raises an error if any of the emails is invalid" do entries = [ { email: "new1@example.com", product_ids: [product1.external_id] }, { email: "invalid", product_ids: [product2.external_id] } ] service = described_class.new(user, entries) expect { service.perform } .to raise_error(ActiveModel::ValidationError) .with_message("Validation failed: Support email is invalid") expect(product1.reload.support_email).to eq("old1@example.com") expect(product2.reload.support_email).to eq("old2@example.com") expect(product3.reload.support_email).to eq("old3@example.com") end it "clears support emails for products not in any entry" do entries = [{ email: "new1@example.com", product_ids: [product1.external_id] }] service = described_class.new(user, entries) expect { service.perform } .to change { product1.reload.support_email }.to("new1@example.com") .and change { product2.reload.support_email }.to(nil) .and change { product3.reload.support_email }.to(nil) end it "clears all support emails when provided empty array" do service = described_class.new(user, []) expect { service.perform } .to change { product1.reload.support_email }.to(nil) .and change { product2.reload.support_email }.to(nil) .and change { product3.reload.support_email }.to(nil) end it "clears all support emails when provided nil" do service = described_class.new(user, nil) expect { service.perform } .to change { product1.reload.support_email }.to(nil) .and change { product2.reload.support_email }.to(nil) .and change { product3.reload.support_email }.to(nil) end it "does not update products that do not belong to the user" do entries = [ { email: "new1@example.com", product_ids: [product1.external_id] }, { email: "new2@example.com", product_ids: [other_user_product.external_id] } ] service = described_class.new(user, entries) expect { service.perform } .to change { product1.reload.support_email }.to("new1@example.com") .and not_change { other_user_product.reload.support_email } end context "when user does not have product_level_support_emails enabled" do before do Feature.deactivate_user(:product_level_support_emails, user) end it "does not update any product support emails" do entries = [{ email: "new@example.com", product_ids: [product1.external_id] }] service = described_class.new(user, entries) service.perform expect(product1.reload.support_email).to eq("old1@example.com") expect(product2.reload.support_email).to eq("old2@example.com") expect(product3.reload.support_email).to eq("old3@example.com") 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/product/save_cancellation_discount_service_spec.rb
spec/services/product/save_cancellation_discount_service_spec.rb
# frozen_string_literal: true RSpec.describe Product::SaveCancellationDiscountService do let(:product) { create(:membership_product_with_preset_tiered_pricing) } let(:service) { described_class.new(product, cancellation_discount_params) } describe "#perform" do context "with fixed amount discount" do let(:cancellation_discount_params) do { discount: { type: "fixed", cents: 100 }, duration_in_billing_cycles: 3 } end it "creates a new fixed amount cancellation discount offer code" do service.perform offer_code = product.cancellation_discount_offer_code expect(offer_code).to be_present expect(offer_code.amount_cents).to eq(100) expect(offer_code.amount_percentage).to be_nil expect(offer_code.duration_in_billing_cycles).to eq(3) expect(offer_code.code).to be_nil expect(offer_code.products).to eq([product]) expect(offer_code.is_cancellation_discount).to eq(true) end context "when duration_in_billing_cycles is nil" do let(:cancellation_discount_params) do { discount: { type: "fixed", cents: 100 }, duration_in_billing_cycles: nil } end it "creates offer code with nil duration" do service.perform offer_code = product.cancellation_discount_offer_code expect(offer_code).to be_present expect(offer_code.duration_in_billing_cycles).to be_nil end end context "when cancellation discount already exists" do let!(:existing_offer_code) { create(:fixed_cancellation_discount_offer_code, user: product.user, products: [product]) } it "updates the existing offer code" do service.perform existing_offer_code.reload expect(existing_offer_code.amount_cents).to eq(100) expect(existing_offer_code.amount_percentage).to be_nil expect(existing_offer_code.duration_in_billing_cycles).to eq(3) end end end context "with percentage discount" do let(:cancellation_discount_params) do { discount: { type: "percentage", percents: 20 }, duration_in_billing_cycles: 2 } end it "creates a new percentage cancellation discount offer code" do service.perform offer_code = product.cancellation_discount_offer_code expect(offer_code).to be_present expect(offer_code.amount_percentage).to eq(20) expect(offer_code.amount_cents).to be_nil expect(offer_code.duration_in_billing_cycles).to eq(2) expect(offer_code).to be_is_cancellation_discount end context "when duration_in_billing_cycles is nil" do let(:cancellation_discount_params) do { discount: { type: "percentage", percents: 20 }, duration_in_billing_cycles: nil } end it "creates offer code with nil duration" do service.perform offer_code = product.cancellation_discount_offer_code expect(offer_code).to be_present expect(offer_code.duration_in_billing_cycles).to be_nil end end context "when cancellation discount already exists" do let!(:existing_offer_code) { create(:percentage_cancellation_discount_offer_code, products: [product]) } it "updates the existing offer code" do service.perform existing_offer_code.reload expect(existing_offer_code.amount_percentage).to eq(20) expect(existing_offer_code.amount_cents).to be_nil expect(existing_offer_code.duration_in_billing_cycles).to eq(2) end context "when params are nil" do let(:cancellation_discount_params) { nil } it "marks the existing offer code as deleted" do service.perform expect(existing_offer_code.reload).to be_deleted expect(product.cancellation_discount_offer_code).to be_nil 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/product/variant_category_updater_service_spec.rb
spec/services/product/variant_category_updater_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::VariantCategoryUpdaterService do describe ".perform" do context "when trying to update a variant from another product" do let(:product) { create(:product) } let(:other_product) { create(:product) } let(:variant) { create(:variant, variant_category: create(:variant_category, link: product)) } let(:other_variant) { create(:variant, variant_category: create(:variant_category, link: other_product)) } let(:variant_category_params) do { id: variant.variant_category.external_id, title: variant.variant_category.title, options: [ { id: other_variant.external_id, name: other_variant.name, } ] } end it "raises an error and does not update the variant" do expect { Product::VariantCategoryUpdaterService.new(product: product, category_params: variant_category_params).perform }.to raise_error(ActiveRecord::RecordNotFound) expect(variant.reload.name).not_to eq other_variant.name end end describe "notifying subscribers of price changes" do let(:product) { create(:product) } let(:was_applying_price_changes_to_existing_memberships) { false } let(:was_subscription_price_change_effective_date) { 10.days.from_now.to_date } let(:variant) do create( :variant, variant_category: create(:variant_category, link: product), apply_price_changes_to_existing_memberships: was_applying_price_changes_to_existing_memberships, subscription_price_change_effective_date: was_subscription_price_change_effective_date ) end let(:variant_category_params) do { id: variant.variant_category.external_id, title: variant.variant_category.title, options: [ { id: variant.external_id, name: variant.name, apply_price_changes_to_existing_memberships:, subscription_price_change_effective_date:, } ] } end context "when apply_price_changes_to_existing_memberships is enabled and the effective date changed" do let(:apply_price_changes_to_existing_memberships) { true } let(:subscription_price_change_effective_date) { 7.days.from_now.to_date } it "schedules ScheduleMembershipPriceUpdatesJob" do expect(ScheduleMembershipPriceUpdatesJob).to receive(:perform_async).with(variant.id) Product::VariantCategoryUpdaterService.new(product: product, category_params: variant_category_params).perform end end context "when disabling apply_price_changes_to_existing_memberships" do let(:was_applying_price_changes_to_existing_memberships) { true } let(:apply_price_changes_to_existing_memberships) { false } let(:subscription_price_change_effective_date) { was_subscription_price_change_effective_date } it "does not schedule ScheduleMembershipPriceUpdatesJob" do expect(ScheduleMembershipPriceUpdatesJob).not_to receive(:perform_async).with(variant.id) end context "when the flags previously changed" do it "notifies Bugsnag" do expect(Bugsnag).to receive(:notify).with("Not notifying subscribers of membership price change - tier: #{variant.id}; apply_price_changes_to_existing_memberships: false; subscription_price_change_effective_date: #{was_subscription_price_change_effective_date}") Product::VariantCategoryUpdaterService.new(product: product, category_params: variant_category_params).perform end end context "when the effective date previously changed" do let(:was_applying_price_changes_to_existing_memberships) { false } let(:apply_price_changes_to_existing_memberships) { false } let(:was_subscription_price_change_effective_date) { 7.days.from_now.to_date } let(:subscription_price_change_effective_date) { 10.days.from_now.to_date } it "notifies Bugsnag" do expect(Bugsnag).to receive(:notify).with("Not notifying subscribers of membership price change - tier: #{variant.id}; apply_price_changes_to_existing_memberships: false; subscription_price_change_effective_date: #{subscription_price_change_effective_date}") Product::VariantCategoryUpdaterService.new(product: product, category_params: variant_category_params).perform end end end context "when changing the effective date and apply_price_changes_to_existing_memberships is already enabled" do let(:was_applying_price_changes_to_existing_memberships) { true } let(:apply_price_changes_to_existing_memberships) { true } let(:subscription_price_change_effective_date) { 7.days.from_now.to_date } it "schedules ScheduleMembershipPriceUpdatesJob" do expect(ScheduleMembershipPriceUpdatesJob).to receive(:perform_async).with(variant.id) Product::VariantCategoryUpdaterService.new(product: product, category_params: variant_category_params).perform end end end context "when associating files" do before do @product = create(:product) vc = create(:variant_category, link: @product) @variant = create(:variant, variant_category: vc) @file1 = create(:product_file, link: @product) @file2 = create(:product_file, link: @product) @variant.product_files << @file1 @variant_category_params = { title: vc.title, id: vc.external_id, options: [ { id: @variant.external_id, name: @variant.name, rich_content: [{ id: nil, title: "Page title", description: [@file1, @file2].map { { type: "fileEmbed", attrs: { id: _1.external_id, uid: SecureRandom.uuid } } } }], } ] } end it "saves new files on versions" do Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform expect(@variant.reload.product_files).to match_array [@file1, @file2] end context "when versions are removed" do it "marks them as deleted and queues a DeleteProductRichContentWorker" do freeze_time do expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: { id: @variant.variant_category.external_id, title: "" }, ).perform end.to change { @variant.reload.deleted_at }.from(nil).to(Time.current) expect(DeleteProductRichContentWorker).to have_enqueued_sidekiq_job(@product.id, @variant.id) end end end end context "for tiered memberships" do before :each do @product = create(:membership_product) @effective_date = 7.days.from_now.to_date @variant_category_params = { title: "Tier", id: @product.tier_category.external_id, options: [ { name: "First Tier", description: nil, price_difference: nil, max_purchase_count: 10, id: nil, url: "http://tier1.com", apply_price_changes_to_existing_memberships: true, subscription_price_change_effective_date: @effective_date.strftime("%Y-%m-%d"), }, { name: "Second Tier", description: nil, price_difference: nil, max_purchase_count: nil, id: nil, } ] } end it "updates the tiers" do Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform first_tier = @product.reload.tier_category.variants.find_by(name: "First Tier") expect(first_tier.max_purchase_count).to eq 10 expect(first_tier.apply_price_changes_to_existing_memberships).to eq true expect(first_tier.subscription_price_change_effective_date).to eq @effective_date end context "with recurrence pricing" do before :each do @variant_category_params[:options][0].merge!( recurrence_price_values: { BasePrice::Recurrence::MONTHLY => { enabled: true, price_cents: 2005, }, BasePrice::Recurrence::QUARTERLY => { enabled: true, price_cents: 4500, }, BasePrice::Recurrence::YEARLY => { enabled: true, price_cents: 12000, }, BasePrice::Recurrence::BIANNUALLY => { enabled: false }, BasePrice::Recurrence::EVERY_TWO_YEARS => { enabled: false } } ) @variant_category_params[:options][1].merge!( recurrence_price_values: { BasePrice::Recurrence::MONTHLY => { enabled: true, price_cents: 1000, }, BasePrice::Recurrence::QUARTERLY => { enabled: true, price_cents: 2500, }, BasePrice::Recurrence::YEARLY => { enabled: true, price_cents: 6000, }, BasePrice::Recurrence::BIANNUALLY => { enabled: false }, BasePrice::Recurrence::EVERY_TWO_YEARS => { enabled: false } } ) end it "saves variants with valid recurrence prices" do Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform variants = @product.reload.tier_category.variants first_tier_prices = variants.find_by!(name: "First Tier").prices.alive second_tier_prices = variants.find_by!(name: "Second Tier").prices.alive expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY).price_cents).to eq 2005 expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::QUARTERLY).price_cents).to eq 4500 expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY).price_cents).to eq 12000 expect(first_tier_prices.find_by(recurrence: BasePrice::Recurrence::BIANNUALLY)).to be nil expect(first_tier_prices.find_by(recurrence: BasePrice::Recurrence::EVERY_TWO_YEARS)).to be nil expect(second_tier_prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY).price_cents).to eq 1000 expect(second_tier_prices.find_by!(recurrence: BasePrice::Recurrence::QUARTERLY).price_cents).to eq 2500 expect(second_tier_prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY).price_cents).to eq 6000 expect(second_tier_prices.find_by(recurrence: BasePrice::Recurrence::BIANNUALLY)).to be nil expect(second_tier_prices.find_by(recurrence: BasePrice::Recurrence::EVERY_TWO_YEARS)).to be nil end context "with pay-what-you-want pricing" do before :each do @variant_category_params[:options][0][:customizable_price] = "1" @variant_category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::MONTHLY][:suggested_price_cents] = 2200 @variant_category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::QUARTERLY][:suggested_price_cents] = 4700 @variant_category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::YEARLY][:suggested_price_cents] = 12200 end it "saves suggested prices" do Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform first_tier = @product.reload.tier_category.variants.find_by(name: "First Tier") first_tier_prices = first_tier.prices.alive expect(first_tier.customizable_price).to be true expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY).suggested_price_cents).to eq 2200 expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::QUARTERLY).suggested_price_cents).to eq 4700 expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY).suggested_price_cents).to eq 12200 end context "without suggested prices" do it "succeeds" do @variant_category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::MONTHLY][:suggested_price_cents] = nil @variant_category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::QUARTERLY].delete(:suggested_price_cents) Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform first_tier = @product.reload.tier_category.variants.find_by(name: "First Tier") first_tier_prices = first_tier.prices.alive expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY).suggested_price_cents).to be_nil expect(first_tier_prices.find_by!(recurrence: BasePrice::Recurrence::QUARTERLY).suggested_price_cents).to be_nil end end context "missing all prices values" do it "raises an error" do category_params = @variant_category_params category_params[:options][0].delete(:recurrence_price_values) expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "Please provide suggested payment options." end end context "with a suggested price that is below price_cents" do it "raises an error" do @variant_category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::MONTHLY][:suggested_price_cents] = 2004 expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "The suggested price you entered was too low." end end end context "with invalid recurrences" do context "such as missing a price for the default recurrence" do it "raises an error" do @variant_category_params[:options].each do |option| option[:recurrence_price_values].delete(BasePrice::Recurrence::MONTHLY) end expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "Please provide a price for the default payment option." end end context "such as specifying enabled: false for the default recurrence" do it "raises an error" do @variant_category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::MONTHLY][:enabled] = false expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: @variant_category_params ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "Please provide a price for the default payment option." end end context "such as different recurrences for different variants" do it "raises an error" do category_params = @variant_category_params category_params[:options][0][:recurrence_price_values].delete(BasePrice::Recurrence::YEARLY) expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "All tiers must have the same set of payment options." end end context "such as missing price for a recurrence" do it "raises an error" do category_params = @variant_category_params category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::MONTHLY].delete(:price_cents) expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "Please provide a price for all selected payment options." end end context "such as a price that is too high" do it "raises an error" do category_params = @variant_category_params category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::MONTHLY][:price_cents] = 500001 expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "Sorry, we don't support pricing products above $5,000." end end context "such as a price that is too low" do it "raises an error" do category_params = @variant_category_params category_params[:options][0][:recurrence_price_values][BasePrice::Recurrence::MONTHLY][:price_cents] = 98 expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "Sorry, a product must be at least $0.99." end end context "such as an invalid recurrence option" do it "raises an error" do category_params = @variant_category_params category_params[:options][0][:recurrence_price_values]["whenever"] = { enabled: true, price_cents: 10000 } category_params[:options][1][:recurrence_price_values]["whenever"] = { enabled: true, price_cents: 10000 } expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: ).perform end.to raise_error Link::LinkInvalid expect(@product.errors.full_messages).to include "Please provide a valid payment option." end end end end context "when tiers are removed" do it "marks them as deleted and queues a DeleteProductRichContentWorker" do tier = @product.tier_category.variants.first freeze_time do expect do Product::VariantCategoryUpdaterService.new( product: @product, category_params: { id: @product.tier_category.external_id, title: "Monthly" }, ).perform end.to change { tier.reload.deleted_at }.from(nil).to(Time.current) expect(DeleteProductRichContentWorker).to have_enqueued_sidekiq_job(@product.id, tier.id) end end end end describe "content upsells" do before do @product = create(:product) @variant_category = create(:variant_category, link: @product) @variant = create(:variant, variant_category: @variant_category) @rich_content = create(:rich_content, entity: @variant, description: [ { "type" => "paragraph", "content" => [ { "type" => "text", "text" => "Original content" } ] } ]) end it "processes content upsells for variant rich content" do new_description = [ { "type" => "paragraph", "content" => [ { "type" => "text", "text" => "New content" } ] } ] expect(SaveContentUpsellsService).to receive(:new).with( seller: @product.user, content: new_description, old_content: @rich_content.description ).and_call_original Product::VariantCategoryUpdaterService.new( product: @product, category_params: { id: @variant_category.external_id, title: @variant_category.title, options: [ { id: @variant.external_id, name: @variant.name, rich_content: [ { id: @rich_content.external_id, title: "Page title", description: new_description } ] } ] } ).perform end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false