repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/chile_bank_accounts.rb
spec/support/factories/chile_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :chile_bank_account do user account_number { "000123456789" } account_number_last_four { "6789" } bank_code { "999" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/bundle_products.rb
spec/support/factories/bundle_products.rb
# frozen_string_literal: true FactoryBot.define do factory :bundle_product do bundle { create(:product, :bundle) } product { create(:product, user: bundle.user) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/variant_prices.rb
spec/support/factories/variant_prices.rb
# frozen_string_literal: true FactoryBot.define do factory :variant_price do variant price_cents { 100 } currency { "usd" } recurrence { "monthly" } factory :pwyw_recurring_variant_price do suggested_price_cents { 200 } after(:create) do |price| price.variant.update!(customizable_price: 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/support/factories/gabon_bank_accounts.rb
spec/support/factories/gabon_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :gabon_bank_account do user account_number { "00001234567890123456789" } account_number_last_four { "6789" } bank_code { "AAAAGAGAXXX" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/disputes.rb
spec/support/factories/disputes.rb
# frozen_string_literal: true FactoryBot.define do factory :dispute do purchase event_created_at { Time.current } end factory :dispute_on_charge, parent: :dispute do purchase { nil } charge end factory :dispute_formalized, parent: :dispute do reason { Dispute::REASON_FRAUDULENT } state { :formalized } formalized_at { Time.current } end factory :dispute_formalized_on_charge, parent: :dispute_on_charge do purchase { nil } charge do charge = create(:charge) charge.purchases << create(:purchase, email: "customer@example.com") charge.purchases << create(:purchase, email: "customer@example.com") charge.purchases << create(:purchase, email: "customer@example.com") charge end state { :formalized } formalized_at { Time.current } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/followers.rb
spec/support/factories/followers.rb
# frozen_string_literal: true FactoryBot.define do factory :follower do user email { generate :email } factory :active_follower do confirmed_at { Time.current } end factory :deleted_follower do deleted_at { Time.current } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/turkey_bank_accounts.rb
spec/support/factories/turkey_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :turkey_bank_account do user account_number { "TR320010009999901234567890" } account_number_last_four { "7890" } bank_code { "ADABTRIS" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/canadian_bank_accounts.rb
spec/support/factories/canadian_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :canadian_bank_account do user account_number { "1234567" } transit_number { "12345" } institution_number { "123" } account_number_last_four { "4567" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/wishlists.rb
spec/support/factories/wishlists.rb
# frozen_string_literal: true FactoryBot.define do factory :wishlist do user sequence(:name) { |n| "Wishlist #{n}" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/oman_bank_accounts.rb
spec/support/factories/oman_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :oman_bank_account do user account_number { "000123456789" } account_number_last_four { "6789" } bank_code { "AAAAOMOMXXX" } account_holder_full_name { "Omani Creator" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/ecuador_bank_accounts.rb
spec/support/factories/ecuador_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :ecuador_bank_account do user account_number { "000123456789" } account_number_last_four { "6789" } bank_code { "AAAAECE1XXX" } account_holder_full_name { "Ecuadorian Creator" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/korea_bank_accounts.rb
spec/support/factories/korea_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :korea_bank_account do user account_number { "000123456789" } bank_number { "SGSEKRSLXXX" } account_number_last_four { "6789" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/variant_categories.rb
spec/support/factories/variant_categories.rb
# frozen_string_literal: true FactoryBot.define do factory :variant_category do association :link, factory: :product title { "Size" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/australian_bank_accounts.rb
spec/support/factories/australian_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :australian_bank_account do user account_number { "1234567" } bsb_number { "062111" } account_number_last_four { "4567" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/peru_bank_accounts.rb
spec/support/factories/peru_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :peru_bank_account do user account_number { "99934500012345670024" } account_number_last_four { "0024" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/subscriptions.rb
spec/support/factories/subscriptions.rb
# frozen_string_literal: true FactoryBot.define do factory :subscription do association :link, factory: :product user is_installment_plan { false } transient do price { nil } purchase_email { nil } end before(:create) do |subscription, evaluator| if subscription.is_installment_plan installment_plan = subscription.link.installment_plan if installment_plan.present? payment_option = create( :payment_option, subscription:, price: evaluator.price || subscription.link.default_price, installment_plan: installment_plan ) subscription.payment_options << payment_option subscription.charge_occurrence_count = installment_plan.number_of_installments else # Create a temporary payment_option without validation to satisfy subscription validation # Tests will destroy this and create their own with proper installment_plan payment_option = build( :payment_option, subscription:, price: evaluator.price || subscription.link.default_price, installment_plan: nil ) payment_option.save!(validate: false) subscription.payment_options << payment_option end else payment_option = create( :payment_option, subscription:, price: evaluator.price || subscription.link.default_price, installment_plan: nil ) subscription.payment_options << payment_option end end factory :subscription_without_user do user { nil } transient do email { generate :email } end before(:create) do |subscription, evaluator| purchase = create(:purchase, link: subscription.link, is_original_subscription_purchase: true, email: evaluator.email) subscription.purchases << purchase end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/payment_options.rb
spec/support/factories/payment_options.rb
# frozen_string_literal: true FactoryBot.define do factory :payment_option do subscription after(:build) do |payment_option| product = payment_option.subscription.link payment_option.price ||= product.default_price end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/service_charges.rb
spec/support/factories/service_charges.rb
# frozen_string_literal: true FactoryBot.define do factory :service_charge do user charge_cents { 1000 } charge_processor_fingerprint { "shfbeg5142fff" } charge_processor_transaction_id { "2763276372637263" } card_type { "visa" } card_visual { "**** **** **** 4062" } card_country { "US" } ip_address { generate :ip } browser_guid { generate :browser_guid } charge_processor_id do if chargeable chargeable.charge_processor_id else charge_processor_transaction_id ? StripeChargeProcessor.charge_processor_id : nil end end merchant_account { charge_processor_transaction_id ? MerchantAccount.gumroad(charge_processor_id) : nil } state { "successful" } succeeded_at { Time.current } factory :service_charge_in_progress do state { "in_progress" } end factory :failed_service_charge do state { "failed" } end factory :authorization_service_charge do state { "authorization_successful" } end factory :free_service_charge do charge_cents { 0 } charge_processor_id { nil } charge_processor_fingerprint { nil } charge_processor_transaction_id { nil } merchant_account { nil } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/uk_bank_accounts.rb
spec/support/factories/uk_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :uk_bank_account do user account_number { "1234567" } sort_code { "06-21-11" } account_number_last_four { "4567" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/installment_events.rb
spec/support/factories/installment_events.rb
# frozen_string_literal: true FactoryBot.define do factory :installment_event do installment event end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/bosnia_and_herzegovina_bank_accounts.rb
spec/support/factories/bosnia_and_herzegovina_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :bosnia_and_herzegovina_bank_account do user account_number { "BA095520001234567812" } account_number_last_four { "7812" } bank_code { "AAAABABAXXX" } account_holder_full_name { "Bosnia and Herzegovina Creator I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/collaborator_invitations.rb
spec/support/factories/collaborator_invitations.rb
# frozen_string_literal: true FactoryBot.define do factory :collaborator_invitation do association :collaborator, factory: :collaborator end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/transcoded_videos.rb
spec/support/factories/transcoded_videos.rb
# frozen_string_literal: true FactoryBot.define do factory :transcoded_video do streamable { create(:streamable_video, is_transcoded_for_hls: true) } transient do key_base_path { "/attachments/#{SecureRandom.hex}" } end original_video_key { "#{key_base_path}/movie.mp4" } transcoded_video_key { "#{key_base_path}/movie/hls/index.m3u8" } job_id { "somejobid" } state { "completed" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/romania_bank_accounts.rb
spec/support/factories/romania_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :romania_bank_account do user account_number { "RO49AAAA1B31007593840000" } account_number_last_four { "0000" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/uae_bank_accounts.rb
spec/support/factories/uae_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :uae_bank_account do user account_number { "AE070331234567890123456" } account_number_last_four { "3456" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/paraguay_bank_accounts.rb
spec/support/factories/paraguay_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :paraguay_bank_account do user account_number { "0567890123456789" } account_number_last_four { "6789" } bank_code { "0" } account_holder_full_name { "Paraguayan Creator" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/blocked_customer_objects.rb
spec/support/factories/blocked_customer_objects.rb
# frozen_string_literal: true FactoryBot.define do factory :blocked_customer_object do seller { create(:user) } object_type { "email" } object_value { generate :email } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/argentina_bank_accounts.rb
spec/support/factories/argentina_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :argentina_bank_account do user account_number { "0110000600000000000000" } account_number_last_four { "0000" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/costa_rica_bank_accounts.rb
spec/support/factories/costa_rica_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :costa_rica_bank_account do user account_number { "CR04010212367856709123" } account_number_last_four { "9123" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/indonesia_bank_accounts.rb
spec/support/factories/indonesia_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :indonesia_bank_account do user account_number { "000123456789" } account_number_last_four { "6789" } bank_code { "000" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/purchase_integrations.rb
spec/support/factories/purchase_integrations.rb
# frozen_string_literal: true FactoryBot.define do factory :purchase_integration do purchase { create(:purchase) } integration { create(:circle_integration) } before(:create) do |purchase_integration| purchase_integration.purchase.link.active_integrations |= [purchase_integration.integration] end factory :discord_purchase_integration do integration { create(:discord_integration) } discord_user_id { "user-0" } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/subscription_plan_changes.rb
spec/support/factories/subscription_plan_changes.rb
# frozen_string_literal: true FactoryBot.define do factory :subscription_plan_change do subscription association :tier, factory: :variant recurrence { "monthly" } perceived_price_cents { 500 } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/url_redirects.rb
spec/support/factories/url_redirects.rb
# frozen_string_literal: true FactoryBot.define do factory :url_redirect do purchase { create(:purchase, purchaser: create(:named_user), link:) } association :link, factory: :product uses { 0 } expires_at { "2012-01-11 12:46:23" } factory :streamable_url_redirect do after(:create) do |url_redirect| create(:streamable_video, :analyze, link: url_redirect.referenced_link) end end factory :readable_url_redirect do after(:create) do |url_redirect| create(:readable_document, :analyze, link: url_redirect.referenced_link) end end factory :listenable_url_redirect do after(:create) do |url_redirect| create(:listenable_audio, :analyze, link: url_redirect.referenced_link) end end end factory :installment_url_redirect, class: UrlRedirect do installment uses { 0 } expires_at { "2012-01-11 12:46:23" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/oauth_applications.rb
spec/support/factories/oauth_applications.rb
# frozen_string_literal: true FactoryBot.define do factory :oauth_application do sequence(:name) { |n| "app#{n}" } redirect_uri { "https://foo" } association :owner, factory: :user factory :oauth_application_valid do factory :oauth_application_with_link do after(:create) { |oauth_application| oauth_application.links << FactoryBot.create(:product) } end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/affiliate_request.rb
spec/support/factories/affiliate_request.rb
# frozen_string_literal: true FactoryBot.define do factory :affiliate_request do association :seller, factory: :user email { generate :email } name { "John Doe" } promotion_text { "Hello there!" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/european_bank_accounts.rb
spec/support/factories/european_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :european_bank_account do user account_number { "DE89370400440532013000" } account_number_last_four { "3000" } account_holder_full_name { "Stripe DE Account" } account_type { "checking" } end factory :nl_bank_account, parent: :european_bank_account do user account_number { "NL89370400440532013000" } account_number_last_four { "3000" } account_holder_full_name { "Stripe NL Account" } account_type { "checking" } end factory :fr_bank_account, parent: :european_bank_account do user account_number { "FR89370400440532013000" } account_number_last_four { "3000" } account_holder_full_name { "Stripe FR Account" } account_type { "checking" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/botswana_bank_accounts.rb
spec/support/factories/botswana_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :botswana_bank_account do user account_number { "000123456789" } account_number_last_four { "6789" } bank_code { "AAAABWBWXXX" } account_holder_full_name { "Botswana Creator" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/bangladesh_bank_accounts.rb
spec/support/factories/bangladesh_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :bangladesh_bank_account do user account_number { "0000123456789" } account_number_last_four { "6789" } bank_code { "110000000" } account_holder_full_name { "Bangladesh Creator" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/morocco_bank_accounts.rb
spec/support/factories/morocco_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :morocco_bank_account do user account_number { "MA64011519000001205000534921" } account_number_last_four { "4921" } bank_code { "AAAAMAMAXXX" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/affiliate_credits.rb
spec/support/factories/affiliate_credits.rb
# frozen_string_literal: true FactoryBot.define do factory :affiliate_credit do basis_points { 300 } association :affiliate_user association :affiliate, factory: :direct_affiliate purchase { create(:purchase) } seller { purchase.seller } link { purchase.link } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/rwanda_bank_accounts.rb
spec/support/factories/rwanda_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :rwanda_bank_account do user account_number { "000123456789" } account_number_last_four { "6789" } bank_code { "AAAARWRWXXX" } account_holder_full_name { "Rwandan Creator" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/discover_search_suggestions.rb
spec/support/factories/discover_search_suggestions.rb
# frozen_string_literal: true FactoryBot.define do factory :discover_search_suggestion do discover_search end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/tags.rb
spec/support/factories/tags.rb
# frozen_string_literal: true FactoryBot.define do factory :tag do sequence :name do |n| "tag name #{n}" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/links.rb
spec/support/factories/links.rb
# frozen_string_literal: true FactoryBot.define do factory :product, class: Link do name { "The Works of Edgar Gumstein" } description { "This is a collection of works spanning 1984 — 1994, while I spent time in a shack in the Andes." } user { create(:user) } price_cents { 100 } display_product_reviews { true } transient do tag { nil } active_integrations { [] } end after(:create) do |product, evaluator| if !evaluator.tag.nil? product.tag!(evaluator.tag) end product.active_integrations |= evaluator.active_integrations end trait :with_custom_receipt do custom_receipt { "Rerum reiciendis doloremque consequuntur sed fuga repellendus ut delectus soluta omnis ipsam ullam sunt qui quos velit iusto eos neque repellat suscipit ratione inventore ex." } end trait :with_custom_fields do after(:create) do |product| product.custom_fields << [ create(:custom_field, name: "Text field", seller: product.user, field_type: "text"), create(:custom_field, name: "Checkbox field", seller: product.user, field_type: "checkbox", required: true), create(:custom_field, name: "http://example.com", seller: product.user, field_type: "terms", required: true) ] end end trait :with_youtube_preview do after(:create) do |product| create(:asset_preview_youtube, link: product) end end trait :with_films_taxonomy do taxonomy { Taxonomy.find_or_create_by(slug: "films") } end trait :with_design_taxonomy do taxonomy { Taxonomy.find_or_create_by(slug: "design") } end trait :with_youtube_preview do after(:create) do |product| create(:asset_preview_youtube, link: product) end end trait :with_installment_plan do price_cents { 3000 } installment_plan { create(:product_installment_plan, link: instance, number_of_installments: 3) } end trait :is_physical do after(:create) do |product| product.require_shipping = true product.native_type = "physical" product.skus_enabled = true product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0) product.skus << Sku.new(price_difference_cents: 0, name: "DEFAULT_SKU", is_default_sku: true) product.is_physical = true product.quantity_enabled = true product.should_show_sales_count = true product.save! end end trait :is_subscription do is_recurring_billing { true } subscription_duration { :monthly } is_tiered_membership { false } end trait :is_collab do is_collab { true } transient do collaborator_cut { 30_00 } collaborator { nil } end after(:create) do |product, evaluator| collaborator = evaluator.collaborator || create(:collaborator, seller: product.user) create(:product_affiliate, product:, affiliate: collaborator, affiliate_basis_points: evaluator.collaborator_cut) end end trait :recommendable do with_films_taxonomy user { create(:recommendable_user, name: "gumbo") } after(:create) do |product| create(:purchase, :with_review, link: product, created_at: 1.week.ago) product.reload end end trait :staff_picked do recommendable after(:create) do |product| product.create_staff_picked_product!(updated_at: product.updated_at) end end trait :with_custom_receipt_unsafe_html do custom_receipt do <<-CUSTOM_RECEIPT <strong>Thanks for purchasing my product. Check out my website for more.</strong> <br /> https://google.com/a?c&d My email is test@gmail.com <i>Reach out and say hi!</i> <meta http-equiv="refresh" content="0; URL='http://example.com/'" /> <!-- <em>You cannot see this.</em> <script>var a = 2;</script> <style>a {color: red;}</style> <iframe src="http://example.com" /> :) CUSTOM_RECEIPT end end trait :bundle do name { "Bundle" } description { "This is a bundle of products" } is_bundle { true } bundle_products do build_list(:bundle_product, 2, bundle: instance) do |bundle_product, i| bundle_product.product.update!(name: "Bundle Product #{i + 1}") end end end trait :unpublished do draft { true } purchase_disabled_at { Time.current } end factory :product_with_files do transient do files_count { 2 } end after(:create) do |product, evaluator| evaluator.files_count.times do |n| create(:product_file, link: product, size: 300 * (n + 1), display_name: "link-#{n}-file", description: "product-#{n}-file-description") end end end factory :product_with_pdf_file do after(:create) do |product| create(:readable_document, link: product, pagelength: 3, size: 50, display_name: "Display Name", description: "Description") end end factory :product_with_pdf_files_with_size do after(:create) do |product| create(:readable_document, link: product, size: 50, display_name: "Display Name") create(:listenable_audio, link: product, size: 310, display_name: "Display Name 2") create(:streamable_video, link: product, size: 502, display_name: "Display Name 3") end end factory :product_with_video_file do after(:create) do |product| create(:streamable_video, link: product) end end factory :product_with_file_and_preview do name { "The Wrath of the River" } description { "A poem not for the lighthearted, but the heavy. Like lead." } preview { Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "kFDzu.png"), "image/png") } end factory :physical_product do is_physical end factory :subscription_product do is_subscription factory :subscription_product_with_versions do after(:create) do |product| category = create(:variant_category, title: "Category", link: product) create(:variant, variant_category: category, name: "Untitled 1") create(:variant, variant_category: category, name: "Untitled 2") end end end factory :product_with_digital_versions do after(:create) do |product| category = create(:variant_category, title: "Category", link: product) create(:variant, variant_category: category, name: "Untitled 1") create(:variant, variant_category: category, name: "Untitled 2") end end factory :product_with_digital_versions_with_price_difference_cents do after(:create) do |product| category = create(:variant_category, title: "Category", link: product) create(:variant, variant_category: category, name: "Untitled 1", price_difference_cents: 100) create(:variant, variant_category: category, name: "Untitled 2", price_difference_cents: 200) end end factory :product_with_discord_integration do after(:create) do |product| integration = create(:discord_integration, server_id: "0") product.active_integrations << integration product.save! end end factory :product_with_circle_integration do after(:create) do |product| integration = create(:circle_integration) product.active_integrations << integration product.save! end end factory :membership_product do is_recurring_billing { true } subscription_duration { :monthly } is_tiered_membership { true } native_type { Link::NATIVE_TYPE_MEMBERSHIP } trait :with_free_trial_enabled do is_recurring_billing { true } subscription_duration { :monthly } is_tiered_membership { true } free_trial_enabled { true } free_trial_duration_amount { 1 } free_trial_duration_unit { :week } end factory :membership_product_with_preset_tiered_pricing do transient do recurrence_price_values do [ { "monthly": { enabled: true, price: 3 } }, { "monthly": { enabled: true, price: 5 } } ] end end after(:create) do |product, evaluator| tier_category = product.tier_category first_tier = tier_category.variants.first first_tier.update!(name: "First Tier") second_tier = create(:variant, variant_category: tier_category, name: "Second Tier") first_tier.save_recurring_prices!(evaluator.recurrence_price_values[0]) second_tier.save_recurring_prices!(evaluator.recurrence_price_values[1]) evaluator.recurrence_price_values[2..-1].each_with_index do |recurrences, index| tier = create(:variant, variant_category: tier_category, name: "Tier #{index + 3}") tier.save_recurring_prices!(recurrences) end product.tiers.reload end end factory :membership_product_with_preset_tiered_pwyw_pricing do after(:create) do |product| tier_category = product.tier_category first_tier = tier_category.variants.first first_tier.update!(name: "First Tier", customizable_price: true) second_tier = create(:variant, variant_category: tier_category, name: "Second Tier") recurrence_values = BasePrice::Recurrence.all.index_with do |recurrence_key| { enabled: true, price: "500", suggested_price: "600" } end first_tier.save_recurring_prices!(recurrence_values) second_tier.save_recurring_prices!(recurrence_values) end end end factory :call_product do user { create(:user, :eligible_for_service_products) } native_type { Link::NATIVE_TYPE_CALL } transient do durations { [30] } end after(:create) do |product, evaluator| category = product.variant_categories.first evaluator.durations.each do |duration| category.variants.create!(duration_in_minutes: duration, name: "#{duration} minutes") end end trait :available_for_a_year do call_availabilities { build_list(:call_availability, 1, call: @instance, start_time: 1.day.ago, end_time: 1.year.from_now) } end end factory :commission_product do user { create(:user, :eligible_for_service_products) } native_type { Link::NATIVE_TYPE_COMMISSION } price_cents { 200 } end factory :coffee_product do user { create(:user, :eligible_for_service_products) } native_type { Link::NATIVE_TYPE_COFFEE } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/seller_profile_rich_text_sections.rb
spec/support/factories/seller_profile_rich_text_sections.rb
# frozen_string_literal: true FactoryBot.define do factory :seller_profile_rich_text_section do seller { create(:user) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/dropbox_files.rb
spec/support/factories/dropbox_files.rb
# frozen_string_literal: true FactoryBot.define do factory :dropbox_file do dropbox_url { "MyString" } state { "in_progress" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/gibraltar_bank_accounts.rb
spec/support/factories/gibraltar_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :gibraltar_bank_account do user account_number { "GI75NWBK000000007099453" } account_number_last_four { "9453" } account_holder_full_name { "Gumbot Gumstein I" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/backtax_collections.rb
spec/support/factories/backtax_collections.rb
# frozen_string_literal: true FactoryBot.define do factory :backtax_collection do user backtax_agreement amount_cents { 1000 } amount_cents_usd { 1000 } currency { "usd" } stripe_transfer_id { "tr_2M97Bm9e1RjUNIyY0WbsSZGp" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/support/factories/guyana_bank_accounts.rb
spec/support/factories/guyana_bank_accounts.rb
# frozen_string_literal: true FactoryBot.define do factory :guyana_bank_account do user account_number { "000123456789" } account_number_last_four { "6789" } bank_code { "AAAAGYGGXYZ" } account_holder_full_name { "Guyana Creator" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/user_presenter_spec.rb
spec/presenters/user_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe UserPresenter do let(:seller) { create(:named_seller) } let(:presenter) { described_class.new(user: seller) } describe "#audience_count" do it "returns audience_members count" do create_list(:audience_member, 3, seller:) expect(presenter.audience_count).to eq(3) end end describe "#audience_types" do it "returns array with matching classes to audience stats" do expect(presenter.audience_types).to be_empty create(:audience_member, seller:, purchases: [{}]) expect(presenter.audience_types).to eq([:customers]) create(:audience_member, seller:, follower: {}) expect(presenter.audience_types).to eq([:customers, :followers]) create(:audience_member, seller:, affiliates: [{}]) expect(presenter.audience_types).to eq([:customers, :followers, :affiliates]) end end describe "#products_for_filter_box" do let!(:product) { create(:product, user: seller) } let!(:deleted_product) { create(:product, user: seller, name: "Deleted", deleted_at: Time.current) } let!(:archived_product) { create(:product, user: seller, name: "Archived", archived: true) } let!(:archived_product_with_sales) { create(:product, user: seller, name: "Archived with sales", archived: true) } before do create(:purchase, link: archived_product_with_sales) index_model_records(Purchase) end it "returns correct products" do expect(presenter.products_for_filter_box).to eq([product, archived_product_with_sales]) end end describe "#affiliate_products_for_filter_box" do let!(:product) { create(:product, user: seller) } let!(:deleted_product) { create(:product, user: seller, name: "Deleted", deleted_at: Time.current) } let!(:archived_product) { create(:product, user: seller, name: "Archived", archived: true) } let!(:archived_product_with_sales) { create(:product, user: seller, name: "Archived with sales", archived: true) } before do create(:purchase, link: archived_product_with_sales) index_model_records(Purchase) end it "returns correct products" do expect(presenter.products_for_filter_box).to eq([product, archived_product_with_sales]) end end describe "#author_byline_props" do it "returns the correct props" do expect(presenter.author_byline_props).to eq( id: seller.external_id, name: seller.name, avatar_url: seller.avatar_url, profile_url: seller.profile_url(recommended_by: nil) ) end context "when given a custom domain" do it "uses the custom domain for the profile url" do expect(presenter.author_byline_props(custom_domain_url: "https://example.com")[:profile_url]).to eq("https://example.com") end end context "when the seller does not have a name" do before { seller.update!(name: nil) } it "returns the username" do expect(presenter.author_byline_props(custom_domain_url: "https://example.com")[:name]).to eq(seller.username) end end context "when given recommended_by" do it "adds the parameter to the profile url" do expect(presenter.author_byline_props(recommended_by: "discover")[:profile_url]).to eq(seller.profile_url(recommended_by: "discover")) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/collaborators_presenter_spec.rb
spec/presenters/collaborators_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe CollaboratorsPresenter do describe "#index_props" do let(:seller) { create(:user) } let(:product_1) { create(:product, user: seller) } let(:product_2) { create(:product, user: seller) } let!(:deleted_collaborator) { create(:collaborator, seller:, products: [product_1], deleted_at: 1.day.ago) } let!(:confirmed_collaborator) { create(:collaborator, seller:, products: [product_1]) } let!(:pending_collaborator) { create(:collaborator, :with_pending_invitation, seller:, products: [product_2]) } it "returns the seller's live collaborators" do props = described_class.new(seller:).index_props expect(props).to match( collaborators: [confirmed_collaborator, pending_collaborator].map do CollaboratorPresenter.new(seller:, collaborator: _1).collaborator_props end, collaborators_disabled_reason: nil, has_incoming_collaborators: false, ) end it "returns collaborators supported as false if using a Brazilian Stripe Connect account" do brazilian_stripe_account = create(:merchant_account_stripe_connect, user: seller, country: "BR") seller.update!(check_merchant_account_is_linked: true) expect(seller.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account props = described_class.new(seller:).index_props expect(props[:collaborators_disabled_reason]).to eq "Collaborators with Brazilian Stripe accounts are not supported." end it "returns if the seller has any incoming collaborations" do props = described_class.new(seller: pending_collaborator.affiliate_user).index_props expect(props[:has_incoming_collaborators]).to eq true pending_collaborator.collaborator_invitation.accept! props = described_class.new(seller: pending_collaborator.affiliate_user).index_props expect(props[:has_incoming_collaborators]).to eq true pending_collaborator.mark_deleted! props = described_class.new(seller: pending_collaborator.affiliate_user).index_props expect(props[:has_incoming_collaborators]).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/presenters/purchase_product_presenter_spec.rb
spec/presenters/purchase_product_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe PurchaseProductPresenter, :versioning do include Rails.application.routes.url_helpers describe "#product_props" do let(:product_created_at) { 5.minutes.ago } let(:seller) { create(:named_seller) } context "when the product is a membership" do before do travel_to product_created_at do @product = create(:membership_product, unique_permalink: "test", name: "Product title v1", user: seller) @product.save_custom_attributes( [ { "name" => "Attribute 1", "value" => "Value 1" }, { "name" => "Attribute 2", "value" => "Value 2" } ] ) @asset_preview = create(:asset_preview, link: @product) end travel_to (product_created_at + 1.minute) do @purchase = create(:membership_purchase, :with_review, link: product) end end let(:product) { @product } let(:asset_preview) { @asset_preview } let(:purchase) { @purchase } let(:presenter) { described_class.new(purchase) } it "returns properties for the product page" do expect(presenter.product_props).to eq( product: { price_cents: 0, covers: [product.asset_previews.first.as_json], currency_code: "usd", custom_view_content_button_text: nil, custom_button_text_option: nil, description_html: "This is a collection of works spanning 1984 — 1994, while I spent time in a shack in the Andes.", pwyw: nil, is_sales_limited: false, is_tiered_membership: true, is_legacy_subscription: false, long_url: short_link_url(product.unique_permalink, host: seller.subdomain_with_protocol), main_cover_id: asset_preview.guid, name: "Product title v1", permalink: "test", preorder: nil, duration_in_months: nil, quantity_remaining: nil, ratings: { count: 1, average: 5, percentages: [0, 0, 0, 0, 100], }, seller: { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), id: seller.external_id, name: "Seller", profile_url: "http://seller.test.gumroad.com:31337", }, is_compliance_blocked: false, is_published: true, is_physical: false, attributes: [ { name: "Attribute 1", value: "Value 1" }, { name: "Attribute 2", value: "Value 2" } ], free_trial: nil, is_quantity_enabled: false, is_multiseat_license: false, is_stream_only: false, options: [{ id: product.variant_categories[0].variants[0].external_id, description: "", name: "Product title v1", is_pwyw: false, price_difference_cents: nil, quantity_left: nil, recurrence_price_values: { "monthly" => { price_cents: 100, suggested_price_cents: nil } }, duration_in_minutes: nil, }], rental: nil, recurrences: { default: "monthly", enabled: [{ id: product.prices.alive.first.external_id, recurrence: "monthly", price_cents: 0 }] }, rental_price_cents: nil, sales_count: nil, summary: nil, thumbnail_url: nil, analytics: product.analytics_data, has_third_party_analytics: false, ppp_details: nil, can_edit: false, refund_policy: nil }, discount_code: nil, purchase: nil ) end context "when the product was updated after the purchase" do before do asset_preview.mark_deleted! create(:asset_preview, link: product) product.update!( name: "Product title v2" ) product.save_custom_attributes( [ { "name" => "Attribute 3", "value" => "Value 3" } ] ) end it "returns the product props at the time of purchase" do expect(presenter.product_props[:product][:name]).to eq("Product title v1") expect(presenter.product_props[:product][:covers]).to eq([asset_preview.as_json]) expect(presenter.product_props[:product][:main_cover_id]).to eq(asset_preview.guid) expect(presenter.product_props[:product][:attributes]).to eq( [ { name: "Attribute 1", value: "Value 1" }, { name: "Attribute 2", value: "Value 2" } ] ) end end context "when the purchase has a refund policy" do let!(:refund_policy) do purchase.create_purchase_refund_policy!( title: RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], fine_print: "This is the fine print.", max_refund_period_in_days: 30 ) end it "returns the refund policy" do expect(presenter.product_props[:product][:refund_policy]).to eq( { title: refund_policy.title, fine_print: "<p>This is the fine print.</p>", updated_at: refund_policy.updated_at } ) end context "when the fine_print is empty" do before do refund_policy.update!(fine_print: "") end it "returns the refund policy" do expect(presenter.product_props[:product][:refund_policy]).to eq( { title: refund_policy.title, fine_print: nil, updated_at: refund_policy.updated_at } ) end end end end context "when the product is not a membership" do before do travel_to product_created_at do @product = create(:product_with_digital_versions, unique_permalink: "test", name: "Product title v1", user: seller) end end let(:product) { @product } let(:purchase) { create(:membership_purchase, :with_review, link: product) } let(:presenter) { described_class.new(purchase) } it "returns properties for the product page" do expect(presenter.product_props).to eq( product: { price_cents: 100, covers: [], currency_code: "usd", custom_view_content_button_text: nil, custom_button_text_option: nil, description_html: "This is a collection of works spanning 1984 — 1994, while I spent time in a shack in the Andes.", pwyw: nil, is_sales_limited: false, is_tiered_membership: false, is_legacy_subscription: false, long_url: short_link_url(product.unique_permalink, host: seller.subdomain_with_protocol), main_cover_id: nil, name: "Product title v1", permalink: "test", preorder: nil, duration_in_months: nil, quantity_remaining: nil, ratings: { count: 1, average: 5, percentages: [0, 0, 0, 0, 100], }, seller: { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), id: seller.external_id, name: "Seller", profile_url: "http://seller.test.gumroad.com:31337", }, is_compliance_blocked: false, is_published: true, is_physical: false, attributes: [], free_trial: nil, is_quantity_enabled: false, is_multiseat_license: false, is_stream_only: false, options: [ product.variant_categories[0].variants[0].to_option, product.variant_categories[0].variants[1].to_option, ], rental: nil, recurrences: nil, rental_price_cents: nil, sales_count: nil, summary: nil, thumbnail_url: nil, analytics: product.analytics_data, has_third_party_analytics: false, ppp_details: nil, can_edit: false, refund_policy: nil, }, discount_code: nil, purchase: 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/presenters/customer_presenter_spec.rb
spec/presenters/customer_presenter_spec.rb
# frozen_string_literal: true describe CustomerPresenter do let(:seller) { create(:named_seller) } describe "#missed_posts" do let(:product) { create(:product, user: seller) } let!(:post1) { create(:installment, link: product, published_at: Time.current, name: "Post 1") } let!(:post2) { create(:installment, link: product, published_at: Time.current, name: "Post 2") } let!(:post3) { create(:installment, link: product, published_at: Time.current, name: "Post 3") } let!(:post4) { create(:installment, link: product, name: "Post 4") } let(:purchase) { create(:purchase, link: product) } before do create(:creator_contacting_customers_email_info_delivered, installment: post1, purchase:) end it "returns the correct props" do expect(described_class.new(purchase:).missed_posts).to eq( [ { id: post2.external_id, name: "Post 2", url: post2.full_url, published_at: post2.published_at, }, { id: post3.external_id, name: "Post 3", url: post3.full_url, published_at: post3.published_at, }, ] ) end end describe "#customer" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, name: "Product", price_cents: 100, is_physical: true, require_shipping: true) } let(:membership) { create(:membership_product_with_preset_tiered_pricing, user: seller, name: "Membership", is_multiseat_license: true, is_licensed: true, native_type: Link::NATIVE_TYPE_MEMBERSHIP) } let(:offer_code) { create(:percentage_offer_code, code: "code", products: [membership], amount_percentage: 100) } let(:purchase1) { create(:physical_purchase, product_review: product_review1, link: product, variant_attributes: [create(:sku, link: product)], full_name: "Customer 1", email: "customer1@gumroad.com", created_at: 1.day.ago, seller:, was_product_recommended: true, recommended_by: RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION, is_purchasing_power_parity_discounted: true, ip_country: "United States", is_additional_contribution: true, is_bundle_purchase: true, can_contact: false) } let(:product_review1) { create(:product_review, rating: 4, message: "This is an amazing product!") } let!(:product_review_response) { create(:product_review_response, message: "Thank you!", user: seller, product_review: product_review1) } let(:purchase2) { create(:membership_purchase, link: membership, full_name: "Customer 2", email: "customer2@gumroad.com", purchaser: create(:user), seller:, is_original_subscription_purchase: true, offer_code:, is_gift_sender_purchase: true, affiliate: create(:direct_affiliate), is_preorder_authorization: true, preorder: create(:preorder), license: create(:license), chargeback_date: Time.current, card_type: CardType::PAYPAL, created_at: 7.months.ago) } let(:pundit_user) { SellerContext.new(user: seller, seller:) } before do purchase1.create_purchasing_power_parity_info!(factor: 0.5) create(:gift, giftee_email: "giftee@gumroad.com", giftee_purchase: create(:purchase), gifter_purchase: purchase2) purchase2.reload create(:upsell_purchase, purchase: purchase1, upsell: create(:upsell, seller:, product:, cross_sell: true)) purchase2.subscription.update!(charge_occurrence_count: 2) create(:purchase_custom_field, purchase: purchase2, name: "Field 1", value: "Value") create(:purchase_custom_field, purchase: purchase2, name: "Field 2", value: false, type: CustomField::TYPE_CHECKBOX) create(:tip, purchase: purchase1, value_cents: 100) end it "returns the correct props for each customer" do allow(purchase1).to receive(:transaction_url_for_seller).and_return("https://google.com") allow(purchase1).to receive(:stripe_partially_refunded?).and_return(true) allow(purchase1).to receive(:stripe_refunded?).and_return(true) expect(described_class.new(purchase: purchase1).customer(pundit_user:)).to eq( { id: purchase1.external_id, email: "customer1@gumroad.com", giftee_email: nil, name: "Customer 1", is_bundle_purchase: true, can_contact: false, is_existing_user: false, product: { name: "Product", permalink: product.unique_permalink, native_type: "digital" }, quantity: 1, created_at: purchase1.created_at.iso8601, price: { cents: 100, cents_before_offer_code: 100, cents_refundable: 100, currency_type: "usd", recurrence: nil, tip_cents: 100, }, discount: nil, subscription: nil, is_multiseat_license: false, upsell: "Upsell", referrer: "Gumroad Product Recommendations", is_additional_contribution: true, ppp: { country: "United States", discount: "50%" }, is_preorder: false, affiliate: nil, license: nil, shipping: { address: purchase1.shipping_information, price: "$0", tracking: { shipped: false }, }, physical: { order_number: purchase1.external_id_numeric.to_s, sku: purchase1.sku&.custom_name_or_external_id, }, review: { rating: 4, message: "This is an amazing product!", response: { message: "Thank you!", }, videos: [], }, call: nil, commission: nil, custom_fields: [], transaction_url_for_seller: "https://google.com", is_access_revoked: nil, refunded: true, partially_refunded: true, paypal_refund_expired: false, chargedback: false, has_options: true, option: purchase1.variant_attributes.first.to_option, utm_link: nil, download_count: nil, } ) expect(described_class.new(purchase: purchase2).customer(pundit_user:)).to eq( { id: purchase2.external_id, email: "customer2@gumroad.com", giftee_email: "giftee@gumroad.com", name: "Customer 2", is_bundle_purchase: false, can_contact: true, is_existing_user: true, product: { name: "Membership", permalink: membership.unique_permalink, native_type: "membership" }, quantity: 1, created_at: purchase2.created_at.iso8601, price: { cents: 0, cents_before_offer_code: 0, cents_refundable: 0, currency_type: "usd", recurrence: "monthly", tip_cents: nil, }, discount: { type: "percent", percents: 100, code: "code" }, subscription: { id: purchase2.subscription.external_id, status: "alive", remaining_charges: 1, is_installment_plan: false, }, is_multiseat_license: true, upsell: nil, referrer: nil, is_additional_contribution: false, ppp: nil, is_preorder: true, affiliate: { email: purchase2.affiliate.affiliate_user.form_email, amount: "$0", type: "DirectAffiliate", }, license: { id: purchase2.license.external_id, enabled: true, key: purchase2.license.serial, }, call: nil, commission: nil, shipping: nil, physical: nil, review: nil, custom_fields: [ { type: "text", attribute: "Field 1", value: "Value" }, { type: "text", attribute: "Field 2", value: "false" }, ], transaction_url_for_seller: nil, is_access_revoked: nil, refunded: false, partially_refunded: false, paypal_refund_expired: true, chargedback: true, has_options: true, option: purchase2.variant_attributes.first.to_option, utm_link: nil, download_count: 0, } ) end context "purchase has a call" do let(:call) { create(:call) } it "includes the call" do expect(described_class.new(purchase: call.purchase).customer(pundit_user:)[:call]).to eq( { id: call.external_id, call_url: call.call_url, start_time: call.start_time.iso8601, end_time: call.end_time.iso8601, } ) end end context "purchase has a commission", :vcr do let(:commission) { create(:commission) } let(:commission_file) { fixture_file_upload("spec/support/fixtures/test.pdf") } let!(:purchase_custom_field_text) { create(:purchase_custom_field, purchase: commission.deposit_purchase, name: "What's your pet's name?", value: "Fido") } let!(:purchase_custom_field_file) { create(:purchase_custom_field, field_type: CustomField::TYPE_FILE, purchase: commission.deposit_purchase, name: CustomField::FILE_FIELD_NAME, value: nil) } before do commission.files.attach(commission_file) purchase_custom_field_file.files.attach(file_fixture("test.pdf")) purchase_custom_field_file.files.attach(file_fixture("smilie.png")) end it "includes the commission and custom fields" do file = commission.files.first props = described_class.new(purchase: commission.deposit_purchase).customer(pundit_user:) expect(props[:commission]).to eq( { id: commission.external_id, files: [ { id: file.signed_id, name: "test", size: 8278, extension: "PDF", key: file.key } ], status: "in_progress", } ) expect(props[:custom_fields]).to eq( [ { type: "text", attribute: "What's your pet's name?", value: "Fido" }, { attribute: "File upload", type: "file", files: [ { id: purchase_custom_field_file.files.first.signed_id, name: "test", size: 8278, extension: "PDF", key: purchase_custom_field_file.files.first.key }, { id: purchase_custom_field_file.files.second.signed_id, name: "smilie", size: 100406, extension: "PNG", key: purchase_custom_field_file.files.second.key } ] }, ] ) end end context "purchase has an installment plan" do let(:installment_plan) { create(:product_installment_plan, number_of_installments: 3, recurrence: "monthly") } let(:purchase) { create(:installment_plan_purchase, link: installment_plan.link) } it "includes the installment plan" do props = described_class.new(purchase:).customer(pundit_user:) expect(props[:subscription]).to eq( { id: purchase.subscription.external_id, status: "alive", remaining_charges: 2, is_installment_plan: true, } ) expect(props[:price]).to include( recurrence: "monthly", ) end end context "purchase has a utm link" do let(:utm_link) { create(:utm_link) } let(:purchase) { create(:purchase, utm_link:) } let!(:utm_link_driven_sale) { create(:utm_link_driven_sale, purchase:, utm_link:) } it "includes the utm_link" do expect(described_class.new(purchase:).customer(pundit_user:)[:utm_link]).to eq( { title: utm_link.title, utm_url: utm_link.utm_url, source: utm_link.utm_source, medium: utm_link.utm_medium, campaign: utm_link.utm_campaign, term: utm_link.utm_term, content: utm_link.utm_content, } ) end end context "purchase has review videos" do let(:purchase) { create(:purchase) } let(:product_review) { create(:product_review, purchase:) } let!(:alive_approved_video) { create(:product_review_video, :approved, product_review:) } let!(:alive_pending_video) { create(:product_review_video, :pending_review, product_review:) } let!(:soft_deleted_video) { create(:product_review_video, :approved, product_review:, deleted_at: Time.current) } it "includes the review videos" do props = described_class.new(purchase: purchase.reload).customer(pundit_user:) expect(props[:review][:videos]).to contain_exactly( ProductReviewVideoPresenter.new(alive_approved_video).props(pundit_user:), ProductReviewVideoPresenter.new(alive_pending_video).props(pundit_user:), ) end end context "purchase has downloads" do let(:purchase) { create(:purchase) } before do create(:url_redirect, purchase:, uses: 5) end it "returns the download count" do presenter = described_class.new(purchase: purchase.reload) expect(presenter.download_count).to eq(5) end end context "purchase without url_redirect" do let(:purchase) { create(:purchase) } it "returns 0 for download count" do presenter = described_class.new(purchase:) expect(presenter.download_count).to eq(0) end end context "purchase for coffee product" do let(:coffee_user) { create(:user, :eligible_for_service_products) } let(:coffee_product) { create(:product, user: coffee_user, native_type: Link::NATIVE_TYPE_COFFEE) } let(:purchase) { create(:purchase, link: coffee_product, seller: coffee_user) } before do create(:url_redirect, purchase:, uses: 10) end it "returns nil for download count" do presenter = described_class.new(purchase: purchase.reload) expect(presenter.download_count).to be_nil end end context "purchase for bundle" do let(:purchase) { create(:purchase, is_bundle_purchase: true) } before do create(:url_redirect, purchase:, uses: 10) end it "returns nil for download count" do presenter = described_class.new(purchase: purchase.reload) expect(presenter.download_count).to be_nil end end end describe "#charge" do let(:purchase) { create(:physical_purchase, stripe_partially_refunded: true, chargeback_date: Time.current, created_at: 7.months.ago, card_type: CardType::PAYPAL) } before do purchase.link.update!(price_currency_type: Currency::EUR, price_cents: 100) allow_any_instance_of(Purchase).to receive(:get_rate).with(Currency::EUR).and_return(0.8) end it "returns the correct props" do expect(described_class.new(purchase:).charge).to eq( { id: purchase.external_id, chargedback: true, created_at: purchase.created_at.iso8601, amount_refundable: 80, currency_type: "eur", is_upgrade_purchase: false, partially_refunded: true, refunded: false, transaction_url_for_seller: nil, paypal_refund_expired: true, } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/tax_center_presenter_spec.rb
spec/presenters/tax_center_presenter_spec.rb
# frozen_string_literal: true describe TaxCenterPresenter do let(:seller) { create(:user, created_at: Time.new(2020, 9, 21)) } let(:presenter) { described_class.new(seller:, year: 2023) } before do travel_to Time.new(2024, 06, 15) Rails.cache.delete("tax_form_data_us_1099_k_2023_#{seller.id}") end describe "#props" do context "when seller has no tax forms" do it "returns empty documents with available years and selected year" do result = presenter.props expect(result.keys).to eq([:documents, :available_years, :selected_year]) expect(result[:documents]).to eq([]) expect(result[:available_years]).to eq([2023, 2022, 2021, 2020]) expect(result[:selected_year]).to eq(2023) end end context "when seller was created in the current year" do let(:seller) { create(:user, created_at: Time.current) } let(:presenter) { described_class.new(seller:, year: Time.current.year) } it "returns empty available years and nil selected year" do result = presenter.props expect(result[:available_years]).to eq([]) expect(result[:selected_year]).to be_nil expect(result[:documents]).to eq([]) end end context "when seller has a tax form for the year" do let!(:tax_form) { create(:user_tax_form, user: seller, tax_year: 2023, tax_form_type: "us_1099_k") } let!(:product) { create(:product, user: seller, price_cents: 1000) } let!(:purchase_2022) { create(:purchase, link: product, created_at: Time.new(2022, 12, 31)) } let!(:purchase_2023_1) { create(:purchase, :with_custom_fee, link: product, created_at: Time.new(2023, 3, 15), fee_cents: 100, tax_cents: 50, gumroad_tax_cents: 30) } let!(:purchase_2023_2) do purchase = create(:purchase, :with_custom_fee, link: product, created_at: Time.new(2023, 6, 20), fee_cents: 120, gumroad_tax_cents: 25 ) purchase.update!(affiliate_credit_cents: 150) purchase end let!(:purchase_2023_3) { create(:purchase, :with_custom_fee, link: product, created_at: Time.new(2023, 9, 10), fee_cents: 80, tax_cents: 75) } let!(:refunded_purchase_2023) do purchase = create(:purchase, link: product, created_at: Time.new(2023, 4, 1), price_cents: 5000) purchase.update!(stripe_refunded: true) create(:refund, purchase:, amount_cents: purchase.price_cents) purchase end let!(:purchase_2024) { create(:purchase, link: product, created_at: Time.new(2024, 1, 1)) } it "returns document with necessary data" do result = presenter.props expect(result[:selected_year]).to eq(2023) document = result[:documents].sole expect(document[:document]).to eq("1099-K") expect(document[:type]).to eq("IRS form") expect(document[:year]).to eq(2023) expect(document[:form_type]).to eq("us_1099_k") expect(document[:gross]).to eq("$30.55") expect(document[:fees]).to eq("$3.00") expect(document[:taxes]).to eq("$1.80") expect(document[:affiliate_credit]).to eq("$1.50") expect(document[:net]).to eq("$24.25") end it "caches the document data" do presenter.props expect(Rails.cache.exist?("tax_form_data_us_1099_k_2023_#{seller.id}")).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/presenters/public_file_presenter_spec.rb
spec/presenters/public_file_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe PublicFilePresenter do include CdnUrlHelper describe "#props" do let(:public_file) { create(:public_file, :with_audio) } let(:presenter) { described_class.new(public_file:) } before do public_file.file.analyze end it "returns necessary file props" do props = presenter.props expect(props).to include( id: public_file.public_id, name: public_file.display_name, extension: "MP3", status: { type: "saved" } ) expect(props[:file_size]).to be > 30_000 expect(props[:url]).to eq(cdn_url_for(public_file.file.blob.url)) end context "when file is not attached" do let(:public_file) { create(:public_file) } it "returns nil file_size and url" do expect(presenter.props[:file_size]).to be_nil expect(presenter.props[:url]).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/presenters/utm_link_presenter_spec.rb
spec/presenters/utm_link_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe UtmLinkPresenter do let(:seller) { create(:named_seller) } let!(:product) { create(:product, user: seller, name: "Product A") } let!(:deleted_product) { create(:product, user: seller, name: "Deleted Product", deleted_at: Time.current) } let!(:post) { create(:audience_post, :published, seller:, name: "Post A", shown_on_profile: true) } let!(:hidden_post) { create(:audience_post, :published, seller:, name: "Hidden Post", shown_on_profile: false) } let!(:workflow_post) { create(:workflow_installment, :published, seller:, name: "Workflow email") } let!(:unpublished_post) { create(:audience_post, seller:, name: "Draft Post", published_at: nil) } let!(:utm_link) do create(:utm_link, seller:, utm_campaign: "spring", utm_medium: "social", utm_source: "facebook", utm_term: "sale", utm_content: "banner", ) end describe "#utm_link_props" do it "returns the UTM link props" do props = described_class.new(seller:, utm_link:).utm_link_props expect(props).to eq({ id: utm_link.external_id, title: utm_link.title, short_url: utm_link.short_url, utm_url: utm_link.utm_url, created_at: utm_link.created_at.iso8601, source: utm_link.utm_source, medium: utm_link.utm_medium, campaign: utm_link.utm_campaign, term: utm_link.utm_term, content: utm_link.utm_content, clicks: utm_link.unique_clicks, destination_option: { id: "profile_page", label: "Profile page", url: seller.profile_url }, sales_count: nil, revenue_cents: nil, conversion_rate: nil }) end it "returns correct 'destination_option' depending on the 'target_resource_type'" do product = create(:product, user: seller, name: "Product A") post = create(:audience_post, seller:, name: "Post A") # resource_type: product_page utm_link.update!(target_resource_type: "product_page", target_resource_id: product.id) expect(described_class.new(seller:, utm_link:).utm_link_props[:destination_option]).to eq({ id: "product_page-#{product.external_id}", label: "Product A", url: product.long_url }) # resource_type: post_page utm_link.update!(target_resource_type: "post_page", target_resource_id: post.id) expect(described_class.new(seller:, utm_link:).utm_link_props[:destination_option]).to eq({ id: "post_page-#{post.external_id}", label: "Post A", url: post.full_url }) # resource_type: subscribe_page utm_link.update!(target_resource_type: "subscribe_page") expect(described_class.new(seller:, utm_link:).utm_link_props[:destination_option]).to eq({ id: "subscribe_page", label: "Subscribe page", url: Rails.application.routes.url_helpers.custom_domain_subscribe_url(host: seller.subdomain_with_protocol) }) # resource_type: profile_page utm_link.update!(target_resource_type: "profile_page") expect(described_class.new(seller:, utm_link:).utm_link_props[:destination_option]).to eq({ id: "profile_page", label: "Profile page", url: seller.profile_url }) end end describe "#new_page_react_props" do it "returns the form context props" do allow(SecureRandom).to receive(:alphanumeric).and_return("unique01") props = described_class.new(seller:).new_page_react_props expect(props).to eq({ context: { destination_options: [ { id: "profile_page", label: "Profile page", url: seller.profile_url }, { id: "subscribe_page", label: "Subscribe page", url: Rails.application.routes.url_helpers.custom_domain_subscribe_url(host: seller.subdomain_with_protocol) }, { id: "product_page-#{product.external_id}", label: "Product — Product A", url: product.long_url }, { id: "post_page-#{post.external_id}", label: "Post — Post A", url: post.full_url } ], short_url: "#{UrlService.short_domain_with_protocol}/u/unique01", utm_fields_values: { campaigns: ["spring"], mediums: ["social"], sources: ["facebook"], terms: ["sale"], contents: ["banner"] } }, utm_link: nil }) end it "returns 'utm_link' in the props when 'copy_from' is provided" do utm_link.update!(title: "Existing UTM Link") props = described_class.new(seller:).new_page_react_props(copy_from: utm_link.external_id) expected_utm_link_props = described_class.new(seller:, utm_link:).utm_link_props.except(:id) expected_utm_link_props[:short_url] = props[:context][:short_url] expect(props[:utm_link]).to eq(expected_utm_link_props) end it "returns empty arrays for utm_fields_values when no UTM links exist" do props = described_class.new(seller: create(:user)).new_page_react_props expect(props[:context][:utm_fields_values]).to eq({ campaigns: [], mediums: [], sources: [], terms: [], contents: [] }) end end describe "#edit_page_react_props" do it "returns the form context props and the UTM link props" do props = described_class.new(seller:, utm_link:).edit_page_react_props expect(props).to eq({ context: { destination_options: [ { id: "profile_page", label: "Profile page", url: seller.profile_url }, { id: "subscribe_page", label: "Subscribe page", url: Rails.application.routes.url_helpers.custom_domain_subscribe_url(host: seller.subdomain_with_protocol) }, { id: "product_page-#{product.external_id}", label: "Product — Product A", url: product.long_url }, { id: "post_page-#{post.external_id}", label: "Post — Post A", url: post.full_url } ], short_url: utm_link.short_url, utm_fields_values: { campaigns: ["spring"], mediums: ["social"], sources: ["facebook"], terms: ["sale"], contents: ["banner"] } }, utm_link: described_class.new(seller:, utm_link:).utm_link_props }) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/utm_links_stats_presenter_spec.rb
spec/presenters/utm_links_stats_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe UtmLinksStatsPresenter do let(:seller) { create(:user) } let!(:utm_link1) { create(:utm_link, seller:, unique_clicks: 3) } let!(:utm_link2) { create(:utm_link, seller:, unique_clicks: 1) } let!(:utm_link3) { create(:utm_link, seller:, unique_clicks: 2) } let!(:another_seller_utm_link) { create(:utm_link, unique_clicks: 1) } let(:product) { create(:product, user: seller) } let(:purchase1) { create(:purchase, price_cents: 1000, seller:, link: product) } let(:purchase2) { create(:purchase, price_cents: 2000, seller:, link: product) } let(:purchase3) { create(:purchase, price_cents: 0, seller:, link: product) } let(:test_purchase) { create(:test_purchase, price_cents: 3000, seller:, link: product) } let(:failed_purchase) { create(:failed_purchase, price_cents: 1000, seller:, link: product) } let!(:utm_link1_driven_sale1) { create(:utm_link_driven_sale, utm_link: utm_link1, purchase: purchase1) } let!(:utm_link1_driven_sale2) { create(:utm_link_driven_sale, utm_link: utm_link1, purchase: purchase2) } let!(:utm_link2_driven_sale1) { create(:utm_link_driven_sale, utm_link: utm_link2, purchase: purchase3) } let!(:utm_link2_driven_sale2) { create(:utm_link_driven_sale, utm_link: utm_link2, purchase: test_purchase) } let!(:utm_link2_driven_sale3) { create(:utm_link_driven_sale, utm_link: utm_link2, purchase: failed_purchase) } before do Feature.activate_user(:utm_links, seller) end describe "#props" do it "returns stats for the requested UTM link IDs" do props = described_class.new(seller:, utm_link_ids: [utm_link1.id, utm_link2.id, utm_link3.id, another_seller_utm_link.id]).props expect(props).to eq({ utm_link1.external_id => { sales_count: 2, revenue_cents: 3000, conversion_rate: 0.6667 }, utm_link2.external_id => { sales_count: 1, revenue_cents: 0, conversion_rate: 1.0 }, utm_link3.external_id => { sales_count: 0, revenue_cents: 0, conversion_rate: 0.0 }, }) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/customers_presenter_spec.rb
spec/presenters/customers_presenter_spec.rb
# frozen_string_literal: true describe CustomersPresenter do let(:seller) { create(:named_seller, :eligible_for_service_products, notification_endpoint: "http://local/host") } let(:product) { create(:product, user: seller, name: "Product", price_cents: 100) } let(:membership) { create(:membership_product_with_preset_tiered_pricing, user: seller, name: "Membership", is_multiseat_license: true) } let(:coffee) { create(:coffee_product, user: seller, name: "Coffee") } let(:offer_code) { create(:offer_code, code: "code", products: [membership]) } let(:purchase1) { create(:purchase, link: product, full_name: "Customer 1", email: "customer1@gumroad.com", created_at: 1.day.ago, seller:, was_product_recommended: true, recommended_by: RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION, is_purchasing_power_parity_discounted: true, ip_country: "United States", is_additional_contribution: true, can_contact: false) } let(:purchase2) { create(:membership_purchase, link: membership, full_name: "Customer 2", email: "customer2@gumroad.com", purchaser: create(:user), created_at: 2.days.ago, seller:, is_original_subscription_purchase: true, offer_code:, is_gift_sender_purchase: true, affiliate: create(:direct_affiliate), is_preorder_authorization: true, preorder: create(:preorder)) } let(:purchase3) { create(:purchase, link: coffee, variant_attributes: [coffee.alive_variants.first]) } let(:pundit_user) { SellerContext.new(user: seller, seller:) } let(:presenter) { described_class.new(pundit_user:, customers: [purchase1, purchase2], pagination: nil, count: 2) } before do purchase1.create_purchasing_power_parity_info!(factor: 0.5) create(:gift, giftee_email: "giftee@gumroad.com", giftee_purchase: create(:purchase), gifter_purchase: purchase2) purchase2.reload create(:upsell_purchase, purchase: purchase1, upsell: create(:upsell, seller:, product:, cross_sell: true)) create(:variant, name: nil, variant_category: coffee.variant_categories_alive.first, price_difference_cents: 100) end describe "#customers_props" do it "returns the correct props" do expect(presenter.customers_props).to eq( { customers: [purchase1, purchase2].map { CustomerPresenter.new(purchase: _1).customer(pundit_user:) }, count: 2, pagination: nil, product_id: nil, products: [ { id: product.external_id, name: "Product", variants: [], }, { id: membership.external_id, name: "Membership", variants: [ { id: membership.alive_variants.first.external_id, name: "First Tier" }, { id: membership.alive_variants.second.external_id, name: "Second Tier" } ], }, { id: coffee.external_id, name: "Coffee", variants: [ { id: coffee.alive_variants.first.external_id, name: "", }, { id: coffee.alive_variants.second.external_id, name: "", }, ], }, ], countries: Compliance::Countries.for_select.map(&:last), currency_type: "usd", can_ping: true, show_refund_fee_notice: false, } ) end end describe "variant belongs to coffee" do let(:seller) { create(:user, :eligible_for_service_products) } let(:coffee) { create(:product, user: seller, native_type: Link::NATIVE_TYPE_COFFEE) } let(:variant_category) { create(:variant_category, link: coffee) } context "name is blank" do it "does not add an error" do variant = build(:variant, variant_category:, price_difference_cents: 100) # Add a valid price expect(variant).to be_valid end end context "price is zero" do it "adds an error" do variant = build(:variant, variant_category:, price_difference_cents: 0) expect(variant).not_to be_valid expect(variant.errors.full_messages).to include("Price difference cents must be greater than 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/presenters/subscriptions_presenter_spec.rb
spec/presenters/subscriptions_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe SubscriptionsPresenter do let(:product) { create(:product, name: "Test product name") } let(:user) { create(:user, email: "user@email.com") } let(:subscription) do subscription = create(:subscription, user:, link: product) create(:membership_purchase, subscription:, email: "purchase@email.com") subscription end describe "#magic_link_props" do it "returns the right props" do result = described_class.new(subscription:).magic_link_props expect(result).to match({ subscription_id: subscription.external_id, is_installment_plan: false, product_name: "Test product name", user_emails: match_array([ { email: EmailRedactorService.redact("user@email.com"), source: be_in([:subscription, :user]) }, { email: EmailRedactorService.redact("purchase@email.com"), source: :purchase }, ]) }) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/collab_products_page_presenter_spec.rb
spec/presenters/collab_products_page_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe CollabProductsPagePresenter, :vcr do include Rails.application.routes.url_helpers # User is a collaborator for two other sellers let(:user) { create(:user) } let(:pundit_user) { SellerContext.new(user:, seller: user) } let(:seller_1) { create(:user) } let(:seller_1_collaborator) { create(:collaborator, seller: seller_1, affiliate_user: user) } let(:seller_2) { create(:user) } let(:seller_2_collaborator) { create(:collaborator, seller: seller_2, affiliate_user: user) } # Products # 1. Owned by user let!(:collab_1) { create(:product, :is_collab, user:, price_cents: 15_00, collaborator_cut: 50_00, created_at: 1.month.ago) } let!(:membership_collab_1) { create(:membership_product_with_preset_tiered_pricing, :is_collab, user:, collaborator_cut: 50_00, created_at: 2.months.ago) } # 2. Owned by others let!(:collab_2) { create(:product, :is_collab, user: seller_1, collaborator_cut: 25_00, collaborator: seller_1_collaborator, created_at: 3.months.ago) } let!(:collab_3) { create(:product, :is_collab, user: seller_2, collaborator_cut: 50_00, collaborator: seller_2_collaborator, created_at: 4.months.ago) } # no purchases let!(:membership_collab_2) { create(:membership_product_with_preset_tiered_pricing, :is_collab, user: seller_2, collaborator_cut: 25_00, collaborator: seller_2_collaborator, created_at: 5.months.ago) } # 3. Non-collab let!(:non_collab_product) { create(:product, user:) } let!(:affiliate_product) { create(:product, user:) } let!(:affiliate) { create(:direct_affiliate, seller: user, products: [affiliate_product]) } # Purchases # 1. For collabs let(:collab_1_purchase_1) { create(:purchase_in_progress, seller: user, link: collab_1, affiliate: collab_1.collaborator) } let(:collab_1_purchase_2) { create(:purchase_in_progress, seller: user, link: collab_1, affiliate: collab_1.collaborator) } let(:collab_1_purchase_3) { create(:purchase_in_progress, seller: user, link: collab_1, affiliate: collab_1.collaborator) } let(:collab_2_purchase_1) { create(:purchase_in_progress, seller: seller_1, link: collab_2, affiliate: collab_2.collaborator) } let(:collab_2_purchase_2) { create(:purchase_in_progress, seller: seller_1, link: collab_2, affiliate: collab_2.collaborator) } let(:collab_2_purchase_3) { create(:purchase_in_progress, seller: seller_1, link: collab_2, affiliate: collab_2.collaborator) } let(:membership_collab_1_purchase_1) do tier = membership_collab_1.tiers.first create(:membership_purchase, purchase_state: "in_progress", seller: user, link: membership_collab_1, price_cents: tier.prices.first.price_cents, # $3 affiliate: membership_collab_1.collaborator, tier:) end let(:membership_collab_1_purchase_2) do tier = membership_collab_1.tiers.last create(:membership_purchase, purchase_state: "in_progress", seller: user, link: membership_collab_1, price_cents: tier.prices.first.price_cents, # $5 affiliate: membership_collab_1.collaborator, tier:) end let(:membership_collab_2_purchase_1) do tier = membership_collab_2.tiers.last create(:membership_purchase, purchase_state: "in_progress", seller: seller_2, link: membership_collab_2, price_cents: tier.prices.first.price_cents, # $5 affiliate: membership_collab_2.collaborator, tier:) end # 2. For non-collabs let(:non_collab_purchase) { create(:purchase_in_progress, seller: user, link: non_collab_product) } let(:affiliate_purchase) { create(:purchase_in_progress, seller: user, link: affiliate_product, affiliate:) } let(:successful_not_reversed_purchases) do [ collab_1_purchase_1, collab_1_purchase_2, collab_1_purchase_3, collab_2_purchase_1, membership_collab_1_purchase_1, membership_collab_1_purchase_2, membership_collab_2_purchase_1, ] end let(:chargedback_purchase) { collab_2_purchase_2 } let(:failed_purchase) { collab_2_purchase_3 } let(:collab_1_revenue) do [collab_1_purchase_1, collab_1_purchase_2, collab_1_purchase_3].sum do |p| # 3 successful p.displayed_price_cents - (p.affiliate_credit_cents + p.affiliate_credit.fee_cents) end end let(:collab_2_revenue) { collab_2_purchase_1.affiliate_credit_cents + collab_2_purchase_1.affiliate_credit.fee_cents } # 1 successful + 1 chargeback + 1 failed let(:collab_3_revenue) { 0 } let(:membership_collab_1_revenue) do [membership_collab_1_purchase_1, membership_collab_1_purchase_2].sum do |p| # 2 successful p.displayed_price_cents - (p.affiliate_credit_cents + p.affiliate_credit.fee_cents) end end let(:membership_collab_2_revenue) { membership_collab_2_purchase_1.affiliate_credit_cents + membership_collab_2_purchase_1.affiliate_credit.fee_cents } # 1 successful let(:total_revenue) { collab_1_revenue + collab_2_revenue + collab_3_revenue + membership_collab_1_revenue + membership_collab_2_revenue } let(:products_props) do [ { "id" => collab_1.id, "edit_url" => edit_link_path(collab_1), "name" => collab_1.name, "permalink" => collab_1.unique_permalink, "price_formatted" => collab_1.price_formatted_including_rental_verbose, "revenue" => collab_1_revenue, "thumbnail" => collab_1.thumbnail&.alive&.as_json, "display_price_cents" => collab_1.display_price_cents, "url" => collab_1.long_url, "url_without_protocol" => collab_1.long_url(include_protocol: false), "has_duration" => collab_1.duration_in_months.present?, "cut" => collab_1.percentage_revenue_cut_for_user(user), "can_edit" => true, "successful_sales_count" => 3, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 4500, }, { "id" => collab_2.id, "edit_url" => edit_link_path(collab_2), "name" => collab_2.name, "permalink" => collab_2.unique_permalink, "price_formatted" => collab_2.price_formatted_including_rental_verbose, "revenue" => collab_2_revenue, "thumbnail" => collab_2.thumbnail&.alive&.as_json, "display_price_cents" => collab_2.display_price_cents, "url" => collab_2.long_url, "url_without_protocol" => collab_2.long_url(include_protocol: false), "has_duration" => collab_2.duration_in_months.present?, "cut" => collab_2.percentage_revenue_cut_for_user(user), "can_edit" => true, "successful_sales_count" => 1, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 100, }, { "id" => collab_3.id, "edit_url" => edit_link_path(collab_3), "name" => collab_3.name, "permalink" => collab_3.unique_permalink, "price_formatted" => collab_3.price_formatted_including_rental_verbose, "revenue" => collab_3_revenue, "thumbnail" => collab_3.thumbnail&.alive&.as_json, "display_price_cents" => collab_3.display_price_cents, "url" => collab_3.long_url, "url_without_protocol" => collab_3.long_url(include_protocol: false), "has_duration" => collab_3.duration_in_months.present?, "cut" => collab_3.percentage_revenue_cut_for_user(user), "can_edit" => true, "successful_sales_count" => 0, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 0, }, ] end let(:memberships_props) do [ { "id" => membership_collab_1.id, "edit_url" => edit_link_path(membership_collab_1), "name" => membership_collab_1.name, "permalink" => membership_collab_1.unique_permalink, "price_formatted" => membership_collab_1.price_formatted_including_rental_verbose, "revenue" => membership_collab_1_revenue, "thumbnail" => membership_collab_1.thumbnail&.alive&.as_json, "display_price_cents" => membership_collab_1.display_price_cents, "url" => membership_collab_1.long_url, "url_without_protocol" => membership_collab_1.long_url(include_protocol: false), "has_duration" => membership_collab_1.duration_in_months.present?, "cut" => membership_collab_1.percentage_revenue_cut_for_user(user), "can_edit" => true, "successful_sales_count" => 2, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => membership_collab_1.monthly_recurring_revenue, "revenue_pending" => 0.0, "total_usd_cents" => 800, }, { "id" => membership_collab_2.id, "edit_url" => edit_link_path(membership_collab_2), "name" => membership_collab_2.name, "permalink" => membership_collab_2.unique_permalink, "price_formatted" => membership_collab_2.price_formatted_including_rental_verbose, "revenue" => membership_collab_2_revenue, "thumbnail" => membership_collab_2.thumbnail&.alive&.as_json, "display_price_cents" => membership_collab_2.display_price_cents, "url" => membership_collab_2.long_url, "url_without_protocol" => membership_collab_2.long_url(include_protocol: false), "has_duration" => membership_collab_2.duration_in_months.present?, "cut" => membership_collab_2.percentage_revenue_cut_for_user(user), "can_edit" => true, "successful_sales_count" => 1, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => membership_collab_2.monthly_recurring_revenue, "revenue_pending" => 0.0, "total_usd_cents" => 500, }, ] end before do purchases = successful_not_reversed_purchases + [chargedback_purchase, non_collab_purchase, affiliate_purchase] purchases.each do |purchase| purchase.process! purchase.update_balance_and_mark_successful! end # chargeback purchase allow_any_instance_of(Purchase).to receive(:fight_chargeback).and_return(true) event_flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, chargedback_purchase.total_transaction_cents) event = build(:charge_event_dispute_formalized, charge_id: chargedback_purchase.stripe_transaction_id, flow_of_funds: event_flow_of_funds) chargedback_purchase.handle_event_dispute_formalized!(event) chargedback_purchase.reload # failed purchase failed_purchase.mark_failed! end describe "#initial_page_props", :sidekiq_inline, :elasticsearch_wait_for_refresh do it "returns stats and collab products" do props = described_class.new(pundit_user:).initial_page_props stats = { total_revenue:, total_customers: 4, total_members: 3, total_collaborations: 5, } expect(props.keys).to match_array [:stats, :archived_tab_visible, :products, :products_pagination, :memberships, :memberships_pagination, :collaborators_disabled_reason] expect(props[:stats]).to match stats expect(props[:products_pagination]).to match({ page: 1, pages: 1 }) expect(props[:memberships_pagination]).to match({ page: 1, pages: 1 }) expect(props[:products]).to match_array products_props expect(props[:memberships]).to match_array memberships_props expect(props[:collaborators_disabled_reason]).to be nil end it "returns collaborators_disabled_reason if using Brazilian Stripe Connect account" do brazilian_stripe_account = create(:merchant_account_stripe_connect, user: pundit_user.seller, country: "BR") pundit_user.seller.update!(check_merchant_account_is_linked: true) expect(pundit_user.seller.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account props = described_class.new(pundit_user:).initial_page_props expect(props[:collaborators_disabled_reason]).to eq "Collaborators with Brazilian Stripe accounts are not supported." end it "caches product data", :sidekiq_inline do expect do described_class.new(pundit_user:).initial_page_props end.to change { ProductCachedValue.count }.from(0).to(5) end end describe "#products_table_props", :sidekiq_inline, :elasticsearch_wait_for_refresh do it "returns product details" do props = described_class.new(pundit_user:).products_table_props expect(props.keys).to match_array [:products, :products_pagination] expect(props[:products]).to match_array products_props end it "caches product data", :sidekiq_inline do expect do described_class.new(pundit_user:).products_table_props end.to change { ProductCachedValue.count }.from(0).to(3) end end describe "#memberships_table_props", :sidekiq_inline, :elasticsearch_wait_for_refresh do it "returns memberships details" do props = described_class.new(pundit_user:).memberships_table_props expect(props.keys).to match_array [:memberships, :memberships_pagination] expect(props[:memberships]).to match_array memberships_props end it "caches memberships data", :sidekiq_inline do expect do described_class.new(pundit_user:).memberships_table_props end.to change { ProductCachedValue.count }.from(0).to(2) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/cart_presenter_spec.rb
spec/presenters/cart_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe CartPresenter do describe "#cart_props" do let(:user) { create(:user) } let(:ip) { "127.0.0.1" } let(:browser_guid) { SecureRandom.uuid } let(:presenter) do described_class.new(logged_in_user: user, ip:, browser_guid:) end context "when the user is not logged in" do let(:user) { nil } it "returns props for the alive guest cart matching the `browser_guid`" do create(:cart, :guest, browser_guid:, email: "john@example.com") create(:cart, user: create(:user), browser_guid:, email: "jane@example.com") expect(presenter.cart_props).to match( email: "john@example.com", returnUrl: "", rejectPppDiscount: false, discountCodes: [], items: [], ) end it "returns nil if no matching guest cart is found" do expect(presenter.cart_props).to be_nil end end context "when the user has no cart" do it "returns nil" do expect(presenter.cart_props).to be_nil end end context "when the user has a cart with items" do let(:cart) { create(:cart, user:, email: "john@example.com") } let(:simple_product) { create(:product) } let(:recurring_product) { create(:membership_product_with_preset_tiered_pricing) } let(:call_product) { create(:call_product, price_cents: 1000, installment_plan: create(:product_installment_plan)) } let(:call_start_time) { 1.hour.from_now.round } before do create(:cart_product, cart:, product: simple_product, referrer: "google.com", call_start_time:, url_parameters: { "utm_source" => "google" }) create(:cart_product, cart:, product: recurring_product, option: recurring_product.variants.first, recurrence: BasePrice::Recurrence::MONTHLY) create(:cart_product, cart:, product: call_product, option: call_product.variants.first, call_start_time:, pay_in_installments: true) end it "returns the correct props" do expect(presenter.cart_props).to match( { email: "john@example.com", returnUrl: "", rejectPppDiscount: false, discountCodes: [], items: [ { product: a_hash_including(permalink: call_product.unique_permalink), price: 1000, option_id: call_product.variants.first.external_id, rent: false, recurrence: nil, quantity: 1, affiliate_id: nil, recommended_by: nil, recommender_model_name: nil, accepted_offer: nil, url_parameters: {}, referrer: "direct", call_start_time: call_start_time, pay_in_installments: true, }, { product: a_hash_including(permalink: recurring_product.unique_permalink), price: 300, option_id: recurring_product.variants.first.external_id, rent: false, recurrence: BasePrice::Recurrence::MONTHLY, quantity: 1, affiliate_id: nil, recommended_by: nil, recommender_model_name: nil, accepted_offer: nil, url_parameters: {}, referrer: "direct", call_start_time: nil, pay_in_installments: false, }, { product: a_hash_including(permalink: simple_product.unique_permalink), price: 100, option_id: nil, rent: false, recurrence: nil, quantity: 1, affiliate_id: nil, recommended_by: nil, recommender_model_name: nil, accepted_offer: nil, url_parameters: { "utm_source" => "google" }, referrer: "google.com", call_start_time: nil, pay_in_installments: false, }, ], } ) end end context "with discount codes and offers" do context "when the user has accepeted an upsell" do let(:discount_codes) do [ { "code" => "SAVEMONEY", "fromUrl" => false }, { "code" => "INVALIDCODE", "fromUrl" => true } ] end let(:cart) { create(:cart, user:, discount_codes:) } let(:product) { create(:product) } let(:offer_code) { create(:offer_code, code: "SAVEMONEY", amount_cents: 100, user: product.user, products: [product]) } let(:upsell) { create(:upsell, seller: product.user, offer_code:, product:) } before do create(:cart_product, cart:, product:, accepted_offer: upsell, accepted_offer_details: { original_product_id: upsell.product.external_id, original_variant_id: nil }) end it "returns the correct props" do expect(presenter.cart_props).to match( { email: nil, returnUrl: "", rejectPppDiscount: false, discountCodes: [ { code: "SAVEMONEY", fromUrl: false, products: { product.unique_permalink => { type: "fixed", cents: 100, product_ids: [product.external_id], expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, } }, }, { code: "INVALIDCODE", fromUrl: true, products: [], } ], items: [ { product: a_hash_including(permalink: product.unique_permalink), price: 100, option_id: nil, rent: false, recurrence: nil, quantity: 1, affiliate_id: nil, recommended_by: nil, recommender_model_name: nil, url_parameters: {}, referrer: "direct", call_start_time: nil, pay_in_installments: false, accepted_offer: { id: upsell.external_id, original_product_id: upsell.product.external_id, original_variant_id: nil, discount: { type: "fixed", cents: 100, product_ids: [product.external_id], expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, }, }, ], } ) end end context "when the user has accepted a cross-sell" do let(:user) { nil } let(:cart) { create(:cart, :guest, browser_guid:) } let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let(:offered_product) { create(:product, user: seller) } let(:cross_sell) { create(:upsell, seller:, product: offered_product, selected_products: [product], offer_code: create(:offer_code, user: seller, products: [offered_product]), cross_sell: true) } before do create(:cart_product, cart:, product:) create(:cart_product, cart:, product: offered_product, accepted_offer: cross_sell, accepted_offer_details: { original_product_id: product.external_id, original_variant_id: nil }) end it "returns the correct props" do expect(presenter.cart_props).to match(a_hash_including( discountCodes: [], items: [ a_hash_including( product: a_hash_including(permalink: offered_product.unique_permalink), accepted_offer: a_hash_including( id: cross_sell.external_id, original_product_id: product.external_id, original_variant_id: nil, discount: a_hash_including( type: "fixed", cents: 100, product_ids: [offered_product.external_id], ), ), ), a_hash_including( product: a_hash_including(permalink: product.unique_permalink), ), ] )) 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/presenters/paginated_community_chat_messages_presenter_spec.rb
spec/presenters/paginated_community_chat_messages_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe PaginatedCommunityChatMessagesPresenter do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, community_chat_enabled: true) } let!(:community) { create(:community, seller:, resource: product) } let(:timestamp) { Time.current.iso8601 } describe "#initialize" do it "raises error when timestamp is missing" do expect { described_class.new(community:, timestamp: nil, fetch_type: "older") } .to raise_error(ArgumentError, "Invalid timestamp") end it "raises error when fetch_type is invalid" do expect { described_class.new(community:, timestamp:, fetch_type: "invalid") } .to raise_error(ArgumentError, "Invalid fetch type") end it "accepts valid fetch types" do expect { described_class.new(community:, timestamp:, fetch_type: "older") }.not_to raise_error expect { described_class.new(community:, timestamp:, fetch_type: "newer") }.not_to raise_error expect { described_class.new(community:, timestamp:, fetch_type: "around") }.not_to raise_error end end describe "#props" do subject(:props) { described_class.new(community:, timestamp:, fetch_type:).props } context "when fetching older messages" do let(:fetch_type) { "older" } let!(:message1) { create(:community_chat_message, community:, user: seller, created_at: 30.minutes.ago) } let!(:message2) { create(:community_chat_message, community:, user: seller, created_at: 20.minutes.ago) } let!(:message3) { create(:community_chat_message, community:, user: seller, created_at: 10.minutes.ago) } let(:timestamp) { 15.minutes.ago.iso8601 } it "returns messages older than timestamp" do expect(props[:messages]).to match_array( [CommunityChatMessagePresenter.new(message: message1).props, CommunityChatMessagePresenter.new(message: message2).props] ) expect(props[:next_older_timestamp]).to be_nil expect(props[:next_newer_timestamp]).to eq(message3.created_at.iso8601) end context "when there are more than MESSAGES_PER_PAGE older messages" do before do CommunityChatMessage.delete_all end let(:timestamp) { 1.minute.ago.iso8601 } let!(:older_messages) do (1..101).map do |i| create(:community_chat_message, community:, user: seller, created_at: (i + 10).minutes.ago) end end it "returns MESSAGES_PER_PAGE messages and next_older_timestamp" do expect(props[:messages].length).to eq(100) expect(props[:next_older_timestamp]).to eq(older_messages.last.created_at.iso8601) expect(props[:next_newer_timestamp]).to be_nil end end end context "when fetching newer messages" do let(:fetch_type) { "newer" } let!(:message1) { create(:community_chat_message, community:, user: seller, created_at: 10.minutes.ago) } let!(:message2) { create(:community_chat_message, community:, user: seller, created_at: 20.minutes.ago) } let!(:message3) { create(:community_chat_message, community:, user: seller, created_at: 30.minutes.ago) } let(:timestamp) { 25.minutes.ago.iso8601 } it "returns messages newer than timestamp" do expect(props[:messages]).to match_array( [CommunityChatMessagePresenter.new(message: message1).props, CommunityChatMessagePresenter.new(message: message2).props] ) expect(props[:next_older_timestamp]).to eq(message3.created_at.iso8601) expect(props[:next_newer_timestamp]).to be_nil end context "when there are more than MESSAGES_PER_PAGE newer messages" do before do CommunityChatMessage.delete_all end let!(:newer_messages) do (1..101).map do |i| create(:community_chat_message, community:, user: seller, created_at: (i + 10).minutes.ago) end end let(:timestamp) { newer_messages.last.created_at.iso8601 } it "returns MESSAGES_PER_PAGE messages and next_newer_timestamp" do expect(props[:messages].length).to eq(100) expect(props[:next_newer_timestamp]).to eq(newer_messages.first.created_at.iso8601) expect(props[:next_older_timestamp]).to be_nil end end end context "when fetching messages around timestamp" do let(:fetch_type) { "around" } let!(:messages) do total_messages = PaginatedCommunityChatMessagesPresenter::MESSAGES_PER_PAGE + 2 (1..total_messages).map do |i| created_at = (i * 10).minutes.ago create(:community_chat_message, content: "#{total_messages + 1 - i}", community:, user: seller, created_at:) end end let(:timestamp) { (messages.find { |m| m.content == "52" }.created_at - 1.minute).iso8601 } it "returns equal number of older and newer messages" do expect(props[:messages].length).to eq(100) older_messages = messages.select { |m| m.content.to_i < 52 } newer_messages = messages.select { |m| m.content.to_i >= 52 }.reverse expect(props[:messages].map { |m| m[:content].to_i }.sort).to eq((older_messages.take(50) + newer_messages.take(50)).map(&:content).map(&:to_i).sort) expect(props[:next_older_timestamp]).to eq(older_messages.last.created_at.iso8601) expect(props[:next_newer_timestamp]).to eq(newer_messages.last.created_at.iso8601) end end context "when messages are deleted" do let(:fetch_type) { "older" } let!(:message1) { create(:community_chat_message, community:, user: seller, created_at: 3.minutes.ago) } let!(:message2) { create(:community_chat_message, community:, user: seller, created_at: 2.minutes.ago) } let!(:message3) { create(:community_chat_message, community:, user: seller, created_at: 1.minute.ago) } let(:timestamp) { message2.created_at.iso8601 } before { message1.update!(deleted_at: Time.current) } it "excludes deleted messages" do expect(props[:messages]).to be_empty expect(props[:next_older_timestamp]).to be_nil expect(props[:next_newer_timestamp]).to eq(timestamp) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/library_presenter_spec.rb
spec/presenters/library_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe LibraryPresenter do include Rails.application.routes.url_helpers let(:creator) { create(:user, name: "Testy", username: "testy") } let(:product) { create(:membership_product, unique_permalink: "test", name: "hello", user: creator) } let(:buyer) { create(:user, name: "Buyer", username: "buyer") } let(:purchase) { create(:membership_purchase, link: product, purchaser: buyer) } describe "#library_cards" do let(:product_details) do { name: "hello", creator_id: creator.external_id, creator: { name: "Testy", profile_url: creator.profile_url(recommended_by: "library"), avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png") }, thumbnail_url: nil, native_type: "membership", updated_at: product.created_at, permalink: product.unique_permalink, has_third_party_analytics: false, } end before do purchase.create_url_redirect! end it "returns all necessary properties for library page" do purchases, creator_counts = described_class.new(buyer).library_cards expect(purchases).to eq([ product: product_details, purchase: { id: purchase.external_id, email: purchase.email, is_archived: false, download_url: purchase.url_redirect.download_page_url, bundle_id: nil, variants: "Untitled", is_bundle_purchase: false, }]) expect(creator_counts).to eq([{ count: 1, id: creator.external_id, name: creator.name }]) end it "does not return the URL of a deleted thumbnail" do create(:thumbnail, product:) purchases, _ = described_class.new(buyer).library_cards expect(purchases[0][:product][:thumbnail_url]).to be_present product.thumbnail.mark_deleted! purchases, _ = described_class.new(buyer).library_cards expect(purchases[0][:product][:thumbnail_url]).to eq(nil) end it "handles users without a username set" do creator.update(username: nil) purchases, _ = described_class.new(buyer).library_cards expect(purchases[0][:creator]).to be_nil end it "handles users without a name set" do creator.update(name: nil) purchases, _ = described_class.new(buyer).library_cards expect(purchases[0][:product][:creator]).to eq( { name: creator.username, profile_url: creator.profile_url(recommended_by: "library"), avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png") } ) end context "when a user has purchased a subscription multiple times" do let!(:purchase_2) do create(:membership_purchase, link: product, purchaser: buyer).tap { _1.create_url_redirect! } end before do create(:recurring_membership_purchase, link: product, purchaser: buyer, subscription: purchase.subscription) create(:membership_purchase, link: product, purchaser: buyer).tap { _1.subscription.update!(cancelled_at: 1.day.ago) } end it "returns results for all live subscriptions" do purchases, creator_counts = described_class.new(buyer).library_cards expect(purchases).to eq([ { product: product_details, purchase: { id: purchase_2.external_id, email: purchase_2.email, is_archived: false, download_url: purchase_2.url_redirect.download_page_url, bundle_id: nil, variants: "Untitled", is_bundle_purchase: false, }, }, { product: product_details, purchase: { id: purchase.external_id, email: purchase.email, is_archived: false, download_url: purchase.url_redirect.download_page_url, bundle_id: nil, variants: "Untitled", is_bundle_purchase: false, }, }, ]) expect(creator_counts).to eq([{ count: 1, id: creator.external_id, name: creator.name }]) end end describe "bundle purchase" do let(:purchase1) { create(:purchase, purchaser: buyer, link: create(:product, :bundle)) } let(:purchase2) { create(:purchase, purchaser: buyer, link: create(:product, :bundle)) } before do purchase1.create_artifacts_and_send_receipt! purchase2.create_artifacts_and_send_receipt! end it "includes the bundle attributes" do purchases, _, bundles = described_class.new(buyer).library_cards expect(purchases.first[:purchase][:id]).to eq(purchase2.product_purchases.second.external_id) expect(purchases.first[:purchase][:bundle_id]).to eq(purchase2.link.external_id) expect(purchases.first[:purchase][:is_bundle_purchase]).to eq(false) expect(purchases.second[:purchase][:id]).to eq(purchase2.product_purchases.first.external_id) expect(purchases.second[:purchase][:bundle_id]).to eq(purchase2.link.external_id) expect(purchases.second[:purchase][:is_bundle_purchase]).to eq(false) expect(purchases.third[:purchase][:id]).to eq(purchase2.external_id) expect(purchases.third[:purchase][:bundle_id]).to be_nil expect(purchases.third[:purchase][:is_bundle_purchase]).to eq(true) expect(bundles).to eq( [ { id: purchase2.link.external_id, label: "Bundle" }, { id: purchase1.link.external_id, label: "Bundle" }, ] ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/dispute_evidence_page_presenter_spec.rb
spec/presenters/dispute_evidence_page_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe DisputeEvidencePagePresenter do let(:dispute_evidence) { create(:dispute_evidence, seller_contacted_at: 1.hour.ago) } let(:presenter) { described_class.new(dispute_evidence) } let(:purchase) { dispute_evidence.disputable.purchase_for_dispute_evidence } let(:purchase_product_presenter) { PurchaseProductPresenter.new(purchase) } describe "#react_props" do it "returns correct props" do receipt_image = dispute_evidence.receipt_image policy_image = dispute_evidence.policy_image expect(presenter.react_props[:dispute_evidence]).to eq( { dispute_reason: Dispute::REASON_FRAUDULENT, customer_email: dispute_evidence.customer_email, purchased_at: dispute_evidence.purchased_at, duration_left_to_submit_evidence_formatted: "71 hours", customer_communication_file_max_size: dispute_evidence.customer_communication_file_max_size, blobs: { receipt_image: { byte_size: receipt_image.byte_size, filename: receipt_image.filename.to_s, key: receipt_image.key, signed_id: nil, title: "Receipt", }, policy_image: { byte_size: policy_image.byte_size, filename: policy_image.filename.to_s, key: policy_image.key, signed_id: nil, title: "Refund policy", }, customer_communication_file: nil, } } ) expect(presenter.react_props[:products]).to eq( [{ name: purchase_product_presenter.product_props[:product][:name], url: purchase_product_presenter.product_props[:product][:long_url], }] ) expect(presenter.react_props[:disputable]).to eq( { purchase_for_dispute_evidence_id: purchase.external_id, formatted_display_price: purchase.formatted_disputed_amount, is_subscription: purchase.subscription.present? } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter_spec.rb
spec/presenters/receipt_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/receipt_presenter_concern" describe ReceiptPresenter do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 1_499, created_at: DateTime.parse("January 1, 2023") ) end let(:presenter) { described_class.new(chargeable, for_email: true) } describe "For Purchase" do let(:chargeable) { purchase } describe "#charge_info" do it "returns a ChargeInfo object" do expect(presenter.charge_info).to be_a(ReceiptPresenter::ChargeInfo) expect(presenter.charge_info.send(:chargeable)).to eq(chargeable) end end describe "#payment_info" do it "returns a PaymentInfo object" do expect(presenter.payment_info).to be_a(ReceiptPresenter::PaymentInfo) expect(presenter.payment_info.send(:chargeable)).to eq(chargeable) end it "includes sales tax breakdown for Canada", :vcr do product = create(:product, price_cents: 200_00, native_type: "digital") purchase1 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "AB", ip_country: "Canada") purchase2 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "BC", ip_country: "Canada") purchase3 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "QC", ip_country: "Canada") Purchase.in_progress.find_each do |purchase| purchase.chargeable = create(:chargeable) purchase.process! purchase.update_balance_and_mark_successful! end presenter = described_class.new(purchase1.reload, for_email: true) expect(presenter.payment_info.today_payment_attributes).to include({ label: "GST/HST", value: "$10" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "PST")) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "QST")) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(purchase2.reload, for_email: true) expect(presenter.payment_info.today_payment_attributes).to include({ label: "GST/HST", value: "$10" }) expect(presenter.payment_info.today_payment_attributes).to include({ label: "PST", value: "$14" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "QST")) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(purchase3.reload, for_email: true) expect(presenter.payment_info.today_payment_attributes).to include({ label: "GST/HST", value: "$10" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "PST")) expect(presenter.payment_info.today_payment_attributes).to include({ label: "QST", value: "$19.95" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "Sales tax")) end end describe "#shipping_info" do it "returns a ShippingInfo object" do expect(presenter.shipping_info).to be_a(ReceiptPresenter::ShippingInfo) expect(presenter.shipping_info.send(:chargeable)).to eq(chargeable) end end describe "#items_infos" do it "returns an array" do expect(ReceiptPresenter::ItemInfo).to receive(:new).with(chargeable).and_call_original purchases = presenter.items_infos expect(purchases.size).to eq(1) expect(purchases.first).to be_a(ReceiptPresenter::ItemInfo) end end describe "#recommended_products_info" do it "returns a RecommendedProductsInfo object" do expect(presenter.recommended_products_info).to be_a(ReceiptPresenter::RecommendedProductsInfo) expect(presenter.recommended_products_info.send(:chargeable)).to eq(chargeable) end end describe "#mail_subject" do it "returns mail subject" do expect(presenter.mail_subject).to eq("You bought The Works of Edgar Gumstein!") end end describe "#footer_info" do it "returns a FooterInfo object" do expect(presenter.footer_info).to be_a(ReceiptPresenter::FooterInfo) expect(presenter.footer_info.send(:chargeable)).to eq(chargeable) end end end describe "For Charge" do let(:charge) { create(:charge, purchases: [purchase]) } let(:chargeable) { charge } describe "#charge_info" do it "returns a ChargeInfo object" do expect(presenter.charge_info).to be_a(ReceiptPresenter::ChargeInfo) expect(presenter.charge_info.send(:chargeable)).to eq(chargeable) end end describe "#payment_info" do it "returns a PaymentInfo object" do expect(presenter.payment_info).to be_a(ReceiptPresenter::PaymentInfo) expect(presenter.payment_info.send(:chargeable)).to eq(chargeable) end it "includes sales tax breakdown for Canada", :vcr do product = create(:product, price_cents: 200_00, native_type: "digital") purchase1 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "AB", ip_country: "Canada") charge1 = create(:charge) charge1.purchases << purchase1 purchase2 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "BC", ip_country: "Canada") charge2 = create(:charge) charge2.purchases << purchase2 purchase3 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "QC", ip_country: "Canada") charge3 = create(:charge) charge3.purchases << purchase3 order = create(:order) order.charges << [charge1, charge2, charge3] order.purchases << [purchase1, purchase2, purchase3] Purchase.in_progress.find_each do |purchase| purchase.chargeable = create(:chargeable) purchase.process! purchase.update_balance_and_mark_successful! end presenter = described_class.new(charge1.reload, for_email: true) expect(presenter.payment_info.today_payment_attributes).to include({ label: "GST/HST", value: "$10" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "PST")) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "QST")) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(charge2.reload, for_email: true) expect(presenter.payment_info.today_payment_attributes).to include({ label: "GST/HST", value: "$10" }) expect(presenter.payment_info.today_payment_attributes).to include({ label: "PST", value: "$14" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "QST")) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(charge3.reload, for_email: true) expect(presenter.payment_info.today_payment_attributes).to include({ label: "GST/HST", value: "$10" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "PST")) expect(presenter.payment_info.today_payment_attributes).to include({ label: "QST", value: "$19.95" }) expect(presenter.payment_info.today_payment_attributes).not_to include(hash_including(label: "Sales tax")) end end describe "#shipping_info" do it "returns a ShippingInfo object" do expect(presenter.shipping_info).to be_a(ReceiptPresenter::ShippingInfo) expect(presenter.shipping_info.send(:chargeable)).to eq(chargeable) end end describe "#items_infos" do it "returns an array" do expect(ReceiptPresenter::ItemInfo).to receive(:new).with(purchase).and_call_original purchases = presenter.items_infos expect(purchases.size).to eq(1) expect(purchases.first).to be_a(ReceiptPresenter::ItemInfo) end end describe "#recommended_products_info" do it "returns a RecommendedProductsInfo object" do expect(presenter.recommended_products_info).to be_a(ReceiptPresenter::RecommendedProductsInfo) expect(presenter.recommended_products_info.send(:chargeable)).to eq(chargeable) end end describe "#mail_subject" do it "returns mail subject" do expect(presenter.mail_subject).to eq("You bought The Works of Edgar Gumstein!") end end describe "#footer_info" do it "returns a FooterInfo object" do expect(presenter.footer_info).to be_a(ReceiptPresenter::FooterInfo) expect(presenter.footer_info.send(:chargeable)).to eq(chargeable) end end describe "#giftee_manage_subscription" do it "returns a GifteeManageSubscription object" do expect(presenter.giftee_manage_subscription).to be_a(ReceiptPresenter::GifteeManageSubscription) expect(presenter.giftee_manage_subscription.send(:chargeable)).to eq(chargeable) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/payouts_presenter_spec.rb
spec/presenters/payouts_presenter_spec.rb
# frozen_string_literal: true describe PayoutsPresenter do include PayoutsHelper include CurrencyHelper describe "#next_payout_period_data" do it "returns not_payable status when user balance is below minimum" do user = create(:user, user_risk_state: "compliant") instance = described_class.new(seller: user) expect(instance.next_payout_period_data).to include( status: "not_payable", is_user_payable: false, has_stripe_connect: false ) end it "returns has_stripe_connect set to false if the user is not stripe connect" do user = create(:user, user_risk_state: "compliant") instance = described_class.new(seller: user) expect(instance.next_payout_period_data).to include(has_stripe_connect: false) end it "returns has_stripe_connect set to true if the user is stripe connect" do user = create(:user, user_risk_state: "compliant") MerchantAccount.create!( user: user, charge_processor_id: StripeChargeProcessor.charge_processor_id, charge_processor_merchant_id: "acct_test123", charge_processor_verified_at: Time.current, charge_processor_alive_at: Time.current, json_data: { meta: { stripe_connect: "true" } } ) instance = described_class.new(seller: user) expect(instance.next_payout_period_data).to include(has_stripe_connect: true) end end describe "#processing_payout_periods_data" do it "returns empty array when no processing payouts exist" do user = create(:user, user_risk_state: "compliant") instance = described_class.new(seller: user) expect(instance.processing_payout_periods_data).to eq([]) end it "adds has_stripe_connect to each processing payout period" do user = create(:user, user_risk_state: "compliant") MerchantAccount.create!( user: user, charge_processor_id: StripeChargeProcessor.charge_processor_id, charge_processor_merchant_id: "acct_test123", charge_processor_verified_at: Time.current, charge_processor_alive_at: Time.current, json_data: { meta: { stripe_connect: "true" } } ) instance = described_class.new(seller: user) instance.processing_payout_periods_data.each do |period| expect(period).to include(has_stripe_connect: true) end end end describe "#instant_payout_data" do it "returns nil when instant payouts are not supported" do user = create(:user, user_risk_state: "compliant") instance = described_class.new(seller: user) expect(instance.instant_payout_data).to be_nil end it "returns instant payout details when supported" do user = create(:user, user_risk_state: "compliant") instance = described_class.new(seller: user) allow(user).to receive(:instant_payouts_supported?).and_return(true) allow(user).to receive(:instantly_payable_unpaid_balance_cents).and_return(1000) allow(user).to receive(:instantly_payable_unpaid_balances).and_return([]) allow(user).to receive_message_chain(:active_bank_account, :bank_account_type).and_return("checking") allow(user).to receive_message_chain(:active_bank_account, :bank_name).and_return("Test Bank") allow(user).to receive_message_chain(:active_bank_account, :routing_number).and_return("123456789") allow(user).to receive_message_chain(:active_bank_account, :account_number_visual).and_return("****1234") expect(instance.instant_payout_data).to eq( { payable_amount_cents: 1000, payable_balances: [], bank_account_type: "checking", bank_name: "Test Bank", routing_number: "123456789", account_number: "****1234" } ) end end describe "#past_payout_period_data" do it "returns empty array when no past payouts exist" do user = create(:user, user_risk_state: "compliant") instance = described_class.new(seller: user) expect(instance.past_payout_period_data).to eq([]) end it "transforms past payouts using payout_period_data helper" do user = create(:user, user_risk_state: "compliant") create(:payment_completed, user: user) instance = described_class.new(seller: user) result = instance.past_payout_period_data expect(result.length).to eq(1) expect(result.first).to include(:payout_displayed_amount) end end describe "#pagination_data" do it "returns pagination props" do user = create(:user, user_risk_state: "compliant") create_list(:payment_completed, 5, user: user) instance = described_class.new(seller: user) result = instance.pagination_data expect(result).to include(:pages) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/paginated_comments_presenter_spec.rb
spec/presenters/paginated_comments_presenter_spec.rb
# frozen_string_literal: true describe PaginatedCommentsPresenter do describe "#result" do let(:product) { create(:product) } let(:post) { create(:published_installment, link: product, installment_type: "product", shown_on_profile: true) } let(:logged_in_user) { create(:user) } let(:logged_in_seller) { logged_in_user } let(:pundit_user) { SellerContext.new(user: logged_in_user, seller: logged_in_seller) } let!(:comment1) { create(:comment, commentable: post, author: logged_in_user, created_at: 1.minute.ago) } let!(:comment2) { create(:comment, commentable: post) } let!(:comment_on_another_post) { create(:comment) } let(:purchase) { nil } let(:options) { {} } let(:presenter) { described_class.new(pundit_user:, commentable: post, purchase:, options:) } before do stub_const("#{described_class}::COMMENTS_PER_PAGE", 1) end context "when 'page' option is not specified" do it "returns paginated comments for the first page along with pagination metadata" do result = presenter.result expect(result[:comments].length).to eq(1) expect(result[:comments].first[:id]).to eq(comment1.external_id) expect(result[:pagination]).to eq(count: 2, items: 1, pages: 2, page: 1, next: 2, prev: nil, last: 2) end end context "when 'page' option is specified" do let(:options) { { page: 2 } } it "returns paginated comments for the specified page along with pagination metadata" do result = presenter.result expect(result[:comments].length).to eq(1) expect(result[:comments].first[:id]).to eq(comment2.external_id) expect(result[:pagination]).to eq(count: 2, items: 1, pages: 2, page: 2, next: nil, prev: 1, last: 2) end end context "when the specified 'page' option is an overflowing page number" do let(:options) { { page: 3 } } it "raises an exception" do expect do presenter.result end.to raise_error(Pagy::OverflowError) end end context "when there exists comments with nested replies" do let!(:reply1_to_comment1) { create(:comment, parent: comment1, commentable: post) } let!(:reply1_to_comment2) { create(:comment, parent: comment2, commentable: post) } let!(:reply_at_depth_2) { create(:comment, parent: reply1_to_comment2, commentable: post) } let!(:reply_at_depth_3) { create(:comment, parent: reply_at_depth_2, commentable: post) } let!(:reply_at_depth_4) { create(:comment, parent: reply_at_depth_3, commentable: post) } let(:options) { { page: 2 } } it "always returns count of all root comments and their descendants irrespective of specified 'page' option" do result = presenter.result expect(result[:comments].length).to eq(5) expect(result[:count]).to eq(7) end context "when 'page' option is specified with value of 1" do let(:options) { { page: 1 } } it "returns paginated roots comments for the first page along with their descendants" do result = presenter.result expect(result[:comments].length).to eq(2) expect(result[:comments].pluck(:id)).to match_array([comment1.external_id, reply1_to_comment1.external_id]) end end context "when 'page' option is specified with value of 2" do let(:options) { { page: 2 } } it "returns paginated roots comments for the second page along with their descendants" do result = presenter.result expect(result[:comments].length).to eq(5) expect(result[:comments].pluck(:id)).to match_array([ comment2.external_id, reply1_to_comment2.external_id, reply_at_depth_2.external_id, reply_at_depth_3.external_id, reply_at_depth_4.external_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/presenters/invoice_presenter_spec.rb
spec/presenters/invoice_presenter_spec.rb
# frozen_string_literal: true describe InvoicePresenter do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 1_499, created_at: DateTime.parse("January 1, 2023") ) end let(:address_fields) do { full_name: "Customer Name", street_address: "1234 Main St", city: "City", state: "State", zip_code: "12345", country: "United States" } end let(:presenter) { described_class.new(chargeable) } describe "For Purchase" do let(:chargeable) { purchase } describe "#supplier_info" do it "returns a SupplierInfo object" do expect(presenter.supplier_info).to be_a(InvoicePresenter::SupplierInfo) expect(presenter.supplier_info.send(:chargeable)).to eq(chargeable) end end describe "#seller_info" do it "returns a SellerInfo object" do expect(presenter.seller_info).to be_a(InvoicePresenter::SellerInfo) expect(presenter.seller_info.send(:chargeable)).to eq(chargeable) end end describe "#order_info" do let(:additional_notes) { "Additional notes" } let(:business_vat_id) { "VAT12345" } let(:presenter) { described_class.new(chargeable, address_fields:, additional_notes:, business_vat_id:) } it "returns an OrderInfo object" do expect(presenter.order_info).to be_a(InvoicePresenter::OrderInfo) expect(presenter.order_info.send(:chargeable)).to eq(chargeable) expect(presenter.order_info.send(:address_fields)).to eq(address_fields) expect(presenter.order_info.send(:additional_notes)).to eq(additional_notes) expect(presenter.order_info.send(:business_vat_id)).to eq(business_vat_id) end it "includes sales tax breakdown for Canada", :vcr do product = create(:product, price_cents: 100_00, native_type: "digital") purchase1 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "AB", ip_country: "Canada") purchase2 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "BC", ip_country: "Canada") purchase3 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "QC", ip_country: "Canada") Purchase.in_progress.find_each do |purchase| purchase.chargeable = create(:chargeable) purchase.process! purchase.update_balance_and_mark_successful! end presenter = described_class.new(purchase1.reload, address_fields:, additional_notes:, business_vat_id: nil) expect(presenter.order_info.form_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "Sales tax")) expect(presenter.order_info.pdf_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(purchase2.reload, address_fields:, additional_notes:, business_vat_id: nil) expect(presenter.order_info.form_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.form_attributes).to include({ label: "PST", value: "$7" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "Sales tax")) expect(presenter.order_info.pdf_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.pdf_attributes).to include({ label: "PST", value: "$7" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(purchase3.reload, address_fields:, additional_notes:, business_vat_id: nil) expect(presenter.order_info.form_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.form_attributes).to include({ label: "QST", value: "$9.98" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "Sales tax")) expect(presenter.order_info.pdf_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.pdf_attributes).to include({ label: "QST", value: "$9.98" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "Sales tax")) end end describe "#invoice_generation_props" do it "returns the correct props structure" do props = presenter.invoice_generation_props expect(props).to match( form_info: be_a(Hash), supplier_info: be_a(Hash), seller_info: be_a(Hash), order_info: be_a(Hash), id: chargeable.external_id_for_invoice, email: purchase.email, countries: be_a(Hash), ) expect(props[:form_info]).to match( heading: be_a(String), display_vat_id: be_in([true, false]), vat_id_label: be_a(String), data: be_a(Hash) ) expect(props[:supplier_info]).to match( heading: be_a(String), attributes: be_an(Array) ) expect(props[:seller_info]).to match( heading: be_a(String), attributes: be_an(Array) ) expect(props[:order_info]).to match( heading: be_a(String), pdf_attributes: be_an(Array), form_attributes: be_an(Array), invoice_date_attribute: be_a(Hash) ) expect(props[:id]).to eq(chargeable.external_id_for_invoice) expect(props[:countries]).to eq(Compliance::Countries.for_select.to_h) expect(props[:email]).to eq(purchase.email) end end end describe "For Charge" do let(:charge) { create(:charge, purchases: [purchase], order: create(:order, purchaser: purchase.purchaser, purchases: [purchase])) } let(:chargeable) { charge } describe "#supplier_info" do it "returns a SupplierInfo object" do expect(presenter.supplier_info).to be_a(InvoicePresenter::SupplierInfo) expect(presenter.supplier_info.send(:chargeable)).to eq(chargeable) end end describe "#seller_info" do it "returns a SellerInfo object" do expect(presenter.seller_info).to be_a(InvoicePresenter::SellerInfo) expect(presenter.seller_info.send(:chargeable)).to eq(chargeable) end end describe "#order_info" do let(:additional_notes) { "Additional notes" } let(:business_vat_id) { "VAT12345" } let(:presenter) { described_class.new(chargeable, address_fields:, additional_notes:, business_vat_id:) } it "returns an OrderInfo object" do expect(presenter.order_info).to be_a(InvoicePresenter::OrderInfo) expect(presenter.order_info.send(:chargeable)).to eq(chargeable) expect(presenter.order_info.send(:address_fields)).to eq(address_fields) expect(presenter.order_info.send(:additional_notes)).to eq(additional_notes) expect(presenter.order_info.send(:business_vat_id)).to eq(business_vat_id) end it "includes sales tax breakdown for Canada", :vcr do product = create(:product, price_cents: 100_00, native_type: "digital") purchase1 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "AB", ip_country: "Canada") charge1 = create(:charge) charge1.purchases << purchase1 purchase2 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "BC", ip_country: "Canada") charge2 = create(:charge) charge2.purchases << purchase2 purchase3 = create(:purchase_in_progress, link: product, was_product_recommended: true, recommended_by: "search", country: "Canada", state: "QC", ip_country: "Canada") charge3 = create(:charge) charge3.purchases << purchase3 order = create(:order) order.charges << [charge1, charge2, charge3] order.purchases << [purchase1, purchase2, purchase3] Purchase.in_progress.find_each do |purchase| purchase.chargeable = create(:chargeable) purchase.process! purchase.update_balance_and_mark_successful! end presenter = described_class.new(charge1.reload, address_fields:, additional_notes:, business_vat_id: nil) expect(presenter.order_info.form_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "Sales tax")) expect(presenter.order_info.pdf_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(charge2.reload, address_fields:, additional_notes:, business_vat_id: nil) expect(presenter.order_info.form_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.form_attributes).to include({ label: "PST", value: "$7" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "Sales tax")) expect(presenter.order_info.pdf_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.pdf_attributes).to include({ label: "PST", value: "$7" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "QST")) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "Sales tax")) presenter = described_class.new(charge3.reload, address_fields:, additional_notes:, business_vat_id: nil) expect(presenter.order_info.form_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.form_attributes).to include({ label: "QST", value: "$9.98" }) expect(presenter.order_info.form_attributes).not_to include(hash_including(label: "Sales tax")) expect(presenter.order_info.pdf_attributes).to include({ label: "GST/HST", value: "$5" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "PST")) expect(presenter.order_info.pdf_attributes).to include({ label: "QST", value: "$9.98" }) expect(presenter.order_info.pdf_attributes).not_to include(hash_including(label: "Sales tax")) end end describe "#invoice_generation_props" do it "returns the correct props structure" do props = presenter.invoice_generation_props expect(props).to include( form_info: be_a(Hash), supplier_info: be_a(Hash), seller_info: be_a(Hash), order_info: be_a(Hash), id: chargeable.external_id_for_invoice, email: purchase.email, countries: be_a(Hash), ) expect(props[:form_info]).to match( heading: be_a(String), display_vat_id: be_in([true, false]), vat_id_label: be_a(String), data: be_a(Hash) ) expect(props[:supplier_info]).to match( heading: be_a(String), attributes: be_an(Array) ) expect(props[:seller_info]).to match( heading: be_a(String), attributes: be_an(Array) ) expect(props[:order_info]).to match( heading: be_a(String), pdf_attributes: be_an(Array), form_attributes: be_an(Array), invoice_date_attribute: be_a(Hash) ) expect(props[:id]).to eq(chargeable.external_id_for_invoice) expect(props[:countries]).to eq(Compliance::Countries.for_select.to_h) expect(props[:email]).to eq(purchase.email) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/profile_sections_presenter_spec.rb
spec/presenters/profile_sections_presenter_spec.rb
# frozen_string_literal: true describe ProfileSectionsPresenter do let(:seller) { create(:named_seller, bio: "Bio") } let(:logged_in_user) { create(:user) } let(:request) { ActionDispatch::TestRequest.create } let(:pundit_user) { SellerContext.new(user: logged_in_user, seller: logged_in_user) } let(:pundit_user_seller) { SellerContext.new(user: seller, seller:) } let(:tags) { create_list(:tag, 2) } let!(:products) { create_list(:product, 2, user: seller, tags:) } let!(:seller_post) { create(:seller_installment, seller:, shown_on_profile: true, published_at: 1.day.ago) } let!(:posts) { build_list(:published_installment, 2, installment_type: Installment::AUDIENCE_TYPE, seller:, shown_on_profile: true) { |p, i| p.update!(published_at: p.published_at - i.days) } } let!(:wishlists) { create_list(:wishlist, 2, user: seller) } let(:products_section) { create(:seller_profile_products_section, seller:, header: "Section!", shown_products: products.map(&:id)) } let(:posts_section) { create(:seller_profile_posts_section, seller:, header: "Section!", shown_posts: posts.map(&:id)) } let(:featured_product_section) { create(:seller_profile_featured_product_section, seller:, header: "Section!", featured_product_id: products.first.id) } let(:rich_text_section) { create(:seller_profile_rich_text_section, seller:, header: "Section!", text: { something: "thing" }) } let(:subscribe_section) { create(:seller_profile_subscribe_section, seller:, header: "Section!", hide_header: true) } let(:wishlists_section) { create(:seller_profile_wishlists_section, seller:, header: "Section!", shown_wishlists: wishlists.map(&:id)) } let!(:sections) { [products_section, posts_section, featured_product_section, rich_text_section, subscribe_section, wishlists_section] } let!(:extra_section) { create(:seller_profile_products_section, seller:) } subject { described_class.new(seller:, query: seller.seller_profile_sections.where(id: sections.map(&:id))) } before do Link.import(force: true, refresh: true) end def common_props(section) { id: section.external_id, type: section.type, header: section.header } end def cached_sections_props [ { **common_props(products_section), default_product_sort: "page_layout", search_results: { total: 2, filetypes_data: [], tags_data: a_collection_containing_exactly(*tags.map { { "doc_count" => 2, "key" => _1.name } }), products: products.map { _1.id.to_s } }, show_filters: false, }, common_props(posts_section), { **common_props(featured_product_section), featured_product_id: products.first.external_id }, { **common_props(rich_text_section), text: rich_text_section.text }, { **common_props(subscribe_section), header: nil, button_label: subscribe_section.button_label }, { **common_props(wishlists_section), shown_wishlists: wishlists.map(&:external_id) } ] end describe "#cached_sections" do it "returns the cached array of sections for the given query" do expect(subject.cached_sections).to match(cached_sections_props) end end describe "#props" do def common_sections_props sections = cached_sections_props sections[0][:search_results][:products] = products.map do |product| ProductPresenter.card_for_web(product:, request:, target: Product::Layout::PROFILE, show_seller: false, compute_description: false) end sections end def post_data(post) { id: post.external_id, name: post.name, slug: post.slug, published_at: post.published_at, } end it "returns the correct props for the seller" do sections = common_sections_props sections[0].merge!({ hide_header: false, shown_products: products.map(&:external_id), add_new_products: true }) sections[1].merge!({ shown_posts: posts.map(&:external_id), hide_header: false }) sections[2].merge!({ hide_header: false }) sections[3].merge!({ hide_header: false }) sections[4].merge!({ hide_header: true, header: subscribe_section.header }) sections[5].merge!(hide_header: false, wishlists: WishlistPresenter.cards_props(wishlists: Wishlist.where(id: wishlists.map(&:id)), pundit_user: pundit_user_seller, layout: Product::Layout::PROFILE)) expect(subject.props(request:, pundit_user: pundit_user_seller, seller_custom_domain_url: nil)).to match({ currency_code: pundit_user_seller.user.currency_type, show_ratings_filter: true, creator_profile: ProfilePresenter.new(seller:, pundit_user: pundit_user_seller).creator_profile, products: products.map { { id: ObfuscateIds.encrypt(_1.id), name: _1.name } }, posts: posts.map(&method(:post_data)), wishlist_options: wishlists.map { { id: _1.external_id, name: _1.name } }, sections:, }) end it "returns the correct props for another user" do sections = common_sections_props sections[1][:posts] = posts.map(&method(:post_data)) sections[2][:props] = ProductPresenter.new(product: products.first, request:, pundit_user:).product_props(seller_custom_domain_url: nil) sections[2].delete(:featured_product_id) sections[5].merge!(wishlists: WishlistPresenter.cards_props(wishlists: Wishlist.where(id: wishlists.map(&:id)), pundit_user: pundit_user, layout: Product::Layout::PROFILE)) expect(subject.props(request:, pundit_user:, seller_custom_domain_url: nil)).to match({ currency_code: pundit_user.user.currency_type, show_ratings_filter: true, creator_profile: ProfilePresenter.new(seller:, pundit_user:).creator_profile, sections: }) end end describe "compute_description parameter" do it "passes compute_description: false to ProductPresenter.card_for_web for search results" do request.query_parameters[:sort] = "recent" expect(ProductPresenter).to receive(:card_for_web).with( product: products.first, request: request, recommended_by: nil, target: Product::Layout::PROFILE, show_seller: false, compute_description: false ).and_call_original expect(ProductPresenter).to receive(:card_for_web).with( product: products.second, request: request, recommended_by: nil, target: Product::Layout::PROFILE, show_seller: false, compute_description: false ).and_call_original subject.props(request:, pundit_user:, seller_custom_domain_url: nil) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/url_redirect_presenter_spec.rb
spec/presenters/url_redirect_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe UrlRedirectPresenter do include Rails.application.routes.url_helpers describe "#download_attributes" do it "returns all necessary attributes for the download page" do allow_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/4768692737035/bb69798a4a694e19a0976390a7e40e6b/original/chapter1.srt?X-Amz-Signature=test") product = create(:product) folder = create(:product_folder, link: product, name: "Folder") file = create(:streamable_video, link: product) folder_file = create(:readable_document, link: product, display_name: "Display Name", description: "Description", folder_id: folder.id, pagelength: 3, size: 50) subtitle_file = create(:subtitle_file, product_file: file) purchase = create(:purchase, link: product) url_redirect = create(:url_redirect, purchase:) user = create(:user) file_media_location = create(:media_location, url_redirect_id: url_redirect.id, purchase_id: purchase.id, product_file_id: file.id, product_id: product.id, location: 3) folder_file_media_location = create(:media_location, url_redirect_id: url_redirect.id, purchase_id: purchase.id, product_file_id: folder_file.id, product_id: product.id, location: 2) instance = described_class.new(url_redirect:, logged_in_user: user) expect(instance.download_attributes).to eq(content_items: [{ type: "folder", id: folder.external_id, name: folder.name, children: [{ type: "file", extension: "PDF", file_name: "Display Name", description: "Description", file_size: 50, isbn: nil, id: folder_file.external_id, pagelength: 3, duration: nil, subtitle_files: [], download_url: url_redirect_download_product_files_path(url_redirect.token, { product_file_ids: [folder_file.external_id] }), stream_url: nil, kindle_data: { email: user.kindle_email, icon_url: ActionController::Base.helpers.asset_path("white-15.png") }, read_url: url_redirect_read_for_product_file_path(url_redirect.token, folder_file.external_id), latest_media_location: folder_file_media_location.as_json, content_length: folder_file.content_length, external_link_url: nil, pdf_stamp_enabled: false, processing: false, thumbnail_url: nil, }] }, { type: "file", extension: "MOV", file_name: "ScreenRecording", description: nil, file_size: nil, id: file.external_id, pagelength: nil, duration: nil, isbn: nil, subtitle_files: [ url: subtitle_file.url, file_name: subtitle_file.s3_display_name, extension: subtitle_file.s3_display_extension, language: subtitle_file.language, file_size: subtitle_file.size, download_url: url_redirect_download_subtitle_file_path(url_redirect.token, file.external_id, subtitle_file.external_id), signed_url: file.signed_download_url_for_s3_key_and_filename(subtitle_file.s3_key, subtitle_file.s3_display_name, is_video: true), ], download_url: url_redirect_download_product_files_path(url_redirect.token, { product_file_ids: [file.external_id] }), stream_url: url_redirect_stream_page_for_product_file_path(url_redirect.token, file.external_id), kindle_data: nil, read_url: nil, latest_media_location: file_media_location.as_json, content_length: file.content_length, external_link_url: nil, pdf_stamp_enabled: false, processing: false, thumbnail_url: nil, }]) end it "omits empty folders" do product = create(:product) folder_one = create(:product_folder, link: product, name: "Folder 1") create(:product_folder, link: product, name: "Empty folder") create(:readable_document, link: product, display_name: "File in Folder 1", folder_id: folder_one.id) purchase = create(:purchase, link: product) url_redirect = create(:url_redirect, purchase:) user = create(:user) instance = described_class.new(url_redirect:, logged_in_user: user) content_items = instance.download_attributes[:content_items] expect(content_items.length).to eq(1) item_one = content_items[0] expect(item_one[:type]).to eq("folder") expect(item_one[:name]).to eq("Folder 1") expect(item_one[:children].length).to eq(1) expect(item_one[:children][0][:file_name]).to eq("File in Folder 1") end it "includes thumbnail_url for product files that have thumbnails" do product = create(:product) file = create(:streamable_video, link: product) file.thumbnail.attach(io: File.open(Rails.root.join("spec", "support", "fixtures", "smilie.png")), filename: "smilie.png") purchase = create(:purchase, link: product) url_redirect = create(:url_redirect, purchase:) user = create(:user) instance = described_class.new(url_redirect:, logged_in_user: user) content_items = instance.download_attributes[:content_items] expect(content_items.length).to eq(1) expect(content_items.first[:thumbnail_url]).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{file.thumbnail_variant.key}") end end describe "#download_page_with_content_props" do before do @user = create(:user, name: "John Doe") @product = create(:product, user: @user) @purchase = create(:purchase, link: @product, is_bundle_product_purchase: true) create(:bundle_product_purchase, product_purchase: @purchase, bundle_purchase: create(:purchase, link: @product, seller: @user)) @installment = create(:seller_installment, seller: @product.user, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) @url_redirect = create(:url_redirect, purchase: @purchase) @props = { content: { license: nil, rich_content_pages: nil, content_items: [], posts: [], video_transcoding_info: nil, custom_receipt: nil, discord: nil, community_chat_url: nil, download_all_button: nil, ios_app_url: IOS_APP_STORE_URL, android_app_url: ANDROID_APP_STORE_URL, }, terms_page_url: HomePageLinkService.terms, token: @url_redirect.token, redirect_id: @url_redirect.external_id, creator: { name: "John Doe", profile_url: @user.profile_url(recommended_by: "library"), avatar_url: @user.avatar_url, }, product_has_third_party_analytics: false, installment: nil, purchase: { id: @purchase.external_id, bundle_purchase_id: @purchase.bundle_purchase.external_id, created_at: @purchase.created_at, email: @purchase.email, email_digest: @purchase.email_digest, is_archived: false, product_long_url: @product.long_url, product_id: @product.external_id, product_name: @product.name, variant_id: nil, variant_name: nil, product_permalink: @product.unique_permalink, allows_review: true, disable_reviews_after_year: false, review: nil, membership: nil, purchase_custom_fields: [], call: nil, }, } end it "returns all props for DownloadPageWithContent component" do instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) @props[:content][:posts] = [{ id: @installment.external_id, name: @installment.displayed_name, action_at: @installment.action_at_for_purchases([@purchase.id]), view_url: custom_domain_view_post_url( username: @installment.user.username, slug: @installment.slug, purchase_id: @purchase.external_id, host: @user.subdomain, protocol: PROTOCOL ) }] expect(instance.download_page_with_content_props).to eq(@props) end it "includes 'custom_receipt' in props" do @product.update!(custom_receipt: "Lorem ipsum <b>dolor</b> sit amet https://example.com") instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:custom_receipt]).to be_nil end it "includes 'discord' in props" do integration = create(:discord_integration) @product.active_integrations << integration instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:discord]).to eq(connected: false) create(:discord_purchase_integration, integration:, purchase: @purchase) expect(instance.download_page_with_content_props[:content][:discord]).to eq(connected: true) end it "includes 'download_all_button' in props for installments with files" do freeze_time do installment = create(:installment, link: @product) url_redirect = create(:url_redirect, installment:) instance = described_class.new(url_redirect:, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:download_all_button]).to be_nil file1 = create(:readable_document) file2 = create(:streamable_video) installment.product_files = [file1, file2] installment.save! url_redirect = create(:url_redirect, installment:) instance = described_class.new(url_redirect:, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:download_all_button]).to be_nil installment.product_files_archives.create!(product_files: installment.product_files, product_files_archive_state: "ready") url_redirect = create(:url_redirect, installment:) instance = described_class.new(url_redirect:, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:download_all_button]).to eq( files: [ { "filename" => file1.s3_filename, "url" => url_redirect.signed_location_for_file(file1) }, { "filename" => file2.s3_filename, "url" => url_redirect.signed_location_for_file(file2) } ] ) end end it "returns nil for `download_all_button` when the URL redirect is not for an installment" do file1 = create(:readable_document) file2 = create(:streamable_video) @product.product_files = [file1, file2] @product.product_files_archives.create!(product_files: @product.product_files, folder_id: SecureRandom.uuid, product_files_archive_state: "ready") instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:download_all_button]).to be_nil end it "includes 'creator' in props" do @user.update!(name: "John Doe") instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) expect(instance.download_page_with_content_props[:creator]).to eq( name: "John Doe", profile_url: @user.profile_url(recommended_by: "library"), avatar_url: @user.avatar_url, ) end it "includes 'membership' in props" do product = create(:membership_product) subscription = create(:subscription, link: product) purchase = create(:purchase, link: product, email: subscription.user.email, is_original_subscription_purchase: true, subscription:, created_at: 2.days.ago) url_redirect = create(:url_redirect, purchase:, link: product) instance = described_class.new(url_redirect:, logged_in_user: @user) expect(instance.download_page_with_content_props[:purchase][:membership]).to eq( has_active_subscription: true, subscription_id: subscription.external_id, is_subscription_ended: false, is_installment_plan_completed: false, is_subscription_cancelled_or_failed: false, is_alive_or_restartable: true, in_free_trial: false, is_installment_plan: false, ) end it "includes rich content in props" do product_content = [{ "content" => [{ "type" => "text", "text" => "Hello" }], "type" => "paragraph" }] rich_content = create(:rich_content, entity: @product, title: "Page title", description: product_content) instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) @props[:content][:rich_content_pages] = [{ id: rich_content.external_id, page_id: rich_content.external_id, variant_id: nil, title: "Page title", description: { content: product_content, type: "doc" }, updated_at: rich_content.updated_at }] expect(instance.download_page_with_content_props).to eq(@props) end describe "'posts' in props" do context "when rich content is present" do context "when rich content contains a 'posts' embed" do before do create(:rich_content, entity: @product, title: "Page title", description: [{ "type" => "posts" }]) end it "includes 'posts' in props" do instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) expect(instance.download_page_with_content_props.dig(:content, :posts).size).to eq(1) end end context "when rich content does not contain a 'posts' embed" do before do create(:rich_content, entity: @product, title: "Page title", description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }]) end it "include empty 'posts' in props" do instance = described_class.new(url_redirect: @url_redirect, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:posts].size).to eq(0) end end end it "includes 'posts' in props for an installment URL redirect" do original_purchase = create(:membership_purchase, purchaser: @user, email: @user.email, is_archived_original_subscription_purchase: true) updated_original_purchase = create(:membership_purchase, purchaser: @user, email: @user.email, purchase_state: "not_charged", subscription: original_purchase.subscription, link: original_purchase.link) post = create(:installment, link: original_purchase.link, published_at: 1.day.ago) create(:creator_contacting_customers_email_info_sent, purchase: updated_original_purchase, installment: post) url_redirect = create(:url_redirect, purchase: original_purchase) instance = described_class.new(url_redirect: url_redirect, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:posts].sole[:id]).to eq(post.external_id) end end it "includes license in props" do product = create(:membership_product, is_licensed: true) purchase = create(:membership_purchase, :with_license, link: product) url_redirect = create(:url_redirect, purchase:) instance = described_class.new(url_redirect:, logged_in_user: @user) expect(instance.download_page_with_content_props[:content][:license]).to eq({ license_key: purchase.license_key, is_multiseat_license: false, seats: 1 }) end describe "video_transcoding_info" do let(:logged_in_user) { @user } let(:presenter) { described_class.new(url_redirect: @url_redirect, logged_in_user:) } context "when rich content is not present" do it "returns nil" do expect(presenter.download_page_with_content_props[:content][:video_transcoding_info]).to be_nil end end context "when rich content does not contain any video embeds" do before do file = create(:readable_document, link: @product) product_content = [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }, { "type" => "fileEmbed", "attrs" => { "id" => file.external_id, "uid" => SecureRandom.uuid } } ] create(:rich_content, entity: @product, description: product_content) end it "returns nil" do expect(presenter.download_page_with_content_props[:content][:video_transcoding_info]).to be_nil end end context "when the rich content contains video embeds" do let(:video1) { create(:streamable_video, link: @product) } let(:video2) { create(:streamable_video, link: @product) } before do product_content = [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }, { "type" => "fileEmbed", "attrs" => { "id" => video1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => video2.external_id, "uid" => SecureRandom.uuid } } ] create(:rich_content, entity: @product, description: product_content) end context "when logged in user is not the seller" do let(:logged_in_user) { create(:user) } it "returns nil" do expect(presenter.download_page_with_content_props[:content][:video_transcoding_info]).to be_nil end end context "when all videos are transcoded" do before do create(:transcoded_video, streamable: video1, is_hls: true) create(:transcoded_video, streamable: video2, is_hls: true) end it "returns nil" do expect(presenter.download_page_with_content_props[:content][:video_transcoding_info]).to be_nil end end context "when all videos are not transcoded" do before do create(:transcoded_video, streamable: video1, is_hls: true) end context "when videos are set to transcode on first sale" do before do @product.update!(transcode_videos_on_purchase: true) end it "returns the video transcoding info" do expect(presenter.download_page_with_content_props[:content][:video_transcoding_info]).to eq(transcode_on_first_sale: true) end end context "when videos are not set to transcode on first sale" do it "returns the video transcoding info" do expect(presenter.download_page_with_content_props[:content][:video_transcoding_info]).to eq(transcode_on_first_sale: false) end end end end end context "when associated with a completed commission", :vcr do let(:commission) { create(:commission, status: Commission::STATUS_COMPLETED) } let(:presenter) { described_class.new(url_redirect: commission.deposit_purchase.url_redirect) } before do commission.files.attach(file_fixture("smilie.png")) commission.files.attach(file_fixture("test.pdf")) commission.deposit_purchase.create_url_redirect! end it "includes commission files in the rich content json" do expect(presenter.download_page_with_content_props[:content][:content_items]).to contain_exactly( { type: "file", file_name: "smilie", description: nil, extension: "PNG", file_size: 100406, pagelength: nil, duration: nil, id: commission.files.first.signed_id, download_url: commission.files.first.blob.url, stream_url: nil, kindle_data: nil, latest_media_location: nil, content_length: nil, read_url: nil, external_link_url: nil, subtitle_files: [], pdf_stamp_enabled: false, processing: false, thumbnail_url: nil }, { type: "file", file_name: "test", description: nil, extension: "PDF", file_size: 8278, pagelength: nil, duration: nil, id: commission.files.second.signed_id, download_url: commission.files.second.blob.url, stream_url: nil, kindle_data: nil, latest_media_location: nil, content_length: nil, read_url: nil, external_link_url: nil, subtitle_files: [], pdf_stamp_enabled: false, processing: false, thumbnail_url: nil } ) end context "when the commission is not completed" do before { commission.update(status: Commission::STATUS_IN_PROGRESS) } it "does not include commission files" do expect(presenter.download_page_with_content_props[:content][:content_items]).to eq([]) end end end context "community_chat_url prop" do let(:product) { create(:product) } let(:purchase) { create(:purchase, link: product, purchaser: @user) } let(:url_redirect) { create(:url_redirect, purchase:) } let(:presenter) { described_class.new(url_redirect:, logged_in_user: @user) } it "returns nil when purchase is not present" do url_redirect = create(:url_redirect, purchase: nil) presenter = described_class.new(url_redirect:, logged_in_user: @user) expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to be_nil end it "returns nil when communities feature is not active for seller" do expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to be_nil end context "when communities feature is active for seller" do before do Feature.activate_user(:communities, product.user) end it "returns nil when community chat is not enabled for product" do expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to be_nil end context "when community chat is enabled for product" do before do product.update!(community_chat_enabled: true) end it "returns nil when product has no active community" do expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to be_nil end it "returns nil when purchase has no purchaser_id" do purchase.update!(purchaser_id: nil) expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to be_nil end it "returns community path when product has an active community" do community = create(:community, seller: product.user, resource: product) expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to eq(community_path(product.user.external_id, community.external_id)) end context "when user is not logged in" do let(:presenter) { described_class.new(url_redirect:, logged_in_user: nil) } it "returns login path with next parameter when user is not logged in" do community = create(:community, seller: product.user, resource: product) expected_path = login_path(email: purchase.email, next: community_path(product.user.external_id, community.external_id)) expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to eq(expected_path) end end context "when purchase has no purchaser_id" do before do purchase.update!(purchaser_id: nil) end it "returns signup path with next parameter" do community = create(:community, seller: product.user, resource: product) expected_path = signup_path(email: purchase.email, next: community_path(product.user.external_id, community.external_id)) expect(presenter.download_page_with_content_props[:content][:community_chat_url]).to eq(expected_path) end end end end end end describe "#download_page_without_content_props" do before do @user = create(:user, name: "John Doe", disable_reviews_after_year: true) @product = create(:membership_product, user: @user) @subscription = create(:subscription, link: @product) @purchase = create(:purchase, link: @product, email: @subscription.user.email, is_original_subscription_purchase: true, subscription: @subscription, created_at: 2.days.ago) @url_redirect = create(:url_redirect, purchase: @purchase, link: @product) @custom_field = create(:custom_field, products: [@product], field_type: CustomField::TYPE_TEXT, is_post_purchase: true) @file_custom_field = create(:custom_field, products: [@product], field_type: CustomField::TYPE_FILE, is_post_purchase: true) @purchase.purchase_custom_fields << PurchaseCustomField.build_from_custom_field(custom_field: @custom_field, value: "Hello") file_custom_field = PurchaseCustomField.build_from_custom_field(custom_field: @file_custom_field, value: nil) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png") file_custom_field.files.attach(blob) @purchase.purchase_custom_fields << file_custom_field end it "returns the correct props" do expect(described_class.new(url_redirect: @url_redirect, logged_in_user: @user).download_page_without_content_props).to eq( creator: { name: "John Doe", profile_url: @user.profile_url(recommended_by: "library"), avatar_url: @user.avatar_url, }, terms_page_url: HomePageLinkService.terms, token: @url_redirect.token, redirect_id: @url_redirect.external_id, installment: nil, purchase: { id: @purchase.external_id, bundle_purchase_id: nil, created_at: @purchase.created_at, email: @purchase.email, email_digest: @purchase.email_digest, is_archived: false, product_id: @product.external_id, product_name: @product.name, variant_id: nil, variant_name: nil, product_permalink: @product.unique_permalink, product_long_url: @product.long_url, allows_review: true, disable_reviews_after_year: true, review: nil, membership: { has_active_subscription: true, subscription_id: @subscription.external_id, is_subscription_ended: false, is_installment_plan_completed: false, is_subscription_cancelled_or_failed: false, is_alive_or_restartable: true, in_free_trial: false, is_installment_plan: false, }, purchase_custom_fields: [ { type: "shortAnswer", custom_field_id: @custom_field.external_id, value: "Hello", }, { custom_field_id: @file_custom_field.external_id, type: "fileUpload", files: [ { name: "smilie", size: 100_406, extension: "PNG" } ] } ], call: nil, }, ) end context "when the purchase is a call purchase" do let!(:call) { create(:call) } before { call.purchase.create_url_redirect! } it "includes the call in the props" do expect(described_class.new(url_redirect: call.purchase.url_redirect).download_page_without_content_props[:purchase][:call]).to eq( { url: "https://zoom.us/j/gmrd", start_time: call.start_time, end_time: call.end_time, } ) end context "when the call has no url" do before { call.update!(call_url: nil) } it "does not include the url in the props" do expect(described_class.new(url_redirect: call.purchase.url_redirect).download_page_without_content_props[:purchase][:call][:url]).to be_nil end end end it "does not include purchase email when the email confirmation is required" do props = described_class.new(url_redirect: @url_redirect, logged_in_user: @user).download_page_without_content_props(content_unavailability_reason_code: UrlRedirectPresenter::CONTENT_UNAVAILABILITY_REASON_CODES[:email_confirmation_required]) expect(props[:purchase]).to include(email: nil) end it "includes 'installment' and correct 'creator' in props" do url_redirect = create(:installment_url_redirect, installment: create(:workflow_installment, name: "Thank you for the purchase!", link: nil, seller: @user, product_files: [create(:product_file)])) props = described_class.new(url_redirect:, logged_in_user: @user).download_page_without_content_props expect(props[:installment]).to eq(name: "Thank you for the purchase!") expect(props[:creator]).to eq( name: "John Doe",
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/bundle_presenter_spec.rb
spec/presenters/bundle_presenter_spec.rb
# frozen_string_literal: true describe BundlePresenter do include Rails.application.routes.url_helpers describe "#bundle_props" do let(:seller) { create(:named_seller, :eligible_for_service_products) } let(:product) { create(:product, user: seller) } let(:versioned_product) { create(:product_with_digital_versions, user: seller, quantity_enabled: true) } let(:bundle) do create(:product, :bundle, user: seller, name: "Bundle", description: "I am a bundle!", custom_permalink: "bundle", customizable_price: true, suggested_price_cents: 200, max_purchase_count: 50, quantity_enabled: true, should_show_sales_count: true, tag: "hi") end let!(:asset_previews) { create_list(:asset_preview, 2, link: bundle) } let!(:thumbnail) { create(:thumbnail, product: bundle) } let!(:refund_policy) { create(:product_refund_policy, product: bundle, seller:) } let!(:other_refund_policy) { create(:product_refund_policy, product: create(:product, user: seller, name: "Other product"), max_refund_period_in_days: 0, fine_print: "This is another refund policy") } before do create(:call_product, user: seller, name: "Call product does not count towards products_count") create(:product, user: seller, archived: true, name: "Archived product") bundle.save_custom_button_text_option("pay_prompt") bundle.save_custom_summary("To summarize, I am a bundle.") bundle.save_custom_attributes({ "Detail 1" => "Value 1" }) bundle.update(bundle_products: [ build(:bundle_product, product: versioned_product, variant: versioned_product.alive_variants.first, quantity: 2, position: 1), build(:bundle_product, product:, position: 0), ] ) end it "returns the correct props" do presenter = described_class.new(bundle:) profile_section = create(:seller_profile_products_section, seller:, shown_products: [bundle.id]) seller.reload expect(presenter.bundle_props).to eq( { bundle: { name: "Bundle", description: "I am a bundle!", custom_permalink: "bundle", price_cents: 100, customizable_price: true, suggested_price_cents: 200, **ProductPresenter::InstallmentPlanProps.new(product: presenter.bundle).props, custom_button_text_option: "pay_prompt", custom_summary: "To summarize, I am a bundle.", custom_attributes: { "Detail 1" => "Value 1" }, max_purchase_count: 50, quantity_enabled: true, should_show_sales_count: true, is_epublication: false, product_refund_policy_enabled: false, refund_policy: { allowed_refund_periods_in_days: [ { key: 0, value: "No refunds allowed" }, { key: 7, value: "7-day money back guarantee" }, { key: 14, value: "14-day money back guarantee" }, { key: 30, value: "30-day money back guarantee" }, { key: 183, value: "6-month money back guarantee" } ], title: "30-day money back guarantee", fine_print: "This is a product-level refund policy", fine_print_enabled: true, max_refund_period_in_days: 30, }, taxonomy_id: nil, tags: ["hi"], display_product_reviews: true, is_adult: false, discover_fee_per_thousand: 100, section_ids: [profile_section.external_id], is_published: true, covers: asset_previews.map(&:as_json), products: [ described_class.bundle_product( product:, quantity: 1, selected_variant_id: nil, ), described_class.bundle_product( product: versioned_product, quantity: 2, selected_variant_id: versioned_product.alive_variants.first.external_id, ), ], collaborating_user: nil, public_files: [], audio_previews_enabled: false, }, id: bundle.external_id, unique_permalink: bundle.unique_permalink, currency_type: "usd", products_count: 5, thumbnail: thumbnail.as_json, ratings: { count: 0, average: 0, percentages: [0, 0, 0, 0, 0], }, sales_count_for_inventory: 0, taxonomies: Discover::TaxonomyPresenter.new.taxonomies_for_nav, profile_sections: [ { id: profile_section.external_id, header: "", product_names: ["Bundle"], default: true, } ], refund_policies: [ { id: other_refund_policy.external_id, title: "No refunds allowed", fine_print: "This is another refund policy", product_name: "Other product", max_refund_period_in_days: 0, } ], seller_refund_policy_enabled: true, seller_refund_policy: { title: "30-day money back guarantee", fine_print: nil, }, is_bundle: true, has_outdated_purchases: false, } ) end context "with public files" do let!(:public_file1) { create(:public_file, :with_audio, resource: bundle) } let!(:public_file2) { create(:public_file, resource: bundle) } let!(:public_file3) { create(:public_file, :with_audio, deleted_at: 1.day.ago) } before do Feature.activate_user(:audio_previews, bundle.user) public_file1.file.analyze end it "includes public files" do props = described_class.new(bundle:).bundle_props[:bundle] expect(props[:public_files].sole).to eq(PublicFilePresenter.new(public_file: public_file1).props) expect(props[:audio_previews_enabled]).to be(true) end end end describe ".bundle_product" do let(:product) { create(:product_with_digital_versions, quantity_enabled: true) } it "returns the correct props" do props = ProductPresenter.card_for_web(product:).merge({ is_quantity_enabled: true, price_cents: 100, quantity: 2, url: product.long_url, variants: { selected_id: product.alive_variants.first.external_id, list: [ { description: "", id: product.alive_variants.first.external_id, name: "Untitled 1", price_difference: 0 }, { description: "", id: product.alive_variants.second.external_id, name: "Untitled 2", price_difference: 0 } ], } }) expect(described_class.bundle_product(product:, quantity: 2, selected_variant_id: product.alive_variants.first.external_id)).to eq(props) end context "when the product has SKUs enabled" do before do product.update!(skus_enabled: true, skus: [build(:sku)]) end it "returns the correct props" do expect(described_class.bundle_product(product:)[:variants]).to eq( { list: [ { description: "", id: product.skus.first.external_id, name: "Large", price_difference: 0, } ], selected_id: product.skus.first.external_id, } ) end end context "product is not a bundle" do let(:product) { create(:product) } it "sets is_bundle to false" do expect(described_class.new(bundle: product).bundle_props[:is_bundle]).to eq(false) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/workflow_presenter_spec.rb
spec/presenters/workflow_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/with_workflow_form_context" describe WorkflowPresenter do let(:seller) { create(:named_seller) } describe "#new_page_react_props" do it_behaves_like "with workflow form 'context' in response" do let(:user) { seller } let(:result) { described_class.new(seller:).new_page_react_props } end end describe "#edit_page_react_props" do it_behaves_like "with workflow form 'context' in response" do let(:user) { seller } let(:result) { described_class.new(seller:, workflow: create(:workflow, link: nil, seller:, workflow_type: Workflow::SELLER_TYPE)).edit_page_react_props } end it "returns the 'workflow' in response" do workflow = create(:workflow, seller:) props = described_class.new(seller:, workflow:).edit_page_react_props expect(props[:workflow]).to be_present end end describe "#workflow_props" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:workflow) { create(:workflow, seller:, link: product) } it "includes the necessary workflow details" do props = described_class.new(seller:, workflow:).workflow_props expect(props).to match(a_hash_including( name: "my workflow", external_id: workflow.external_id, workflow_type: "product", workflow_trigger: nil, recipient_name: "The Works of Edgar Gumstein", published: false, first_published_at: nil, send_to_past_customers: false )) expect(props.keys).to_not include(:abandoned_cart_products, :seller_has_products) end it "includes 'abandoned_cart_products' for an abandoned cart workflow" do workflow.update!(workflow_type: Workflow::ABANDONED_CART_TYPE) presenter = described_class.new(seller:, workflow:) expect(presenter.workflow_props).to include(abandoned_cart_products: workflow.abandoned_cart_products) end it "includes 'seller_has_products' for an abandoned cart workflow" do workflow.update!(workflow_type: Workflow::ABANDONED_CART_TYPE) presenter = described_class.new(seller:, workflow:) expect(presenter.workflow_props).to include(seller_has_products: true) end context "when the workflow is published" do before do workflow.update!(published_at: DateTime.current, first_published_at: 2.days.ago, send_to_past_customers: true) end it "includes the necessary workflow details" do props = described_class.new(seller:, workflow:).workflow_props expect(props).to match(a_hash_including( name: "my workflow", external_id: workflow.external_id, workflow_type: "product", workflow_trigger: nil, recipient_name: "The Works of Edgar Gumstein", published: true, first_published_at: be_present, send_to_past_customers: true )) end end context "when the workflow has installments" do let(:installment1) { create(:installment, link: product, workflow:, published_at: 1.day.ago, name: "1 day") } let(:installment2) { create(:installment, link: product, workflow:, published_at: Time.current, name: "5 hours") } let(:installment3) { create(:installment, link: product, workflow:, published_at: Time.current, name: "1 hour") } before do create(:installment_rule, installment: installment1, delayed_delivery_time: 1.day) create(:installment_rule, installment: installment2, delayed_delivery_time: 5.hours) create(:installment_rule, installment: installment3, delayed_delivery_time: 1.hour) end it "returns installments in order of which ones will be delivered first" do props = described_class.new(seller:, workflow:).workflow_props expect(props[:installments]).to eq([ { name: "1 hour", message: installment3.message, files: [], published_at: installment3.published_at, updated_at: installment3.updated_at, published_once_already: true, member_cancellation: false, external_id: installment3.external_id, stream_only: false, call_to_action_text: nil, call_to_action_url: nil, new_customers_only: false, streamable: false, sent_count: nil, click_count: 0, open_count: 0, click_rate: nil, open_rate: nil, send_emails: true, shown_on_profile: false, installment_type: "product", paid_more_than_cents: nil, paid_less_than_cents: nil, allow_comments: true, display_type: "published", unique_permalink: product.unique_permalink, delayed_delivery_time_duration: 1, delayed_delivery_time_period: "hour", displayed_delayed_delivery_time_period: "Hour" }, { name: "5 hours", message: installment2.message, files: [], published_at: installment2.published_at, updated_at: installment2.updated_at, published_once_already: true, member_cancellation: false, external_id: installment2.external_id, stream_only: false, call_to_action_text: nil, call_to_action_url: nil, new_customers_only: false, streamable: false, sent_count: nil, click_count: 0, open_count: 0, click_rate: nil, open_rate: nil, send_emails: true, shown_on_profile: false, installment_type: "product", paid_more_than_cents: nil, paid_less_than_cents: nil, allow_comments: true, display_type: "published", unique_permalink: product.unique_permalink, delayed_delivery_time_duration: 5, delayed_delivery_time_period: "hour", displayed_delayed_delivery_time_period: "Hours" }, { name: "1 day", message: installment1.message, files: [], published_at: installment1.published_at, updated_at: installment1.updated_at, published_once_already: true, member_cancellation: false, external_id: installment1.external_id, stream_only: false, call_to_action_text: nil, call_to_action_url: nil, new_customers_only: false, streamable: false, sent_count: nil, click_count: 0, open_count: 0, click_rate: nil, open_rate: nil, send_emails: true, shown_on_profile: false, installment_type: "product", paid_more_than_cents: nil, paid_less_than_cents: nil, allow_comments: true, display_type: "published", unique_permalink: product.unique_permalink, delayed_delivery_time_duration: 24, delayed_delivery_time_period: "hour", displayed_delayed_delivery_time_period: "Hours" } ]) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/community_presenter_spec.rb
spec/presenters/community_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe CommunityPresenter do let(:seller) { create(:named_seller) } let(:buyer) { create(:user) } let(:community) { create(:community, seller:) } let(:presenter) { described_class.new(community:, current_user: buyer) } describe "#props" do subject(:props) { presenter.props } it "returns appropriate props" do expect(props).to eq( id: community.external_id, name: community.name, thumbnail_url: community.thumbnail_url, seller: { id: seller.external_id, name: seller.display_name, avatar_url: seller.avatar_url, }, last_read_community_chat_message_created_at: nil, unread_count: 0, ) end context "when extras are provided" do let(:last_read_at) { 1.day.ago } let(:unread_count) { 5 } let(:presenter) do described_class.new( community:, current_user: buyer, extras: { last_read_community_chat_message_created_at: last_read_at.iso8601, unread_count:, } ) end it "uses the provided values instead of querying the database" do expect(props[:last_read_community_chat_message_created_at]).to eq(last_read_at.iso8601) expect(props[:unread_count]).to eq(unread_count) end end context "when there are unread messages" do let!(:message1) { create(:community_chat_message, community:, user: seller, created_at: 3.minutes.ago) } let!(:message2) { create(:community_chat_message, community:, user: seller, created_at: 2.minutes.ago) } let!(:message3) { create(:community_chat_message, community:, user: seller, created_at: 1.minute.ago) } let!(:last_read) do create(:last_read_community_chat_message, user: buyer, community:, community_chat_message: message1) end it "returns the last read message timestamp" do expect(props[:last_read_community_chat_message_created_at]).to eq(message1.created_at.iso8601) end it "returns the correct unread count" do expect(props[:unread_count]).to eq(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/presenters/pagy_presenter_spec.rb
spec/presenters/pagy_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe PagyPresenter do it "formats a Pagy instance for the frontend" do pagy = Pagy.new(page: 2, count: 100, limit: 40) expect(PagyPresenter.new(pagy).props).to eq({ pages: 3, page: 2 }) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/comment_presenter_spec.rb
spec/presenters/comment_presenter_spec.rb
# frozen_string_literal: true describe CommentPresenter do describe "#comment_component_props" do let(:seller) { create(:named_seller) } let(:commenter) { create(:user) } let(:product) { create(:product, user: seller) } let(:product_post) { create(:published_installment, link: product, installment_type: "product", shown_on_profile: true) } let(:comment) { create(:comment, commentable: product_post, author: commenter) } let(:purchase) { nil } let(:presenter) { described_class.new(pundit_user:, comment:, purchase:) } context "when signed in user is the commenter" do let(:pundit_user) { SellerContext.new(user: commenter, seller: commenter) } it "returns comment details needed to present on frontend" do travel_to(DateTime.current) do props = presenter.comment_component_props expect(props).to eq( id: comment.external_id, parent_id: nil, author_id: commenter.external_id, author_name: commenter.display_name, author_avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), purchase_id: nil, content: { original: comment.content, formatted: CGI.escapeHTML(comment.content) }, created_at: DateTime.current.utc.iso8601, created_at_humanized: "less than a minute ago", depth: 0, is_editable: true, is_deletable: true ) end end it "returns both original content as well as formatted content" do content = %(That's a great article!<script type="text/html">console.log("Executing evil script...")</script>) comment = create(:comment, content:) presenter = described_class.new(pundit_user:, comment:, purchase:) expect(presenter.comment_component_props[:content]).to eq( original: content, formatted: "That&#39;s a great article!&lt;script type=&quot;text/html&quot;&gt;console.log(&quot;Executing evil script...&quot;)&lt;/script&gt;", ) end it "returns formatted content by turning URLs into noreferrer hyperlinks" do content = %(Nice article! Please visit my website at https://example.com) comment = create(:comment, content:) presenter = described_class.new(pundit_user:, comment:, purchase:) expect(presenter.comment_component_props[:content]).to eq( original: content, formatted: %(Nice article! Please visit my website at <a href="https://example.com" target="_blank" rel="noopener noreferrer nofollow">https://example.com</a>), ) end it "returns comment details with 'is_deletable' set to true" do expect(presenter.comment_component_props[:is_deletable]).to eq(true) end it "returns comment details with 'is_editable' set to true" do expect(presenter.comment_component_props[:is_editable]).to eq(true) end end context "when signed in user is the author of the post" do let(:pundit_user) { SellerContext.new(user: seller, seller:) } it "returns comment details with 'is_deletable' set to true" do expect(presenter.comment_component_props[:is_deletable]).to eq(true) end it "returns comment details with 'is_editable' set to false" do expect(presenter.comment_component_props[:is_editable]).to eq(false) end end context "when signed in user is admin for seller (author of the post)" do let(:logged_in_user) { create(:user, username: "adminforseller") } let(:pundit_user) { SellerContext.new(user: logged_in_user, seller:) } before do create(:team_membership, user: logged_in_user, seller:, role: TeamMembership::ROLE_ADMIN) end it "returns comment details with 'is_deletable' set to true" do expect(presenter.comment_component_props[:is_deletable]).to eq(true) end it "returns comment details with 'is_editable' set to false" do expect(presenter.comment_component_props[:is_editable]).to eq(false) end end context "when signed in user is neither the commenter nor the author of the post" do let(:other_user) { create(:user) } let(:pundit_user) { SellerContext.new(user: other_user, seller: other_user) } it "returns comment details with 'is_deletable' set to false" do expect(presenter.comment_component_props[:is_deletable]).to eq(false) end it "returns comment details with 'is_editable' set to false" do expect(presenter.comment_component_props[:is_editable]).to eq(false) end end context "when user is not signed in" do let(:pundit_user) { SellerContext.logged_out } it "returns comment details with 'is_deletable' set to false" do expect(presenter.comment_component_props[:is_deletable]).to eq(false) end it "returns comment details with 'is_editable' set to false" do expect(presenter.comment_component_props[:is_editable]).to eq(false) end it "returns the default avatar URL with 'author_avatar_url'" do expect(presenter.comment_component_props[:author_avatar_url]).to eq(ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png")) end end context "when comment author has an avatar picture" do let(:commenter) { create(:user, :with_avatar) } let(:pundit_user) { SellerContext.new(user: commenter, seller: commenter) } it "returns the URL to author's avatar with 'author_avatar_url'" do expect(presenter.comment_component_props[:author_avatar_url]).to eq(commenter.avatar_url) end end context "when comment author does not have an avatar picture" do let(:pundit_user) { SellerContext.new(user: commenter, seller: commenter) } it "returns the default avatar URL with 'author_avatar_url'" do expect(presenter.comment_component_props[:author_avatar_url]).to eq(ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png")) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/paginated_installments_presenter_spec.rb
spec/presenters/paginated_installments_presenter_spec.rb
# frozen_string_literal: true describe PaginatedInstallmentsPresenter do describe "#props" do let(:seller) { create(:user) } let!(:published_installment1) { create(:installment, name: "Exciting offer - Email 1", seller:, published_at: 2.days.ago) } let!(:published_installment2) { create(:installment, name: "Hello world!", seller:, published_at: 1.day.ago) } let!(:draft_installment) { create(:installment, name: "Exciting offer - Email 3", seller:) } let(:type) { "published" } let(:page) { nil } let(:query) { nil } let(:presenter) { described_class.new(seller:, type:, page:, query:) } before do stub_const("#{described_class}::PER_PAGE", 1) end context "when 'page' option is not specified" do it "returns paginated installments for the first page" do result = presenter.props expect(result[:pagination]).to eq(count: 2, next: 2) expect(result[:installments].sole).to eq(InstallmentPresenter.new(seller:, installment: published_installment2).props) expect(result[:has_posts]).to be(true) end end context "when 'page' option is specified" do let(:page) { 2 } it "returns paginated installments for the specified page" do result = presenter.props expect(result[:pagination]).to eq(count: 2, next: nil) expect(result[:installments].sole).to eq(InstallmentPresenter.new(seller:, installment: published_installment1).props) end end context "when the specified 'page' option is an overflowing page number" do let(:page) { 3 } it "returns an empty page" do result = presenter.props expect(result[:pagination]).to eq(count: 2, next: nil) expect(result[:installments]).to be_empty end end context "when 'type' is 'scheduled'" do let(:type) { "scheduled" } let(:scheduled_installment1) { create(:installment, seller:, ready_to_publish: true) } let!(:scheduled_installment1_rule) { create(:installment_rule, installment: scheduled_installment1, to_be_published_at: 3.days.from_now.to_date + 4.hours) } let(:scheduled_installment2) { create(:installment, seller:, ready_to_publish: true) } let!(:scheduled_installment2_rule) { create(:installment_rule, installment: scheduled_installment2, to_be_published_at: 1.days.from_now.to_date + 2.hours) } let(:scheduled_installment3) { create(:installment, seller:, ready_to_publish: true) } let!(:scheduled_installment3_rule) { create(:installment_rule, installment: scheduled_installment3, to_be_published_at: 1.day.from_now.to_date + 10.hours) } before do stub_const("#{described_class}::PER_PAGE", 10) end it "returns scheduled installments ordered by 'to_be_published_at' earliest first" do result = presenter.props expect(result[:pagination]).to eq(count: 3, next: nil) expect(result[:installments]).to eq([ InstallmentPresenter.new(seller:, installment: scheduled_installment2).props, InstallmentPresenter.new(seller:, installment: scheduled_installment3).props, InstallmentPresenter.new(seller:, installment: scheduled_installment1).props, ]) end end context "when the specified 'type' option is invalid" do let(:type) { "invalid" } it "raises an error" do expect { presenter.props }.to raise_error(ArgumentError, "Invalid type") end end context "when seller has no installments" do let(:seller_without_installments) { create(:user) } let(:presenter) { described_class.new(seller: seller_without_installments, type:, page:, query:) } it "returns has_posts as false" do result = presenter.props expect(result[:has_posts]).to be(false) end end context "when a non-nil 'query' option is specified" do let!(:published_installment3) { create(:installment, name: "Exciting offer - Email 2", seller:, published_at: 3.days.ago) } let(:query) { "offer" } before do index_model_records(Installment) end it "returns paginated installments for the specified query for the first page" do expect(InstallmentSearchService).to receive(:search).with({ exclude_deleted: true, type:, exclude_workflow_installments: true, seller:, q: query, fields: %w[name message], from: 0, size: 1, sort: [:_score, { created_at: :desc }, { id: :desc }] }).and_call_original result = presenter.props expect(result[:pagination]).to eq(count: 2, next: 2) expect(result[:installments].sole).to eq(InstallmentPresenter.new(seller:, installment: published_installment3).props) end context "when 'page' option is specified" do let(:page) { 2 } it "returns paginated installments for the specified query for the specified page" do expect(InstallmentSearchService).to receive(:search).with({ exclude_deleted: true, type:, exclude_workflow_installments: true, seller:, q: query, fields: %w[name message], from: 1, size: 1, sort: [:_score, { created_at: :desc }, { id: :desc }] }).and_call_original result = presenter.props expect(result[:pagination]).to eq(count: 2, next: nil) expect(result[:installments].sole).to eq(InstallmentPresenter.new(seller:, installment: published_installment1).props) 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/presenters/community_notification_setting_presenter_spec.rb
spec/presenters/community_notification_setting_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe CommunityNotificationSettingPresenter do let(:user) { create(:user) } let(:seller) { create(:user) } let(:settings) { create(:community_notification_setting, user:, seller:) } let(:presenter) { described_class.new(settings:) } describe "#props" do subject(:props) { presenter.props } it "returns appropriate props" do expect(props).to eq(recap_frequency: "daily") end context "when recap frequency is weekly" do let(:settings) { create(:community_notification_setting, :weekly_recap, user:, seller:) } it "returns weekly recap frequency" do expect(props[:recap_frequency]).to eq("weekly") end end context "when recap frequency is not set" do let(:settings) { create(:community_notification_setting, :no_recap, user:, seller:) } it "returns nil recap frequency" do expect(props[:recap_frequency]).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/presenters/paginated_utm_links_presenter_spec.rb
spec/presenters/paginated_utm_links_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe PaginatedUtmLinksPresenter do let(:seller) { create(:named_seller) } let!(:utm_link1) { create(:utm_link, seller:, created_at: 1.day.ago, unique_clicks: 3) } let!(:utm_link2) { create(:utm_link, seller:, created_at: 3.days.ago, unique_clicks: 1) } let!(:utm_link3) { create(:utm_link, seller:, created_at: 2.days.ago, unique_clicks: 0) } let(:product) { create(:product, user: seller) } let(:purchase1) { create(:purchase, price_cents: 1000, seller:, link: product) } let(:purchase2) { create(:purchase, price_cents: 2000, seller:, link: product) } let(:purchase3) { create(:purchase, price_cents: 500, seller:, link: product) } let(:test_purchase) { create(:test_purchase, price_cents: 3000, seller:, link: product) } let(:failed_purchase) { create(:failed_purchase, price_cents: 1000, seller:, link: product) } let!(:utm_link1_driven_sale1) { create(:utm_link_driven_sale, utm_link: utm_link1, purchase: purchase1) } let!(:utm_link1_driven_sale2) { create(:utm_link_driven_sale, utm_link: utm_link1, purchase: purchase2) } let!(:utm_link2_driven_sale1) { create(:utm_link_driven_sale, utm_link: utm_link2, purchase: purchase3) } let!(:utm_link2_driven_sale2) { create(:utm_link_driven_sale, utm_link: utm_link2, purchase: test_purchase) } let!(:utm_link2_driven_sale3) { create(:utm_link_driven_sale, utm_link: utm_link2, purchase: failed_purchase) } describe "#props" do it "returns the paginated UTM links props" do stub_const("PaginatedUtmLinksPresenter::PER_PAGE", 2) props = described_class.new(seller:).props expect(props).to match(PaginatedUtmLinksPresenter.new(seller:).props) expect(props[:utm_links]).to match_array([ UtmLinkPresenter.new(seller:, utm_link: utm_link1).utm_link_props, UtmLinkPresenter.new(seller:, utm_link: utm_link3).utm_link_props, ]) expect(props[:utm_links].map { [_1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] }).to match_array([[nil, nil, nil], [nil, nil, nil]]) expect(props[:pagination]).to eq(pages: 2, page: 1) props = described_class.new(seller:, page: 2).props expect(props).to match(PaginatedUtmLinksPresenter.new(seller:, page: 2).props) expect(props[:utm_links]).to match_array([UtmLinkPresenter.new(seller:, utm_link: utm_link2).utm_link_props]) expect(props[:utm_links].map { [_1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] }).to match_array([[nil, nil, nil]]) expect(props[:pagination]).to eq(pages: 2, page: 2) # When the page is greater than the number of pages, it returns the last page expect do props = described_class.new(seller:, page: 3).props expect(props[:utm_links]).to match_array([UtmLinkPresenter.new(seller:, utm_link: utm_link2).utm_link_props]) expect(props[:pagination]).to eq(pages: 2, page: 2) end.not_to raise_error end it "sorts by date by default" do props = described_class.new(seller:).props expect(props[:utm_links].map { _1[:id] }).to eq([ utm_link1.external_id, utm_link3.external_id, utm_link2.external_id ]) end describe "sorting" do it "sorts by different columns" do utm_link1.update!(title: "C Link", utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", unique_clicks: 10) utm_link2.update!(title: "A Link", utm_source: "twitter", utm_medium: "paid", utm_campaign: "winter", unique_clicks: 30) utm_link3.update!(title: "B Link", utm_source: "google", utm_medium: "organic", utm_campaign: "summer", unique_clicks: 20) sort_key_to_response_key_map = { "link" => :title, "date" => :created_at, "source" => :source, "medium" => :medium, "campaign" => :campaign, "clicks" => :clicks, "sales_count" => :sales_count, "revenue_cents" => :revenue_cents, "conversion_rate" => :conversion_rate, } sort_key_to_response_key_map.each do |key, column| ascending = described_class.new(seller:, sort: { key:, direction: "asc" }).props expect(ascending[:utm_links].map { _1[column] }).to eq(ascending[:utm_links].map { _1[column] }.sort) descending = described_class.new(seller:, sort: { key:, direction: "desc" }).props expect(descending[:utm_links].map { _1[column] }).to eq(descending[:utm_links].map { _1[column] }.sort.reverse) end end context "when sorted by sales_count, revenue_cents, or conversion_rate columns" do it "returns values for stats" do props = described_class.new(seller:, sort: { key: "sales_count", direction: "asc" }).props stats = props[:utm_links].map { [_1[:id], _1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] } expect(stats).to eq([ [utm_link3.external_id, 0, 0, 0.0], [utm_link2.external_id, 1, 500, 1.0], [utm_link1.external_id, 2, 3000, 0.6667], ]) props = described_class.new(seller:, sort: { key: "sales_count", direction: "desc" }).props stats = props[:utm_links].map { [_1[:id], _1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] } expect(stats).to eq([ [utm_link1.external_id, 2, 3000, 0.6667], [utm_link2.external_id, 1, 500, 1.0], [utm_link3.external_id, 0, 0, 0.0], ]) props = described_class.new(seller:, sort: { key: "revenue_cents", direction: "asc" }).props stats = props[:utm_links].map { [_1[:id], _1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] } expect(stats).to eq([ [utm_link3.external_id, 0, 0, 0.0], [utm_link2.external_id, 1, 500, 1.0], [utm_link1.external_id, 2, 3000, 0.6667], ]) props = described_class.new(seller:, sort: { key: "revenue_cents", direction: "desc" }).props stats = props[:utm_links].map { [_1[:id], _1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] } expect(stats).to eq([ [utm_link1.external_id, 2, 3000, 0.6667], [utm_link2.external_id, 1, 500, 1.0], [utm_link3.external_id, 0, 0, 0.0], ]) props = described_class.new(seller:, sort: { key: "conversion_rate", direction: "asc" }).props stats = props[:utm_links].map { [_1[:id], _1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] } expect(stats).to eq([ [utm_link3.external_id, 0, 0, 0.0], [utm_link1.external_id, 2, 3000, 0.6667], [utm_link2.external_id, 1, 500, 1.0], ]) props = described_class.new(seller:, sort: { key: "conversion_rate", direction: "desc" }).props stats = props[:utm_links].map { [_1[:id], _1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] } expect(stats).to eq([ [utm_link2.external_id, 1, 500, 1.0], [utm_link1.external_id, 2, 3000, 0.6667], [utm_link3.external_id, 0, 0, 0.0], ]) end end context "when sorted by any other column" do it "returns nil values for stats" do props = described_class.new(seller:, sort: { key: "link", direction: "asc" }).props stats = props[:utm_links].map { [_1[:sales_count], _1[:revenue_cents], _1[:conversion_rate]] } expect(stats).to eq([ [nil, nil, nil], [nil, nil, nil], [nil, nil, nil], ]) end end end it "filters UTM links by search query" do utm_link1.update!( title: "Facebook Summer Sale", utm_source: "facebook", utm_medium: "social", utm_campaign: "summer_2024", utm_term: "discount", utm_content: "banner_ad" ) utm_link2.update!( title: "Twitter Winter Promo", utm_source: "twitter", utm_medium: "social", utm_campaign: "winter_2024", utm_term: "sale", utm_content: "post" ) utm_link3.update!( title: "Google Summer Sale", utm_source: "google", utm_medium: "organic", utm_campaign: "summer_2024", utm_term: "discount", utm_content: "video_ad" ) # Search by title props = described_class.new(seller:, query: "SuMMer", sort: { key: "link", direction: "desc" }).props expect(props[:utm_links].map { _1[:id] }).to match_array([utm_link3.external_id, utm_link1.external_id]) # Search by source props = described_class.new(seller:, query: "twitter").props expect(props[:utm_links].map { _1[:id] }).to match_array([utm_link2.external_id]) # Search by medium props = described_class.new(seller:, query: "social").props expect(props[:utm_links].map { _1[:id] }).to match_array([utm_link1.external_id, utm_link2.external_id]) # Search by campaign props = described_class.new(seller:, query: "winter").props expect(props[:utm_links].map { _1[:id] }).to match_array([utm_link2.external_id]) # Search by term props = described_class.new(seller:, query: "discount").props expect(props[:utm_links].map { _1[:id] }).to match_array([utm_link1.external_id, utm_link3.external_id]) # Search by content props = described_class.new(seller:, query: "video").props expect(props[:utm_links].map { _1[:id] }).to match_array([utm_link3.external_id]) # Search with no matches props = described_class.new(seller:, query: "nonexistent").props expect(props[:utm_links]).to be_empty # Search with whitespace props = described_class.new(seller:, query: " ").props expect(props[:utm_links].map { _1[:id] }).to match_array([utm_link1.external_id, utm_link2.external_id, utm_link3.external_id]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/mobile_tracking_presenter_spec.rb
spec/presenters/mobile_tracking_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe MobileTrackingPresenter do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } subject { described_class.new(seller:) } describe "#product_props" do it "returns the correct props" do expect(subject.product_props(product:)).to eq( enabled: false, seller_id: seller.external_id, analytics: { google_analytics_id: nil, facebook_pixel_id: nil, free_sales: true, }, has_product_third_party_analytics: false, has_receipt_third_party_analytics: false, third_party_analytics_domain: THIRD_PARTY_ANALYTICS_DOMAIN, permalink: product.unique_permalink, name: product.name, ) end context "when the seller has analytics enabled in production" do before do allow(Rails.env).to receive(:production?).and_return(true) seller.update!(google_analytics_id: "G-123", facebook_pixel_id: "fbid") end it "returns the correct props" do expect(subject.product_props(product:)).to eq( enabled: true, seller_id: seller.external_id, analytics: { google_analytics_id: "G-123", facebook_pixel_id: "fbid", free_sales: true, }, has_product_third_party_analytics: false, has_receipt_third_party_analytics: false, third_party_analytics_domain: THIRD_PARTY_ANALYTICS_DOMAIN, permalink: product.unique_permalink, name: product.name, ) end end context "when the seller has third party analytics on the product page" do before do create(:third_party_analytic, user: product.user, link: product, location: "product") end it "returns the correct props" do expect(subject.product_props(product:)).to include( has_product_third_party_analytics: true, has_receipt_third_party_analytics: false, ) end end context "when the seller has third party analytics on the receipt page" do before do create(:third_party_analytic, user: product.user, link: product, location: "receipt") end it "returns the correct props" do expect(subject.product_props(product:)).to include( has_product_third_party_analytics: false, has_receipt_third_party_analytics: true, ) end end context "when the seller has third party analytics on the receipt page" do before do create(:third_party_analytic, user: product.user, link: product, location: "all") end it "returns the correct props" do expect(subject.product_props(product:)).to include( has_product_third_party_analytics: true, has_receipt_third_party_analytics: 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/presenters/checkout_presenter_spec.rb
spec/presenters/checkout_presenter_spec.rb
# frozen_string_literal: true describe CheckoutPresenter do include ManageSubscriptionHelpers include Rails.application.routes.url_helpers describe "#checkout_props" do before do vcr_turned_on do VCR.use_cassette "checkout presenter saved credit card" do @user = create(:user, currency_type: "jpy", credit_card: create(:credit_card)) end end @instance = described_class.new(logged_in_user: @user, ip: "104.193.168.19") TipOptionsService.set_tip_options([5, 15, 25]) TipOptionsService.set_default_tip_option(15) end let(:browser_guid) { SecureRandom.uuid } it "returns basic props for the checkout page" do expect(@instance.checkout_props(params: {}, browser_guid:)).to eq( discover_url: discover_url(protocol: PROTOCOL, host: DISCOVER_DOMAIN), countries: Compliance::Countries.for_select.to_h, us_states: STATES, ca_provinces: Compliance::Countries.subdivisions_for_select(Compliance::Countries::CAN.alpha2).map(&:first), country: "US", state: "CA", address: { city: nil, street: nil, zip: nil }, add_products: [], clear_cart: false, gift: nil, saved_credit_card: { expiration_date: "12/23", number: "**** **** **** 4242", type: "visa", requires_mandate: false }, recaptcha_key: GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY"), paypal_client_id: PAYPAL_PARTNER_CLIENT_ID, cart: nil, max_allowed_cart_products: Cart::MAX_ALLOWED_CART_PRODUCTS, tip_options: [5, 15, 25], default_tip_option: 15, ) end it "returns cart props" do create(:cart, user: @user) expect(@instance.checkout_props(params: {}, browser_guid:)).to include(cart: { email: nil, returnUrl: "", rejectPppDiscount: false, discountCodes: [], items: [] }) end it "does not show paused upsells" do product = create(:product_with_digital_versions, user: create(:named_user)) upsell = create(:upsell, seller: product.user, product:) params = { product: product.unique_permalink } expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:product][:upsell]).to be_present upsell.update!(paused: true) expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:product][:upsell]).to be_nil end it "does not show paused upsell variants" do product = create(:product_with_digital_versions, user: create(:named_user)) upsell = create(:upsell, seller: product.user, product:) create(:upsell_variant, upsell:, selected_variant: product.alive_variants.first, offered_variant: product.alive_variants.second) options = product.options params = { product: product.unique_permalink, option: options.first[:id] } expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:product][:options].first[:upsell_offered_variant_id]).to be_present upsell.update!(paused: true) expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:product][:options].first[:upsell_offered_variant_id]).to be_nil end it "does not show paused cross-sells" do product = create(:product, user: create(:named_user)) offered_product = create(:product, user: product.user) upsell = create(:upsell, selected_products: [product], seller: product.user, product: offered_product, cross_sell: true) params = { product: product.unique_permalink } expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:product][:cross_sells]).to be_present upsell.update!(paused: true) expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:product][:cross_sells]).to be_empty end it "does not accept paused upsells as accepted offers" do product = create(:product_with_digital_versions, user: create(:named_user)) upsell = create(:upsell, seller: product.user, product:) params = { product: product.unique_permalink, accepted_offer_id: upsell.external_id } expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:accepted_offer]).to be_present upsell.update!(paused: true) expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:accepted_offer]).to be_nil end it "allows adding a product" do product = create(:product_with_digital_versions, name: "Sample Product", description: "Simple description", user: create(:named_user), duration_in_months: 6) product.alive_variants.first.update!(max_purchase_count: 0) upsell = create(:upsell, seller: product.user, product:, description: "Visit https://google.com to learn more about this offer") create(:upsell_variant, upsell:, selected_variant: product.alive_variants.first, offered_variant: product.alive_variants.second) create(:upsell_variant, upsell:, selected_variant: product.alive_variants.second, offered_variant: product.alive_variants.first) offered_product = create(:product_with_digital_versions, user: product.user) offered_product.alive_variants.first.update!(max_purchase_count: 0) create(:upsell, name: "Cross-sell 1", selected_products: [product], seller: product.user, product: offered_product, variant: offered_product.alive_variants.first, cross_sell: true, replace_selected_products: true) cross_sell2 = create(:upsell, name: "Cross-sell 2", description: "https://gumroad.com is the best!", selected_products: [product], seller: product.user, product: offered_product, offer_code: create(:offer_code, user: product.user, products: [offered_product]), cross_sell: true) options = product.options params = { product: product.unique_permalink, recommended_by: "discover", option: options[1][:id] } expect(@instance.checkout_props(params:, browser_guid:)).to eq( discover_url: discover_url(protocol: PROTOCOL, host: DISCOVER_DOMAIN), countries: Compliance::Countries.for_select.to_h, us_states: STATES, ca_provinces: Compliance::Countries.subdivisions_for_select(Compliance::Countries::CAN.alpha2).map(&:first), country: "US", state: "CA", address: { city: nil, street: nil, zip: nil }, saved_credit_card: { expiration_date: "12/23", number: "**** **** **** 4242", type: "visa", requires_mandate: false }, recaptcha_key: GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY"), paypal_client_id: PAYPAL_PARTNER_CLIENT_ID, gift: nil, clear_cart: false, add_products: [{ product: { permalink: product.unique_permalink, id: product.external_id, name: "Sample Product", creator: { name: product.user.name, profile_url: product.user.profile_url(recommended_by: "discover"), avatar_url: product.user.avatar_url, id: product.user.external_id, }, url: product.long_url, thumbnail_url: nil, native_type: "digital", quantity_remaining: nil, is_preorder: false, is_multiseat_license: false, free_trial: nil, options: [options.first.merge({ upsell_offered_variant_id: options.second[:id] }), options.second.merge({ upsell_offered_variant_id: nil })], require_shipping: false, shippable_country_codes: [], custom_fields: [], supports_paypal: nil, has_offer_codes: false, has_tipping_enabled: false, analytics: product.analytics_data, exchange_rate: 1, currency_code: "usd", is_legacy_subscription: false, is_quantity_enabled: false, is_tiered_membership: false, price_cents: 100, pwyw: nil, installment_plan: nil, recurrences: nil, duration_in_months: 6, rental: nil, ppp_details: nil, can_gift: true, upsell: { id: upsell.external_id, description: 'Visit <a href="https://google.com" target="_blank" rel="noopener">https://google.com</a> to learn more about this offer', text: "Take advantage of this excellent offer!", }, archived: false, cross_sells: [ { id: cross_sell2.external_id, replace_selected_products: false, text: "Take advantage of this excellent offer!", description: '<a href="https://gumroad.com" target="_blank" rel="noopener">https://gumroad.com</a> is the best!', ratings: { count: 0, average: 0 }, discount: { type: "fixed", cents: 100, product_ids: [offered_product.external_id], expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, offered_product: @instance.checkout_product(offered_product, offered_product.cart_item({}), {}, include_cross_sells: false), }, ], bundle_products: [], }, price: product.price_cents, option_id: options[1][:id], rent: false, quantity: nil, recurrence: nil, recommended_by: "discover", affiliate_id: nil, recommender_model_name: nil, call_start_time: nil, accepted_offer: nil, pay_in_installments: false }], max_allowed_cart_products: Cart::MAX_ALLOWED_CART_PRODUCTS, tip_options: [5, 15, 25], default_tip_option: 15, cart: nil, ) end it "allows adding products from a wishlist" do wishlist = create(:wishlist) physical_product = create(:product, :is_physical) create(:wishlist_product, wishlist:, product: physical_product, quantity: 5) rental_product = create(:product, purchase_type: :buy_and_rent, rental_price_cents: 99) create(:wishlist_product, wishlist:, product: rental_product, rent: true) subscription_product = create(:subscription_product) create(:wishlist_product, wishlist:, product: subscription_product, recurrence: "monthly") versioned_product = create(:product_with_digital_versions) create(:wishlist_product, wishlist:, product: versioned_product, variant: versioned_product.alive_variants.first) params = { wishlist: wishlist.external_id, recommended_by: "discover" } expect(@instance.checkout_props(params:, browser_guid:)).to include( add_products: [ { product: a_hash_including(id: physical_product.external_id), price: physical_product.price_cents, option_id: nil, rent: false, quantity: 5, recurrence: nil, recommended_by: "discover", affiliate_id: wishlist.user.global_affiliate.external_id_numeric.to_s, recommender_model_name: nil, call_start_time: nil, accepted_offer: nil, pay_in_installments: false }, { product: a_hash_including(id: rental_product.external_id), price: rental_product.rental_price_cents, option_id: nil, rent: true, quantity: 1, recurrence: nil, recommended_by: "discover", affiliate_id: wishlist.user.global_affiliate.external_id_numeric.to_s, recommender_model_name: nil, call_start_time: nil, accepted_offer: nil, pay_in_installments: false }, { product: a_hash_including(id: subscription_product.external_id), price: subscription_product.price_cents, option_id: nil, rent: false, quantity: 1, recurrence: "monthly", recommended_by: "discover", affiliate_id: wishlist.user.global_affiliate.external_id_numeric.to_s, recommender_model_name: nil, call_start_time: nil, accepted_offer: nil, pay_in_installments: false }, { product: a_hash_including(id: versioned_product.external_id), price: versioned_product.price_cents, option_id: versioned_product.options.first[:id], rent: false, quantity: 1, recurrence: nil, recommended_by: "discover", affiliate_id: wishlist.user.global_affiliate.external_id_numeric.to_s, recommender_model_name: nil, call_start_time: nil, accepted_offer: nil, pay_in_installments: false } ] ) end it "does not add deleted wishlist products" do wishlist = create(:wishlist) alive_product = create(:wishlist_product, wishlist:) create(:wishlist_product, wishlist:, deleted_at: Time.current) params = { wishlist: wishlist.external_id, recommended_by: "discover" } expect(@instance.checkout_props(params:, browser_guid:)[:add_products].sole[:product][:id]).to eq alive_product.product.external_id end context "when gifting a wishlist product" do let(:user) { create(:user, name: "Jane Gumroad") } let(:wishlist) { create(:wishlist, user:) } let(:wishlist_product) { create(:wishlist_product, wishlist:) } let(:params) { { gift_wishlist_product: wishlist_product.external_id } } it "clears the cart and gifts the product" do expect(@instance.checkout_props(params:, browser_guid:)).to include( clear_cart: true, gift: { type: "anonymous", id: wishlist.user.external_id, name: wishlist.user.name, note: "" }, add_products: [{ product: a_hash_including(id: wishlist_product.product.external_id), price: wishlist_product.product.price_cents, option_id: nil, rent: false, quantity: 1, recurrence: nil, recommended_by: RecommendationType::WISHLIST_RECOMMENDATION, affiliate_id: nil, recommender_model_name: nil, call_start_time: nil, accepted_offer: nil, pay_in_installments: false }] ) end it "falls back to the username when the user has not set a name" do wishlist.user.update!(name: nil) expect(@instance.checkout_props(params:, browser_guid:)).to include( gift: { type: "anonymous", id: wishlist.user.external_id, name: wishlist.user.username, note: "" } ) end end it "does not add unavailable wishlist products" do wishlist = create(:wishlist) available_product = create(:product) create(:wishlist_product, wishlist:, product: available_product) unpublished_product = create(:product, purchase_disabled_at: Time.current) create(:wishlist_product, wishlist:, product: unpublished_product) suspended_user_product = create(:product, user: create(:tos_user)) create(:wishlist_product, wishlist:, product: suspended_user_product) params = { wishlist: wishlist.external_id, recommended_by: "discover" } expect(@instance.checkout_props(params:, browser_guid:)).to include( add_products: [ { product: a_hash_including(id: available_product.external_id), price: available_product.price_cents, option_id: nil, rent: false, quantity: 1, recurrence: nil, recommended_by: "discover", affiliate_id: wishlist.user.global_affiliate.external_id_numeric.to_s, recommender_model_name: nil, call_start_time: nil, accepted_offer: nil, pay_in_installments: false } ] ) end it "respects single-unit currencies in exchange_rate" do $currency_namespace = Redis::Namespace.new(:currencies, redis: $redis) $currency_namespace.set("JPY", 149) product = create(:product, price_cents: 1000, price_currency_type: "jpy") params = { product: product.unique_permalink } expect(@instance.checkout_props(params:, browser_guid:)[:add_products].first[:product][:exchange_rate]).to eq 1.49 end context "when all PayPal sales are disabled" do let!(:product) { create(:product) } it "returns nil for supports_paypal when the creator does not have their PayPal account connected" do Feature.deactivate(:disable_braintree_sales) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to eq "braintree" Feature.activate(:disable_paypal_sales) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to be_nil end it "returns nil for supports_paypal when the creator has their PayPal account connected" do create(:merchant_account_paypal, charge_processor_merchant_id: "CJS32DZ7NDN5L", user: product.user, country: "GB", currency: "gbp") create(:user_compliance_info, user: product.user) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to eq "native" Feature.activate(:disable_paypal_sales) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to be_nil end end context "when PayPal Connect sales are disabled" do before do Feature.activate(:disable_paypal_connect_sales) Feature.deactivate(:disable_braintree_sales) end context "when the product is a recurring subscription" do let (:product) { create(:subscription_product) } it "returns nil for supports_paypal" do expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to be_nil end end context "when the product is not a recurring subscription" do let (:product) { create(:product) } it "returns braintree for supports_paypal" do expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to eq "braintree" end it "returns nil for supports_paypal if Braintree sales are also disabled" do Feature.activate(:disable_braintree_sales) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to be_nil end end end context "when PayPal Connect sales are disabled for NSFW products" do before do Feature.activate(:disable_nsfw_paypal_connect_sales) end context "when the product is NSFW" do let(:product) { create(:product, is_adult: true) } it "returns nil for supports_paypal" do expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to be_nil end end end context "when Braintree sales are disabled" do before do Feature.activate(:disable_braintree_sales) end it "returns nil for supports_paypal if product doesn't support native PayPal" do product = create(:product) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to be_nil end it "returns native for supports_paypal if product supports native PayPal" do seller = create(:user) create(:merchant_account_paypal, user: seller) product = create(:product, user: seller) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to eq "native" end it "returns nil for supports_paypal if native PayPal is also disabled" do Feature.activate(:disable_paypal_connect_sales) seller = create(:user) create(:merchant_account_paypal, user: seller) product = create(:product, user: seller) expect(@instance.checkout_props(params: { product: product.unique_permalink }, browser_guid:)[:add_products].first[:product][:supports_paypal]).to be_nil end end context "when the product is a bundle product" do let(:bundle) { create(:product, is_bundle: true) } before do create(:bundle_product, bundle:, product: create(:product, :with_custom_fields, user: bundle.user, require_shipping: true), quantity: 2, position: 1) versioned_product = create(:product_with_digital_versions, user: bundle.user) versioned_product.alive_variants.second.update(price_difference_cents: 200) create(:bundle_product, bundle:, product: versioned_product, variant: versioned_product.alive_variants.second, position: 0) bundle.reload end it "includes the bundle products" do product_props = @instance.checkout_props(params: { product: bundle.unique_permalink }, browser_guid:)[:add_products].first[:product] expect(product_props[:require_shipping]).to eq(true) expect(product_props[:bundle_products]).to eq( [ { product_id: bundle.bundle_products.second.product.external_id, name: "The Works of Edgar Gumstein", native_type: "digital", quantity: 1, thumbnail_url: nil, variant: { id: bundle.bundle_products.second.variant.external_id, name: "Untitled 2" }, custom_fields: [], }, { product_id: bundle.bundle_products.first.product.external_id, name: "The Works of Edgar Gumstein", native_type: "digital", quantity: 2, thumbnail_url: nil, variant: nil, custom_fields: [ { id: bundle.bundle_products.first.product.custom_fields.first.external_id, name: "Text field", required: false, collect_per_product: false, type: "text", }, { id: bundle.bundle_products.first.product.custom_fields.second.external_id, name: "Checkbox field", required: true, collect_per_product: false, type: "checkbox", }, { id: bundle.bundle_products.first.product.custom_fields.third.external_id, name: "http://example.com", required: true, collect_per_product: false, type: "terms", }, ], }, ] ) end end end describe "#subscription_manager_props", :vcr do context "tiered membership product" do before :each do @product = create(:membership_product_with_preset_tiered_pricing) @default_tier = @product.default_tier @product_price = @product.prices.alive.find_by(recurrence: "monthly") @tier_price = @default_tier.prices.alive.find_by(recurrence: "monthly") @original_price_cents = @tier_price.price_cents @subscription = create(:subscription, link: @product, price: @product.default_price, credit_card: create(:credit_card), cancelled_at: 1.week.from_now) @purchase = create(:membership_purchase, link: @product, subscription: @subscription, email: "jgumroad@example.com", full_name: "Jane Gumroad", street_address: "100 Main St", city: "San Francisco", state: "CA", zip_code: "00000", country: "USA", variant_attributes: [@default_tier], price_cents: @original_price_cents) end it "returns subscription data object for the subscription manage page" do @purchase.update!(offer_code: create(:offer_code, products: [@product])) @subscription.reload tier1 = @product.tier_category.variants.first tier2 = @product.tier_category.variants.second result = described_class.new(logged_in_user: nil, ip: "127.0.0.1").subscription_manager_props(subscription: @subscription) expect(result).to eq({ product: { name: @product.name, native_type: @product.native_type, supports_paypal: nil, creator: { id: @product.user.external_id, name: @product.user.username, profile_url: @product.user.profile_url, avatar_url: @product.user.avatar_url, }, require_shipping: false, shippable_country_codes: [], custom_fields: [], currency_code: "usd", permalink: @product.unique_permalink, options: [{ description: "", id: tier1.external_id, is_pwyw: false, name: "First Tier", price_difference_cents: nil, quantity_left: nil, recurrence_price_values: { "monthly" => { price_cents: 300, suggested_price_cents: nil } }, duration_in_minutes: nil, }, { description: "", id: tier2.external_id, is_pwyw: false, name: "Second Tier", price_difference_cents: 0, quantity_left: nil, recurrence_price_values: { "monthly" => { price_cents: 500, suggested_price_cents: nil } }, duration_in_minutes: nil, }], pwyw: nil, price_cents: 0, installment_plan: nil, is_tiered_membership: true, is_legacy_subscription: false, recurrences: [{ id: @product_price.external_id, price_cents: 0, recurrence: "monthly" }], exchange_rate: 1, is_multiseat_license: false, }, subscription: { id: @subscription.external_id, option_id: @default_tier.external_id, recurrence: "monthly", quantity: 1, price: @original_price_cents, prorated_discount_price_cents: @subscription.prorated_discount_price_cents, alive: false, pending_cancellation: true, discount: { type: "fixed", cents: 100, product_ids: [@product.external_id], expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, end_time_of_subscription: @subscription.end_time_of_subscription.iso8601, successful_purchases_count: 1, is_in_free_trial: false, is_test: false, is_overdue_for_charge: false, is_gift: false, is_installment_plan: false, }, contact_info: { city: "San Francisco", country: "US", email: @subscription.email, full_name: "Jane Gumroad", state: "CA", street: "100 Main St", zip: "00000" }, discover_url: discover_url(protocol: PROTOCOL, host: DISCOVER_DOMAIN), countries: Compliance::Countries.for_select.to_h, us_states: STATES, ca_provinces: Compliance::Countries.subdivisions_for_select(Compliance::Countries::CAN.alpha2).map(&:first), used_card: { expiration_date: "12/24", number: "**** **** **** 4242", type: "visa", requires_mandate: false }, recaptcha_key: GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY"), paypal_client_id: PAYPAL_PARTNER_CLIENT_ID, }) end context "membership missing variants" do before :each do @purchase.variant_attributes = [] end it "returns the default tier variant ID" do result = described_class.new(logged_in_user: nil, ip: "127.0.0.1").subscription_manager_props(subscription: @subscription) expect(result[:subscription][:option_id]).to eq @default_tier.external_id end context "when price has changed" do it "uses the new price for the default tier price" do @tier_price.update!(price_cents: @original_price_cents + 500) result = described_class.new(logged_in_user: nil, ip: "127.0.0.1").subscription_manager_props(subscription: @subscription) variant_data = result[:product][:options][0] expect(variant_data[:id]).to eq @default_tier.external_id expect(variant_data[:recurrence_price_values]["monthly"][:price_cents]).to eq @tier_price.price_cents end end end context "membership for PWYW tier" do before do @default_tier.update!(customizable_price: true) @pwyw_price_cents = @original_price_cents + 200 @subscription.original_purchase.update!(displayed_price_cents: @pwyw_price_cents) end it "returns the correct current subscription price and tier displayed price" do result = described_class.new(logged_in_user: nil, ip: "127.0.0.1").subscription_manager_props(subscription: @subscription) current_subscription_price = result[:subscription][:price] displayed_tier_price = result[:product][:options][0][:recurrence_price_values]["monthly"][:price_cents] expect(current_subscription_price).to eq @pwyw_price_cents expect(displayed_tier_price).to eq @original_price_cents end it "returns the tier price when the tier price is lower than the current plan price" do new_price = @pwyw_price_cents - 100 @tier_price.update!(price_cents: new_price) result = described_class.new(logged_in_user: nil, ip: "127.0.0.1").subscription_manager_props(subscription: @subscription) displayed_tier_price = result[:product][:options][0][:recurrence_price_values]["monthly"][:price_cents] expect(displayed_tier_price).to eq new_price end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/auth_presenter_spec.rb
spec/presenters/auth_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe AuthPresenter do let(:params) { {} } let(:application) { nil } let(:presenter) { described_class.new(params:, application:) } before do allow(GlobalConfig).to receive(:get).with("RECAPTCHA_LOGIN_SITE_KEY").and_return("recaptcha_login_site_key") allow(GlobalConfig).to receive(:get).with("RECAPTCHA_SIGNUP_SITE_KEY").and_return("recaptcha_signup_site_key") end describe "#login_props" do context "with no params" do it "returns correct props" do expect(presenter.login_props).to eq( { email: nil, application_name: nil, recaptcha_site_key: GlobalConfig.get("RECAPTCHA_LOGIN_SITE_KEY"), } ) end end context "with an oauth application" do let(:application) { create(:oauth_application, name: "Test App") } it "returns correct props" do expect(presenter.login_props).to eq( { email: nil, application_name: "Test App", recaptcha_site_key: GlobalConfig.get("RECAPTCHA_LOGIN_SITE_KEY"), } ) end end end describe "#signup_props" do context "with no options and data" do before do $redis.del(RedisKey.total_made) $redis.del(RedisKey.number_of_creators) end it "returns correct props" do expect(presenter.signup_props).to eq( { email: nil, application_name: nil, referrer: nil, stats: { number_of_creators: 0, total_made: 0, }, recaptcha_site_key: GlobalConfig.get("RECAPTCHA_SIGNUP_SITE_KEY"), } ) end end context "with options passed" do let(:referrer) { create(:user, name: "Test Referrer") } let(:params) { { referrer: referrer.username } } let(:application) { create(:oauth_application, name: "Test App") } before do $redis.mset( RedisKey.total_made, 923_456_789, RedisKey.number_of_creators, 56_789 ) end it "returns correct props" do expect(presenter.signup_props).to eq( { email: nil, application_name: "Test App", referrer: { id: referrer.external_id, name: referrer.name, }, stats: { number_of_creators: 56_789, total_made: 923_456_789, }, recaptcha_site_key: GlobalConfig.get("RECAPTCHA_SIGNUP_SITE_KEY"), } ) end end context "with a team invitation" do let(:team_invitation) { create(:team_invitation) } let(:params) do { next: Rails.application.routes.url_helpers.accept_settings_team_invitation_path(team_invitation.external_id, email: team_invitation.email) } end it "extracts the email to prefill" do expect(presenter.signup_props).to include(email: team_invitation.email) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/affiliated_products_presenter_spec.rb
spec/presenters/affiliated_products_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe AffiliatedProductsPresenter do include CurrencyHelper describe "#affiliated_products_page_props", :vcr do # Users let(:creator_one) { create(:user, username: "creator1") } let(:creator_two) { create(:user, username: "creator2") } let(:affiliate_user) { create(:affiliate_user) } # Products let!(:creator_one_product_one) { create(:product, name: "Creator 1 Product 1", user: creator_one, price_cents: 1000, purchase_disabled_at: 1.minute.ago) } let!(:creator_one_product_two) { create(:physical_product, name: "Creator 1 Product 2", user: creator_one, price_cents: 2000) } let!(:creator_one_product_three) { create(:subscription_product, name: "Creator 1 Product 3", deleted_at: DateTime.current, user: creator_one, price_cents: 250) } let!(:creator_two_product_one) { create(:product, name: "Creator 2 Product 1", user: creator_two, price_cents: 5000) } let!(:creator_two_product_two) { create(:physical_product, name: "Creator 2 Product 2", user: creator_two, price_cents: 2500) } let!(:creator_two_product_three) { create(:subscription_product, name: "Creator 2 Product 3", user: creator_two, price_cents: 1000) } let!(:creator_two_product_four) { create(:product, name: "Creator 2 Product 4", user: creator_two, price_cents: 1000) } let!(:global_affiliate_eligible_product) { create(:product, :recommendable, user: creator_one) } let!(:global_affiliate_eligible_product_two) { create(:product, :recommendable, name: "PWYW Product", price_cents: 0, customizable_price: true) } let!(:another_product) { create(:product, name: "Another Product 1") } # Global affiliate let(:global_affiliate) { affiliate_user.global_affiliate } let!(:archived_affiliate) do affiliate = create(:direct_affiliate, affiliate_user:, seller: creator_one, affiliate_basis_points: 15_00, apply_to_all_products: true, deleted_at: 1.day.ago, created_at: 1.week.ago) create(:product_affiliate, affiliate:, product: creator_one_product_one, affiliate_basis_points: 15_00) create(:product_affiliate, affiliate:, product: creator_one_product_two, affiliate_basis_points: 15_00) create(:product_affiliate, affiliate:, product: creator_one_product_three, affiliate_basis_points: 15_00) affiliate end # Creator 1 affiliates let!(:direct_affiliate_one) do affiliate = create(:direct_affiliate, affiliate_user:, seller: creator_one, affiliate_basis_points: 15_00, apply_to_all_products: true, created_at: 1.week.ago) create(:product_affiliate, affiliate:, product: creator_one_product_one, affiliate_basis_points: 15_00) create(:product_affiliate, affiliate:, product: creator_one_product_two, affiliate_basis_points: 15_00) create(:product_affiliate, affiliate:, product: creator_one_product_three, affiliate_basis_points: 15_00) create(:product_affiliate, affiliate:, product: global_affiliate_eligible_product, affiliate_basis_points: 15_00) affiliate end # Creator 2 affiliates let!(:direct_affiliate_two) do affiliate = create(:direct_affiliate, affiliate_user:, seller: creator_two, created_at: 1.day.ago) create(:product_affiliate, affiliate:, product: creator_two_product_two, affiliate_basis_points: 500) create(:product_affiliate, affiliate:, product: creator_two_product_three, affiliate_basis_points: 2500) create(:product_affiliate, affiliate:, product: creator_two_product_four, affiliate_basis_points: 1000) affiliate end # Purchases let!(:purchase_one) { create(:purchase_in_progress, seller: creator_one, link: creator_one_product_one, affiliate: direct_affiliate_one) } let!(:purchase_two) { create(:purchase_in_progress, seller: creator_one, link: creator_one_product_one, affiliate: direct_affiliate_one) } let!(:purchase_three) { create(:purchase_in_progress, seller: creator_one, link: creator_one_product_three, affiliate: direct_affiliate_one, subscription: create(:subscription, link: creator_one_product_three), is_original_subscription_purchase: true) } let!(:purchase_four) { create(:purchase_in_progress, seller: creator_two, link: creator_two_product_one, affiliate: direct_affiliate_two) } let!(:purchase_five) { create(:purchase_in_progress, seller: creator_two, link: creator_two_product_two, affiliate: direct_affiliate_two, full_name: "John Doe", street_address: "123, Down the street", city: "Barnabasville", state: "CA", country: "United States", zip_code: "94114") } let!(:purchase_six) { create(:purchase_in_progress, seller: creator_two, link: creator_two_product_three, affiliate: direct_affiliate_two, subscription: create(:subscription, link: creator_two_product_three), is_original_subscription_purchase: true) } let!(:purchase_seven) { create(:purchase_in_progress, seller: creator_two, link: creator_two_product_three, affiliate: direct_affiliate_two, subscription: create(:subscription, link: creator_two_product_three), is_original_subscription_purchase: true) } let!(:purchase_eight) { create(:purchase_in_progress, seller: creator_two, link: creator_two_product_three, affiliate: direct_affiliate_two, subscription: create(:subscription, link: creator_two_product_three), is_original_subscription_purchase: true, chargeable: create(:chargeable)) } let!(:purchase_nine) { create(:purchase_in_progress, seller: creator_two, link: creator_two_product_four, affiliate: direct_affiliate_two) } let!(:purchase_ten) { create(:purchase_in_progress, link: another_product, affiliate: direct_affiliate_two) } let!(:purchase_eleven) { create(:purchase_in_progress, seller: global_affiliate_eligible_product.user, link: global_affiliate_eligible_product, affiliate: global_affiliate) } let!(:purchase_twelve) { create(:purchase_in_progress, seller: global_affiliate_eligible_product_two.user, link: global_affiliate_eligible_product_two, affiliate: global_affiliate) } let!(:purchase_thirteen) { create(:purchase_in_progress, seller: global_affiliate_eligible_product.user, link: global_affiliate_eligible_product, affiliate: direct_affiliate_one) } let(:successful_not_reversed_purchases) { [purchase_one, purchase_two, purchase_three, purchase_four, purchase_five, purchase_six, purchase_seven, purchase_eleven, purchase_twelve, purchase_thirteen] } let(:refunded_purchase) { purchase_eight } let(:chargedback_purchase) { purchase_nine } let(:all_product_details) do [ { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) }, { fee_percentage: 15, humanized_revenue: "$0", product_name: "Creator 1 Product 2", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_two) }, { fee_percentage: 15, humanized_revenue: "$0.01", product_name: global_affiliate_eligible_product.name, revenue: 1, sales_count: 1, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(global_affiliate_eligible_product) }, { fee_percentage: 5, humanized_revenue: "$1.04", product_name: "Creator 2 Product 2", revenue: 104, sales_count: 1, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_two) }, { fee_percentage: 25, humanized_revenue: "$3.94", product_name: "Creator 2 Product 3", revenue: 394, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_three) }, { fee_percentage: 10, humanized_revenue: "$0", product_name: "Creator 2 Product 4", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_four) }, { fee_percentage: 10, humanized_revenue: "$0", product_name: global_affiliate_eligible_product.name, revenue: 0, sales_count: 0, affiliate_type: "global_affiliate", url: global_affiliate.referral_url_for_product(global_affiliate_eligible_product) }, { fee_percentage: 10, humanized_revenue: "$0", product_name: global_affiliate_eligible_product_two.name, revenue: 0, sales_count: 0, affiliate_type: "global_affiliate", url: global_affiliate.referral_url_for_product(global_affiliate_eligible_product_two) } ] end before do purchases = successful_not_reversed_purchases + [refunded_purchase, chargedback_purchase] purchases.each do |purchase| purchase.process! purchase.update_balance_and_mark_successful! end refunded_purchase.refund_and_save!(nil) # chargeback purchase allow_any_instance_of(Purchase).to receive(:fight_chargeback).and_return(true) event_flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, chargedback_purchase.total_transaction_cents) event = build(:charge_event_dispute_formalized, charge_id: chargedback_purchase.stripe_transaction_id, flow_of_funds: event_flow_of_funds) chargedback_purchase.handle_event_dispute_formalized!(event) chargedback_purchase.reload # failed purchase create(:purchase_in_progress, seller: creator_one, link: creator_one_product_one, affiliate: direct_affiliate_one).mark_failed! # collaborator (excluded from result) create(:product, :is_collab, user: affiliate_user) end it "returns affiliated products details, stats, and global affiliates data" do props = described_class.new(affiliate_user).affiliated_products_page_props stats = { total_revenue: successful_not_reversed_purchases.sum(&:affiliate_credit_cents), total_sales: 10, total_products: 7, total_affiliated_creators: 3, } global_affiliates_data = { global_affiliate_id: global_affiliate.external_id_numeric, global_affiliate_sales: formatted_dollar_amount(purchase_eleven.affiliate_credit_cents, with_currency: false), cookie_expiry_days: GlobalAffiliate::AFFILIATE_COOKIE_LIFETIME_DAYS, affiliate_query_param: Affiliate::SHORT_QUERY_PARAM, } expect(props[:affiliated_products]).to match_array all_product_details expect(props[:stats]).to eq stats expect(props[:global_affiliates_data]).to eq global_affiliates_data expect(props[:discover_url]).to eq UrlService.discover_domain_with_protocol expect(props[:affiliates_disabled_reason]).to be nil end it "returns affiliates_disabled_reason if using Brazilian Stripe Connect account" do brazilian_stripe_account = create(:merchant_account_stripe_connect, user: affiliate_user, country: "BR") affiliate_user.update!(check_merchant_account_is_linked: true) expect(affiliate_user.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account props = described_class.new(affiliate_user).affiliated_products_page_props expect(props[:affiliates_disabled_reason]).to eq "Affiliates with Brazilian Stripe accounts are not supported." end context "when there is a search query" do context "when the query exactly matches an affiliated product" do let(:query) { "Creator 1 Product 1" } it "returns only the matching product" do props = described_class.new(affiliate_user, query:).affiliated_products_page_props products_details = [ { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) } ] expect(props[:affiliated_products]).to match_array products_details end end context "when the query partially matches an affiliated product" do let(:query) { "Creator 1" } it "returns all matching products" do props = described_class.new(affiliate_user, query:).affiliated_products_page_props products_details = [ { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) }, { fee_percentage: 15, humanized_revenue: "$0", product_name: "Creator 1 Product 2", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_two) } ] expect(props[:affiliated_products]).to match_array products_details end end context "when the query does not match any affiliated products" do let(:query) { "Creator Nobody" } it "returns an empty array" do props = described_class.new(affiliate_user, query:).affiliated_products_page_props expect(props[:affiliated_products]).to be_empty end end end context "supports pagination" do before { stub_const("AffiliatedProductsPresenter::PER_PAGE", 5) } it "returns page 1 by default" do props = described_class.new(affiliate_user).affiliated_products_page_props expect(props[:affiliated_products].count).to eq 5 expect(props[:affiliated_products]).to match_array all_product_details.take(5) pagination = props[:pagination] expect(pagination[:page]).to eq(1) expect(pagination[:pages]).to eq(2) end it "returns the specified page if in range" do props = described_class.new(affiliate_user, page: 2).affiliated_products_page_props expect(props[:affiliated_products].count).to eq 3 expect(props[:affiliated_products]).to match_array all_product_details.drop(5) pagination = props[:pagination] expect(pagination[:page]).to eq(2) expect(pagination[:pages]).to eq(2) end it "raises an error if out of range" do expect do described_class.new(affiliate_user, page: 3).affiliated_products_page_props end.to raise_error(Pagy::OverflowError) end end context "when sorting" do before { stub_const("AffiliatedProductsPresenter::PER_PAGE", 1) } it "returns the products sorted by created timestamp by default" do props = described_class.new(affiliate_user).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) }) props = described_class.new(affiliate_user, page: 2).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$0", product_name: "Creator 1 Product 2", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_two) }) end it "returns the products sorted by revenue when specified" do props = described_class.new(affiliate_user, sort: { key: "revenue", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$0", product_name: "Creator 1 Product 2", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_two) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "revenue", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 10, humanized_revenue: "$0", product_name: "Creator 2 Product 4", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_four) }) props = described_class.new(affiliate_user, sort: { key: "revenue", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 25, humanized_revenue: "$3.94", product_name: "Creator 2 Product 3", revenue: 394, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_three) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "revenue", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) }) end it "returns the products sorted by sales when specified" do props = described_class.new(affiliate_user, sort: { key: "sales_count", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$0", product_name: "Creator 1 Product 2", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_two) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "sales_count", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 10, humanized_revenue: "$0", product_name: "Creator 2 Product 4", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_four) }) props = described_class.new(affiliate_user, sort: { key: "sales_count", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "sales_count", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 25, humanized_revenue: "$3.94", product_name: "Creator 2 Product 3", revenue: 394, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_three) }) end it "returns the products sorted by name when specified" do props = described_class.new(affiliate_user, sort: { key: "product_name", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "product_name", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$0", product_name: "Creator 1 Product 2", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_two) }) props = described_class.new(affiliate_user, sort: { key: "product_name", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly({ fee_percentage: 15, humanized_revenue: "$0.01", product_name: global_affiliate_eligible_product.name, revenue: 1, sales_count: 1, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(global_affiliate_eligible_product) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "product_name", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly({ fee_percentage: 10, humanized_revenue: "$0", product_name: global_affiliate_eligible_product.name, revenue: 0, sales_count: 0, affiliate_type: "global_affiliate", url: global_affiliate.referral_url_for_product(global_affiliate_eligible_product), }) end it "returns the products sorted by commission when specified" do props = described_class.new(affiliate_user, sort: { key: "commission", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 5, humanized_revenue: "$1.04", product_name: "Creator 2 Product 2", revenue: 104, sales_count: 1, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_two) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "commission", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 10, humanized_revenue: "$0", product_name: "Creator 2 Product 4", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_four) }) props = described_class.new(affiliate_user, sort: { key: "commission", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 25, humanized_revenue: "$3.94", product_name: "Creator 2 Product 3", revenue: 394, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_two.referral_url_for_product(creator_two_product_three) }) props = described_class.new(affiliate_user, page: 2, sort: { key: "commission", direction: "desc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly( { fee_percentage: 15, humanized_revenue: "$2.36", product_name: "Creator 1 Product 1", revenue: 236, sales_count: 2, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_one) }) end it "returns the products sorted by created timestamp when the sort field is invalid" do props = described_class.new(affiliate_user, sort: { key: "invalid", direction: "asc" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly all_product_details.first end it "returns the products in ascending order when the sort direction is invalid" do props = described_class.new(affiliate_user, sort: { key: "revenue", direction: "desc; invalid or nefarious SQL" }).affiliated_products_page_props expect(props[:affiliated_products]).to contain_exactly({ fee_percentage: 15, humanized_revenue: "$0", product_name: "Creator 1 Product 2", revenue: 0, sales_count: 0, affiliate_type: "direct_affiliate", url: direct_affiliate_one.referral_url_for_product(creator_one_product_two) }) end end end describe "#archived_tab_visible" do let(:seller) { create(:user, username: "seller1") } let!(:product) { create(:product, archived: true, user: seller) } it "returns archived products present and feature active" do expect(described_class.new(seller).affiliated_products_page_props[:archived_tab_visible]).to eq(true) product.destroy! expect(described_class.new(seller).affiliated_products_page_props[:archived_tab_visible]).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/presenters/post_presenter_spec.rb
spec/presenters/post_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe PostPresenter do before do @creator = create(:named_user) @product = create(:product, user: @creator) @product_post = create(:published_installment, link: @product, seller: @creator, call_to_action_url: "https://example.com", call_to_action_text: "Example") @follower_post = create(:follower_installment, seller: @creator, published_at: 3.days.ago, shown_on_profile: true) @user = create(:user) @purchase = create(:purchase, link: @product, purchaser: @user, created_at: 1.minute.ago) create(:follower, user: @creator, email: @user.email, confirmed_at: Time.current) end describe "#initialize" do it "sets the presented identifiers as instance variables" do pundit_user = SellerContext.new(user: @user, seller: @user) presenter_with_logged_in_user = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: nil) expect(presenter_with_logged_in_user.post).to eq @product_post expect(presenter_with_logged_in_user.pundit_user).to eq pundit_user expect(presenter_with_logged_in_user.purchase).to eq @purchase another_product = create(:product, user: @creator) another_purchase = create(:purchase, link: another_product, purchaser: @user) pundit_user = SellerContext.logged_out user_presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: another_purchase.external_id) expect(user_presenter.post).to eq @product_post expect(user_presenter.purchase).to eq another_purchase end end describe "#post_component_props" do before do @comment1 = create(:comment, commentable: @product_post, author: @user, created_at: 20.seconds.ago) @comment1_reply = create(:comment, commentable: @product_post, author: @user, parent: @comment1, created_at: 10.seconds.ago) @comment2 = create(:comment, commentable: @product_post, created_at: Time.current) @another_product_post = create(:published_installment, link: @product, seller: @creator) create(:seller_profile_posts_section, seller: @creator, shown_posts: []) end it "returns props for the post component" do @creator.reload pundit_user = SellerContext.new(user: @user, seller: @user) presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: "test") expect(presenter.post_component_props).to eq( creator_profile: ProfilePresenter.new(pundit_user:, seller: @creator).creator_profile, subject: @product_post.subject, slug: @product_post.slug, external_id: @product_post.external_id, purchase_id: nil, published_at: @product_post.published_at, message: @product_post.message, call_to_action: { text: "Example", url: "https://example.com" }, download_url: nil, has_posts_on_profile: true, recent_posts: [{ name: @another_product_post.name, published_at: @another_product_post.published_at, slug: @another_product_post.slug, truncated_description: @another_product_post.truncated_description, purchase_id: @purchase.external_id }], paginated_comments: { comments: [ { id: @comment1.external_id, parent_id: nil, author_id: @comment1.author.external_id, author_name: @comment1.author.display_name, author_avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), purchase_id: nil, content: { original: @comment1.content, formatted: CGI.escapeHTML(@comment1.content) }, created_at: @comment1.created_at.iso8601, created_at_humanized: "less than a minute ago", depth: 0, is_editable: true, is_deletable: true }, { id: @comment1_reply.external_id, parent_id: @comment1.external_id, author_id: @comment1_reply.author.external_id, author_name: @comment1_reply.author.display_name, author_avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), purchase_id: nil, content: { original: @comment1_reply.content, formatted: CGI.escapeHTML(@comment1_reply.content) }, created_at: @comment1_reply.created_at.iso8601, created_at_humanized: "less than a minute ago", depth: 1, is_editable: true, is_deletable: true }, { id: @comment2.external_id, parent_id: nil, author_id: @comment2.author.external_id, author_name: @comment2.author.display_name, author_avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), purchase_id: nil, content: { original: @comment2.content, formatted: CGI.escapeHTML(@comment2.content) }, created_at: @comment2.created_at.iso8601, created_at_humanized: "less than a minute ago", depth: 0, is_editable: false, is_deletable: false } ], count: 3, pagination: { count: 2, items: PaginatedCommentsPresenter::COMMENTS_PER_PAGE, last: 1, pages: 1, page: 1, next: nil, prev: nil } }, comments_max_allowed_depth: 4, ) end context "when 'allow_comments' flag is disabled" do pundit_user = SellerContext.logged_out let(:presenter) { PostPresenter.new(pundit_user:, post: create(:published_installment, allow_comments: false), purchase_id_param: "test") } it "responds with 'paginated_comments' set to nil" do expect(presenter.post_component_props[:paginated_comments]).to be_nil end end end describe ".snippet" do it "returns a sanitized version of the message limited to 150 characters" do message = Faker::Lorem.paragraphs(number: 10).join post = create(:published_installment, seller: @user, message:) pundit_user = SellerContext.new(user: @user, seller: @user) presenter = PostPresenter.new(pundit_user:, post:, purchase_id_param: nil) expect(presenter.snippet).to eq(message.first(150)) end it "snips post the sanitization and retains more information" do message = "<div class=\"medium-insert-images contains-image-1530256361\"><figure contenteditable=\"false\">\n <img src=\"#{AWS_S3_ENDPOINT}/gumroad/files/6282492303727/495e31a6aa1b41b5b580ed6775899d2e/original/TwitterGraphic.png\" alt=\"\">\n \n</figure></div><p class=\"\">Today, we're launching the Gumroad creator dashboard app for Android.</p><p class=\"\">You can download it from the Play store here:&nbsp;<a href=\"https://play.google.com/store/apps/details?id=com.gumroad.creator\" target=\"_blank\" rel=\"noopener noreferrer\">https://play.google.com/store/apps/details?id=com.gumroad.creator</a></p><h3>Feature Parity</h3><p class=\"\">Once you log into your Gumroad account on the Android app, you'll be able to see daily, monthly, and lifetime sales on your account. For each transaction, you can see your customer's email, what they bought, when they bought it, and how much they paid. If you have email notifications turned on, you can also get push notifications from the app itself every time you make a sale. This matches the functionality of the iOS app.<br></p><div class=\"medium-insert-images contains-image--2098371296\"><figure contenteditable=\"false\">\n <img src=\"#{AWS_S3_ENDPOINT}/gumroad/files/6282492303727/77b3ca4900024c91a9fd192307784177/original/screenshot_frame_light1-2.png\" alt=\"\">\n \n</figure></div><p>The app is a read-only view of this data: you can't issue refunds, look at analytics, send posts, or take any other actions on the app. For that, you'll need to head over to your account on the web. The app also does not currently show sales that you drove as an affiliate. Now that we have an iOS and an Android engineer working at Gumroad again, we will be able to bring more feature updates to all Gumroad apps, though our upcoming focus is on improving the consumer app on both operating systems.</p><p>Oh, and we couldn't resist throwing in one thing that iOS doesn't have: dark mode!</p><div class=\"medium-insert-images contains-image--738016557\"><figure contenteditable=\"false\">\n <img src=\"#{AWS_S3_ENDPOINT}/gumroad/files/6282492303727/7e96cabd43d74332bbfcc842fafe78d3/original/screenshot_frame_dark1.png\" alt=\"\">\n \n</figure></div><h3>Why We Built It</h3><p class=\"\">Gumroad builds tools for creators, which includes building tools for said creators' audiences. With limited engineering resources, we focus on building for the web, which is cross-platform and gives the highest return on investment. However, we offer both creators and their audiences apps. The Gumroad app for customers is the Gumroad library app, which lets you download and view content that you've bought on Gumroad. The creator app, also known as the dashboard app, lets you see your sales. While the customer app has been available on both Android and iOS for quite some time, the creator app was iOS-only until today.<br></p><p class=\"\">We are working on <a href=\"https://www.notion.so/gumroad/Roadmap-ce2ad07c483046e7941227ad7810730d\" target=\"_blank\" rel=\"noopener noreferrer\">lots of stuff </a>at Gumroad, so why invest in creating an Android app for creators? Well, people were asking for it, and the data backs up these requests.<br></p><div class=\"medium-insert-images contains-image-661100503\"><figure contenteditable=\"false\">\n <img src=\"#{AWS_S3_ENDPOINT}/gumroad/files/6282492303727/b3f0237666c44981a372d4858b167455/original/Screen%20Shot%202020-12-07%20at%2010.19.46%20AM.png\" alt=\"\">\n \n</figure></div><p>In November, 13.88% of creators with a session that included visiting gumroad.com/dashboard/sales viewed it on a device running android, but 20.07% of the sessions were from that OS. While more iOS users overall viewed the page, including more new users, they were responsible for far fewer sessions per user, suggesting that the availability of the iOS app cuts down on the amount of times creators have to check their analytics when all they want to know is recent and total sales figures.<br></p><h3>Available Today</h3><p class=\"\">If you are a Gumroad Creator with an Android device, download it today from the Google Play Store!<br></p><p class=\"\"><a href=\"https://play.google.com/store/apps/details?id=com.gumroad.creator\" target=\"_blank\" rel=\"noopener noreferrer\">https://play.google.com/store/apps/details?id=com.gumroad.creator</a><br></p><h3>Plus: Upcoming Event</h3><p class=\"\">On Wednesday, December 9th, at 10 AM PST, Randall Kanna is hosting \"The 5 Things You Need To Fix If You Want to Skyrocket your Sales\" on Zoom. Join live and ask questions or check the event out afterwards on YouTube.</p><p class=\"\">Register here:&nbsp;<a href=\"https://us02web.zoom.us/webinar/register/6416073525016/WN_qUH_4J-6TpW2dqiDc-PRhg\" target=\"_blank\" rel=\"noopener noreferrer\">https://us02web.zoom.us/webinar/register/6416073525016/WN_qUH_4J-6TpW2dqiDc-PRhg</a></p>" post = create(:published_installment, seller: @user, message:) pundit_user = SellerContext.new(user: @user, seller: @user) presenter = PostPresenter.new(pundit_user:, post:, purchase_id_param: nil) expect(presenter.snippet).to eq("Today, we're launching the Gumroad creator dashboard app for Android. You can download it from the Play store here: https://play.google.com/store/apps") end end describe "#social_image" do it "returns a Post::SocialImage with properly set url and caption" do post = build( :published_installment, seller: @user, message: <<~HTML <figure> <img src="path/to/image.jpg"> <p class="figcaption">Caption</p> </figure> HTML ) pundit_user = SellerContext.new(user: @user, seller: @user) presenter = PostPresenter.new(pundit_user:, post:, purchase_id_param: nil) expect(presenter.social_image.url).to eq("path/to/image.jpg") expect(presenter.social_image.caption).to eq("Caption") end end describe "#e404?" do let(:unpublished_post) { create(:installment, seller: @creator, published_at: nil) } let(:hidden_post) { create(:published_installment, seller: @creator, link: @product, shown_on_profile: false) } let(:workflow_post) { create(:workflow_installment, seller: @creator, link: @product, bought_products: [@product.unique_permalink]) } let(:seller_post) { create(:seller_post, seller: @creator, bought_products: [@product.external_id], shown_on_profile: true, send_emails: false) } context "when the creator is viewing the post" do let(:pundit_user) { SellerContext.new(user: @creator, seller: @creator) } it "returns false for an unpublished post" do presenter = PostPresenter.new(pundit_user:, post: unpublished_post, purchase_id_param: nil) expect(presenter.e404?).to be(false) end it "returns false for a shown_on_profile=false post" do presenter = PostPresenter.new(pundit_user:, post: hidden_post, purchase_id_param: nil) expect(presenter.e404?).to be(false) end it "returns false for a product post" do presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: nil) expect(presenter.e404?).to be(false) end it "returns false for a workflow post" do presenter = PostPresenter.new(pundit_user:, post: workflow_post, purchase_id_param: nil) expect(presenter.e404?).to be(false) end end context "when a customer with a relevant purchase is viewing the post" do let(:pundit_user) { SellerContext.new(user: @user, seller: @user) } it "returns true for an unpublished post" do presenter = PostPresenter.new(pundit_user:, post: unpublished_post, purchase_id_param: nil) expect(presenter.e404?).to be(true) end it "returns true for an published post that has been deleted" do post = create(:published_installment, seller: @user, shown_on_profile: true, deleted_at: Time.current) presenter = PostPresenter.new(pundit_user:, post:, purchase_id_param: nil) expect(presenter.e404?).to be(true) end it "returns false for a shown_on_profile=false post" do presenter = PostPresenter.new(pundit_user:, post: hidden_post, purchase_id_param: nil) expect(presenter.e404?).to be(false) end it "returns false for a workflow post" do presenter = PostPresenter.new(pundit_user:, post: workflow_post, purchase_id_param: nil) expect(presenter.e404?).to be(false) end end context "when a customer without a relevant purchase is viewing the post" do let(:user) { create(:purchase, link: create(:product, user: @creator)).purchaser } let(:pundit_user) { SellerContext.new(user:, seller: user) } it "returns true for a product-type post" do presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: nil) expect(presenter.e404?).to be(true) end it "returns true for a seller-type shown-on-profile post" do presenter = PostPresenter.new(pundit_user:, post: seller_post, purchase_id_param: nil) expect(presenter.e404?).to be(true) end end context "when a non-customer is viewing the post" do let(:user) { create(:user) } let(:pundit_user) { SellerContext.new(user:, seller: user) } it "returns true for a shown_on_profile=false post" do presenter = PostPresenter.new(pundit_user:, post: hidden_post, purchase_id_param: nil) expect(presenter.e404?).to be(true) end end context "when an unauthenticated user is viewing the post" do let(:pundit_user) { SellerContext.logged_out } it "returns true with a refunded purchase's param" do purchase = create(:refunded_purchase, link: @product) presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: purchase.external_id) expect(presenter.e404?).to be(true) end it "returns true with a chargedback purchase's param" do purchase = create(:purchase, link: @product, chargeback_date: Date.today) presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: purchase.external_id) expect(presenter.e404?).to be(true) end it "returns true with a purchase param that should not have access to a product-type post" do purchase = create(:purchase, link: create(:product, user: @creator)) # another of the seller's products presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: purchase.external_id) expect(presenter.e404?).to be(true) end it "returns true with a purchase param that should not have access to a seller-type shown-on-profile post" do purchase = create(:purchase, link: create(:product, user: @creator)) # another of the seller's products presenter = PostPresenter.new(pundit_user:, post: seller_post, purchase_id_param: purchase.external_id) expect(presenter.e404?).to be(true) end it "returns false with a valid purchase's param" do purchase = create(:purchase, link: @product) presenter = PostPresenter.new(pundit_user:, post: @product_post, purchase_id_param: purchase.external_id) expect(presenter.e404?).to be(false) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/paginated_product_posts_presenter_spec.rb
spec/presenters/paginated_product_posts_presenter_spec.rb
# frozen_string_literal: true describe PaginatedProductPostsPresenter do describe "#index_props" do let(:product) { create(:product) } let!(:seller_post_for_customers_of_all_products) { create(:seller_post, seller: product.user, published_at: 3.hours.ago) } let!(:product_workflow_post) { create(:workflow_installment, workflow: create(:product_workflow, seller: product.user, link: product, published_at: 1.day.ago, bought_products: [product.unique_permalink]), link: product, published_at: 1.day.ago, bought_products: [product.unique_permalink]) } let(:options) { {} } let(:presenter) { described_class.new(product:, variant_external_id: nil, options:) } before do stub_const("#{described_class}::PER_PAGE", 1) end context "when 'page' option is not specified" do it "returns paginated posts for the first page" do result = presenter.index_props expect(result[:total]).to eq(2) expect(result[:next_page]).to eq(2) expect(result[:posts].size).to eq(1) expect(result[:posts].first).to eq( id: product_workflow_post.external_id, name: product_workflow_post.name, date: { type: "workflow_email_rule", time_duration: product_workflow_post.installment_rule.displayable_time_duration, time_period: product_workflow_post.installment_rule.time_period }, url: product_workflow_post.full_url ) end end context "when 'page' option is specified" do let(:options) { { page: 2 } } it "returns paginated posts for the specified page" do result = presenter.index_props expect(result[:total]).to eq(2) expect(result[:next_page]).to be_nil expect(result[:posts].size).to eq(1) expect(result[:posts].first).to eq( id: seller_post_for_customers_of_all_products.external_id, name: seller_post_for_customers_of_all_products.name, date: { type: "date", value: seller_post_for_customers_of_all_products.published_at }, url: seller_post_for_customers_of_all_products.full_url ) end end context "when the specified 'page' option is an overflowing page number" do let(:options) { { page: 3 } } it "raises an exception" do expect do presenter.index_props end.to raise_error(Pagy::OverflowError) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/dashboard_products_page_presenter_spec.rb
spec/presenters/dashboard_products_page_presenter_spec.rb
# frozen_string_literal: true describe DashboardProductsPagePresenter do let(:marketing_for_seller) { create(:user, username: "marketingforseller") } let(:support_for_seller) { create(:user, username: "supportforseller") } let(:seller) { create(:named_seller) } let(:pundit_user) { SellerContext.new(user: marketing_for_seller, seller:) } before do create(:team_membership, user: marketing_for_seller, seller:, role: TeamMembership::ROLE_MARKETING) create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT) end describe "#page_props" do let(:membership) { create(:membership_product, user: seller, name: "Strong, stronger & <strong>strongest</strong>") } let(:product) { create(:product, user: seller, name: "Strong, stronger & <strong>strongest</strong>") } let(:presenter) do described_class.new( pundit_user:, memberships: [membership], memberships_pagination: nil, products: [product], products_pagination: nil ) end it "caches dashboard data", :sidekiq_inline do expect do presenter.page_props end.to change { ProductCachedValue.count }.from(0).to(2) end context "when the user has full access" do it "returns memberships and products data for the dashboard products page" do expect(presenter.page_props).to match( { memberships: [ { "id" => be_present, "edit_url" => be_present, "is_duplicating" => false, "is_unpublished" => false, "name" => "Strong, stronger & <strong>strongest</strong>", "permalink" => be_present, "price_formatted" => "$1 a month", "display_price_cents" => 100, "revenue" => 0.0, "status" => "published", "thumbnail" => nil, "url" => be_present, "url_without_protocol" => be_present, "has_duration" => false, "successful_sales_count" => 0, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 0, "can_edit" => true, "can_destroy" => true, "can_duplicate" => true, "can_archive" => true, "can_unarchive" => false } ], memberships_pagination: nil, products: [ { "id" => be_present, "edit_url" => be_present, "is_duplicating" => false, "is_unpublished" => false, "name" => "Strong, stronger & <strong>strongest</strong>", "permalink" => be_present, "price_formatted" => "$1", "display_price_cents" => 100, "revenue" => 0, "status" => "published", "thumbnail" => nil, "url" => be_present, "url_without_protocol" => be_present, "has_duration" => false, "successful_sales_count" => 0, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 0, "can_edit" => true, "can_destroy" => true, "can_duplicate" => true, "can_archive" => true, "can_unarchive" => false }, ], products_pagination: nil, archived_products_count: 0, can_create_product: true, } ) end end context "when the user has read-only access" do let(:expected_policy_props) do { "can_edit" => false, "can_destroy" => false, "can_duplicate" => false, "can_archive" => false, "can_unarchive" => false, } end let(:pundit_user) { SellerContext.new(user: support_for_seller, seller:) } it "returns correct policy props" do expect(presenter.page_props[:memberships].first.slice(*expected_policy_props.keys)).to eq(expected_policy_props) expect(presenter.page_props[:products].first.slice(*expected_policy_props.keys)).to eq(expected_policy_props) end end end describe "#memberships_table_props" do before do @memberships = create_list(:membership_product, 2, user: seller) @instance = described_class.new( pundit_user:, memberships: @memberships, memberships_pagination: nil, products: nil, products_pagination: nil ) end it "returns memberships data for the memberships table component" do expect(@instance.memberships_table_props).to match( { memberships: [ { "id" => be_present, "edit_url" => be_present, "is_duplicating" => false, "is_unpublished" => false, "name" => "The Works of Edgar Gumstein", "permalink" => be_present, "price_formatted" => "$1 a month", "display_price_cents" => 100, "revenue" => 0, "status" => "published", "thumbnail" => nil, "url" => be_present, "url_without_protocol" => be_present, "has_duration" => false, "successful_sales_count" => 0, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 0, "can_edit" => true, "can_destroy" => true, "can_duplicate" => true, "can_archive" => true, "can_unarchive" => false }, { "id" => be_present, "edit_url" => be_present, "is_duplicating" => false, "is_unpublished" => false, "name" => "The Works of Edgar Gumstein", "permalink" => be_present, "price_formatted" => "$1 a month", "display_price_cents" => 100, "revenue" => 0, "status" => "published", "thumbnail" => nil, "url" => be_present, "url_without_protocol" => be_present, "has_duration" => false, "successful_sales_count" => 0, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 0, "can_edit" => true, "can_destroy" => true, "can_duplicate" => true, "can_archive" => true, "can_unarchive" => false } ], memberships_pagination: nil, } ) end end describe "#products_table_props" do before do @products = create_list(:product, 2, user: seller) @instance = described_class.new( pundit_user:, memberships: nil, memberships_pagination: nil, products: @products, products_pagination: nil ) end it "returns products data for the products table component" do expect(@instance.products_table_props).to match( { products: [ { "id" => be_present, "edit_url" => be_present, "is_duplicating" => false, "is_unpublished" => false, "name" => "The Works of Edgar Gumstein", "permalink" => be_present, "price_formatted" => "$1", "display_price_cents" => 100, "revenue" => 0, "status" => "published", "thumbnail" => nil, "url" => be_present, "url_without_protocol" => be_present, "has_duration" => false, "successful_sales_count" => 0, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 0, "can_edit" => true, "can_destroy" => true, "can_duplicate" => true, "can_archive" => true, "can_unarchive" => false }, { "id" => be_present, "edit_url" => be_present, "is_duplicating" => false, "is_unpublished" => false, "name" => "The Works of Edgar Gumstein", "permalink" => be_present, "price_formatted" => "$1", "display_price_cents" => 100, "revenue" => 0, "status" => "published", "thumbnail" => nil, "url" => be_present, "url_without_protocol" => be_present, "has_duration" => false, "successful_sales_count" => 0, "remaining_for_sale_count" => nil, "monthly_recurring_revenue" => 0.0, "revenue_pending" => 0.0, "total_usd_cents" => 0, "can_edit" => true, "can_destroy" => true, "can_duplicate" => true, "can_archive" => true, "can_unarchive" => false }, ], products_pagination: nil } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/installment_presenter_spec.rb
spec/presenters/installment_presenter_spec.rb
# frozen_string_literal: true describe InstallmentPresenter do let(:seller) { create(:named_seller) } describe "#new_page_props" do let!(:product1) { create(:product_with_digital_versions, name: "Product 1", user: seller) } let!(:product2) { create(:product, name: "Product 2", user: seller, archived: true) } let!(:membership) { create(:membership_product, name: "Membership product", user: seller) } let!(:physical_product) { create(:physical_product, name: "Physical product", user: seller, skus_enabled: true) } let!(:sku1) { create(:sku, link: physical_product, name: "Blue - Large") } let!(:sku2) { create(:sku, link: physical_product, name: "Green - Small") } let!(:installment) { create(:installment, seller:, allow_comments: true) } it "returns the correct display_type" do expect(described_class.new(seller:, installment:).props[:display_type]).to eq("draft") end it "returns necessary props" do section = create(:seller_profile_posts_section, seller:) props = described_class.new(seller:).new_page_props expect(props.keys).to include(:context) expect(props[:context].keys).to match_array(%i(audience_types products affiliate_products timezone currency_type countries profile_sections has_scheduled_emails aws_access_key_id s3_url user_id allow_comments_by_default from_tab)) expect(props[:context][:products]).to match_array( [ { permalink: product1.unique_permalink, name: "Product 1", archived: false, variants: [ { id: product1.variants.first.external_id, name: "Untitled 1" }, { id: product1.variants.second.external_id, name: "Untitled 2" } ] }, { permalink: membership.unique_permalink, name: "Membership product", archived: false, variants: [ { id: membership.tiers.sole.external_id, name: "Untitled" } ] }, { permalink: physical_product.unique_permalink, name: "Physical product", archived: false, variants: [ { id: sku1.external_id, name: "Blue - Large" }, { id: sku2.external_id, name: "Green - Small" } ] } ] ) expect(props[:context][:affiliate_products]).to match_array( [ { permalink: product1.unique_permalink, name: "Product 1", archived: false }, { permalink: membership.unique_permalink, name: "Membership product", archived: false }, { permalink: physical_product.unique_permalink, name: "Physical product", archived: false } ] ) expect(props[:context][:timezone]).to eq(ActiveSupport::TimeZone[seller.timezone].now.strftime("%Z")) expect(props[:context][:currency_type]).to eq("usd") expect(props[:context][:countries]).to match_array(["United States"] + Compliance::Countries.for_select.map { _1.last }.without("United States")) expect(props[:context][:profile_sections]).to eq([{ id: section.external_id, name: nil }]) expect(props[:context][:has_scheduled_emails]).to be(false) expect(props[:context][:user_id]).to eq(seller.external_id) expect(props[:context][:allow_comments_by_default]).to be(true) end it "returns true 'has_scheduled_emails' when seller has scheduled emails" do create(:installment, seller:, ready_to_publish: true) expect(described_class.new(seller:).new_page_props[:context][:has_scheduled_emails]).to be(true) end it "returns necessary props with `installment` attribute when `copy_from` is present" do reference_installment = create(:product_installment, seller:, link: product1) props = described_class.new(seller:).new_page_props(copy_from: reference_installment.external_id) expect(props.keys).to match_array(%i(context installment)) expect(props[:installment]).to eq(described_class.new(seller:, installment: reference_installment).props.except(:external_id)) end end describe "#edit_page_props" do let!(:product) { create(:product_with_digital_versions, name: "Product 1", user: seller) } let!(:installment) { create(:installment, seller:, link: product, allow_comments: false) } it "returns necessary props" do props = described_class.new(seller:, installment:).edit_page_props expect(props.keys).to match_array(%i(context installment)) expect(props[:context].keys).to match_array(%i(audience_types products affiliate_products timezone currency_type countries profile_sections has_scheduled_emails aws_access_key_id s3_url user_id allow_comments_by_default from_tab)) expect(props[:context][:products]).to match_array( [ { permalink: product.unique_permalink, name: "Product 1", archived: false, variants: [ { id: product.variants.first.external_id, name: "Untitled 1" }, { id: product.variants.second.external_id, name: "Untitled 2" } ] } ] ) expect(props[:context][:affiliate_products]).to match_array( [ { permalink: product.unique_permalink, name: "Product 1", archived: false } ] ) expect(props[:context][:timezone]).to eq(ActiveSupport::TimeZone[seller.timezone].now.strftime("%Z")) expect(props[:context][:currency_type]).to eq("usd") expect(props[:context][:countries]).to match_array(["United States"] + Compliance::Countries.for_select.map { _1.last }.without("United States")) expect(props[:context][:profile_sections]).to eq([]) expect(props[:context][:has_scheduled_emails]).to be(false) expect(props[:context][:user_id]).to eq(seller.external_id) expect(props[:context][:allow_comments_by_default]).to be(false) expect(props[:installment]).to eq(described_class.new(seller:, installment:).props) end end describe "#props" do let(:product) { create(:product, user: seller) } let(:installment) { create(:installment, link: product, published_at: 1.day.ago, name: "1 day") } before do create(:installment_rule, installment:, delayed_delivery_time: 1.day) end it "includes the necessary installment details" do section = create(:seller_profile_posts_section, seller:, shown_posts: [installment.id]) create(:seller_profile_posts_section, seller:, shown_posts: [create(:installment).id]) installment.update!(shown_on_profile: true) props = described_class.new(seller:, installment:).props expect(props).to match(a_hash_including( name: "1 day", message: installment.message, files: [], published_at: installment.published_at, updated_at: installment.updated_at, external_id: installment.external_id, stream_only: false, call_to_action_text: nil, call_to_action_url: nil, streamable: false, sent_count: nil, click_count: 0, open_count: 0, click_rate: nil, open_rate: nil, clicked_urls: [], view_count: 0, full_url: installment.full_url, send_emails: true, shown_on_profile: true, has_been_blasted: false, shown_in_profile_sections: [section.external_id] )) expect(props.keys).to_not include(:published_once_already, :member_cancellation, :new_customers_only, :delayed_delivery_time_duration, :delayed_delivery_time_period, :displayed_delayed_delivery_time_period) expect(props.keys).to_not include(:recipient_description, :to_be_published_at) end context "when installment is of type `product`" do let!(:installment) { create(:product_installment, seller:, link: product, paid_more_than_cents: 100, paid_less_than_cents: 200, bought_from: "Japan", created_before: "2024-05-30", created_after: "2024-01-01", allow_comments: false) } it "includes necessary attributes" do props = described_class.new(seller:, installment:).props expect(props).to match(a_hash_including( external_id: installment.external_id, installment_type: "product", unique_permalink: product.unique_permalink, paid_more_than_cents: 100, paid_less_than_cents: 200, bought_from: "Japan", created_after: Date.parse("2024-01-01"), created_before: Date.parse("2024-05-30"), allow_comments: false, )) end end context "when installment is of type `variant`" do let(:variant) { create(:variant, variant_category: create(:variant_category, link: product)) } let!(:installment) { create(:variant_installment, seller:, base_variant: variant) } it "includes necessary attributes" do props = described_class.new(seller:, installment:).props expect(props).to match(a_hash_including( installment_type: "variant", variant_external_id: variant.external_id )) end end context "when installment is of type `seller`" do let(:variant) { create(:variant, variant_category: create(:variant_category, link: product)) } let(:product2) { create(:product, user: seller) } let!(:installment) { create(:seller_installment, seller:, bought_products: [product.unique_permalink], bought_variants: [variant.external_id], not_bought_products: [product2.unique_permalink]) } it "includes necessary attributes" do props = described_class.new(seller:, installment:).props expect(props).to match(a_hash_including( installment_type: "seller", bought_products: [product.unique_permalink], bought_variants: [variant.external_id], not_bought_products: [product2.unique_permalink] )) end end context "when installment is of type `follower`" do let!(:installment) { create(:follower_installment, seller:) } it "includes necessary attributes" do expect(described_class.new(seller:, installment:).props[:installment_type]).to eq("follower") end end context "when installment is of type `audience`" do let!(:installment) { create(:audience_installment, seller:) } it "includes necessary attributes" do expect(described_class.new(seller:, installment:).props[:installment_type]).to eq("audience") end end context "when installment is of type `affiliate`" do let!(:installment) { create(:affiliate_installment, seller:, affiliate_products: [product.unique_permalink]) } it "includes necessary attributes" do expect(described_class.new(seller:, installment:).props).to match(a_hash_including( installment_type: "affiliate", affiliate_products: [product.unique_permalink] )) end end context "when installment is not published" do before do installment.update!(published_at: nil) end it "includes appropriate 'recipient_description' for a seller type installment" do installment.update!(installment_type: Installment::SELLER_TYPE) props = described_class.new(seller:, installment:).props expect(props[:recipient_description]).to eq("Your customers") end it "includes appropriate 'recipient_description' for a product type installment" do installment.update!(installment_type: Installment::PRODUCT_TYPE) props = described_class.new(seller:, installment:).props expect(props[:recipient_description]).to eq("Customers of #{product.name}") end it "includes appropriate 'recipient_description' for a variant type installment" do variant = create(:variant) installment.update!(installment_type: Installment::VARIANT_TYPE, base_variant: variant) props = described_class.new(seller:, installment:).props expect(props[:recipient_description]).to eq("Customers of #{product.name} - #{variant.name}") end it "includes appropriate 'recipient_description' for a follower type installment" do installment.update!(installment_type: Installment::FOLLOWER_TYPE) props = described_class.new(seller:, installment:).props expect(props[:recipient_description]).to eq("Your followers") end it "includes appropriate 'recipient_description' for an audience type installment" do installment.update!(installment_type: Installment::AUDIENCE_TYPE) props = described_class.new(seller:, installment:).props expect(props[:recipient_description]).to eq("Your customers and followers") end it "includes appropriate 'recipient_description' for an affiliate type installment" do installment.update!(installment_type: Installment::AFFILIATE_TYPE) props = described_class.new(seller:, installment:).props expect(props[:recipient_description]).to eq("Your affiliates") end it "includes appropriate 'recipient_description' for an affiliate product post" do installment.update!(installment_type: Installment::AFFILIATE_TYPE, affiliate_products: [product.unique_permalink]) props = described_class.new(seller:, installment:).props expect(props[:recipient_description]).to eq("Affiliates of #{product.name}") end context "when installment is scheduled" do it "includes 'to_be_published_at'" do installment.update!(ready_to_publish: true) props = described_class.new(seller:, installment:).props expect(props[:to_be_published_at]).to eq(installment.installment_rule.to_be_published_at) end end context "when installment is in draft" do it "does not include 'to_be_published_at'" do props = described_class.new(seller:, installment:).props expect(props).to_not have_key(:to_be_published_at) end end end context "for a workflow installment" do let(:workflow) { create(:workflow, seller:, link: product) } before do installment.update!(workflow:) end it "includes additional workflow-related details" do props = described_class.new(seller:, installment:).props expect(props).to match(a_hash_including( published_once_already: true, member_cancellation: false, new_customers_only: false, delayed_delivery_time_duration: 24, delayed_delivery_time_period: "hour", displayed_delayed_delivery_time_period: "Hours" )) expect(props.keys).to_not include(:clicked_urls, :view_count, :full_url, :recipient_description, :to_be_published_at) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/affiliates_presenter_spec.rb
spec/presenters/affiliates_presenter_spec.rb
# frozen_string_literal: true describe AffiliatesPresenter do describe "#index_props" do let(:seller) { create(:named_user) } let(:admin_for_seller) { create(:user, username: "adminforseller") } let(:support_for_seller) { create(:user, username: "supportforseller") } let(:pundit_user) { SellerContext.new(user: admin_for_seller, seller:) } before do create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN) create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT) end let(:affiliate_user) { create(:affiliate_user, name: "Affiliated") } let(:product) { create(:product, name: "Gumbot bits", unique_permalink: "test", user: seller) } let!(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller:, products: [product]) } let!(:affiliate_request) { create(:affiliate_request, seller:) } it "returns the necessary props to render the affiliates page" do props = described_class.new(pundit_user, should_get_affiliate_requests: true).index_props expect(JSON.parse(props.to_json).deep_symbolize_keys!).to match( { affiliate_requests: [affiliate_request.as_json(pundit_user:)], affiliates: [ { id: direct_affiliate.external_id, affiliate_user_name: "Affiliated", destination_url: nil, email: affiliate_user.email, fee_percent: 3, product_referral_url: direct_affiliate.referral_url_for_product(product), apply_to_all_products: true, products: [ { id: product.external_id_numeric, name: "Gumbot bits", fee_percent: 3, referral_url: "#{direct_affiliate.referral_url}/test", destination_url: nil, } ] } ], pagination: { page: 1, pages: 1 }, allow_approve_all_requests: false, affiliates_disabled_reason: nil, }) end context "when search query is present" do context "when partially matching an affiliate user" do let(:query) { "affil" } it "returns the necessary props to render the affiliates page" do props = described_class.new(pundit_user, query:).index_props expect(JSON.parse(props.to_json).deep_symbolize_keys!).to match( { affiliate_requests: [], affiliates: [direct_affiliate.as_json], pagination: { page: 1, pages: 1 }, allow_approve_all_requests: false, affiliates_disabled_reason: nil, }) end end context "and value does not match any affiliate users" do let(:query) { "gumbot" } it "returns the necessary props to render the affiliates page" do props = described_class.new(pundit_user, query:).index_props expect(JSON.parse(props.to_json).deep_symbolize_keys!).to match( { affiliate_requests: [], affiliates: [], pagination: { page: 1, pages: 1 }, allow_approve_all_requests: false, affiliates_disabled_reason: nil, }) end end context "and value is empty" do let(:query) { "" } it "returns the necessary props to render the affiliates page" do props = described_class.new(pundit_user, query:, should_get_affiliate_requests: true).index_props expect(JSON.parse(props.to_json).deep_symbolize_keys!).to match( { affiliate_requests: [affiliate_request.as_json(pundit_user:)], affiliates: [direct_affiliate.as_json], pagination: { page: 1, pages: 1 }, allow_approve_all_requests: false, affiliates_disabled_reason: nil, }) end end end end describe "#onboarding_form_props" do let(:seller) { create(:named_user) } let(:admin_for_seller) { create(:user, username: "adminforseller") } let(:support_for_seller) { create(:user, username: "supportforseller") } let(:pundit_user) { SellerContext.new(user: admin_for_seller, seller:) } before do create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN) create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT) end let!(:product_one) { create(:product, name: "First product", user: seller) } let!(:product_two) { create(:product, name: "Learn Ruby", user: seller) } let!(:product_three) { create(:product, name: "My product", user: seller, purchase_disabled_at: DateTime.current) } let!(:product_four) { create(:product, name: "Microeconomics 101", user: seller) } let!(:product_five) { create(:product, name: "A product", user: seller) } let!(:archived_product_enabled) { create(:product, name: "Archived product enabled", user: seller, archived: true) } let!(:archived_product_not_enabled) { create(:product, name: "Archived product not enabled", user: seller, archived: true) } let!(:other_archived_product) { create(:product, name: "Other archived product", user: seller, archived: true) } let!(:self_service_affiliate_product_two) { create(:self_service_affiliate_product, seller:, product: product_two, enabled: false) } let!(:self_service_affiliate_product_four) { create(:self_service_affiliate_product, seller:, product: product_four, enabled: true) } let!(:self_service_affiliate_archived_product) { create(:self_service_affiliate_product, seller:, product: archived_product_enabled, enabled: true) } let!(:self_service_affiliate_archived_product_not_enabled) { create(:self_service_affiliate_product, seller:, product: archived_product_not_enabled, enabled: false) } it "returns the necessary props to render the affiliate onboarding page" do props = described_class.new(pundit_user).onboarding_props expect(JSON.parse(props.to_json).deep_symbolize_keys!).to match( { creator_subdomain: seller.subdomain, products: [ { name: "Archived product enabled", enabled: true, id: archived_product_enabled.external_id_numeric, fee_percent: 5, destination_url: nil }, { name: "Microeconomics 101", enabled: true, id: product_four.external_id_numeric, fee_percent: 5, destination_url: nil }, { name: "A product", enabled: false, id: product_five.external_id_numeric, fee_percent: nil, destination_url: nil }, { name: "First product", enabled: false, id: product_one.external_id_numeric, fee_percent: nil, destination_url: nil }, { name: "Learn Ruby", enabled: false, id: product_two.external_id_numeric, fee_percent: 5, destination_url: nil }, ], disable_global_affiliate: false, global_affiliate_percentage: 10, affiliates_disabled_reason: nil, }) end end describe "#new_affiliate_props" do let(:seller) { create(:named_user) } let(:admin_for_seller) { create(:user, username: "adminforseller") } let(:pundit_user) { SellerContext.new(user: admin_for_seller, seller:) } before do create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN) end let!(:product) { create(:product, name: "Test Product", user: seller) } it "returns products with enabled: false and default values" do props = described_class.new(pundit_user).new_affiliate_props expect(props[:products]).to be_an(Array) expect(props[:products].first).to include( enabled: false, fee_percent: nil, referral_url: "", destination_url: nil ) expect(props[:affiliates_disabled_reason]).to be_nil end context "when seller has Brazilian Stripe account" do before do allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(true) end it "returns the disabled reason" do props = described_class.new(pundit_user).new_affiliate_props expect(props[:affiliates_disabled_reason]).to eq("Affiliates with Brazilian Stripe accounts are not supported.") end end end describe "#edit_affiliate_props" do let(:seller) { create(:named_user) } let(:admin_for_seller) { create(:user, username: "adminforseller") } let(:pundit_user) { SellerContext.new(user: admin_for_seller, seller:) } let(:affiliate_user) { create(:affiliate_user) } let(:product) { create(:product, user: seller) } let!(:affiliate) { create(:direct_affiliate, seller:, affiliate_user:, products: [product]) } before do create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN) end it "returns affiliate data with products" do props = described_class.new(pundit_user).edit_affiliate_props(affiliate) expect(props[:affiliate]).to be_a(Hash) expect(props[:affiliate][:id]).to eq(affiliate.external_id) expect(props[:affiliate][:email]).to eq(affiliate_user.email) expect(props[:affiliate][:products]).to be_an(Array) expect(props[:affiliates_disabled_reason]).to be_nil end context "when seller has Brazilian Stripe account" do before do allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(true) end it "returns the disabled reason" do props = described_class.new(pundit_user).edit_affiliate_props(affiliate) expect(props[:affiliates_disabled_reason]).to eq("Affiliates with Brazilian Stripe accounts are not supported.") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/workflows_presenter_spec.rb
spec/presenters/workflows_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe WorkflowsPresenter do describe "#workflows_props" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let!(:workflow1) { create(:workflow, link: product, seller:, workflow_type: Workflow::FOLLOWER_TYPE, created_at: 1.day.ago) } let!(:_workflow2) { create(:workflow, link: nil, seller:, workflow_type: Workflow::SELLER_TYPE, deleted_at: DateTime.current) } let!(:workflow3) { create(:workflow, link: product, seller:) } let!(:workflow4) { create(:workflow, link: nil, seller:, workflow_type: Workflow::SELLER_TYPE) } it "returns alive workflows ordered by created at descending" do result = described_class.new(seller:).workflows_props expect(result).to eq({ workflows: [ WorkflowPresenter.new(seller:, workflow: workflow3).workflow_props, WorkflowPresenter.new(seller:, workflow: workflow4).workflow_props, WorkflowPresenter.new(seller:, workflow: workflow1).workflow_props, ] }) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/creator_home_presenter_spec.rb
spec/presenters/creator_home_presenter_spec.rb
# frozen_string_literal: true describe CreatorHomePresenter do let(:admin_for_seller) { create(:user, username: "adminforseller") } let(:marketing_for_seller) { create(:user, username: "marketingforseller") } let(:support_for_seller) { create(:user, username: "supportforseller") } let(:seller) { create(:user, created_at: 60.days.ago) } let(:pundit_user) { SellerContext.new(user: admin_for_seller, seller:) } let(:presenter) { described_class.new(pundit_user) } around do |example| travel_to Time.utc(2022, 5, 17) do example.run end end before do create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN) create(:team_membership, user: marketing_for_seller, seller:, role: TeamMembership::ROLE_MARKETING) create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT) end describe "#creator_home_props" do it "deduces creator name from payout info" do expect(presenter.creator_home_props[:name]).to match("") create(:user_compliance_info, user: seller) expect(presenter.creator_home_props[:name]).to match("Chuck") end it "when creator has made a sale" do expect(presenter.creator_home_props[:has_sale]).to eq(false) create(:purchase, :from_seller, seller:) expect(presenter.creator_home_props[:has_sale]).to eq(true) end it "includes initial user getting started stats" do expect(presenter.creator_home_props[:getting_started_stats]).to match( { "customized_profile" => false, "first_email" => false, "first_follower" => false, "first_payout" => true, "first_product" => false, "first_sale" => false, "purchased_small_bets" => false, } ) end it "doesn't consider workflow installments for first_email" do create(:installment, seller:, workflow_id: 1) expect(presenter.creator_home_props[:getting_started_stats]["first_email"]).to eq(false) end it "doesn't consider bundle product purchases for first_sale" do create(:purchase, :from_seller, seller:, is_bundle_product_purchase: true) expect(presenter.creator_home_props[:getting_started_stats]["first_sale"]).to eq(false) end it "includes updated user getting started stats" do seller.update!(name: "Gumbo") create(:post, seller:) create(:active_follower, user: seller) create(:purchase, :from_seller, seller:) create(:payment_completed, user: seller) expect(presenter.creator_home_props[:getting_started_stats]).to match( { "customized_profile" => true, "first_email" => true, "first_follower" => true, "first_payout" => true, "first_product" => true, "first_sale" => true, "purchased_small_bets" => false, } ) end it "includes product data", :sidekiq_inline, :elasticsearch_wait_for_refresh do recreate_model_index(Purchase) product1 = create(:product, user: seller) product2 = create(:product, user: seller) create(:purchase, link: product1, price_cents: 100, created_at: 30.days.ago) create(:purchase, link: product2, price_cents: 500, created_at: Time.current) create(:purchase, link: product2, price_cents: 1500, created_at: 6.days.ago) expect(presenter.creator_home_props[:sales]).to match( [ { "id" => product2.unique_permalink, "name" => "The Works of Edgar Gumstein", "thumbnail" => nil, "revenue" => 2000.0, "sales" => 2, "visits" => 0, "today" => 500, "last_7" => 2000, "last_30" => 2000, }, { "id" => product1.unique_permalink, "name" => "The Works of Edgar Gumstein", "thumbnail" => nil, "sales" => 1, "revenue" => 100.0, "visits" => 0, "today" => 0, "last_7" => 0, "last_30" => 100, }, ] ) end it "excludes soft-deleted thumbnails from product data" do # TODO(tech debt): Remove the top-level travel_to. travel_back product1 = create(:product, user: seller) product2 = create(:product, user: seller) thumbnail1 = create(:thumbnail, product: product1) thumbnail2 = create(:thumbnail, product: product2) thumbnail1.mark_deleted! sales_data = presenter.creator_home_props[:sales] product1_data = sales_data.find { |s| s["id"] == product1.unique_permalink } product2_data = sales_data.find { |s| s["id"] == product2.unique_permalink } expect(product1_data["thumbnail"]).to be_nil expect(product2_data["thumbnail"]).to eq(thumbnail2.url) end it "excludes deleted products from the Best Selling section", :sidekiq_inline, :elasticsearch_wait_for_refresh do active_product = create(:product, user: seller, price_cents: 1000) deleted_product = create(:product, user: seller, price_cents: 2000) create_list(:purchase, 3, link: active_product, price_cents: active_product.price_cents, created_at: 1.day.ago) create_list(:purchase, 5, link: deleted_product, price_cents: deleted_product.price_cents, created_at: 2.days.ago) deleted_product.update!(deleted_at: Time.current) sales_data = presenter.creator_home_props[:sales] expect(sales_data.map { |p| p["id"] }).to contain_exactly(active_product.unique_permalink) expect(sales_data).not_to include(hash_including("id" => deleted_product.unique_permalink)) end it "shows the 3 most sold products in past 30 days", :sidekiq_inline, :elasticsearch_wait_for_refresh do product1 = create(:product, user: seller) product2 = create(:product, user: seller) product3 = create(:product, user: seller, price_cents: 1500) product4 = create(:product, user: seller, price_cents: 99) create_list(:purchase, 10, link: product1, price_cents: product1.price_cents, created_at: 31.days.ago) create_list(:purchase, 5, link: product2, price_cents: product2.price_cents, created_at: 3.days.ago) create_list(:purchase, 2, link: product3, price_cents: product3.price_cents, created_at: 6.days.ago) create_list(:purchase, 7, link: product4, price_cents: product4.price_cents, created_at: 1.day.ago) expect(presenter.creator_home_props[:sales]).to match( [ { "id" => product4.unique_permalink, "name" => "The Works of Edgar Gumstein", "thumbnail" => nil, "sales" => 7, "revenue" => 693.0, "visits" => 0, "today" => 0, "last_7" => 693, "last_30" => 693, }, { "id" => product2.unique_permalink, "name" => "The Works of Edgar Gumstein", "thumbnail" => nil, "revenue" => 500.0, "sales" => 5, "visits" => 0, "today" => 0, "last_7" => 500, "last_30" => 500, }, { "id" => product3.unique_permalink, "name" => "The Works of Edgar Gumstein", "thumbnail" => nil, "sales" => 2, "revenue" => 3000.0, "visits" => 0, "today" => 0, "last_7" => 3000, "last_30" => 3000, }, ] ) end it "includes sorted interlaced activity items", :sidekiq_inline, :elasticsearch_wait_for_refresh do seller.update!(created_at: 60.days.ago) sales = [ create(:purchase, :from_seller, seller:, created_at: 8.hours.ago), create(:purchase, :from_seller, seller:, created_at: 6.hours.ago), create(:purchase, :from_seller, seller:, created_at: 4.hours.ago), create(:purchase, :from_seller, seller:, created_at: 2.hours.ago), create(:purchase, :from_seller, seller:, created_at: 1.hour.ago, is_bundle_product_purchase: true) ] followers = [ create(:follower, user: seller, confirmed_at: 7.hours.ago), create(:follower, user: seller, confirmed_at: 5.hours.ago), create(:follower, user: seller, confirmed_at: 3.hour.ago), ] followers.last.update!(confirmed_at: nil, deleted_at: 1.hour.ago) # fourth event # Limiting to 3 allows us to check that we're truncating the results from the correct end: # Grab the last 3 sales + last 3 followers events, then get the last 3 of that. stub_const("#{described_class}::ACTIVITY_ITEMS_LIMIT", 3) expect(presenter.creator_home_props[:activity_items]).to match_array( [ { "type" => "follower_removed", "timestamp" => "2022-05-16T23:00:00Z", "details" => { "email" => followers.last.email, "name" => nil } }, { "type" => "new_sale", "timestamp" => "2022-05-16T22:00:00Z", "details" => { "price_cents" => sales.second_to_last.price_cents, "email" => sales.second_to_last.email, "full_name" => nil, "product_name" => sales.second_to_last.link.name, "product_unique_permalink" => sales.second_to_last.link.unique_permalink } }, { "type" => "follower_added", "timestamp" => "2022-05-16T21:00:00Z", "details" => { "email" => followers.last.email, "name" => nil } } ] ) end it "includes the verification error message from Stripe if there's an active Stripe account" do create(:merchant_account, user: seller) create(:user_compliance_info_request, user: seller, field_needed: UserComplianceInfoFields::Individual::STRIPE_IDENTITY_DOCUMENT_ID, verification_error: { code: "verification_document_fraudulent" }) expect(seller.stripe_account).to be_present expect(presenter.creator_home_props[:stripe_verification_message]).to eq "The document might have been altered so it could not be verified." seller.stripe_account.delete_charge_processor_account! expect(seller.stripe_account).to be_nil expect(presenter.creator_home_props[:stripe_verification_message]).to be_nil end describe "balances" do before do allow_any_instance_of(UserBalanceStatsService).to receive(:fetch).and_return( { overview: { balance: 10_000, last_seven_days_sales_total: 5_000, last_28_days_sales_total: 15_000, sales_cents_total: 50_000 }, } ) end it "includes formatted balance information" do balances = presenter.creator_home_props[:balances] expect(balances[:balance]).to eq "$100" expect(balances[:last_seven_days_sales_total]).to eq "$50" expect(balances[:last_28_days_sales_total]).to eq "$150" expect(balances[:total]).to eq "$500" end context "when seller should be shown currencies always" do before do allow(seller).to receive(:should_be_shown_currencies_always?).and_return(true) end it "includes currency in formatted balance information" do balances = presenter.creator_home_props[:balances] expect(balances[:balance]).to eq "$100 USD" expect(balances[:last_seven_days_sales_total]).to eq "$50 USD" expect(balances[:last_28_days_sales_total]).to eq "$150 USD" expect(balances[:total]).to eq "$500 USD" end end end describe "tax forms" do download_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/nyt.pdf" before do seller.update!(created_at: 2.years.ago) allow(seller).to receive(:eligible_for_1099?).and_return(true) allow(seller).to receive(:tax_form_1099_download_url).and_return(download_url) end it "includes tax forms since the seller's account was created" do expect(presenter.creator_home_props[:tax_forms]).to eq( { 2022 => download_url, 2021 => download_url, 2020 => download_url, } ) end it "only includes years where the seller is eligible for a 1099" do allow(seller).to receive(:eligible_for_1099?) do |year| [2022, 2021].include?(year) end expect(presenter.creator_home_props[:tax_forms]).to eq( { 2022 => download_url, 2021 => download_url, }) end it "only includes years that have downloadable tax forms" do allow(seller).to receive(:tax_form_1099_download_url) do |year:| year == 2021 ? download_url : nil end expect(presenter.creator_home_props[:tax_forms]).to eq( { 2021 => download_url, } ) end it "returns empty tax forms when tax_center feature flag is enabled" do Feature.activate_user(:tax_center, seller) create(:user_tax_form, user: seller, tax_year: 2021, tax_form_type: "us_1099_k") props = presenter.creator_home_props expect(props[:tax_center_enabled]).to be(true) expect(props[:tax_forms]).to eq([]) expect(props[:show_1099_download_notice]).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/presenters/analytics_presenter_spec.rb
spec/presenters/analytics_presenter_spec.rb
# frozen_string_literal: true describe AnalyticsPresenter do let(:seller) { create(:user) } let(:presenter) { described_class.new(seller:) } let!(:alive_product) { create(:product, user: seller) } let!(:deleted_with_sales) { create(:product, user: seller, deleted_at: Time.current) } let!(:deleted_without_sales) { create(:product, user: seller, deleted_at: Time.current) } before { create(:purchase, link: deleted_with_sales) } describe "#page_props" do it "returns the correct props" do expect(presenter.page_props[:products]).to contain_exactly( { id: alive_product.external_id, alive: true, unique_permalink: alive_product.unique_permalink, name: alive_product.name }, { id: deleted_with_sales.external_id, alive: false, unique_permalink: deleted_with_sales.unique_permalink, name: deleted_with_sales.name } ) expect(presenter.page_props[:country_codes]).to include("United States" => "US") expect(presenter.page_props[:state_names].first).to eq("Alabama") expect(presenter.page_props[:state_names].last).to eq("Other") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/product_review_video_presenter_spec.rb
spec/presenters/product_review_video_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe ProductReviewVideoPresenter do let(:seller) { create(:user) } let(:another_seller) { create(:user) } let(:link) { create(:product, user: seller) } let(:purchase) { create(:purchase, seller:, link:) } let(:product_review) { create(:product_review, purchase:) } let(:video) { create(:product_review_video, :approved, product_review:) } let(:pundit_user) { SellerContext.new(user: seller, seller:) } describe "#props" do it "returns the correct props" do presenter = described_class.new(video) expect(presenter.props(pundit_user:)).to match( id: video.external_id, approval_status: video.approval_status, thumbnail_url: video.video_file.thumbnail_url, can_approve: true, can_reject: true, ) end describe "can_approve" do context "when the user has approval permission" do let(:pundit_user) { SellerContext.new(user: seller, seller:) } it "returns true" do presenter = described_class.new(video) expect(presenter.props(pundit_user:)[:can_approve]).to eq(true) end end context "when the user does not have approval permission" do let(:pundit_user) { SellerContext.new(user: another_seller, seller: another_seller) } it "returns false" do presenter = described_class.new(video) expect(presenter.props(pundit_user:)[:can_approve]).to eq(false) end end end describe "can_reject" do context "when the user has rejection permission" do let(:pundit_user) { SellerContext.new(user: seller, seller:) } it "returns true" do presenter = described_class.new(video) expect(presenter.props(pundit_user:)[:can_reject]).to eq(true) end end context "when the user does not have rejection permission" do let(:pundit_user) { SellerContext.new(user: another_seller, seller: another_seller) } it "returns false" do presenter = described_class.new(video) expect(presenter.props(pundit_user:)[:can_reject]).to eq(false) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/settings_presenter_spec.rb
spec/presenters/settings_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe SettingsPresenter do let(:product) do create(:product, purchasing_power_parity_disabled: true, user: create(:named_seller, purchasing_power_parity_limit: 60)) end let(:seller) { product.user } let(:user) { seller } let(:pundit_user) { SellerContext.new(user:, seller:) } let(:presenter) { described_class.new(pundit_user:) } describe "#pages" do context "with owner as logged in user" do it "returns correct pages" do expect(presenter.pages).to eq( %w(main profile team payments password third_party_analytics advanced) ) end context "when there is at least one alive OAuth app" do before do create("doorkeeper/access_token", resource_owner_id: seller.id, scopes: "creator_api") end it "includes authorized_applications page" do expect(presenter.pages).to include("authorized_applications") end end end context "with user as admin for owner" do let(:user) { create(:user) } before do create(:team_membership, user:, seller:, role: TeamMembership::ROLE_ADMIN) end it "returns correct pages" do expect(presenter.pages).to eq( %w(main profile team payments third_party_analytics advanced) ) end end [TeamMembership::ROLE_ACCOUNTANT, TeamMembership::ROLE_MARKETING, TeamMembership::ROLE_SUPPORT].each do |role| context "with user as #{role} for owner" do let(:user) { create(:user) } before do create(:team_membership, user:, seller:, role:) end it "returns correct pages" do expect(presenter.pages).to eq( %w(profile team) ) end end end end describe "#main_props" do before { Feature.activate(:product_level_support_emails) } it "returns correct props" do expect(presenter.main_props).to eq( settings_pages: presenter.pages, is_form_disabled: false, invalidate_active_sessions: true, ios_app_store_url: IOS_APP_STORE_URL, android_app_store_url: ANDROID_APP_STORE_URL, timezones: ActiveSupport::TimeZone.all.map { |tz| { name: tz.name, offset: tz.formatted_offset } }, currencies: CURRENCY_CHOICES.map { |k, v| { name: v[:display_format], code: k } }, user: { email: seller.form_email, support_email: seller.support_email, locale: seller.locale, timezone: seller.timezone, currency_type: seller.currency_type, has_unconfirmed_email: false, compliance_country: nil, purchasing_power_parity_enabled: false, purchasing_power_parity_limit: 60, purchasing_power_parity_payment_verification_disabled: false, products: [{ id: product.external_id, name: product.name }], purchasing_power_parity_excluded_product_ids: [product.external_id], enable_payment_email: true, enable_payment_push_notification: true, enable_recurring_subscription_charge_email: false, enable_recurring_subscription_charge_push_notification: false, enable_free_downloads_email: true, enable_free_downloads_push_notification: true, announcement_notification_enabled: true, disable_comments_email: false, disable_reviews_email: false, show_nsfw_products: false, disable_affiliate_requests: false, product_level_support_emails: [], seller_refund_policy: { enabled: true, allowed_refund_periods_in_days: [ { key: 0, value: "No refunds allowed" }, { key: 7, value: "7-day money back guarantee" }, { key: 14, value: "14-day money back guarantee" }, { key: 30, value: "30-day money back guarantee" }, { key: 183, value: "6-month money back guarantee" } ], max_refund_period_in_days: 30, fine_print: nil, fine_print_enabled: false } } ) end context "when support emails exist" do before { product.update!(support_email: "support@example.com") } it "includes product_level_support_emails in main_props" do expect(presenter.main_props[:user][:product_level_support_emails]).to contain_exactly( { email: "support@example.com", product_ids: [product.external_id] } ) end end context "when product_level_support_emails feature is disabled" do before { Feature.deactivate(:product_level_support_emails) } before { product.update!(support_email: "support@example.com") } it "returns nil for product_level_support_emails" do expect(presenter.main_props[:user][:product_level_support_emails]).to be_nil end end context "when user has unconfirmed email" do before do seller.update!(unconfirmed_email: "john@example.com") end it "returns `user.has_unconfirmed_email` as true" do expect(presenter.main_props[:user][:has_unconfirmed_email]).to be(true) end end context "when comments are disabled" do before do seller.update!(disable_comments_email: true) end it "returns `user.disable_comments_email` as true" do expect(presenter.main_props[:user][:disable_comments_email]).to be(true) end end end describe "#application_props" do let(:app) do create(:oauth_application, name: "Test", redirect_uri: "https://example.com/test", uid: "uid-1234", secret: "secret-123") end it "returns the correct data" do expect(presenter.application_props(app)).to eq( { settings_pages: presenter.pages, application: { id: app.external_id, name: "Test", redirect_uri: "https://example.com/test", icon_url: app.icon_url, uid: "uid-1234", secret: "secret-123", } }) end end describe "#advanced_props" do let!(:custom_domain) { create(:custom_domain, user: seller, domain: "example.com") } context "when custom domain is unverified" do before do allow(CustomDomainVerificationService).to receive(:new).and_return(double(process: true)) seller.update!(notification_endpoint: "https://example.org") end it "returns correct props" do expect(presenter.advanced_props).to eq({ settings_pages: presenter.pages, user_id: ObfuscateIds.encrypt(seller.id), notification_endpoint: "https://example.org", blocked_customer_emails: "", custom_domain_name: "example.com", custom_domain_verification_status: { message: "example.com domain is correctly configured!", success: true }, applications: [], allow_deactivation: true, formatted_balance_to_forfeit_on_account_deletion: nil, }) end end context "when custom domain is verified" do before do custom_domain.mark_verified! create(:blocked_customer_object, seller:, object_value: "test1@example.com", blocked_at: Time.current) create(:blocked_customer_object, seller:, object_value: "test2@example.net", blocked_at: Time.current) end it "returns correct props" do expect(presenter.advanced_props).to eq({ settings_pages: presenter.pages, user_id: ObfuscateIds.encrypt(seller.id), notification_endpoint: "", blocked_customer_emails: "test1@example.com\ntest2@example.net", custom_domain_name: "example.com", custom_domain_verification_status: nil, applications: [], allow_deactivation: true, formatted_balance_to_forfeit_on_account_deletion: nil, }) end end context "when user has unpaid balances" do before do @balance = create(:balance, user: seller, state: :unpaid, amount_cents: 25_00) Feature.activate_user(:delete_account_forfeit_balance, seller) end it "returns correct props" do expect(presenter.advanced_props).to eq({ settings_pages: presenter.pages, user_id: ObfuscateIds.encrypt(seller.id), notification_endpoint: "", blocked_customer_emails: "", custom_domain_name: "example.com", custom_domain_verification_status: { message: "Domain verification failed. Please make sure you have correctly configured the DNS record for example.com.", success: false }, applications: [], allow_deactivation: true, formatted_balance_to_forfeit_on_account_deletion: Money.new(2500, :usd).format(no_cents_if_whole: true), }) end end end describe "#third_party_analytics_props" do let!(:third_party_analytic) { create(:third_party_analytic, user: seller) } it "returns the correct props" do expect(presenter.third_party_analytics_props).to eq ({ disable_third_party_analytics: false, google_analytics_id: "", facebook_pixel_id: "", skip_free_sale_analytics: false, facebook_meta_tag: "", enable_verify_domain_third_party_services: false, snippets: [{ id: third_party_analytic.external_id, name: third_party_analytic.name, location: third_party_analytic.location, code: third_party_analytic.analytics_code, product: third_party_analytic.link.unique_permalink, }] }) end context "when attributes are set" do let(:seller_options) do { disable_third_party_analytics: true, google_analytics_id: "G-123456789-1", facebook_pixel_id: "1234567899", skip_free_sale_analytics: true, facebook_meta_tag: '<meta name="facebook-domain-verification" content="y5fgkbh7x91y5tnt6yt3sttk" />', enable_verify_domain_third_party_services: true, } end let(:snippets) do [{ id: third_party_analytic.external_id, name: third_party_analytic.name, location: third_party_analytic.location, code: third_party_analytic.analytics_code, product: third_party_analytic.link.unique_permalink, }] end before do seller.update!(seller_options) end it "returns correct values for props" do expect(presenter.third_party_analytics_props).to eq( seller_options.merge(snippets:) ) end end end describe "#password_props" do let(:settings_pages) { %w(main profile team payments password third_party_analytics advanced) } context "when seller is registered using a social provider" do before do seller.update!(provider: "facebook") end it "returns the correct props" do expect(presenter.password_props).to eq(require_old_password: false, settings_pages:) end end context "when seller is registered using email" do it "returns the correct props" do expect(presenter.password_props).to eq(require_old_password: true, settings_pages:) end end end describe "#authorized_applications_props" do context "when some applications have no access grants" do let(:oauth_application1) { create(:oauth_application, owner: seller) } let!(:oauth_application2) { create(:oauth_application, owner: seller) } before do oauth_application1.get_or_generate_access_token @access_grant = Doorkeeper::AccessGrant.create!(application_id: oauth_application1.id, resource_owner_id: seller.id, redirect_uri: oauth_application1.redirect_uri, expires_in: 1.day.from_now, scopes: Doorkeeper.configuration.public_scopes.join(" ")) end it "returns props with only applications which have access grants" do expect(presenter.authorized_applications_props).to eq({ authorized_applications: [{ name: oauth_application1.name, icon_url: oauth_application1.icon_url, is_own_app: true, first_authorized_at: @access_grant.created_at.iso8601, scopes: oauth_application1.scopes, id: oauth_application1.external_id, }], settings_pages: %w(main profile team payments authorized_applications password third_party_analytics advanced), }) end end context "when seller is not the owner of the application" do let(:oauth_application1) { create(:oauth_application) } before do create("doorkeeper/access_token", resource_owner_id: seller.id, application: oauth_application1, scopes: Doorkeeper.configuration.public_scopes.join(" ")) @access_grant = Doorkeeper::AccessGrant.create!(application_id: oauth_application1.id, resource_owner_id: seller.id, redirect_uri: oauth_application1.redirect_uri, expires_in: 1.day.from_now, scopes: Doorkeeper.configuration.public_scopes.join(" ")) end it "returns props with is_own_app set to false" do expect(presenter.authorized_applications_props).to eq({ authorized_applications: [{ name: oauth_application1.name, icon_url: oauth_application1.icon_url, is_own_app: false, first_authorized_at: @access_grant.created_at.iso8601, scopes: oauth_application1.scopes, id: oauth_application1.external_id, }], settings_pages: %w(main profile team payments authorized_applications password third_party_analytics advanced), }) end end it "returns authorized applications ordered by first_authorized_at" do oauth_application1 = create(:oauth_application, owner: seller) oauth_application2 = create(:oauth_application, owner: seller) oauth_application1.get_or_generate_access_token oauth_application2.get_or_generate_access_token access_grant1 = Doorkeeper::AccessGrant.create!(application_id: oauth_application1.id, resource_owner_id: seller.id, redirect_uri: oauth_application1.redirect_uri, expires_in: 1.day.from_now, scopes: Doorkeeper.configuration.public_scopes.join(" ")) access_grant2 = Doorkeeper::AccessGrant.create!(application_id: oauth_application2.id, resource_owner_id: seller.id, redirect_uri: oauth_application2.redirect_uri, expires_in: 1.day.from_now, scopes: Doorkeeper.configuration.public_scopes.join(" ")) access_grant1.update!(created_at: 1.day.ago) access_grant2.update!(created_at: 2.days.ago) expect(presenter.authorized_applications_props).to eq({ authorized_applications: [{ name: oauth_application2.name, icon_url: oauth_application2.icon_url, is_own_app: true, first_authorized_at: access_grant2.created_at.iso8601, scopes: oauth_application2.scopes, id: oauth_application2.external_id, }, { name: oauth_application1.name, icon_url: oauth_application1.icon_url, is_own_app: true, first_authorized_at: access_grant1.created_at.iso8601, scopes: oauth_application1.scopes, id: oauth_application1.external_id, }], settings_pages: %w(main profile team payments authorized_applications password third_party_analytics advanced), }) end end describe "#payments_props" do before do seller.update(payment_address: "") @base_props = { settings_pages: presenter.pages, is_form_disabled: false, should_show_country_modal: true, aus_backtax_details: { show_au_backtax_prompt: false, total_amount_to_au: "$0.00", au_backtax_amount: "$0.00", opt_in_date: nil, credit_creation_date: Date.today.next_month.beginning_of_month.strftime("%B %-d, %Y"), opted_in_to_au_backtax: false, legal_entity_name: "", are_au_backtaxes_paid: false, au_backtaxes_paid_date: nil, }, stripe_connect: { has_connected_stripe: false, stripe_connect_account_id: nil, stripe_disconnect_allowed: true, supported_countries_help_text: "This feature is available in <a href='https://stripe.com/en-in/global'>all countries where Stripe operates</a>, except India, Indonesia, Malaysia, Mexico, Philippines, and Thailand.", }, countries: Compliance::Countries.for_select.to_h, ip_country_code: nil, bank_account_details: { show_bank_account: false, show_paypal: true, card_data_handling_mode: "stripejs.0", is_a_card: false, card: nil, routing_number: nil, account_number_visual: nil, bank_account: nil, }, paypal_address: seller.payment_address, show_verification_section: false, paypal_connect: { show_paypal_connect: false, allow_paypal_connect: false, unsupported_countries: PaypalMerchantAccountManager::COUNTRY_CODES_NOT_SUPPORTED_BY_PCP.map { |code| ISO3166::Country[code].common_name }, email: nil, charge_processor_merchant_id: nil, charge_processor_verified: false, needs_email_confirmation: false, paypal_disconnect_allowed: true, }, fee_info: { card_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: 10% + 50¢ Gumroad fee + 2.9% + 30¢ credit card fee.\n• Discover sales: 30% flat\n", paypal_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: 10% + 50¢ Gumroad fee + 2.9% + 30¢ PayPal fee.\n• Discover sales: 30% flat\n", connect_account_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: 10% + 50¢\n• Discover sales: 30% flat\n", }, user: { country_supports_native_payouts: false, country_supports_iban: false, country_code: nil, payout_currency: nil, is_from_europe: false, need_full_ssn: false, individual_tax_id_needed_countries: [Compliance::Countries::USA.alpha2, Compliance::Countries::CAN.alpha2, Compliance::Countries::HKG.alpha2, Compliance::Countries::SGP.alpha2, Compliance::Countries::ARE.alpha2, Compliance::Countries::MEX.alpha2, Compliance::Countries::BGD.alpha2, Compliance::Countries::MOZ.alpha2, Compliance::Countries::URY.alpha2, Compliance::Countries::ARG.alpha2, Compliance::Countries::PER.alpha2, Compliance::Countries::CRI.alpha2, Compliance::Countries::CHL.alpha2, Compliance::Countries::COL.alpha2, Compliance::Countries::GTM.alpha2, Compliance::Countries::DOM.alpha2, Compliance::Countries::BOL.alpha2, Compliance::Countries::KAZ.alpha2, Compliance::Countries::PRY.alpha2, Compliance::Countries::PAK.alpha2], individual_tax_id_entered: false, business_tax_id_entered: false, requires_credit_card: false, can_connect_stripe: false, is_charged_paypal_payout_fee: true, joined_at: seller.created_at.iso8601, }, compliance_info: { is_business: false, business_name: nil, business_name_kanji: nil, business_name_kana: nil, business_type: nil, business_street_address: nil, business_building_number: nil, business_street_address_kanji: nil, business_street_address_kana: nil, business_city: nil, business_state: nil, business_country: nil, business_zip_code: nil, business_phone: nil, job_title: nil, first_name: nil, last_name: nil, first_name_kanji: nil, last_name_kanji: nil, first_name_kana: nil, last_name_kana: nil, street_address: nil, building_number: nil, street_address_kanji: nil, street_address_kana: nil, city: nil, state: nil, country: nil, zip_code: nil, phone: nil, nationality: nil, dob_month: 0, dob_day: 0, dob_year: 0, }, min_dob_year: Date.today.year - UserComplianceInfo::MINIMUM_DATE_OF_BIRTH_AGE, uae_business_types: UserComplianceInfo::BusinessTypes::BUSINESS_TYPES_UAE.map { |code, name| { code:, name: } }, india_business_types: UserComplianceInfo::BusinessTypes::BUSINESS_TYPES_INDIA.map { |code, name| { code:, name: } }, canada_business_types: UserComplianceInfo::BusinessTypes::BUSINESS_TYPES_CANADA.map { |code, name| { code:, name: } }, states: { us: Compliance::Countries.subdivisions_for_select(Compliance::Countries::USA.alpha2).map { |code, name| { code:, name: } }, ca: Compliance::Countries.subdivisions_for_select(Compliance::Countries::CAN.alpha2).map { |code, name| { code:, name: } }, au: Compliance::Countries.subdivisions_for_select(Compliance::Countries::AUS.alpha2).map { |code, name| { code:, name: } }, mx: Compliance::Countries.subdivisions_for_select(Compliance::Countries::MEX.alpha2).map { |code, name| { code:, name: } }, ae: Compliance::Countries.subdivisions_for_select(Compliance::Countries::ARE.alpha2).map { |code, name| { code:, name: } }, ir: Compliance::Countries.subdivisions_for_select(Compliance::Countries::IRL.alpha2).map { |code, name| { code:, name: } }, br: Compliance::Countries.subdivisions_for_select(Compliance::Countries::BRA.alpha2).map { |code, name| { code:, name: } }, }, saved_card: nil, formatted_balance_to_forfeit_on_country_change: nil, formatted_balance_to_forfeit_on_payout_method_change: nil, payouts_paused_internally: false, payouts_paused_by: nil, payouts_paused_for_reason: nil, payouts_paused_by_user: false, payout_threshold_cents: 1000, minimum_payout_threshold_cents: 1000, payout_frequency: User::PayoutSchedule::WEEKLY, payout_frequency_daily_supported: false, } end it "returns correct props for a seller who has no compliance info or payout method" do expect(presenter.payments_props).to eq(@base_props) end it "shows the AU backtax prompt when the feature is on and the creator owes more than $100 and the creator has received an email" do Feature.activate_user(:au_backtaxes, seller) seller.update!(au_backtax_owed_cents: 100_01) create(:australia_backtax_email_info, user: seller) expect(presenter.payments_props).to eq(@base_props.merge!({ aus_backtax_details: @base_props[:aus_backtax_details].merge({ show_au_backtax_prompt: true, au_backtax_amount: "$100.01" }), })) end it "does not show the AU backtax prompt when the creator owes less than $100" do Feature.activate_user(:au_backtaxes, seller) seller.update!(au_backtax_owed_cents: 99_00) create(:australia_backtax_email_info, user: seller) expect(presenter.payments_props).to eq(@base_props.merge!({ aus_backtax_details: @base_props[:aus_backtax_details].merge({ show_au_backtax_prompt: false, au_backtax_amount: "$99.00" }), })) end context "when seller is from the US" do before do @user_compliance_info = create(:user_compliance_info, user: seller) @user_details = @base_props[:user].merge({ country_supports_native_payouts: true, country_code: "US", payout_currency: "usd", individual_tax_id_needed_countries: [Compliance::Countries::USA.alpha2, Compliance::Countries::CAN.alpha2, Compliance::Countries::HKG.alpha2, Compliance::Countries::SGP.alpha2, Compliance::Countries::ARE.alpha2, Compliance::Countries::MEX.alpha2, Compliance::Countries::BGD.alpha2, Compliance::Countries::MOZ.alpha2, Compliance::Countries::URY.alpha2, Compliance::Countries::ARG.alpha2, Compliance::Countries::PER.alpha2, Compliance::Countries::CRI.alpha2, Compliance::Countries::CHL.alpha2, Compliance::Countries::COL.alpha2, Compliance::Countries::GTM.alpha2, Compliance::Countries::DOM.alpha2, Compliance::Countries::BOL.alpha2, Compliance::Countries::KAZ.alpha2, Compliance::Countries::PRY.alpha2, Compliance::Countries::PAK.alpha2], individual_tax_id_entered: true, }) @compliance_info_details = @base_props[:compliance_info].merge({ first_name: @user_compliance_info.first_name, last_name: @user_compliance_info.last_name, street_address: @user_compliance_info.street_address, city: @user_compliance_info.city,
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/communities_presenter_spec.rb
spec/presenters/communities_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe CommunitiesPresenter do let(:seller) { create(:named_seller) } let(:buyer) { create(:user) } let(:product) { create(:product, user: seller, community_chat_enabled: true) } let!(:community) { create(:community, seller:, resource: product) } let(:presenter) { described_class.new(current_user:) } describe "#props" do let(:current_user) { buyer } subject(:props) { presenter.props } context "when user has no accessible communities" do it "returns appropriate props" do expect(props).to eq( has_products: false, communities: [], notification_settings: {}, ) end end context "when user has accessible communities" do let(:current_user) { buyer } let!(:purchase) { create(:purchase, purchaser: buyer, link: product) } let!(:notification_setting) { create(:community_notification_setting, user: buyer, seller:) } before do Feature.activate_user(:communities, seller) product.update!(community_chat_enabled: true) end it "returns appropriate props" do expect(props).to eq( has_products: false, communities: [ CommunityPresenter.new(community:, current_user:).props ], notification_settings: { seller.external_id => { recap_frequency: "daily" } } ) end context "when notification settings are missing" do before { notification_setting.destroy! } it "returns default notification settings" do expect(props[:notification_settings]).to eq({}) end end context "when there are unread messages" do let!(:message1) { create(:community_chat_message, community:, user: seller, created_at: 3.minutes.ago) } let!(:message2) { create(:community_chat_message, community:, user: seller, created_at: 2.minutes.ago) } let!(:message3) { create(:community_chat_message, community:, user: seller, created_at: 1.minute.ago) } let!(:last_read) do create(:last_read_community_chat_message, user: buyer, community:, community_chat_message: message1) end it "includes unread counts and last read timestamps" do community_props = props[:communities].sole expect(community_props[:last_read_community_chat_message_created_at]).to eq(message1.created_at.iso8601) expect(community_props[:unread_count]).to eq(2) end end context "when there are no last read messages" do let!(:message1) { create(:community_chat_message, community:, user: seller, created_at: 3.minutes.ago) } let!(:message2) { create(:community_chat_message, community:, user: seller, created_at: 2.minutes.ago) } let!(:message3) { create(:community_chat_message, community:, user: seller, created_at: 1.minute.ago) } it "returns all messages as unread" do community_props = props[:communities].sole expect(community_props[:last_read_community_chat_message_created_at]).to be_nil expect(community_props[:unread_count]).to eq(3) end end context "when user has multiple communities" do let(:other_seller) { create(:user, username: "otherseller123", email: "other_seller@example.com") } let(:other_product) { create(:product, user: other_seller, community_chat_enabled: true) } let!(:other_community) { create(:community, seller: other_seller, resource: other_product) } let!(:other_purchase) { create(:purchase, purchaser: buyer, link: other_product) } let!(:other_notification_setting) { create(:community_notification_setting, user: buyer, seller: other_seller) } before do Feature.activate_user(:communities, other_seller) other_product.update!(community_chat_enabled: true) end it "returns appropriate props" do expect(props[:communities].size).to eq(2) expect(props[:communities].map { |c| c[:id] }).to match_array([community.external_id, other_community.external_id]) expect(props[:notification_settings]).to eq({ seller.external_id => { recap_frequency: "daily" }, other_seller.external_id => { recap_frequency: "daily" } }) 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/presenters/reviews_presenter_spec.rb
spec/presenters/reviews_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe ReviewsPresenter do describe "#reviews_props" do let(:user) { create(:user) } let(:presenter) { described_class.new(user) } let(:seller) { create(:user, name: "Seller") } let!(:reviews) do build_list(:product_review, 3) do |review, i| review.purchase.purchaser = user review.message = if i > 0 then "Message #{i}" else nil end review.update!(rating: i + 1) review.link.update!(user: seller) end end let!(:thumbnail) { create(:thumbnail, product: reviews.first.link) } let!(:product1) { create(:product, user: seller, name: "Product 1") } let!(:product2) { create(:product, user: seller, name: "Product 2") } let!(:product3) { create(:product, name: "Product 3") } let!(:purchase1) { create(:purchase, purchaser: user, link: product1) } let!(:purchase2) { create(:purchase, purchaser: user, link: product2) } let!(:purchase3) { create(:purchase, purchaser: user, link: product3, created_at: 3.years.ago) } let!(:thumbnail1) { create(:thumbnail, product: product1) } before { purchase3.seller.update!(disable_reviews_after_year: true) } it "returns props for the reviews page" do expect(presenter.reviews_props).to eq( { reviews: [ ProductReviewPresenter.new(reviews.first).review_form_props.merge( id: reviews.first.external_id, purchase_id: reviews.first.purchase.external_id, purchase_email_digest: reviews.first.purchase.email_digest, product: { name: reviews.first.link.name, url: reviews.first.link.long_url(recommended_by: "library"), permalink: reviews.first.link.unique_permalink, thumbnail_url: thumbnail.url, native_type: "digital", seller: { name: "Seller", url: seller.profile_url, } } ), ProductReviewPresenter.new(reviews.second).review_form_props.merge( id: reviews.second.external_id, purchase_id: reviews.second.purchase.external_id, purchase_email_digest: reviews.second.purchase.email_digest, product: { name: reviews.second.link.name, url: reviews.second.link.long_url(recommended_by: "library"), permalink: reviews.second.link.unique_permalink, thumbnail_url: nil, native_type: "digital", seller: { name: "Seller", url: seller.profile_url, } } ), ProductReviewPresenter.new(reviews.third).review_form_props.merge( id: reviews.third.external_id, purchase_id: reviews.third.purchase.external_id, purchase_email_digest: reviews.third.purchase.email_digest, product: { name: reviews.third.link.name, url: reviews.third.link.long_url(recommended_by: "library"), permalink: reviews.third.link.unique_permalink, thumbnail_url: nil, native_type: "digital", seller: { name: "Seller", url: seller.profile_url, } } ) ], purchases: [ { id: purchase1.external_id, email_digest: purchase1.email_digest, product: { name: product1.name, url: product1.long_url(recommended_by: "library"), permalink: product1.unique_permalink, thumbnail_url: thumbnail1.url, native_type: "digital", seller: { name: "Seller", url: seller.profile_url, } } }, { id: purchase2.external_id, email_digest: purchase2.email_digest, product: { name: product2.name, url: product2.long_url(recommended_by: "library"), permalink: product2.unique_permalink, thumbnail_url: nil, native_type: "digital", seller: { name: "Seller", url: seller.profile_url, } } } ], } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/community_chat_message_presenter_spec.rb
spec/presenters/community_chat_message_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe CommunityChatMessagePresenter do let(:seller) { create(:named_seller) } let(:buyer) { create(:user) } let(:community) { create(:community, seller:) } let(:message) { create(:community_chat_message, community:, user: buyer) } let(:presenter) { described_class.new(message:) } describe "#props" do subject(:props) { presenter.props } it "returns message data in the expected format" do expect(props).to eq({ id: message.external_id, community_id: community.external_id, content: message.content, created_at: message.created_at.iso8601, updated_at: message.updated_at.iso8601, user: { id: buyer.external_id, name: buyer.display_name, avatar_url: buyer.avatar_url, is_seller: false } }) end context "when message is from the community seller" do let(:message) { create(:community_chat_message, community:, user: seller) } it "sets is_seller to true" do expect(props[:user][:is_seller]).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/presenters/wishlist_presenter_spec.rb
spec/presenters/wishlist_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe WishlistPresenter do include Rails.application.routes.url_helpers describe ".library_props" do let(:wishlist1) { create(:wishlist, name: "My Wishlist 1", user: create(:user, name: "Wishlist 1 User"), discover_opted_out: true) } let(:wishlist2) { create(:wishlist, name: "My Wishlist 2") } before do create(:wishlist_product, wishlist: wishlist1) create(:wishlist_product, wishlist: wishlist1) create(:wishlist_product, wishlist: wishlist2) end it "returns the correct props for creator" do expect(described_class.library_props(wishlists: Wishlist.all)).to eq( [ { id: wishlist1.external_id, name: wishlist1.name, url: wishlist_url(wishlist1.url_slug, host: wishlist1.user.subdomain_with_protocol), product_count: 2, creator: nil, discover_opted_out: true, }, { id: wishlist2.external_id, name: wishlist2.name, url: wishlist_url(wishlist2.url_slug, host: wishlist2.user.subdomain_with_protocol), product_count: 1, creator: nil, discover_opted_out: false, } ] ) end it "returns the correct props for non-creator" do expect(described_class.library_props(wishlists: Wishlist.all, is_wishlist_creator: false)).to eq( [ { id: wishlist1.external_id, name: wishlist1.name, url: wishlist_url(wishlist1.url_slug, host: wishlist1.user.subdomain_with_protocol), product_count: 2, creator: { name: wishlist1.user.name_or_username, profile_url: wishlist1.user.profile_url, avatar_url: wishlist1.user.avatar_url }, discover_opted_out: nil, }, { id: wishlist2.external_id, name: wishlist2.name, url: wishlist_url(wishlist2.url_slug, host: wishlist2.user.subdomain_with_protocol), product_count: 1, creator: { name: wishlist2.user.name_or_username, profile_url: wishlist2.user.profile_url, avatar_url: wishlist2.user.avatar_url }, discover_opted_out: nil, } ] ) end end describe ".cards_props" do let(:wishlist1) { create(:wishlist, name: "My Wishlist 1", user: create(:user, name: "Wishlist 1 User")) } let(:wishlist2) { create(:wishlist, name: "My Wishlist 2") } let(:pundit_user) { SellerContext.logged_out } before do create_list(:wishlist_follower, 2, wishlist: wishlist1) end it "returns the correct props" do expect(described_class.cards_props(wishlists: Wishlist.where(id: [wishlist1.id, wishlist2.id]), pundit_user:)).to eq( [ described_class.new(wishlist: wishlist1).card_props(pundit_user:, following: false), described_class.new(wishlist: wishlist2).card_props(pundit_user:, following: false), ] ) end context "when the user is following the wishlist" do let(:user) { create(:user) } let(:pundit_user) { SellerContext.new(user:, seller: user) } before do create(:wishlist_follower, wishlist: wishlist1, follower_user: user) end it "returns true for following" do expect(described_class.cards_props(wishlists: Wishlist.where(id: wishlist1.id), pundit_user:).sole[:following]).to eq(true) end end end describe "#listing_props" do let(:wishlist) { create(:wishlist, name: "My Wishlist") } it "returns the correct props" do expect(described_class.new(wishlist: wishlist).listing_props).to eq( id: wishlist.external_id, name: wishlist.name ) end context "when given a product" do let(:product) { create(:product) } it "returns whether the product is in the wishlist" do expect(described_class.new(wishlist:).listing_props(product:)).to eq( id: wishlist.external_id, name: wishlist.name, selections_in_wishlist: [] ) create(:wishlist_product, wishlist:, product:) wishlist.reload expect(described_class.new(wishlist:).listing_props(product:)).to eq( id: wishlist.external_id, name: wishlist.name, selections_in_wishlist: [{ variant_id: nil, recurrence: nil, rent: false, quantity: 1 }] ) end it "ignores deleted wishlist products" do wishlist_product = create(:wishlist_product, wishlist:, product:) wishlist_product.mark_deleted! wishlist.reload expect(described_class.new(wishlist:).listing_props(product:)).to eq( id: wishlist.external_id, name: wishlist.name, selections_in_wishlist: [] ) end context "when the product has variants" do let(:product) { create(:membership_product_with_preset_tiered_pricing) } it "returns which variants are in the wishlist" do expect(described_class.new(wishlist:).listing_props(product:)).to eq( id: wishlist.external_id, name: wishlist.name, selections_in_wishlist: [] ) create(:wishlist_product, wishlist:, product:, variant: product.alive_variants.first, recurrence: BasePrice::Recurrence::MONTHLY) create(:wishlist_product, wishlist:, product:, variant: product.alive_variants.second, recurrence: BasePrice::Recurrence::MONTHLY) wishlist.reload expect(described_class.new(wishlist:).listing_props(product:)).to eq( id: wishlist.external_id, name: wishlist.name, selections_in_wishlist: [ { variant_id: product.alive_variants.first.external_id, recurrence: BasePrice::Recurrence::MONTHLY, rent: false, quantity: 1 }, { variant_id: product.alive_variants.second.external_id, recurrence: BasePrice::Recurrence::MONTHLY, rent: false, quantity: 1 } ] ) end end end end describe "#public_props" do let(:wishlist) { create(:wishlist, name: "My Wishlist", description: "I recommend these", user: create(:user, name: "Wishlister")) } let(:pundit_user) { SellerContext.new(user: wishlist.user, seller: wishlist.user) } before do create(:wishlist_product, :with_quantity, wishlist:) create(:wishlist_product, :with_recurring_variant, wishlist:) end it "returns the correct props" do expect(described_class.new(wishlist:).public_props(request: nil, pundit_user: nil)).to match( id: wishlist.external_id, name: wishlist.name, description: wishlist.description, url: Rails.application.routes.url_helpers.wishlist_url(wishlist.url_slug, host: wishlist.user.subdomain_with_protocol), user: { name: "Wishlister", avatar_url: wishlist.user.avatar_url, profile_url: wishlist.user.profile_url, }, following: false, can_follow: true, can_edit: false, checkout_enabled: true, discover_opted_out: nil, items: [ { id: wishlist.wishlist_products.first.external_id, product: a_hash_including( id: wishlist.wishlist_products.first.product.external_id, ), purchasable: true, giftable: true, option: nil, quantity: 5, recurrence: nil, rent: false, created_at: wishlist.wishlist_products.first.created_at }, { id: wishlist.wishlist_products.second.external_id, product: a_hash_including( id: wishlist.wishlist_products.second.product.external_id, ), purchasable: true, giftable: true, option: wishlist.wishlist_products.second.variant.to_option, quantity: 1, recurrence: "monthly", rent: false, created_at: wishlist.wishlist_products.second.created_at } ], pagination: { count: 2, items: 20, page: 1, pages: 1, prev: nil, next: nil, last: 1 }, ) end context "with profile layout" do it "includes creator_profile in props" do props = described_class.new(wishlist:).public_props(request: nil, pundit_user: nil, layout: Product::Layout::PROFILE) expect(props[:layout]).to eq(Product::Layout::PROFILE) expect(props[:creator_profile]).to be_present expect(props[:creator_profile]).to include(:name, :avatar_url) end end context "with discover layout" do let(:taxonomies_for_nav) { [{ name: "Test", slug: "test" }] } it "includes taxonomies_for_nav in props" do props = described_class.new(wishlist:).public_props( request: nil, pundit_user: nil, layout: Product::Layout::DISCOVER, taxonomies_for_nav: ) expect(props[:layout]).to eq(Product::Layout::DISCOVER) expect(props[:taxonomies_for_nav]).to eq(taxonomies_for_nav) end it "does not include taxonomies_for_nav when not provided" do props = described_class.new(wishlist:).public_props( request: nil, pundit_user: nil, layout: Product::Layout::DISCOVER ) expect(props[:layout]).to eq(Product::Layout::DISCOVER) expect(props).not_to have_key(:taxonomies_for_nav) end end context "for a pre-order product" do it "is not giftable" do wishlist.wishlist_products.first.product.update!(is_in_preorder_state: true) expect(described_class.new(wishlist:).public_props(request: nil, pundit_user: nil)[:items].first[:giftable]).to eq(false) end end context "for the user's own wishlist" do it "is not giftable" do expect(described_class.new(wishlist:).public_props(request: nil, pundit_user:)[:items]).to be_all { |item| item[:giftable] == false } end it "cannot be followed" do expect(described_class.new(wishlist:).public_props(request: nil, pundit_user:)[:can_follow]).to eq(false) end it "does not return user props" do expect(described_class.new(wishlist:).public_props(request: nil, pundit_user:)[:user]).to be_nil end end context "when no products are purchaseable" do before do wishlist.wishlist_products.each { |wishlist_product| wishlist_product.product.unpublish! } end it "disables checkout" do expect(described_class.new(wishlist:).public_props(request: nil, pundit_user:)[:checkout_enabled]).to eq(false) end end context "when the user is following the wishlist" do let(:user) { create(:user) } let(:pundit_user) { SellerContext.new(user:, seller: user) } before do create(:wishlist_follower, wishlist:, follower_user: user) end it "returns true for following" do expect(described_class.new(wishlist:).public_props(request: nil, pundit_user:)[:following]).to eq(true) end end context "when the follow feature flag is disabled" do before { Feature.deactivate(:follow_wishlists) } it "cannot be followed" do expect(described_class.new(wishlist:).public_props(request: nil, pundit_user:)[:can_follow]).to eq(false) end end end describe "#public_items" do let(:wishlist) { create(:wishlist, name: "My Wishlist", user: create(:user, name: "Wishlister")) } let(:pundit_user) { SellerContext.logged_out } let(:request) { nil } it "returns items with pagination metadata" do create(:wishlist_product, :with_quantity, wishlist:) create(:wishlist_product, :with_recurring_variant, wishlist:) result = described_class.new(wishlist:).public_items(request:, pundit_user:) expect(result[:items].length).to eq(2) expect(result[:items].first).to include( :id, :product, :option, :recurrence, :quantity, :rent, :created_at, :purchasable, :giftable ) expect(result[:pagination]).to include( count: 2, items: 20, page: 1, pages: 1 ) end it "paginates items correctly" do create_list(:wishlist_product, 25, wishlist:) first_page = described_class.new(wishlist:).public_items(request:, pundit_user:, page: 1) second_page = described_class.new(wishlist:).public_items(request:, pundit_user:, page: 2) expect(first_page[:items].length).to eq(20) expect(first_page[:pagination]).to include(page: 1, pages: 2, next: 2) expect(second_page[:items].length).to eq(5) expect(second_page[:pagination]).to include(page: 2, prev: 1, next: nil) end end describe "#card_props" do let(:wishlist) { create(:wishlist, name: "My Wishlist", description: "I recommend these", user: create(:user, name: "Wishlister")) } let(:pundit_user) { SellerContext.logged_out } let!(:product_with_thumbnail) { create(:product) } before do create(:thumbnail, product: product_with_thumbnail) create(:wishlist_product, wishlist:) create(:wishlist_product, wishlist:, product: product_with_thumbnail) create(:wishlist_follower, wishlist:) end it "returns the correct props" do expect(described_class.new(wishlist:).card_props(pundit_user: nil, following: false)).to eq( id: wishlist.external_id, url: Rails.application.routes.url_helpers.wishlist_url(wishlist.url_slug, host: wishlist.user.subdomain_with_protocol), name: wishlist.name, description: wishlist.description, seller: { id: wishlist.user.external_id, name: "Wishlister", avatar_url: wishlist.user.avatar_url, profile_url: wishlist.user.profile_url, }, thumbnails: [ { url: product_with_thumbnail.thumbnail_alive.url, native_type: "digital" }, ], product_count: 2, follower_count: 1, following: false, can_follow: true, ) end it "passes through the layout param to the url" do expect(described_class.new(wishlist:).card_props(pundit_user:, following: false, layout: Product::Layout::PROFILE)[:url]).to eq( Rails.application.routes.url_helpers.wishlist_url(wishlist.url_slug, host: wishlist.user.subdomain_with_protocol, layout: Product::Layout::PROFILE) ) end context "when there are 4 or more products" do before do create(:wishlist_product, wishlist:, product: create(:product)) create(:wishlist_product, wishlist:, product: create(:product)) end it "returns 4 thumbnails" do expect(described_class.new(wishlist:).card_props(pundit_user:, following: false)[:thumbnails]).to eq( [ { url: nil, native_type: "digital" }, { url: product_with_thumbnail.thumbnail_alive.url, native_type: "digital" }, { url: nil, native_type: "digital" }, { url: nil, native_type: "digital" }, ] ) end end context "thumbnails" do let!(:product_with_only_thumbnail) { create(:product) } let!(:product_with_only_cover) { create(:product) } let!(:product_with_neither_1) { create(:product) } let!(:product_with_neither_2) { create(:product) } let!(:thumbnail) { create(:thumbnail, product: product_with_only_thumbnail) } let!(:cover_image) { create(:asset_preview_jpg, link: product_with_only_cover) } let!(:wishlist_for_thumbnails) do create( :wishlist, wishlist_products: [ build(:wishlist_product, product: product_with_only_thumbnail), build(:wishlist_product, product: product_with_only_cover), build(:wishlist_product, product: product_with_neither_1), build(:wishlist_product, product: product_with_neither_2), ], ) end it "falls back to cover image url" do result = described_class.new(wishlist: wishlist_for_thumbnails) .card_props(pundit_user:, following: false) expect(result[:thumbnails]).to contain_exactly( { url: thumbnail.url, native_type: "digital" }, { url: cover_image.url, native_type: "digital" }, { url: nil, native_type: "digital" }, { url: nil, native_type: "digital" }, ) end end context "for the user's own wishlist" do let(:pundit_user) { SellerContext.new(user: wishlist.user, seller: wishlist.user) } it "cannot be followed" do expect(described_class.new(wishlist:).card_props(pundit_user:, following: false)[:can_follow]).to eq(false) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/collaborator_presenter_spec.rb
spec/presenters/collaborator_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe CollaboratorPresenter do describe "#new_collaborator_props" do let(:seller) { create(:user) } let!(:visible_product) { create(:product, user: seller) } let!(:archived_product) { create(:product, user: seller, archived: true) } let!(:deleted_product) { create(:product, user: seller, deleted_at: 1.day.ago) } let!(:product_with_affiliates) { create(:product, user: seller).tap { |product| create(:direct_affiliate, products: [product]) } } let!(:ineligible_product) { create(:product, user: seller).tap { |product| create(:collaborator, products: [product]) } } let!(:product_with_global_affiliate) do create(:product, user: seller, purchase_disabled_at: Time.current).tap do |product| create(:product_affiliate, product:, affiliate: create(:user).global_affiliate) end end let!(:product_with_deleted_collaborator) do create(:product, user: seller).tap do |product| create(:collaborator, seller:, products: [product], deleted_at: 1.day.ago) end end it "returns the seller's visible and not archived products" do expect(described_class.new(seller:).new_collaborator_props).to eq( { products: [ { id: visible_product.external_id, name: visible_product.name, published: true, has_another_collaborator: false, has_affiliates: false, enabled: false, percent_commission: nil, dont_show_as_co_creator: false }, { id: product_with_affiliates.external_id, name: product_with_affiliates.name, published: true, has_another_collaborator: false, has_affiliates: true, enabled: false, percent_commission: nil, dont_show_as_co_creator: false }, { id: ineligible_product.external_id, name: ineligible_product.name, published: true, has_another_collaborator: true, has_affiliates: false, enabled: false, percent_commission: nil, dont_show_as_co_creator: false }, { id: product_with_global_affiliate.external_id, name: product_with_global_affiliate.name, published: false, has_another_collaborator: false, has_affiliates: false, enabled: false, percent_commission: nil, dont_show_as_co_creator: false }, { id: product_with_deleted_collaborator.external_id, name: product_with_deleted_collaborator.name, published: true, has_another_collaborator: false, has_affiliates: false, enabled: false, percent_commission: nil, dont_show_as_co_creator: false }, ], collaborators_disabled_reason: nil, } ) end end describe "#collaborator_props" do let(:seller) { create(:user) } let(:visible_product) { create(:product, user: seller) } let!(:archived_product) { create(:product, user: seller, archived: true) } let!(:deleted_product) { create(:product, user: seller, deleted_at: 1.day.ago) } let!(:ineligible_product) { create(:product, user: seller).tap { |product| create(:collaborator, products: [product]) } } let(:collaborator) { create(:collaborator, seller:, products: [visible_product]) } it "returns the collaborator and its products" do props = described_class.new(seller:, collaborator:).collaborator_props expect(props.except(:products)).to match(collaborator.as_json) expect(props[:products]).to match_array([{ id: visible_product.external_id, name: visible_product.name, percent_commission: nil }]) end end describe "#edit_collaborator_props" do let(:seller) { create(:user) } let(:visible_product) { create(:product, user: seller) } let!(:archived_product) { create(:product, user: seller, archived: true) } let!(:deleted_product) { create(:product, user: seller, deleted_at: 1.day.ago) } let!(:ineligible_product) { create(:product, user: seller).tap { |product| create(:collaborator, products: [product]) } } let!(:collaborator) { create(:collaborator, seller:, products: [visible_product]) } it "returns the collaborator and eligible products" do props = described_class.new(seller:, collaborator:).edit_collaborator_props expect(props.except(:products, :collaborators_disabled_reason)).to match(collaborator.as_json) expect(props[:products]).to match_array([ { id: visible_product.external_id, name: visible_product.name, published: true, has_another_collaborator: false, has_affiliates: false, enabled: true, percent_commission: nil, dont_show_as_co_creator: false }, { id: ineligible_product.external_id, name: ineligible_product.name, published: true, has_another_collaborator: true, has_affiliates: false, enabled: false, percent_commission: nil, dont_show_as_co_creator: false }, ]) expect(props[:collaborators_disabled_reason]).to eq(nil) end context "when the seller has a Brazilian Stripe Connect account" do before do allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(true) end it "returns the appropriate disabled reason" do props = described_class.new(seller:, collaborator:).edit_collaborator_props expect(props[:collaborators_disabled_reason]).to eq("Collaborators with Brazilian Stripe accounts are not supported.") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/product_review_presenter_spec.rb
spec/presenters/product_review_presenter_spec.rb
# frozen_string_literal: true describe ProductReviewPresenter do include ActionView::Helpers::DateHelper let(:product_review) { create(:product_review) } describe "#product_review_props" do it "returns the correct props" do expect(described_class.new(product_review).product_review_props).to eq( { id: product_review.external_id, message: product_review.message, rater: { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), name: "Anonymous" }, rating: product_review.rating, purchase_id: product_review.purchase.external_id, is_new: true, response: nil, video: nil } ) end context "product review is more than a month old" do before { product_review.update!(created_at: 2.months.ago) } it "returns is_new as false" do expect(described_class.new(product_review).product_review_props[:is_new]).to be false end end context "product review has a response" do let!(:product_review_response) { create(:product_review_response, product_review:) } it "returns the correct props" do expect(described_class.new(product_review).product_review_props[:response]).to eq( { message: product_review_response.message, } ) end end context "product review is not associated with an account" do before { product_review.purchase.update!(full_name: "Purchaser") } it "uses the purchase's full name" do expect(described_class.new(product_review).product_review_props[:rater]).to eq( { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), name: "Purchaser", } ) end end context "product review is associated with an account" do let(:purchaser) { create(:user, :with_avatar, name: "Reviewer") } before do product_review.purchase.update!(purchaser:) end it "uses the account's avatar and name" do expect(described_class.new(product_review).product_review_props[:rater]).to eq( { avatar_url: purchaser.avatar_variant.url, name: "Reviewer", } ) end context "account's name is blank" do before { purchaser.update!(name: nil) } it "uses 'Anonymous'" do expect(described_class.new(product_review).product_review_props[:rater][:name]).to eq("Anonymous") end context "purchase's full name is present" do before { product_review.purchase.update!(full_name: "Purchaser") } it "uses the purchase's full name" do expect(described_class.new(product_review).product_review_props[:rater][:name]).to eq("Purchaser") end end end end context "product review has videos" do let(:video) { create(:product_review_video, product_review:) } it "only includes the approved video" do video.pending_review! product_review.reload expect(described_class.new(product_review).product_review_props[:video]).to be nil video.approved! product_review.reload expect(described_class.new(product_review).product_review_props[:video]).to eq( { id: video.external_id, thumbnail_url: video.video_file.thumbnail_url, } ) end end end describe "#review_form_props" do it "returns the correct props" do expect(described_class.new(product_review).review_form_props).to eq( { message: product_review.message, rating: product_review.rating, video: nil } ) end context "product review has a rejected video" do let!(:video) { create(:product_review_video, :rejected, product_review:) } it "does not include the video props" do expect(described_class.new(product_review).review_form_props[:video]).to be nil end end context "product review has a pending video" do let!(:video) { create(:product_review_video, :pending_review, product_review:) } it "includes the video props" do expect(described_class.new(product_review).review_form_props[:video]).to eq( { id: video.external_id, thumbnail_url: video.video_file.thumbnail_url, } ) end end context "product review has an approved video" do let!(:video) { create(:product_review_video, :approved, product_review:) } it "includes the video props" do expect(described_class.new(product_review).review_form_props[:video]).to eq( { id: video.external_id, thumbnail_url: video.video_file.thumbnail_url, } ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/widget_presenter_spec.rb
spec/presenters/widget_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe WidgetPresenter do include Rails.application.routes.url_helpers let!(:demo_product) { create(:product, unique_permalink: "demo") } describe "#widget_props" do context "when user is signed in" do let(:user) { create(:user) } subject { described_class.new(seller: user) } context "when user doesn't have own products" do it "returns a demo product" do expect(subject.widget_props).to eq( { display_product_select: true, default_product: { name: "The Works of Edgar Gumstein", url: demo_product.long_url, gumroad_domain_url: demo_product.long_url, script_base_url: UrlService.root_domain_with_protocol }, products: [ { name: "The Works of Edgar Gumstein", url: demo_product.long_url, gumroad_domain_url: demo_product.long_url, script_base_url: UrlService.root_domain_with_protocol } ], affiliated_products: [], }) end end context "when user has own products" do let!(:product) { create(:product, user:) } it "returns user's own products" do expect(subject.widget_props).to eq( { display_product_select: true, default_product: { name: product.name, url: product.long_url, gumroad_domain_url: product.long_url, script_base_url: UrlService.root_domain_with_protocol }, products: [ { name: product.name, url: product.long_url, gumroad_domain_url: product.long_url, script_base_url: UrlService.root_domain_with_protocol } ], affiliated_products: [], }) end end context "when user has affiliated products" do let(:affiliate_product) { create(:product) } let!(:direct_affiliate) { create(:direct_affiliate, affiliate_user: user, products: [affiliate_product]) } it "returns demo product and affiliated products" do expect(subject.widget_props).to eq( { display_product_select: true, default_product: { name: demo_product.name, url: demo_product.long_url, gumroad_domain_url: demo_product.long_url, script_base_url: UrlService.root_domain_with_protocol }, products: [ { name: demo_product.name, url: demo_product.long_url, gumroad_domain_url: demo_product.long_url, script_base_url: UrlService.root_domain_with_protocol } ], affiliated_products: [ { name: affiliate_product.name, url: affiliate_product_url(affiliate_id: direct_affiliate.external_id_numeric, unique_permalink: affiliate_product.unique_permalink, host: UrlService.root_domain_with_protocol), gumroad_domain_url: affiliate_product_url(affiliate_id: direct_affiliate.external_id_numeric, unique_permalink: affiliate_product.unique_permalink, host: UrlService.root_domain_with_protocol), script_base_url: UrlService.root_domain_with_protocol } ], }) end end context "when user has multiple products" do let!(:new_product) { create(:product, user:, name: "New Product", created_at: DateTime.current - 1.hour) } let!(:old_product) { create(:product, user:, name: "Old Product", created_at: DateTime.current - 2.hours) } context "when product argument is provided" do subject { described_class.new(seller: user, product: old_product) } it "returns the default_product as the provided product" do expect(subject.widget_props).to eq( { display_product_select: false, default_product: { name: "Old Product", url: old_product.long_url, gumroad_domain_url: old_product.long_url, script_base_url: UrlService.root_domain_with_protocol }, products: [ { name: "New Product", url: new_product.long_url, gumroad_domain_url: new_product.long_url, script_base_url: UrlService.root_domain_with_protocol }, { name: "Old Product", url: old_product.long_url, gumroad_domain_url: old_product.long_url, script_base_url: UrlService.root_domain_with_protocol } ], affiliated_products: [], }) end end context "when product argument is not provided" do subject { described_class.new(seller: user) } it "returns the default_product as the newest user product" do expect(subject.widget_props).to eq( { display_product_select: true, default_product: { name: "New Product", url: new_product.long_url, gumroad_domain_url: new_product.long_url, script_base_url: UrlService.root_domain_with_protocol }, products: [ { name: "New Product", url: new_product.long_url, gumroad_domain_url: new_product.long_url, script_base_url: UrlService.root_domain_with_protocol }, { name: "Old Product", url: old_product.long_url, gumroad_domain_url: old_product.long_url, script_base_url: UrlService.root_domain_with_protocol } ], affiliated_products: [], }) end end end end context "when user is not signed in" do subject { described_class.new(seller: nil) } it "returns a demo product" do expect(subject.widget_props).to eq( { display_product_select: false, default_product: { name: "The Works of Edgar Gumstein", url: demo_product.long_url, gumroad_domain_url: demo_product.long_url, script_base_url: UrlService.root_domain_with_protocol }, products: [ { name: "The Works of Edgar Gumstein", url: demo_product.long_url, gumroad_domain_url: demo_product.long_url, script_base_url: UrlService.root_domain_with_protocol } ], affiliated_products: [], }) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/user_memberships_presenter_spec.rb
spec/presenters/user_memberships_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe UserMembershipsPresenter do let(:user) { create(:user) } let(:seller_one) { create(:user, :without_username) } let(:seller_two) { create(:user) } let(:seller_three) { create(:user) } let!(:team_membership_owner) { user.create_owner_membership_if_needed! } let!(:team_membership_one) { create(:team_membership, user:, seller: seller_one) } let!(:team_membership_two) { create(:team_membership, user:, seller: seller_two) } let!(:team_membership_three) { create(:team_membership, seller: seller_three) } # for other user let(:pundit_user) { SellerContext.new(user:, seller: seller_one) } it "returns all memberships that belong to the user, ordered" do team_membership_one.update!(last_accessed_at: Time.current) props = UserMembershipsPresenter.new(pundit_user:).props expect(props.length).to eq(3) expect(props[0]).to eq(expected_memberships(team_membership_one, has_some_read_only_access: false, is_selected: true)) expect(props[1]).to eq(expected_memberships(team_membership_two, has_some_read_only_access: false)) expect(props[2]).to eq(expected_memberships(team_membership_owner, has_some_read_only_access: false)) end context "when role is marketing" do before do team_membership_one.update!( last_accessed_at: Time.current, role: TeamMembership::ROLE_MARKETING ) end it "returns correct has_some_read_only_access" do props = UserMembershipsPresenter.new(pundit_user:).props expect(props[0]).to eq(expected_memberships(team_membership_one, has_some_read_only_access: true, is_selected: true)) end end context "with deleted membership" do before do team_membership_two.update_as_deleted! end it "doesn't include deleted membership" do props = UserMembershipsPresenter.new(pundit_user:).props expect(props.length).to eq(2) expect(props[0]).to eq(expected_memberships(team_membership_one, has_some_read_only_access: false, is_selected: true)) expect(props[1]).to eq(expected_memberships(team_membership_owner, has_some_read_only_access: false)) end end def expected_memberships(team_membership, has_some_read_only_access:, is_selected: false) seller = team_membership.seller { id: team_membership.external_id, seller_name: seller.display_name(prefer_email_over_default_username: true), seller_avatar_url: seller.avatar_url, has_some_read_only_access:, is_selected: } end context "when owner membership is missing" do before do team_membership_owner.destroy! end context "with other memberships present" do it "notifies Bugsnag" do expect(Bugsnag).to receive(:notify).exactly(:once).with("Missing owner team membership for user #{user.id}") props = UserMembershipsPresenter.new(pundit_user:).props expect(props).to eq([]) end end context "without other memberships" do before do user.user_memberships.delete_all end it "doesn't notify" do expect(Bugsnag).not_to receive(:notify) props = UserMembershipsPresenter.new(pundit_user:).props expect(props).to eq([]) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false